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