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