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