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