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