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