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