]> git.saurik.com Git - wxWidgets.git/blob - src/common/utilscmn.cpp
correct idle tag type; remove unneeded includes
[wxWidgets.git] / src / common / utilscmn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/utilscmn.cpp
3 // Purpose: Miscellaneous utility functions and classes
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 29/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/app.h"
29 #include "wx/string.h"
30 #include "wx/utils.h"
31 #include "wx/intl.h"
32 #include "wx/log.h"
33
34 #if wxUSE_GUI
35 #include "wx/window.h"
36 #include "wx/frame.h"
37 #include "wx/menu.h"
38 #include "wx/msgdlg.h"
39 #include "wx/textdlg.h"
40 #include "wx/textctrl.h" // for wxTE_PASSWORD
41 #if wxUSE_ACCEL
42 #include "wx/menuitem.h"
43 #include "wx/accel.h"
44 #endif // wxUSE_ACCEL
45 #endif // wxUSE_GUI
46 #endif // WX_PRECOMP
47
48 #include "wx/apptrait.h"
49
50 #include "wx/process.h"
51 #include "wx/txtstrm.h"
52 #include "wx/uri.h"
53 #include "wx/mimetype.h"
54 #include "wx/config.h"
55
56 #if defined(__WXWINCE__) && wxUSE_DATETIME
57 #include "wx/datetime.h"
58 #endif
59
60 #include <ctype.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64
65 #if !wxONLY_WATCOM_EARLIER_THAN(1,4)
66 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
67 #include <errno.h>
68 #endif
69 #endif
70
71 #if wxUSE_GUI
72 #include "wx/colordlg.h"
73 #include "wx/fontdlg.h"
74 #include "wx/notebook.h"
75 #include "wx/statusbr.h"
76 #endif // wxUSE_GUI
77
78 #ifndef __WXWINCE__
79 #include <time.h>
80 #else
81 #include "wx/msw/wince/time.h"
82 #endif
83
84 #ifdef __WXMAC__
85 #include "wx/mac/private.h"
86 #ifndef __DARWIN__
87 #include "InternetConfig.h"
88 #endif
89 #endif
90
91 #if !defined(__MWERKS__) && !defined(__WXWINCE__)
92 #include <sys/types.h>
93 #include <sys/stat.h>
94 #endif
95
96 #if defined(__WXMSW__)
97 #include "wx/msw/private.h"
98 #include "wx/msw/registry.h"
99 #include <shellapi.h> // needed for SHELLEXECUTEINFO
100 #endif
101
102 #if wxUSE_BASE
103
104 // ----------------------------------------------------------------------------
105 // common data
106 // ----------------------------------------------------------------------------
107
108 // ============================================================================
109 // implementation
110 // ============================================================================
111
112 #if WXWIN_COMPATIBILITY_2_4
113
114 wxChar *
115 copystring (const wxChar *s)
116 {
117 if (s == NULL) s = wxEmptyString;
118 size_t len = wxStrlen (s) + 1;
119
120 wxChar *news = new wxChar[len];
121 memcpy (news, s, len * sizeof(wxChar)); // Should be the fastest
122
123 return news;
124 }
125
126 #endif // WXWIN_COMPATIBILITY_2_4
127
128 // ----------------------------------------------------------------------------
129 // String <-> Number conversions (deprecated)
130 // ----------------------------------------------------------------------------
131
132 #if WXWIN_COMPATIBILITY_2_4
133
134 WXDLLIMPEXP_DATA_BASE(const wxChar *) wxFloatToStringStr = wxT("%.2f");
135 WXDLLIMPEXP_DATA_BASE(const wxChar *) wxDoubleToStringStr = wxT("%.2f");
136
137 void
138 StringToFloat (const wxChar *s, float *number)
139 {
140 if (s && *s && number)
141 *number = (float) wxStrtod (s, (wxChar **) NULL);
142 }
143
144 void
145 StringToDouble (const wxChar *s, double *number)
146 {
147 if (s && *s && number)
148 *number = wxStrtod (s, (wxChar **) NULL);
149 }
150
151 wxChar *
152 FloatToString (float number, const wxChar *fmt)
153 {
154 static wxChar buf[256];
155
156 wxSprintf (buf, fmt, number);
157 return buf;
158 }
159
160 wxChar *
161 DoubleToString (double number, const wxChar *fmt)
162 {
163 static wxChar buf[256];
164
165 wxSprintf (buf, fmt, number);
166 return buf;
167 }
168
169 void
170 StringToInt (const wxChar *s, int *number)
171 {
172 if (s && *s && number)
173 *number = (int) wxStrtol (s, (wxChar **) NULL, 10);
174 }
175
176 void
177 StringToLong (const wxChar *s, long *number)
178 {
179 if (s && *s && number)
180 *number = wxStrtol (s, (wxChar **) NULL, 10);
181 }
182
183 wxChar *
184 IntToString (int number)
185 {
186 static wxChar buf[20];
187
188 wxSprintf (buf, wxT("%d"), number);
189 return buf;
190 }
191
192 wxChar *
193 LongToString (long number)
194 {
195 static wxChar buf[20];
196
197 wxSprintf (buf, wxT("%ld"), number);
198 return buf;
199 }
200
201 #endif // WXWIN_COMPATIBILITY_2_4
202
203 // Array used in DecToHex conversion routine.
204 static wxChar hexArray[] = wxT("0123456789ABCDEF");
205
206 // Convert 2-digit hex number to decimal
207 int wxHexToDec(const wxString& buf)
208 {
209 int firstDigit, secondDigit;
210
211 if (buf.GetChar(0) >= wxT('A'))
212 firstDigit = buf.GetChar(0) - wxT('A') + 10;
213 else
214 firstDigit = buf.GetChar(0) - wxT('0');
215
216 if (buf.GetChar(1) >= wxT('A'))
217 secondDigit = buf.GetChar(1) - wxT('A') + 10;
218 else
219 secondDigit = buf.GetChar(1) - wxT('0');
220
221 return (firstDigit & 0xF) * 16 + (secondDigit & 0xF );
222 }
223
224 // Convert decimal integer to 2-character hex string
225 void wxDecToHex(int dec, wxChar *buf)
226 {
227 int firstDigit = (int)(dec/16.0);
228 int secondDigit = (int)(dec - (firstDigit*16.0));
229 buf[0] = hexArray[firstDigit];
230 buf[1] = hexArray[secondDigit];
231 buf[2] = 0;
232 }
233
234 // Convert decimal integer to 2-character hex string
235 wxString wxDecToHex(int dec)
236 {
237 wxChar buf[3];
238 wxDecToHex(dec, buf);
239 return wxString(buf);
240 }
241
242 // ----------------------------------------------------------------------------
243 // misc functions
244 // ----------------------------------------------------------------------------
245
246 // Return the current date/time
247 wxString wxNow()
248 {
249 #ifdef __WXWINCE__
250 #if wxUSE_DATETIME
251 wxDateTime now = wxDateTime::Now();
252 return now.Format();
253 #else
254 return wxEmptyString;
255 #endif
256 #else
257 time_t now = time((time_t *) NULL);
258 char *date = ctime(&now);
259 date[24] = '\0';
260 return wxString::FromAscii(date);
261 #endif
262 }
263
264 void wxUsleep(unsigned long milliseconds)
265 {
266 wxMilliSleep(milliseconds);
267 }
268
269 const wxChar *wxGetInstallPrefix()
270 {
271 wxString prefix;
272
273 if ( wxGetEnv(wxT("WXPREFIX"), &prefix) )
274 return prefix.c_str();
275
276 #ifdef wxINSTALL_PREFIX
277 return wxT(wxINSTALL_PREFIX);
278 #else
279 return wxEmptyString;
280 #endif
281 }
282
283 wxString wxGetDataDir()
284 {
285 wxString dir = wxGetInstallPrefix();
286 dir << wxFILE_SEP_PATH << wxT("share") << wxFILE_SEP_PATH << wxT("wx");
287 return dir;
288 }
289
290 bool wxIsPlatformLittleEndian()
291 {
292 // Are we little or big endian? This method is from Harbison & Steele.
293 union
294 {
295 long l;
296 char c[sizeof(long)];
297 } u;
298 u.l = 1;
299
300 return u.c[0] == 1;
301 }
302
303
304 /*
305 * Class to make it easier to specify platform-dependent values
306 */
307
308 wxArrayInt* wxPlatform::sm_customPlatforms = NULL;
309
310 void wxPlatform::Copy(const wxPlatform& platform)
311 {
312 m_longValue = platform.m_longValue;
313 m_doubleValue = platform.m_doubleValue;
314 m_stringValue = platform.m_stringValue;
315 }
316
317 wxPlatform wxPlatform::If(int platform, long value)
318 {
319 if (Is(platform))
320 return wxPlatform(value);
321 else
322 return wxPlatform();
323 }
324
325 wxPlatform wxPlatform::IfNot(int platform, long value)
326 {
327 if (!Is(platform))
328 return wxPlatform(value);
329 else
330 return wxPlatform();
331 }
332
333 wxPlatform& wxPlatform::ElseIf(int platform, long value)
334 {
335 if (Is(platform))
336 m_longValue = value;
337 return *this;
338 }
339
340 wxPlatform& wxPlatform::ElseIfNot(int platform, long value)
341 {
342 if (!Is(platform))
343 m_longValue = value;
344 return *this;
345 }
346
347 wxPlatform wxPlatform::If(int platform, double value)
348 {
349 if (Is(platform))
350 return wxPlatform(value);
351 else
352 return wxPlatform();
353 }
354
355 wxPlatform wxPlatform::IfNot(int platform, double value)
356 {
357 if (!Is(platform))
358 return wxPlatform(value);
359 else
360 return wxPlatform();
361 }
362
363 wxPlatform& wxPlatform::ElseIf(int platform, double value)
364 {
365 if (Is(platform))
366 m_doubleValue = value;
367 return *this;
368 }
369
370 wxPlatform& wxPlatform::ElseIfNot(int platform, double value)
371 {
372 if (!Is(platform))
373 m_doubleValue = value;
374 return *this;
375 }
376
377 wxPlatform wxPlatform::If(int platform, const wxString& value)
378 {
379 if (Is(platform))
380 return wxPlatform(value);
381 else
382 return wxPlatform();
383 }
384
385 wxPlatform wxPlatform::IfNot(int platform, const wxString& value)
386 {
387 if (!Is(platform))
388 return wxPlatform(value);
389 else
390 return wxPlatform();
391 }
392
393 wxPlatform& wxPlatform::ElseIf(int platform, const wxString& value)
394 {
395 if (Is(platform))
396 m_stringValue = value;
397 return *this;
398 }
399
400 wxPlatform& wxPlatform::ElseIfNot(int platform, const wxString& value)
401 {
402 if (!Is(platform))
403 m_stringValue = value;
404 return *this;
405 }
406
407 wxPlatform& wxPlatform::Else(long value)
408 {
409 m_longValue = value;
410 return *this;
411 }
412
413 wxPlatform& wxPlatform::Else(double value)
414 {
415 m_doubleValue = value;
416 return *this;
417 }
418
419 wxPlatform& wxPlatform::Else(const wxString& value)
420 {
421 m_stringValue = value;
422 return *this;
423 }
424
425 void wxPlatform::AddPlatform(int platform)
426 {
427 if (!sm_customPlatforms)
428 sm_customPlatforms = new wxArrayInt;
429 sm_customPlatforms->Add(platform);
430 }
431
432 void wxPlatform::ClearPlatforms()
433 {
434 delete sm_customPlatforms;
435 sm_customPlatforms = NULL;
436 }
437
438 /// Function for testing current platform
439
440 bool wxPlatform::Is(int platform)
441 {
442 #ifdef __WXMSW__
443 if (platform == wxOS_WINDOWS)
444 return true;
445 #endif
446 #ifdef __WXWINCE__
447 if (platform == wxOS_WINDOWS_CE)
448 return true;
449 #endif
450
451 #if 0
452
453 // FIXME: wxWinPocketPC and wxWinSmartPhone are unknown symbols
454
455 #if defined(__WXWINCE__) && defined(__POCKETPC__)
456 if (platform == wxWinPocketPC)
457 return true;
458 #endif
459 #if defined(__WXWINCE__) && defined(__SMARTPHONE__)
460 if (platform == wxWinSmartPhone)
461 return true;
462 #endif
463
464 #endif
465
466 #ifdef __WXGTK__
467 if (platform == wxPORT_GTK)
468 return true;
469 #endif
470 #ifdef __WXMAC__
471 if (platform == wxPORT_MAC)
472 return true;
473 #endif
474 #ifdef __WXX11__
475 if (platform == wxPORT_X11)
476 return true;
477 #endif
478 #ifdef __UNIX__
479 if (platform == wxOS_UNIX)
480 return true;
481 #endif
482 #ifdef __WXMGL__
483 if (platform == wxPORT_MGL)
484 return true;
485 #endif
486 #ifdef __WXOS2__
487 if (platform == wxPORT_OS2)
488 return true;
489 #endif
490 #ifdef __WXCOCOA__
491 if (platform == wxPORT_MAC)
492 return true;
493 #endif
494
495 if (sm_customPlatforms && sm_customPlatforms->Index(platform) != wxNOT_FOUND)
496 return true;
497
498 return false;
499 }
500
501 // ----------------------------------------------------------------------------
502 // network and user id functions
503 // ----------------------------------------------------------------------------
504
505 // Get Full RFC822 style email address
506 bool wxGetEmailAddress(wxChar *address, int maxSize)
507 {
508 wxString email = wxGetEmailAddress();
509 if ( !email )
510 return false;
511
512 wxStrncpy(address, email, maxSize - 1);
513 address[maxSize - 1] = wxT('\0');
514
515 return true;
516 }
517
518 wxString wxGetEmailAddress()
519 {
520 wxString email;
521
522 wxString host = wxGetFullHostName();
523 if ( !host.empty() )
524 {
525 wxString user = wxGetUserId();
526 if ( !user.empty() )
527 {
528 email << user << wxT('@') << host;
529 }
530 }
531
532 return email;
533 }
534
535 wxString wxGetUserId()
536 {
537 static const int maxLoginLen = 256; // FIXME arbitrary number
538
539 wxString buf;
540 bool ok = wxGetUserId(wxStringBuffer(buf, maxLoginLen), maxLoginLen);
541
542 if ( !ok )
543 buf.Empty();
544
545 return buf;
546 }
547
548 wxString wxGetUserName()
549 {
550 static const int maxUserNameLen = 1024; // FIXME arbitrary number
551
552 wxString buf;
553 bool ok = wxGetUserName(wxStringBuffer(buf, maxUserNameLen), maxUserNameLen);
554
555 if ( !ok )
556 buf.Empty();
557
558 return buf;
559 }
560
561 wxString wxGetHostName()
562 {
563 static const size_t hostnameSize = 257;
564
565 wxString buf;
566 bool ok = wxGetHostName(wxStringBuffer(buf, hostnameSize), hostnameSize);
567
568 if ( !ok )
569 buf.Empty();
570
571 return buf;
572 }
573
574 wxString wxGetFullHostName()
575 {
576 static const size_t hostnameSize = 257;
577
578 wxString buf;
579 bool ok = wxGetFullHostName(wxStringBuffer(buf, hostnameSize), hostnameSize);
580
581 if ( !ok )
582 buf.Empty();
583
584 return buf;
585 }
586
587 wxString wxGetHomeDir()
588 {
589 wxString home;
590 wxGetHomeDir(&home);
591
592 return home;
593 }
594
595 #if 0
596
597 wxString wxGetCurrentDir()
598 {
599 wxString dir;
600 size_t len = 1024;
601 bool ok;
602 do
603 {
604 ok = getcwd(dir.GetWriteBuf(len + 1), len) != NULL;
605 dir.UngetWriteBuf();
606
607 if ( !ok )
608 {
609 if ( errno != ERANGE )
610 {
611 wxLogSysError(_T("Failed to get current directory"));
612
613 return wxEmptyString;
614 }
615 else
616 {
617 // buffer was too small, retry with a larger one
618 len *= 2;
619 }
620 }
621 //else: ok
622 } while ( !ok );
623
624 return dir;
625 }
626
627 #endif // 0
628
629 // ----------------------------------------------------------------------------
630 // wxExecute
631 // ----------------------------------------------------------------------------
632
633 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
634 //
635 // returns true if ok, false if error
636 #if wxUSE_STREAMS
637 static bool ReadAll(wxInputStream *is, wxArrayString& output)
638 {
639 wxCHECK_MSG( is, false, _T("NULL stream in wxExecute()?") );
640
641 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
642 is->Reset();
643
644 wxTextInputStream tis(*is);
645
646 bool cont = true;
647 while ( cont )
648 {
649 wxString line = tis.ReadLine();
650 if ( is->Eof() )
651 break;
652
653 if ( !*is )
654 {
655 cont = false;
656 }
657 else
658 {
659 output.Add(line);
660 }
661 }
662
663 return cont;
664 }
665 #endif // wxUSE_STREAMS
666
667 // this is a private function because it hasn't a clean interface: the first
668 // array is passed by reference, the second by pointer - instead we have 2
669 // public versions of wxExecute() below
670 static long wxDoExecuteWithCapture(const wxString& command,
671 wxArrayString& output,
672 wxArrayString* error,
673 int flags)
674 {
675 // create a wxProcess which will capture the output
676 wxProcess *process = new wxProcess;
677 process->Redirect();
678
679 long rc = wxExecute(command, wxEXEC_SYNC | flags, process);
680
681 #if wxUSE_STREAMS
682 if ( rc != -1 )
683 {
684 if ( !ReadAll(process->GetInputStream(), output) )
685 rc = -1;
686
687 if ( error )
688 {
689 if ( !ReadAll(process->GetErrorStream(), *error) )
690 rc = -1;
691 }
692
693 }
694 #else
695 wxUnusedVar(output);
696 wxUnusedVar(error);
697 #endif // wxUSE_STREAMS/!wxUSE_STREAMS
698
699 delete process;
700
701 return rc;
702 }
703
704 long wxExecute(const wxString& command, wxArrayString& output, int flags)
705 {
706 return wxDoExecuteWithCapture(command, output, NULL, flags);
707 }
708
709 long wxExecute(const wxString& command,
710 wxArrayString& output,
711 wxArrayString& error,
712 int flags)
713 {
714 return wxDoExecuteWithCapture(command, output, &error, flags);
715 }
716
717 // ----------------------------------------------------------------------------
718 // Launch default browser
719 // ----------------------------------------------------------------------------
720
721 bool wxLaunchDefaultBrowser(const wxString& urlOrig, int flags)
722 {
723 wxUnusedVar(flags);
724
725 // set the scheme of url to http if it does not have one
726 wxString url(urlOrig);
727 if ( !wxURI(url).HasScheme() )
728 url.Prepend(wxT("http://"));
729
730 #if defined(__WXMSW__)
731
732 #if wxUSE_IPC
733 if ( flags & wxBROWSER_NEW_WINDOW )
734 {
735 // ShellExecuteEx() opens the URL in an existing window by default so
736 // we can't use it if we need a new window
737 wxRegKey key(wxRegKey::HKCR, url.BeforeFirst(':') + _T("\\shell\\open"));
738 if ( key.Exists() )
739 {
740 wxRegKey keyDDE(key, wxT("DDEExec"));
741 if ( keyDDE.Exists() )
742 {
743 const wxString ddeTopic = wxRegKey(keyDDE, wxT("topic"));
744
745 // we only know the syntax of WWW_OpenURL DDE request for IE,
746 // optimistically assume that all other browsers are compatible
747 // with it
748 wxString ddeCmd;
749 bool ok = ddeTopic == wxT("WWW_OpenURL");
750 if ( ok )
751 {
752 ddeCmd = keyDDE.QueryDefaultValue();
753 ok = !ddeCmd.empty();
754 }
755
756 if ( ok )
757 {
758 // for WWW_OpenURL, the index of the window to open the URL
759 // in is -1 (meaning "current") by default, replace it with
760 // 0 which means "new" (see KB article 160957)
761 ok = ddeCmd.Replace(wxT("-1"), wxT("0"),
762 false /* only first occurence */) == 1;
763 }
764
765 if ( ok )
766 {
767 // and also replace the parameters: the topic should
768 // contain a placeholder for the URL
769 ok = ddeCmd.Replace(wxT("%1"), url, false) == 1;
770 }
771
772 if ( ok )
773 {
774 // try to send it the DDE request now but ignore the errors
775 wxLogNull noLog;
776
777 const wxString ddeServer = wxRegKey(keyDDE, wxT("application"));
778 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCmd) )
779 return true;
780
781 // this is not necessarily an error: maybe browser is
782 // simply not running, but no matter, in any case we're
783 // going to launch it using ShellExecuteEx() below now and
784 // we shouldn't try to open a new window if we open a new
785 // browser anyhow
786 }
787 }
788 }
789 }
790 #endif // wxUSE_IPC
791
792 WinStruct<SHELLEXECUTEINFO> sei;
793 sei.lpFile = url.c_str();
794 sei.lpVerb = _T("open");
795 sei.nShow = SW_SHOWNORMAL;
796
797 ::ShellExecuteEx(&sei);
798
799 const int nResult = (int) sei.hInstApp;
800
801 // Firefox returns file not found for some reason, so make an exception
802 // for it
803 if ( nResult > 32 || nResult == SE_ERR_FNF )
804 {
805 #ifdef __WXDEBUG__
806 // Log something if SE_ERR_FNF happens
807 if ( nResult == SE_ERR_FNF )
808 wxLogDebug(wxT("SE_ERR_FNF from ShellExecute -- maybe FireFox?"));
809 #endif // __WXDEBUG__
810 return true;
811 }
812 #elif defined(__WXMAC__)
813 OSStatus err;
814 ICInstance inst;
815 SInt32 startSel;
816 SInt32 endSel;
817
818 err = ICStart(&inst, 'STKA'); // put your app creator code here
819 if (err == noErr)
820 {
821 #if !TARGET_CARBON
822 err = ICFindConfigFile(inst, 0, NULL);
823 #endif
824 if (err == noErr)
825 {
826 ConstStr255Param hint = 0;
827 startSel = 0;
828 endSel = url.length();
829 err = ICLaunchURL(inst, hint, url.fn_str(), endSel, &startSel, &endSel);
830 if (err != noErr)
831 wxLogDebug(wxT("ICLaunchURL error %d"), (int) err);
832 }
833 ICStop(inst);
834 return true;
835 }
836 else
837 {
838 wxLogDebug(wxT("ICStart error %d"), (int) err);
839 return false;
840 }
841 #elif wxUSE_MIMETYPE
842 // Non-windows way
843 bool ok = false;
844 wxString cmd;
845
846 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(_T("html"));
847 if ( ft )
848 {
849 wxString mt;
850 ft->GetMimeType(&mt);
851
852 ok = ft->GetOpenCommand(&cmd, wxFileType::MessageParameters(url));
853 delete ft;
854 }
855
856 if ( !ok || cmd.empty() )
857 {
858 // fallback to checking for the BROWSER environment variable
859 cmd = wxGetenv(wxT("BROWSER"));
860 if ( !cmd.empty() )
861 cmd << _T(' ') << url;
862 }
863
864 ok = ( !cmd.empty() && wxExecute(cmd) );
865 if (ok)
866 return ok;
867
868 // no file type for HTML extension
869 wxLogError(_T("No default application configured for HTML files."));
870
871 #endif // !wxUSE_MIMETYPE && !__WXMSW__
872
873 wxLogSysError(_T("Failed to open URL \"%s\" in default browser."),
874 url.c_str());
875
876 return false;
877 }
878
879 // ----------------------------------------------------------------------------
880 // wxApp::Yield() wrappers for backwards compatibility
881 // ----------------------------------------------------------------------------
882
883 bool wxYield()
884 {
885 return wxTheApp && wxTheApp->Yield();
886 }
887
888 bool wxYieldIfNeeded()
889 {
890 return wxTheApp && wxTheApp->Yield(true);
891 }
892
893 #endif // wxUSE_BASE
894
895 // ============================================================================
896 // GUI-only functions from now on
897 // ============================================================================
898
899 #if wxUSE_GUI
900
901 // Id generation
902 static long wxCurrentId = 100;
903
904 long wxNewId()
905 {
906 // skip the part of IDs space that contains hard-coded values:
907 if (wxCurrentId == wxID_LOWEST)
908 wxCurrentId = wxID_HIGHEST + 1;
909
910 return wxCurrentId++;
911 }
912
913 long
914 wxGetCurrentId(void) { return wxCurrentId; }
915
916 void
917 wxRegisterId (long id)
918 {
919 if (id >= wxCurrentId)
920 wxCurrentId = id + 1;
921 }
922
923 // ----------------------------------------------------------------------------
924 // Menu accelerators related functions
925 // ----------------------------------------------------------------------------
926
927 wxChar *wxStripMenuCodes(const wxChar *in, wxChar *out)
928 {
929 #if wxUSE_MENUS
930 wxString s = wxMenuItem::GetLabelFromText(in);
931 #else
932 wxString str(in);
933 wxString s = wxStripMenuCodes(str);
934 #endif // wxUSE_MENUS
935 if ( out )
936 {
937 // go smash their buffer if it's not big enough - I love char * params
938 memcpy(out, s.c_str(), s.length() * sizeof(wxChar));
939 }
940 else
941 {
942 // MYcopystring - for easier search...
943 out = new wxChar[s.length() + 1];
944 wxStrcpy(out, s.c_str());
945 }
946
947 return out;
948 }
949
950 wxString wxStripMenuCodes(const wxString& in, int flags)
951 {
952 wxASSERT_MSG( flags, _T("this is useless to call without any flags") );
953
954 wxString out;
955
956 size_t len = in.length();
957 out.reserve(len);
958
959 for ( size_t n = 0; n < len; n++ )
960 {
961 wxChar ch = in[n];
962 if ( (flags & wxStrip_Mnemonics) && ch == _T('&') )
963 {
964 // skip it, it is used to introduce the accel char (or to quote
965 // itself in which case it should still be skipped): note that it
966 // can't be the last character of the string
967 if ( ++n == len )
968 {
969 wxLogDebug(_T("Invalid menu string '%s'"), in.c_str());
970 }
971 else
972 {
973 // use the next char instead
974 ch = in[n];
975 }
976 }
977 else if ( (flags & wxStrip_Accel) && ch == _T('\t') )
978 {
979 // everything after TAB is accel string, exit the loop
980 break;
981 }
982
983 out += ch;
984 }
985
986 return out;
987 }
988
989 // ----------------------------------------------------------------------------
990 // Window search functions
991 // ----------------------------------------------------------------------------
992
993 /*
994 * If parent is non-NULL, look through children for a label or title
995 * matching the specified string. If NULL, look through all top-level windows.
996 *
997 */
998
999 wxWindow *
1000 wxFindWindowByLabel (const wxString& title, wxWindow * parent)
1001 {
1002 return wxWindow::FindWindowByLabel( title, parent );
1003 }
1004
1005
1006 /*
1007 * If parent is non-NULL, look through children for a name
1008 * matching the specified string. If NULL, look through all top-level windows.
1009 *
1010 */
1011
1012 wxWindow *
1013 wxFindWindowByName (const wxString& name, wxWindow * parent)
1014 {
1015 return wxWindow::FindWindowByName( name, parent );
1016 }
1017
1018 // Returns menu item id or wxNOT_FOUND if none.
1019 int
1020 wxFindMenuItemId (wxFrame * frame, const wxString& menuString, const wxString& itemString)
1021 {
1022 #if wxUSE_MENUS
1023 wxMenuBar *menuBar = frame->GetMenuBar ();
1024 if ( menuBar )
1025 return menuBar->FindMenuItem (menuString, itemString);
1026 #endif // wxUSE_MENUS
1027
1028 return wxNOT_FOUND;
1029 }
1030
1031 // Try to find the deepest child that contains 'pt'.
1032 // We go backwards, to try to allow for controls that are spacially
1033 // within other controls, but are still siblings (e.g. buttons within
1034 // static boxes). Static boxes are likely to be created _before_ controls
1035 // that sit inside them.
1036 wxWindow* wxFindWindowAtPoint(wxWindow* win, const wxPoint& pt)
1037 {
1038 if (!win->IsShown())
1039 return NULL;
1040
1041 // Hack for wxNotebook case: at least in wxGTK, all pages
1042 // claim to be shown, so we must only deal with the selected one.
1043 #if wxUSE_NOTEBOOK
1044 if (win->IsKindOf(CLASSINFO(wxNotebook)))
1045 {
1046 wxNotebook* nb = (wxNotebook*) win;
1047 int sel = nb->GetSelection();
1048 if (sel >= 0)
1049 {
1050 wxWindow* child = nb->GetPage(sel);
1051 wxWindow* foundWin = wxFindWindowAtPoint(child, pt);
1052 if (foundWin)
1053 return foundWin;
1054 }
1055 }
1056 #endif
1057
1058 wxWindowList::compatibility_iterator node = win->GetChildren().GetLast();
1059 while (node)
1060 {
1061 wxWindow* child = node->GetData();
1062 wxWindow* foundWin = wxFindWindowAtPoint(child, pt);
1063 if (foundWin)
1064 return foundWin;
1065 node = node->GetPrevious();
1066 }
1067
1068 wxPoint pos = win->GetPosition();
1069 wxSize sz = win->GetSize();
1070 if ( !win->IsTopLevel() && win->GetParent() )
1071 {
1072 pos = win->GetParent()->ClientToScreen(pos);
1073 }
1074
1075 wxRect rect(pos, sz);
1076 if (rect.Inside(pt))
1077 return win;
1078
1079 return NULL;
1080 }
1081
1082 wxWindow* wxGenericFindWindowAtPoint(const wxPoint& pt)
1083 {
1084 // Go backwards through the list since windows
1085 // on top are likely to have been appended most
1086 // recently.
1087 wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetLast();
1088 while (node)
1089 {
1090 wxWindow* win = node->GetData();
1091 wxWindow* found = wxFindWindowAtPoint(win, pt);
1092 if (found)
1093 return found;
1094 node = node->GetPrevious();
1095 }
1096 return NULL;
1097 }
1098
1099 // ----------------------------------------------------------------------------
1100 // GUI helpers
1101 // ----------------------------------------------------------------------------
1102
1103 /*
1104 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
1105 * since otherwise the generic code may be pulled in unnecessarily.
1106 */
1107
1108 #if wxUSE_MSGDLG
1109
1110 int wxMessageBox(const wxString& message, const wxString& caption, long style,
1111 wxWindow *parent, int WXUNUSED(x), int WXUNUSED(y) )
1112 {
1113 long decorated_style = style;
1114
1115 if ( ( style & ( wxICON_EXCLAMATION | wxICON_HAND | wxICON_INFORMATION | wxICON_QUESTION ) ) == 0 )
1116 {
1117 decorated_style |= ( style & wxYES ) ? wxICON_QUESTION : wxICON_INFORMATION ;
1118 }
1119
1120 wxMessageDialog dialog(parent, message, caption, decorated_style);
1121
1122 int ans = dialog.ShowModal();
1123 switch ( ans )
1124 {
1125 case wxID_OK:
1126 return wxOK;
1127 case wxID_YES:
1128 return wxYES;
1129 case wxID_NO:
1130 return wxNO;
1131 case wxID_CANCEL:
1132 return wxCANCEL;
1133 }
1134
1135 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
1136
1137 return wxCANCEL;
1138 }
1139
1140 #endif // wxUSE_MSGDLG
1141
1142 #if wxUSE_TEXTDLG
1143
1144 wxString wxGetTextFromUser(const wxString& message, const wxString& caption,
1145 const wxString& defaultValue, wxWindow *parent,
1146 wxCoord x, wxCoord y, bool centre )
1147 {
1148 wxString str;
1149 long style = wxTextEntryDialogStyle;
1150
1151 if (centre)
1152 style |= wxCENTRE;
1153 else
1154 style &= ~wxCENTRE;
1155
1156 wxTextEntryDialog dialog(parent, message, caption, defaultValue, style, wxPoint(x, y));
1157
1158 if (dialog.ShowModal() == wxID_OK)
1159 {
1160 str = dialog.GetValue();
1161 }
1162
1163 return str;
1164 }
1165
1166 wxString wxGetPasswordFromUser(const wxString& message,
1167 const wxString& caption,
1168 const wxString& defaultValue,
1169 wxWindow *parent,
1170 wxCoord x, wxCoord y, bool centre )
1171 {
1172 wxString str;
1173 long style = wxTextEntryDialogStyle;
1174
1175 if (centre)
1176 style |= wxCENTRE;
1177 else
1178 style &= ~wxCENTRE;
1179
1180 wxPasswordEntryDialog dialog(parent, message, caption, defaultValue,
1181 style, wxPoint(x, y));
1182 if ( dialog.ShowModal() == wxID_OK )
1183 {
1184 str = dialog.GetValue();
1185 }
1186
1187 return str;
1188 }
1189
1190 #endif // wxUSE_TEXTDLG
1191
1192 #if wxUSE_COLOURDLG
1193
1194 wxColour wxGetColourFromUser(wxWindow *parent, const wxColour& colInit, const wxString& caption)
1195 {
1196 wxColourData data;
1197 data.SetChooseFull(true);
1198 if ( colInit.Ok() )
1199 {
1200 data.SetColour((wxColour &)colInit); // const_cast
1201 }
1202
1203 wxColour colRet;
1204 wxColourDialog dialog(parent, &data);
1205 if (!caption.empty())
1206 dialog.SetTitle(caption);
1207 if ( dialog.ShowModal() == wxID_OK )
1208 {
1209 colRet = dialog.GetColourData().GetColour();
1210 }
1211 //else: leave it invalid
1212
1213 return colRet;
1214 }
1215
1216 #endif // wxUSE_COLOURDLG
1217
1218 #if wxUSE_FONTDLG
1219
1220 wxFont wxGetFontFromUser(wxWindow *parent, const wxFont& fontInit, const wxString& caption)
1221 {
1222 wxFontData data;
1223 if ( fontInit.Ok() )
1224 {
1225 data.SetInitialFont(fontInit);
1226 }
1227
1228 wxFont fontRet;
1229 wxFontDialog dialog(parent, data);
1230 if (!caption.empty())
1231 dialog.SetTitle(caption);
1232 if ( dialog.ShowModal() == wxID_OK )
1233 {
1234 fontRet = dialog.GetFontData().GetChosenFont();
1235 }
1236 //else: leave it invalid
1237
1238 return fontRet;
1239 }
1240
1241 #endif // wxUSE_FONTDLG
1242
1243 // ----------------------------------------------------------------------------
1244 // wxSafeYield and supporting functions
1245 // ----------------------------------------------------------------------------
1246
1247 void wxEnableTopLevelWindows(bool enable)
1248 {
1249 wxWindowList::compatibility_iterator node;
1250 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1251 node->GetData()->Enable(enable);
1252 }
1253
1254 wxWindowDisabler::wxWindowDisabler(wxWindow *winToSkip)
1255 {
1256 // remember the top level windows which were already disabled, so that we
1257 // don't reenable them later
1258 m_winDisabled = NULL;
1259
1260 wxWindowList::compatibility_iterator node;
1261 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1262 {
1263 wxWindow *winTop = node->GetData();
1264 if ( winTop == winToSkip )
1265 continue;
1266
1267 // we don't need to disable the hidden or already disabled windows
1268 if ( winTop->IsEnabled() && winTop->IsShown() )
1269 {
1270 winTop->Disable();
1271 }
1272 else
1273 {
1274 if ( !m_winDisabled )
1275 {
1276 m_winDisabled = new wxWindowList;
1277 }
1278
1279 m_winDisabled->Append(winTop);
1280 }
1281 }
1282 }
1283
1284 wxWindowDisabler::~wxWindowDisabler()
1285 {
1286 wxWindowList::compatibility_iterator node;
1287 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1288 {
1289 wxWindow *winTop = node->GetData();
1290 if ( !m_winDisabled || !m_winDisabled->Find(winTop) )
1291 {
1292 winTop->Enable();
1293 }
1294 //else: had been already disabled, don't reenable
1295 }
1296
1297 delete m_winDisabled;
1298 }
1299
1300 // Yield to other apps/messages and disable user input to all windows except
1301 // the given one
1302 bool wxSafeYield(wxWindow *win, bool onlyIfNeeded)
1303 {
1304 wxWindowDisabler wd(win);
1305
1306 bool rc;
1307 if (onlyIfNeeded)
1308 rc = wxYieldIfNeeded();
1309 else
1310 rc = wxYield();
1311
1312 return rc;
1313 }
1314
1315 // Don't synthesize KeyUp events holding down a key and producing KeyDown
1316 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
1317 // in utilsgtk.cpp.
1318 #ifndef __WXGTK__
1319 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag) )
1320 {
1321 return true; // detectable auto-repeat is the only mode MSW supports
1322 }
1323 #endif // !wxGTK
1324
1325 #endif // wxUSE_GUI