Applied patch [ 1202417 ] Make wxLaunchDefaultBrowser windows fallback work with...
[wxWidgets.git] / src / common / utilscmn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: 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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) && !defined(__EMX__)
21 // Some older compilers (such as EMX) cannot handle
22 // #pragma interface/implementation correctly, iff
23 // #pragma implementation is used in _two_ translation
24 // units (as created by e.g. event.cpp compiled for
25 // libwx_base and event.cpp compiled for libwx_gui_core).
26 // So we must not use those pragmas for those compilers in
27 // such files.
28 #pragma implementation "utils.h"
29 #endif
30
31 // For compilers that support precompilation, includes "wx.h".
32 #include "wx/wxprec.h"
33
34 #ifdef __BORLANDC__
35 #pragma hdrstop
36 #endif
37
38 #ifndef WX_PRECOMP
39 #include "wx/app.h"
40 #include "wx/string.h"
41 #include "wx/utils.h"
42 #include "wx/intl.h"
43 #include "wx/log.h"
44
45 #if wxUSE_GUI
46 #include "wx/window.h"
47 #include "wx/frame.h"
48 #include "wx/menu.h"
49 #include "wx/msgdlg.h"
50 #include "wx/textdlg.h"
51 #include "wx/textctrl.h" // for wxTE_PASSWORD
52 #if wxUSE_ACCEL
53 #include "wx/menuitem.h"
54 #include "wx/accel.h"
55 #endif // wxUSE_ACCEL
56 #endif // wxUSE_GUI
57 #endif // WX_PRECOMP
58
59 #include "wx/apptrait.h"
60
61 #include "wx/process.h"
62 #include "wx/txtstrm.h"
63 #include "wx/uri.h"
64 #include "wx/mimetype.h"
65 #include "wx/config.h"
66
67 #if defined(__WXWINCE__) && wxUSE_DATETIME
68 #include "wx/datetime.h"
69 #endif
70
71 #include <ctype.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75
76 #if !defined(__WATCOMC__)
77 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
78 #include <errno.h>
79 #endif
80 #endif
81
82 #if wxUSE_GUI
83 #include "wx/colordlg.h"
84 #include "wx/fontdlg.h"
85 #include "wx/notebook.h"
86 #include "wx/frame.h"
87 #include "wx/statusbr.h"
88 #endif // wxUSE_GUI
89
90 #ifndef __WXWINCE__
91 #include <time.h>
92 #else
93 #include "wx/msw/wince/time.h"
94 #endif
95
96 #if !defined(__MWERKS__) && !defined(__WXWINCE__)
97 #include <sys/types.h>
98 #include <sys/stat.h>
99 #endif
100
101 #if defined(__WXMSW__)
102 #include "wx/msw/private.h"
103 #endif
104
105 #if wxUSE_BASE
106
107 // ----------------------------------------------------------------------------
108 // common data
109 // ----------------------------------------------------------------------------
110
111 #if WXWIN_COMPATIBILITY_2_2
112 const wxChar *wxInternalErrorStr = wxT("wxWidgets Internal Error");
113 const wxChar *wxFatalErrorStr = wxT("wxWidgets Fatal Error");
114 #endif // WXWIN_COMPATIBILITY_2_2
115
116 // ============================================================================
117 // implementation
118 // ============================================================================
119
120 #if WXWIN_COMPATIBILITY_2_4
121
122 wxChar *
123 copystring (const wxChar *s)
124 {
125 if (s == NULL) s = wxEmptyString;
126 size_t len = wxStrlen (s) + 1;
127
128 wxChar *news = new wxChar[len];
129 memcpy (news, s, len * sizeof(wxChar)); // Should be the fastest
130
131 return news;
132 }
133
134 #endif // WXWIN_COMPATIBILITY_2_4
135
136 // ----------------------------------------------------------------------------
137 // String <-> Number conversions (deprecated)
138 // ----------------------------------------------------------------------------
139
140 #if WXWIN_COMPATIBILITY_2_4
141
142 WXDLLIMPEXP_DATA_BASE(const wxChar *) wxFloatToStringStr = wxT("%.2f");
143 WXDLLIMPEXP_DATA_BASE(const wxChar *) wxDoubleToStringStr = wxT("%.2f");
144
145 void
146 StringToFloat (const wxChar *s, float *number)
147 {
148 if (s && *s && number)
149 *number = (float) wxStrtod (s, (wxChar **) NULL);
150 }
151
152 void
153 StringToDouble (const wxChar *s, double *number)
154 {
155 if (s && *s && number)
156 *number = wxStrtod (s, (wxChar **) NULL);
157 }
158
159 wxChar *
160 FloatToString (float number, const wxChar *fmt)
161 {
162 static wxChar buf[256];
163
164 wxSprintf (buf, fmt, number);
165 return buf;
166 }
167
168 wxChar *
169 DoubleToString (double number, const wxChar *fmt)
170 {
171 static wxChar buf[256];
172
173 wxSprintf (buf, fmt, number);
174 return buf;
175 }
176
177 void
178 StringToInt (const wxChar *s, int *number)
179 {
180 if (s && *s && number)
181 *number = (int) wxStrtol (s, (wxChar **) NULL, 10);
182 }
183
184 void
185 StringToLong (const wxChar *s, long *number)
186 {
187 if (s && *s && number)
188 *number = wxStrtol (s, (wxChar **) NULL, 10);
189 }
190
191 wxChar *
192 IntToString (int number)
193 {
194 static wxChar buf[20];
195
196 wxSprintf (buf, wxT("%d"), number);
197 return buf;
198 }
199
200 wxChar *
201 LongToString (long number)
202 {
203 static wxChar buf[20];
204
205 wxSprintf (buf, wxT("%ld"), number);
206 return buf;
207 }
208
209 #endif // WXWIN_COMPATIBILITY_2_4
210
211 // Array used in DecToHex conversion routine.
212 static wxChar hexArray[] = wxT("0123456789ABCDEF");
213
214 // Convert 2-digit hex number to decimal
215 int wxHexToDec(const wxString& buf)
216 {
217 int firstDigit, secondDigit;
218
219 if (buf.GetChar(0) >= wxT('A'))
220 firstDigit = buf.GetChar(0) - wxT('A') + 10;
221 else
222 firstDigit = buf.GetChar(0) - wxT('0');
223
224 if (buf.GetChar(1) >= wxT('A'))
225 secondDigit = buf.GetChar(1) - wxT('A') + 10;
226 else
227 secondDigit = buf.GetChar(1) - wxT('0');
228
229 return (firstDigit & 0xF) * 16 + (secondDigit & 0xF );
230 }
231
232 // Convert decimal integer to 2-character hex string
233 void wxDecToHex(int dec, wxChar *buf)
234 {
235 int firstDigit = (int)(dec/16.0);
236 int secondDigit = (int)(dec - (firstDigit*16.0));
237 buf[0] = hexArray[firstDigit];
238 buf[1] = hexArray[secondDigit];
239 buf[2] = 0;
240 }
241
242 // Convert decimal integer to 2-character hex string
243 wxString wxDecToHex(int dec)
244 {
245 wxChar buf[3];
246 wxDecToHex(dec, buf);
247 return wxString(buf);
248 }
249
250 // ----------------------------------------------------------------------------
251 // misc functions
252 // ----------------------------------------------------------------------------
253
254 // Return the current date/time
255 wxString wxNow()
256 {
257 #ifdef __WXWINCE__
258 #if wxUSE_DATETIME
259 wxDateTime now = wxDateTime::Now();
260 return now.Format();
261 #else
262 return wxEmptyString;
263 #endif
264 #else
265 time_t now = time((time_t *) NULL);
266 char *date = ctime(&now);
267 date[24] = '\0';
268 return wxString::FromAscii(date);
269 #endif
270 }
271
272 void wxUsleep(unsigned long milliseconds)
273 {
274 wxMilliSleep(milliseconds);
275 }
276
277 const wxChar *wxGetInstallPrefix()
278 {
279 wxString prefix;
280
281 if ( wxGetEnv(wxT("WXPREFIX"), &prefix) )
282 return prefix.c_str();
283
284 #ifdef wxINSTALL_PREFIX
285 return wxT(wxINSTALL_PREFIX);
286 #else
287 return wxEmptyString;
288 #endif
289 }
290
291 wxString wxGetDataDir()
292 {
293 wxString dir = wxGetInstallPrefix();
294 dir << wxFILE_SEP_PATH << wxT("share") << wxFILE_SEP_PATH << wxT("wx");
295 return dir;
296 }
297
298 int wxGetOsVersion(int *verMaj, int *verMin)
299 {
300 // we want this function to work even if there is no wxApp
301 wxConsoleAppTraits traitsConsole;
302 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
303 if ( ! traits )
304 traits = &traitsConsole;
305
306 wxToolkitInfo& info = traits->GetToolkitInfo();
307 if ( verMaj )
308 *verMaj = info.versionMajor;
309 if ( verMin )
310 *verMin = info.versionMinor;
311 return info.os;
312 }
313
314 // ----------------------------------------------------------------------------
315 // network and user id functions
316 // ----------------------------------------------------------------------------
317
318 // Get Full RFC822 style email address
319 bool wxGetEmailAddress(wxChar *address, int maxSize)
320 {
321 wxString email = wxGetEmailAddress();
322 if ( !email )
323 return false;
324
325 wxStrncpy(address, email, maxSize - 1);
326 address[maxSize - 1] = wxT('\0');
327
328 return true;
329 }
330
331 wxString wxGetEmailAddress()
332 {
333 wxString email;
334
335 wxString host = wxGetFullHostName();
336 if ( !host.empty() )
337 {
338 wxString user = wxGetUserId();
339 if ( !user.empty() )
340 {
341 email << user << wxT('@') << host;
342 }
343 }
344
345 return email;
346 }
347
348 wxString wxGetUserId()
349 {
350 static const int maxLoginLen = 256; // FIXME arbitrary number
351
352 wxString buf;
353 bool ok = wxGetUserId(wxStringBuffer(buf, maxLoginLen), maxLoginLen);
354
355 if ( !ok )
356 buf.Empty();
357
358 return buf;
359 }
360
361 wxString wxGetUserName()
362 {
363 static const int maxUserNameLen = 1024; // FIXME arbitrary number
364
365 wxString buf;
366 bool ok = wxGetUserName(wxStringBuffer(buf, maxUserNameLen), maxUserNameLen);
367
368 if ( !ok )
369 buf.Empty();
370
371 return buf;
372 }
373
374 wxString wxGetHostName()
375 {
376 static const size_t hostnameSize = 257;
377
378 wxString buf;
379 bool ok = wxGetHostName(wxStringBuffer(buf, hostnameSize), hostnameSize);
380
381 if ( !ok )
382 buf.Empty();
383
384 return buf;
385 }
386
387 wxString wxGetFullHostName()
388 {
389 static const size_t hostnameSize = 257;
390
391 wxString buf;
392 bool ok = wxGetFullHostName(wxStringBuffer(buf, hostnameSize), hostnameSize);
393
394 if ( !ok )
395 buf.Empty();
396
397 return buf;
398 }
399
400 wxString wxGetHomeDir()
401 {
402 wxString home;
403 wxGetHomeDir(&home);
404
405 return home;
406 }
407
408 #if 0
409
410 wxString wxGetCurrentDir()
411 {
412 wxString dir;
413 size_t len = 1024;
414 bool ok;
415 do
416 {
417 ok = getcwd(dir.GetWriteBuf(len + 1), len) != NULL;
418 dir.UngetWriteBuf();
419
420 if ( !ok )
421 {
422 if ( errno != ERANGE )
423 {
424 wxLogSysError(_T("Failed to get current directory"));
425
426 return wxEmptyString;
427 }
428 else
429 {
430 // buffer was too small, retry with a larger one
431 len *= 2;
432 }
433 }
434 //else: ok
435 } while ( !ok );
436
437 return dir;
438 }
439
440 #endif // 0
441
442 // ----------------------------------------------------------------------------
443 // wxExecute
444 // ----------------------------------------------------------------------------
445
446 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
447 //
448 // returns true if ok, false if error
449 #if wxUSE_STREAMS
450 static bool ReadAll(wxInputStream *is, wxArrayString& output)
451 {
452 wxCHECK_MSG( is, false, _T("NULL stream in wxExecute()?") );
453
454 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
455 is->Reset();
456
457 wxTextInputStream tis(*is);
458
459 bool cont = true;
460 while ( cont )
461 {
462 wxString line = tis.ReadLine();
463 if ( is->Eof() )
464 break;
465
466 if ( !*is )
467 {
468 cont = false;
469 }
470 else
471 {
472 output.Add(line);
473 }
474 }
475
476 return cont;
477 }
478 #endif // wxUSE_STREAMS
479
480 // this is a private function because it hasn't a clean interface: the first
481 // array is passed by reference, the second by pointer - instead we have 2
482 // public versions of wxExecute() below
483 static long wxDoExecuteWithCapture(const wxString& command,
484 wxArrayString& output,
485 wxArrayString* error,
486 int flags)
487 {
488 // create a wxProcess which will capture the output
489 wxProcess *process = new wxProcess;
490 process->Redirect();
491
492 long rc = wxExecute(command, wxEXEC_SYNC | flags, process);
493
494 #if wxUSE_STREAMS
495 if ( rc != -1 )
496 {
497 if ( !ReadAll(process->GetInputStream(), output) )
498 rc = -1;
499
500 if ( error )
501 {
502 if ( !ReadAll(process->GetErrorStream(), *error) )
503 rc = -1;
504 }
505
506 }
507 #else
508 wxUnusedVar(output);
509 wxUnusedVar(error);
510 #endif // wxUSE_STREAMS/!wxUSE_STREAMS
511
512 delete process;
513
514 return rc;
515 }
516
517 long wxExecute(const wxString& command, wxArrayString& output, int flags)
518 {
519 return wxDoExecuteWithCapture(command, output, NULL, flags);
520 }
521
522 long wxExecute(const wxString& command,
523 wxArrayString& output,
524 wxArrayString& error,
525 int flags)
526 {
527 return wxDoExecuteWithCapture(command, output, &error, flags);
528 }
529
530 // ----------------------------------------------------------------------------
531 // Launch default browser
532 // ----------------------------------------------------------------------------
533
534 bool wxLaunchDefaultBrowser(const wxString& url)
535 {
536 wxString finalurl = url;
537
538 //if it isn't a full url, try appending http:// to it
539 if(wxURI(url).IsReference())
540 finalurl = wxString(wxT("http://")) + url;
541
542 #if defined(__WXMSW__) && wxUSE_CONFIG_NATIVE
543
544 wxString command;
545
546 // ShellExecute() always opens in the same window,
547 // so do it manually for new window (from Mahogany)
548 wxRegKey key(wxRegKey::HKCR, url.BeforeFirst(':') + wxT("\\shell\\open"));
549 if ( key.Exists() )
550 {
551 wxRegKey keyDDE(key, wxT("DDEExec"));
552 if ( keyDDE.Exists() )
553 {
554 wxString ddeTopic = wxRegKey(keyDDE, wxT("topic"));
555
556 // we only know the syntax of WWW_OpenURL DDE request
557 if ( ddeTopic == wxT("WWW_OpenURL") )
558 {
559 wxString ddeCmd = keyDDE;
560
561 // this is a bit naive but should work as -1 can't appear
562 // elsewhere in the DDE topic, normally
563 if ( ddeCmd.Replace(wxT("-1"), wxT("0"),
564 false /* only first occurence */) == 1 )
565 {
566 // and also replace the parameters
567 if ( ddeCmd.Replace(wxT("%1"), url, false) == 1 )
568 {
569 // magic incantation understood by wxMSW
570 command << wxT("WX_DDE#")
571 << wxRegKey(key, wxT("command")).QueryDefaultValue() << wxT('#')
572 << wxRegKey(keyDDE, wxT("application")).QueryDefaultValue()
573 << wxT('#') << ddeTopic << wxT('#')
574 << ddeCmd;
575 }
576 }
577 }
578 }
579 }
580
581 //Try wxExecute - if it doesn't work or the regkey stuff
582 //above failed, fallback to opening the file in the same
583 //browser window
584 if ( command.empty() || wxExecute(command) == -1)
585 {
586 int nResult; //HINSTANCE error code
587
588 #if !defined(__WXWINCE__)
589 // CYGWIN and MINGW may have problems - so load ShellExecute
590 // dynamically
591 typedef HINSTANCE (WINAPI *LPShellExecute)(HWND hwnd, const wxChar* lpOperation,
592 const wxChar* lpFile,
593 const wxChar* lpParameters,
594 const wxChar* lpDirectory,
595 INT nShowCmd);
596
597 HINSTANCE hShellDll = ::LoadLibrary(wxT("shell32.dll"));
598 if(hShellDll == NULL)
599 return false;
600
601 LPShellExecute lpShellExecute =
602 (LPShellExecute) ::GetProcAddress(hShellDll,
603 wxString::Format(wxT("ShellExecute%s"),
604
605 #ifdef __WXUNICODE__
606 wxT("W")
607 #else
608 wxT("A")
609 #endif
610 #ifdef __WXWINCE__
611 )
612 #else
613 ).mb_str(wxConvLocal)
614 #endif
615 );
616 if(lpShellExecute == NULL)
617 return false;
618
619 // Windows sometimes doesn't open the browser correctly when using mime
620 // types, so do ShellExecute - i.e. start <url> (from James Carroll)
621 nResult = (int) (*lpShellExecute)(NULL, NULL, finalurl.c_str(),
622 NULL, wxT(""), SW_SHOWNORMAL);
623 // Unload Shell32.dll
624 ::FreeLibrary(hShellDll);
625 #else
626 //Windows CE does not have normal ShellExecute - but it has
627 //ShellExecuteEx all the way back to version 1.0
628
629
630 //Set up the SHELLEXECUTEINFO structure to pass to ShellExecuteEx
631 SHELLEXECUTEINFO sei;
632 sei.cbSize = sizeof(SHELLEXECUTEINFO);
633 sei.dwHotKey = 0;
634 sei.fMask = 0;
635 sei.hIcon = NULL;
636 sei.hInstApp = NULL;
637 sei.hkeyClass = NULL;
638 sei.hMonitor = NULL;
639 sei.hProcess = NULL;
640 sei.hwnd = NULL;
641 sei.lpClass = NULL;
642 sei.lpDirectory = NULL;
643 sei.lpFile = finalurl.c_str();
644 sei.lpIDList = NULL;
645 sei.lpParameters = NULL;
646 sei.lpVerb = TEXT("open");
647 sei.nShow = SW_SHOWNORMAL;
648
649 //Call ShellExecuteEx
650 ShellExecuteEx(&sei);
651
652 //Get error code
653 nResult = (int) sei.hInstApp;
654 #endif
655
656 // Hack for Firefox (returns file not found for some reason)
657 // from Angelo Mandato's wxHyperlinksCtrl
658 // HINSTANCE_ERROR == 32 (HINSTANCE_ERROR does not exist on Windows CE)
659 if (nResult <= 32 && nResult != SE_ERR_FNF)
660 return false;
661
662 #ifdef __WXDEBUG__
663 // Log something if SE_ERR_FNF happens
664 if(nResult == SE_ERR_FNF)
665 wxLogDebug(wxT("Got SE_ERR_FNF from ShellExecute - maybe FireFox"));
666 #endif
667 }
668
669 #elif wxUSE_MIMETYPE
670
671 // Non-windows way
672 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension (_T("html"));
673 if (!ft)
674 {
675 wxLogError(_T("No default application can open .html extension"));
676 return false;
677 }
678
679 wxString mt;
680 ft->GetMimeType(&mt);
681
682 wxString cmd;
683 bool ok = ft->GetOpenCommand (&cmd, wxFileType::MessageParameters(finalurl));
684 delete ft;
685
686 if (ok)
687 {
688 if( wxExecute (cmd, wxEXEC_ASYNC) == -1 )
689 {
690 wxLogError(_T("Failed to launch application for wxLaunchDefaultBrowser"));
691 return false;
692 }
693 }
694 else
695 {
696 // fallback to checking for the BROWSER environment variable
697 cmd = wxGetenv(wxT("BROWSER"));
698 if ( cmd.empty() || wxExecute(cmd + wxT(" ") + finalurl) == -1)
699 return false;
700 }
701
702
703 #else // !wxUSE_MIMETYPE && !(WXMSW && wxUSE_NATIVE_CONFIG)
704
705 return false;
706
707 #endif
708
709 //success - hopefully
710 return true;
711 }
712
713 // ----------------------------------------------------------------------------
714 // wxApp::Yield() wrappers for backwards compatibility
715 // ----------------------------------------------------------------------------
716
717 bool wxYield()
718 {
719 return wxTheApp && wxTheApp->Yield();
720 }
721
722 bool wxYieldIfNeeded()
723 {
724 return wxTheApp && wxTheApp->Yield(true);
725 }
726
727 #endif // wxUSE_BASE
728
729 // ============================================================================
730 // GUI-only functions from now on
731 // ============================================================================
732
733 #if wxUSE_GUI
734
735 // Id generation
736 static long wxCurrentId = 100;
737
738 long wxNewId()
739 {
740 // skip the part of IDs space that contains hard-coded values:
741 if (wxCurrentId == wxID_LOWEST)
742 wxCurrentId = wxID_HIGHEST + 1;
743
744 return wxCurrentId++;
745 }
746
747 long
748 wxGetCurrentId(void) { return wxCurrentId; }
749
750 void
751 wxRegisterId (long id)
752 {
753 if (id >= wxCurrentId)
754 wxCurrentId = id + 1;
755 }
756
757 #if wxUSE_MENUS
758
759 // ----------------------------------------------------------------------------
760 // Menu accelerators related functions
761 // ----------------------------------------------------------------------------
762
763 wxChar *wxStripMenuCodes(const wxChar *in, wxChar *out)
764 {
765 wxString s = wxMenuItem::GetLabelFromText(in);
766 if ( out )
767 {
768 // go smash their buffer if it's not big enough - I love char * params
769 memcpy(out, s.c_str(), s.length() * sizeof(wxChar));
770 }
771 else
772 {
773 // MYcopystring - for easier search...
774 out = new wxChar[s.length() + 1];
775 wxStrcpy(out, s.c_str());
776 }
777
778 return out;
779 }
780
781 wxString wxStripMenuCodes(const wxString& in)
782 {
783 wxString out;
784
785 size_t len = in.length();
786 out.reserve(len);
787
788 for ( size_t n = 0; n < len; n++ )
789 {
790 wxChar ch = in[n];
791 if ( ch == _T('&') )
792 {
793 // skip it, it is used to introduce the accel char (or to quote
794 // itself in which case it should still be skipped): note that it
795 // can't be the last character of the string
796 if ( ++n == len )
797 {
798 wxLogDebug(_T("Invalid menu string '%s'"), in.c_str());
799 }
800 else
801 {
802 // use the next char instead
803 ch = in[n];
804 }
805 }
806 else if ( ch == _T('\t') )
807 {
808 // everything after TAB is accel string, exit the loop
809 break;
810 }
811
812 out += ch;
813 }
814
815 return out;
816 }
817
818 #endif // wxUSE_MENUS
819
820 // ----------------------------------------------------------------------------
821 // Window search functions
822 // ----------------------------------------------------------------------------
823
824 /*
825 * If parent is non-NULL, look through children for a label or title
826 * matching the specified string. If NULL, look through all top-level windows.
827 *
828 */
829
830 wxWindow *
831 wxFindWindowByLabel (const wxString& title, wxWindow * parent)
832 {
833 return wxWindow::FindWindowByLabel( title, parent );
834 }
835
836
837 /*
838 * If parent is non-NULL, look through children for a name
839 * matching the specified string. If NULL, look through all top-level windows.
840 *
841 */
842
843 wxWindow *
844 wxFindWindowByName (const wxString& name, wxWindow * parent)
845 {
846 return wxWindow::FindWindowByName( name, parent );
847 }
848
849 // Returns menu item id or wxNOT_FOUND if none.
850 int
851 wxFindMenuItemId (wxFrame * frame, const wxString& menuString, const wxString& itemString)
852 {
853 #if wxUSE_MENUS
854 wxMenuBar *menuBar = frame->GetMenuBar ();
855 if ( menuBar )
856 return menuBar->FindMenuItem (menuString, itemString);
857 #endif // wxUSE_MENUS
858
859 return wxNOT_FOUND;
860 }
861
862 // Try to find the deepest child that contains 'pt'.
863 // We go backwards, to try to allow for controls that are spacially
864 // within other controls, but are still siblings (e.g. buttons within
865 // static boxes). Static boxes are likely to be created _before_ controls
866 // that sit inside them.
867 wxWindow* wxFindWindowAtPoint(wxWindow* win, const wxPoint& pt)
868 {
869 if (!win->IsShown())
870 return NULL;
871
872 // Hack for wxNotebook case: at least in wxGTK, all pages
873 // claim to be shown, so we must only deal with the selected one.
874 #if wxUSE_NOTEBOOK
875 if (win->IsKindOf(CLASSINFO(wxNotebook)))
876 {
877 wxNotebook* nb = (wxNotebook*) win;
878 int sel = nb->GetSelection();
879 if (sel >= 0)
880 {
881 wxWindow* child = nb->GetPage(sel);
882 wxWindow* foundWin = wxFindWindowAtPoint(child, pt);
883 if (foundWin)
884 return foundWin;
885 }
886 }
887 #endif
888
889 wxWindowList::compatibility_iterator node = win->GetChildren().GetLast();
890 while (node)
891 {
892 wxWindow* child = node->GetData();
893 wxWindow* foundWin = wxFindWindowAtPoint(child, pt);
894 if (foundWin)
895 return foundWin;
896 node = node->GetPrevious();
897 }
898
899 wxPoint pos = win->GetPosition();
900 wxSize sz = win->GetSize();
901 if (win->GetParent())
902 {
903 pos = win->GetParent()->ClientToScreen(pos);
904 }
905
906 wxRect rect(pos, sz);
907 if (rect.Inside(pt))
908 return win;
909 else
910 return NULL;
911 }
912
913 wxWindow* wxGenericFindWindowAtPoint(const wxPoint& pt)
914 {
915 // Go backwards through the list since windows
916 // on top are likely to have been appended most
917 // recently.
918 wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetLast();
919 while (node)
920 {
921 wxWindow* win = node->GetData();
922 wxWindow* found = wxFindWindowAtPoint(win, pt);
923 if (found)
924 return found;
925 node = node->GetPrevious();
926 }
927 return NULL;
928 }
929
930 // ----------------------------------------------------------------------------
931 // GUI helpers
932 // ----------------------------------------------------------------------------
933
934 /*
935 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
936 * since otherwise the generic code may be pulled in unnecessarily.
937 */
938
939 #if wxUSE_MSGDLG
940
941 int wxMessageBox(const wxString& message, const wxString& caption, long style,
942 wxWindow *parent, int WXUNUSED(x), int WXUNUSED(y) )
943 {
944 long decorated_style = style;
945
946 if ( ( style & ( wxICON_EXCLAMATION | wxICON_HAND | wxICON_INFORMATION | wxICON_QUESTION ) ) == 0 )
947 {
948 decorated_style |= ( style & wxYES ) ? wxICON_QUESTION : wxICON_INFORMATION ;
949 }
950
951 wxMessageDialog dialog(parent, message, caption, decorated_style);
952
953 int ans = dialog.ShowModal();
954 switch ( ans )
955 {
956 case wxID_OK:
957 return wxOK;
958 case wxID_YES:
959 return wxYES;
960 case wxID_NO:
961 return wxNO;
962 case wxID_CANCEL:
963 return wxCANCEL;
964 }
965
966 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
967
968 return wxCANCEL;
969 }
970
971 #endif // wxUSE_MSGDLG
972
973 #if wxUSE_TEXTDLG
974
975 wxString wxGetTextFromUser(const wxString& message, const wxString& caption,
976 const wxString& defaultValue, wxWindow *parent,
977 wxCoord x, wxCoord y, bool centre )
978 {
979 wxString str;
980 long style = wxTextEntryDialogStyle;
981
982 if (centre)
983 style |= wxCENTRE;
984 else
985 style &= ~wxCENTRE;
986
987 wxTextEntryDialog dialog(parent, message, caption, defaultValue, style, wxPoint(x, y));
988
989 if (dialog.ShowModal() == wxID_OK)
990 {
991 str = dialog.GetValue();
992 }
993
994 return str;
995 }
996
997 wxString wxGetPasswordFromUser(const wxString& message,
998 const wxString& caption,
999 const wxString& defaultValue,
1000 wxWindow *parent,
1001 wxCoord x, wxCoord y, bool centre )
1002 {
1003 wxString str;
1004 long style = wxTextEntryDialogStyle;
1005
1006 if (centre)
1007 style |= wxCENTRE;
1008 else
1009 style &= ~wxCENTRE;
1010
1011 wxPasswordEntryDialog dialog(parent, message, caption, defaultValue,
1012 style, wxPoint(x, y));
1013 if ( dialog.ShowModal() == wxID_OK )
1014 {
1015 str = dialog.GetValue();
1016 }
1017
1018 return str;
1019 }
1020
1021 #endif // wxUSE_TEXTDLG
1022
1023 #if wxUSE_COLOURDLG
1024
1025 wxColour wxGetColourFromUser(wxWindow *parent, const wxColour& colInit)
1026 {
1027 wxColourData data;
1028 data.SetChooseFull(true);
1029 if ( colInit.Ok() )
1030 {
1031 data.SetColour((wxColour &)colInit); // const_cast
1032 }
1033
1034 wxColour colRet;
1035 wxColourDialog dialog(parent, &data);
1036 if ( dialog.ShowModal() == wxID_OK )
1037 {
1038 colRet = dialog.GetColourData().GetColour();
1039 }
1040 //else: leave it invalid
1041
1042 return colRet;
1043 }
1044
1045 #endif // wxUSE_COLOURDLG
1046
1047 #if wxUSE_FONTDLG
1048
1049 wxFont wxGetFontFromUser(wxWindow *parent, const wxFont& fontInit)
1050 {
1051 wxFontData data;
1052 if ( fontInit.Ok() )
1053 {
1054 data.SetInitialFont(fontInit);
1055 }
1056
1057 wxFont fontRet;
1058 wxFontDialog dialog(parent, data);
1059 if ( dialog.ShowModal() == wxID_OK )
1060 {
1061 fontRet = dialog.GetFontData().GetChosenFont();
1062 }
1063 //else: leave it invalid
1064
1065 return fontRet;
1066 }
1067
1068 #endif // wxUSE_FONTDLG
1069
1070 // ----------------------------------------------------------------------------
1071 // wxSafeYield and supporting functions
1072 // ----------------------------------------------------------------------------
1073
1074 void wxEnableTopLevelWindows(bool enable)
1075 {
1076 wxWindowList::compatibility_iterator node;
1077 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1078 node->GetData()->Enable(enable);
1079 }
1080
1081 wxWindowDisabler::wxWindowDisabler(wxWindow *winToSkip)
1082 {
1083 // remember the top level windows which were already disabled, so that we
1084 // don't reenable them later
1085 m_winDisabled = NULL;
1086
1087 wxWindowList::compatibility_iterator node;
1088 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1089 {
1090 wxWindow *winTop = node->GetData();
1091 if ( winTop == winToSkip )
1092 continue;
1093
1094 // we don't need to disable the hidden or already disabled windows
1095 if ( winTop->IsEnabled() && winTop->IsShown() )
1096 {
1097 winTop->Disable();
1098 }
1099 else
1100 {
1101 if ( !m_winDisabled )
1102 {
1103 m_winDisabled = new wxWindowList;
1104 }
1105
1106 m_winDisabled->Append(winTop);
1107 }
1108 }
1109 }
1110
1111 wxWindowDisabler::~wxWindowDisabler()
1112 {
1113 wxWindowList::compatibility_iterator node;
1114 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1115 {
1116 wxWindow *winTop = node->GetData();
1117 if ( !m_winDisabled || !m_winDisabled->Find(winTop) )
1118 {
1119 winTop->Enable();
1120 }
1121 //else: had been already disabled, don't reenable
1122 }
1123
1124 delete m_winDisabled;
1125 }
1126
1127 // Yield to other apps/messages and disable user input to all windows except
1128 // the given one
1129 bool wxSafeYield(wxWindow *win, bool onlyIfNeeded)
1130 {
1131 wxWindowDisabler wd(win);
1132
1133 bool rc;
1134 if (onlyIfNeeded)
1135 rc = wxYieldIfNeeded();
1136 else
1137 rc = wxYield();
1138
1139 return rc;
1140 }
1141
1142 // Don't synthesize KeyUp events holding down a key and producing KeyDown
1143 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
1144 // in utilsgtk.cpp.
1145 #ifndef __WXGTK__
1146 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag) )
1147 {
1148 return true; // detectable auto-repeat is the only mode MSW supports
1149 }
1150 #endif // !wxGTK
1151
1152 #endif // wxUSE_GUI
1153