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