]> git.saurik.com Git - wxWidgets.git/blob - src/common/utilscmn.cpp
starting blend modes for Core Graphics
[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 #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 // network and user id functions
308 // ----------------------------------------------------------------------------
309
310 // Get Full RFC822 style email address
311 bool wxGetEmailAddress(wxChar *address, int maxSize)
312 {
313 wxString email = wxGetEmailAddress();
314 if ( !email )
315 return false;
316
317 wxStrncpy(address, email, maxSize - 1);
318 address[maxSize - 1] = wxT('\0');
319
320 return true;
321 }
322
323 wxString wxGetEmailAddress()
324 {
325 wxString email;
326
327 wxString host = wxGetFullHostName();
328 if ( !host.empty() )
329 {
330 wxString user = wxGetUserId();
331 if ( !user.empty() )
332 {
333 email << user << wxT('@') << host;
334 }
335 }
336
337 return email;
338 }
339
340 wxString wxGetUserId()
341 {
342 static const int maxLoginLen = 256; // FIXME arbitrary number
343
344 wxString buf;
345 bool ok = wxGetUserId(wxStringBuffer(buf, maxLoginLen), maxLoginLen);
346
347 if ( !ok )
348 buf.Empty();
349
350 return buf;
351 }
352
353 wxString wxGetUserName()
354 {
355 static const int maxUserNameLen = 1024; // FIXME arbitrary number
356
357 wxString buf;
358 bool ok = wxGetUserName(wxStringBuffer(buf, maxUserNameLen), maxUserNameLen);
359
360 if ( !ok )
361 buf.Empty();
362
363 return buf;
364 }
365
366 wxString wxGetHostName()
367 {
368 static const size_t hostnameSize = 257;
369
370 wxString buf;
371 bool ok = wxGetHostName(wxStringBuffer(buf, hostnameSize), hostnameSize);
372
373 if ( !ok )
374 buf.Empty();
375
376 return buf;
377 }
378
379 wxString wxGetFullHostName()
380 {
381 static const size_t hostnameSize = 257;
382
383 wxString buf;
384 bool ok = wxGetFullHostName(wxStringBuffer(buf, hostnameSize), hostnameSize);
385
386 if ( !ok )
387 buf.Empty();
388
389 return buf;
390 }
391
392 wxString wxGetHomeDir()
393 {
394 wxString home;
395 wxGetHomeDir(&home);
396
397 return home;
398 }
399
400 #if 0
401
402 wxString wxGetCurrentDir()
403 {
404 wxString dir;
405 size_t len = 1024;
406 bool ok;
407 do
408 {
409 ok = getcwd(dir.GetWriteBuf(len + 1), len) != NULL;
410 dir.UngetWriteBuf();
411
412 if ( !ok )
413 {
414 if ( errno != ERANGE )
415 {
416 wxLogSysError(_T("Failed to get current directory"));
417
418 return wxEmptyString;
419 }
420 else
421 {
422 // buffer was too small, retry with a larger one
423 len *= 2;
424 }
425 }
426 //else: ok
427 } while ( !ok );
428
429 return dir;
430 }
431
432 #endif // 0
433
434 // ----------------------------------------------------------------------------
435 // wxExecute
436 // ----------------------------------------------------------------------------
437
438 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
439 //
440 // returns true if ok, false if error
441 #if wxUSE_STREAMS
442 static bool ReadAll(wxInputStream *is, wxArrayString& output)
443 {
444 wxCHECK_MSG( is, false, _T("NULL stream in wxExecute()?") );
445
446 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
447 is->Reset();
448
449 wxTextInputStream tis(*is);
450
451 bool cont = true;
452 while ( cont )
453 {
454 wxString line = tis.ReadLine();
455 if ( is->Eof() )
456 break;
457
458 if ( !*is )
459 {
460 cont = false;
461 }
462 else
463 {
464 output.Add(line);
465 }
466 }
467
468 return cont;
469 }
470 #endif // wxUSE_STREAMS
471
472 // this is a private function because it hasn't a clean interface: the first
473 // array is passed by reference, the second by pointer - instead we have 2
474 // public versions of wxExecute() below
475 static long wxDoExecuteWithCapture(const wxString& command,
476 wxArrayString& output,
477 wxArrayString* error,
478 int flags)
479 {
480 // create a wxProcess which will capture the output
481 wxProcess *process = new wxProcess;
482 process->Redirect();
483
484 long rc = wxExecute(command, wxEXEC_SYNC | flags, process);
485
486 #if wxUSE_STREAMS
487 if ( rc != -1 )
488 {
489 if ( !ReadAll(process->GetInputStream(), output) )
490 rc = -1;
491
492 if ( error )
493 {
494 if ( !ReadAll(process->GetErrorStream(), *error) )
495 rc = -1;
496 }
497
498 }
499 #else
500 wxUnusedVar(output);
501 wxUnusedVar(error);
502 #endif // wxUSE_STREAMS/!wxUSE_STREAMS
503
504 delete process;
505
506 return rc;
507 }
508
509 long wxExecute(const wxString& command, wxArrayString& output, int flags)
510 {
511 return wxDoExecuteWithCapture(command, output, NULL, flags);
512 }
513
514 long wxExecute(const wxString& command,
515 wxArrayString& output,
516 wxArrayString& error,
517 int flags)
518 {
519 return wxDoExecuteWithCapture(command, output, &error, flags);
520 }
521
522 // ----------------------------------------------------------------------------
523 // Launch default browser
524 // ----------------------------------------------------------------------------
525
526 bool wxLaunchDefaultBrowser(const wxString& urlOrig, int flags)
527 {
528 wxUnusedVar(flags);
529
530 // set the scheme of url to http if it does not have one
531 wxString url(urlOrig);
532 if ( !wxURI(url).HasScheme() )
533 url.Prepend(wxT("http://"));
534
535 #if defined(__WXMSW__)
536
537 #if wxUSE_IPC
538 if ( flags & wxBROWSER_NEW_WINDOW )
539 {
540 // ShellExecuteEx() opens the URL in an existing window by default so
541 // we can't use it if we need a new window
542 wxRegKey key(wxRegKey::HKCR, url.BeforeFirst(':') + _T("\\shell\\open"));
543 if ( key.Exists() )
544 {
545 wxRegKey keyDDE(key, wxT("DDEExec"));
546 if ( keyDDE.Exists() )
547 {
548 const wxString ddeTopic = wxRegKey(keyDDE, wxT("topic"));
549
550 // we only know the syntax of WWW_OpenURL DDE request for IE,
551 // optimistically assume that all other browsers are compatible
552 // with it
553 wxString ddeCmd;
554 bool ok = ddeTopic == wxT("WWW_OpenURL");
555 if ( ok )
556 {
557 ddeCmd = keyDDE.QueryDefaultValue();
558 ok = !ddeCmd.empty();
559 }
560
561 if ( ok )
562 {
563 // for WWW_OpenURL, the index of the window to open the URL
564 // in is -1 (meaning "current") by default, replace it with
565 // 0 which means "new" (see KB article 160957)
566 ok = ddeCmd.Replace(wxT("-1"), wxT("0"),
567 false /* only first occurence */) == 1;
568 }
569
570 if ( ok )
571 {
572 // and also replace the parameters: the topic should
573 // contain a placeholder for the URL
574 ok = ddeCmd.Replace(wxT("%1"), url, false) == 1;
575 }
576
577 if ( ok )
578 {
579 // try to send it the DDE request now but ignore the errors
580 wxLogNull noLog;
581
582 const wxString ddeServer = wxRegKey(keyDDE, wxT("application"));
583 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCmd) )
584 return true;
585
586 // this is not necessarily an error: maybe browser is
587 // simply not running, but no matter, in any case we're
588 // going to launch it using ShellExecuteEx() below now and
589 // we shouldn't try to open a new window if we open a new
590 // browser anyhow
591 }
592 }
593 }
594 }
595 #endif // wxUSE_IPC
596
597 WinStruct<SHELLEXECUTEINFO> sei;
598 sei.lpFile = url.c_str();
599 sei.lpVerb = _T("open");
600 sei.nShow = SW_SHOWNORMAL;
601
602 ::ShellExecuteEx(&sei);
603
604 const int nResult = (int) sei.hInstApp;
605
606 // Firefox returns file not found for some reason, so make an exception
607 // for it
608 if ( nResult > 32 || nResult == SE_ERR_FNF )
609 {
610 #ifdef __WXDEBUG__
611 // Log something if SE_ERR_FNF happens
612 if ( nResult == SE_ERR_FNF )
613 wxLogDebug(wxT("SE_ERR_FNF from ShellExecute -- maybe FireFox?"));
614 #endif // __WXDEBUG__
615 return true;
616 }
617 #elif defined(__WXMAC__)
618 OSStatus err;
619 ICInstance inst;
620 SInt32 startSel;
621 SInt32 endSel;
622
623 err = ICStart(&inst, 'STKA'); // put your app creator code here
624 if (err == noErr) {
625 #if !TARGET_CARBON
626 err = ICFindConfigFile(inst, 0, nil);
627 #endif
628 if (err == noErr)
629 {
630 ConstStr255Param hint = 0;
631 startSel = 0;
632 endSel = url.Length();
633 err = ICLaunchURL(inst, hint, url.fn_str(), endSel, &startSel, &endSel);
634 if (err != noErr)
635 wxLogDebug(wxT("ICLaunchURL error %d"), (int) err);
636 }
637 ICStop(inst);
638 return true;
639 }
640 else
641 {
642 wxLogDebug(wxT("ICStart error %d"), (int) err);
643 return false;
644 }
645 #elif wxUSE_MIMETYPE
646 // Non-windows way
647 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension (_T("html"));
648 if ( ft )
649 {
650 wxString mt;
651 ft->GetMimeType(&mt);
652
653 wxString cmd;
654 bool ok = ft->GetOpenCommand(&cmd, wxFileType::MessageParameters(url));
655 delete ft;
656
657 if ( !ok || cmd.empty() )
658 {
659 // fallback to checking for the BROWSER environment variable
660 cmd = wxGetenv(wxT("BROWSER"));
661 if ( !cmd.empty() )
662 cmd << _T(' ') << url;
663 }
664
665 if ( !cmd.empty() && wxExecute(cmd) )
666 return true;
667 }
668 else // no file type for html extension
669 {
670 wxLogError(_T("No default application configured for HTML files."));
671 }
672 #endif // !wxUSE_MIMETYPE && !__WXMSW__
673
674 wxLogSysError(_T("Failed to open URL \"%s\" in default browser."),
675 url.c_str());
676
677 return false;
678 }
679
680 // ----------------------------------------------------------------------------
681 // wxApp::Yield() wrappers for backwards compatibility
682 // ----------------------------------------------------------------------------
683
684 bool wxYield()
685 {
686 return wxTheApp && wxTheApp->Yield();
687 }
688
689 bool wxYieldIfNeeded()
690 {
691 return wxTheApp && wxTheApp->Yield(true);
692 }
693
694 #endif // wxUSE_BASE
695
696 // ============================================================================
697 // GUI-only functions from now on
698 // ============================================================================
699
700 #if wxUSE_GUI
701
702 // Id generation
703 static long wxCurrentId = 100;
704
705 long wxNewId()
706 {
707 // skip the part of IDs space that contains hard-coded values:
708 if (wxCurrentId == wxID_LOWEST)
709 wxCurrentId = wxID_HIGHEST + 1;
710
711 return wxCurrentId++;
712 }
713
714 long
715 wxGetCurrentId(void) { return wxCurrentId; }
716
717 void
718 wxRegisterId (long id)
719 {
720 if (id >= wxCurrentId)
721 wxCurrentId = id + 1;
722 }
723
724 #if wxUSE_MENUS
725
726 // ----------------------------------------------------------------------------
727 // Menu accelerators related functions
728 // ----------------------------------------------------------------------------
729
730 wxChar *wxStripMenuCodes(const wxChar *in, wxChar *out)
731 {
732 wxString s = wxMenuItem::GetLabelFromText(in);
733 if ( out )
734 {
735 // go smash their buffer if it's not big enough - I love char * params
736 memcpy(out, s.c_str(), s.length() * sizeof(wxChar));
737 }
738 else
739 {
740 // MYcopystring - for easier search...
741 out = new wxChar[s.length() + 1];
742 wxStrcpy(out, s.c_str());
743 }
744
745 return out;
746 }
747
748 wxString wxStripMenuCodes(const wxString& in)
749 {
750 wxString out;
751
752 size_t len = in.length();
753 out.reserve(len);
754
755 for ( size_t n = 0; n < len; n++ )
756 {
757 wxChar ch = in[n];
758 if ( ch == _T('&') )
759 {
760 // skip it, it is used to introduce the accel char (or to quote
761 // itself in which case it should still be skipped): note that it
762 // can't be the last character of the string
763 if ( ++n == len )
764 {
765 wxLogDebug(_T("Invalid menu string '%s'"), in.c_str());
766 }
767 else
768 {
769 // use the next char instead
770 ch = in[n];
771 }
772 }
773 else if ( ch == _T('\t') )
774 {
775 // everything after TAB is accel string, exit the loop
776 break;
777 }
778
779 out += ch;
780 }
781
782 return out;
783 }
784
785 #endif // wxUSE_MENUS
786
787 // ----------------------------------------------------------------------------
788 // Window search functions
789 // ----------------------------------------------------------------------------
790
791 /*
792 * If parent is non-NULL, look through children for a label or title
793 * matching the specified string. If NULL, look through all top-level windows.
794 *
795 */
796
797 wxWindow *
798 wxFindWindowByLabel (const wxString& title, wxWindow * parent)
799 {
800 return wxWindow::FindWindowByLabel( title, parent );
801 }
802
803
804 /*
805 * If parent is non-NULL, look through children for a name
806 * matching the specified string. If NULL, look through all top-level windows.
807 *
808 */
809
810 wxWindow *
811 wxFindWindowByName (const wxString& name, wxWindow * parent)
812 {
813 return wxWindow::FindWindowByName( name, parent );
814 }
815
816 // Returns menu item id or wxNOT_FOUND if none.
817 int
818 wxFindMenuItemId (wxFrame * frame, const wxString& menuString, const wxString& itemString)
819 {
820 #if wxUSE_MENUS
821 wxMenuBar *menuBar = frame->GetMenuBar ();
822 if ( menuBar )
823 return menuBar->FindMenuItem (menuString, itemString);
824 #endif // wxUSE_MENUS
825
826 return wxNOT_FOUND;
827 }
828
829 // Try to find the deepest child that contains 'pt'.
830 // We go backwards, to try to allow for controls that are spacially
831 // within other controls, but are still siblings (e.g. buttons within
832 // static boxes). Static boxes are likely to be created _before_ controls
833 // that sit inside them.
834 wxWindow* wxFindWindowAtPoint(wxWindow* win, const wxPoint& pt)
835 {
836 if (!win->IsShown())
837 return NULL;
838
839 // Hack for wxNotebook case: at least in wxGTK, all pages
840 // claim to be shown, so we must only deal with the selected one.
841 #if wxUSE_NOTEBOOK
842 if (win->IsKindOf(CLASSINFO(wxNotebook)))
843 {
844 wxNotebook* nb = (wxNotebook*) win;
845 int sel = nb->GetSelection();
846 if (sel >= 0)
847 {
848 wxWindow* child = nb->GetPage(sel);
849 wxWindow* foundWin = wxFindWindowAtPoint(child, pt);
850 if (foundWin)
851 return foundWin;
852 }
853 }
854 #endif
855
856 wxWindowList::compatibility_iterator node = win->GetChildren().GetLast();
857 while (node)
858 {
859 wxWindow* child = node->GetData();
860 wxWindow* foundWin = wxFindWindowAtPoint(child, pt);
861 if (foundWin)
862 return foundWin;
863 node = node->GetPrevious();
864 }
865
866 wxPoint pos = win->GetPosition();
867 wxSize sz = win->GetSize();
868 if (win->GetParent())
869 {
870 pos = win->GetParent()->ClientToScreen(pos);
871 }
872
873 wxRect rect(pos, sz);
874 if (rect.Inside(pt))
875 return win;
876 else
877 return NULL;
878 }
879
880 wxWindow* wxGenericFindWindowAtPoint(const wxPoint& pt)
881 {
882 // Go backwards through the list since windows
883 // on top are likely to have been appended most
884 // recently.
885 wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetLast();
886 while (node)
887 {
888 wxWindow* win = node->GetData();
889 wxWindow* found = wxFindWindowAtPoint(win, pt);
890 if (found)
891 return found;
892 node = node->GetPrevious();
893 }
894 return NULL;
895 }
896
897 // ----------------------------------------------------------------------------
898 // GUI helpers
899 // ----------------------------------------------------------------------------
900
901 /*
902 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
903 * since otherwise the generic code may be pulled in unnecessarily.
904 */
905
906 #if wxUSE_MSGDLG
907
908 int wxMessageBox(const wxString& message, const wxString& caption, long style,
909 wxWindow *parent, int WXUNUSED(x), int WXUNUSED(y) )
910 {
911 long decorated_style = style;
912
913 if ( ( style & ( wxICON_EXCLAMATION | wxICON_HAND | wxICON_INFORMATION | wxICON_QUESTION ) ) == 0 )
914 {
915 decorated_style |= ( style & wxYES ) ? wxICON_QUESTION : wxICON_INFORMATION ;
916 }
917
918 wxMessageDialog dialog(parent, message, caption, decorated_style);
919
920 int ans = dialog.ShowModal();
921 switch ( ans )
922 {
923 case wxID_OK:
924 return wxOK;
925 case wxID_YES:
926 return wxYES;
927 case wxID_NO:
928 return wxNO;
929 case wxID_CANCEL:
930 return wxCANCEL;
931 }
932
933 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
934
935 return wxCANCEL;
936 }
937
938 #endif // wxUSE_MSGDLG
939
940 #if wxUSE_TEXTDLG
941
942 wxString wxGetTextFromUser(const wxString& message, const wxString& caption,
943 const wxString& defaultValue, wxWindow *parent,
944 wxCoord x, wxCoord y, bool centre )
945 {
946 wxString str;
947 long style = wxTextEntryDialogStyle;
948
949 if (centre)
950 style |= wxCENTRE;
951 else
952 style &= ~wxCENTRE;
953
954 wxTextEntryDialog dialog(parent, message, caption, defaultValue, style, wxPoint(x, y));
955
956 if (dialog.ShowModal() == wxID_OK)
957 {
958 str = dialog.GetValue();
959 }
960
961 return str;
962 }
963
964 wxString wxGetPasswordFromUser(const wxString& message,
965 const wxString& caption,
966 const wxString& defaultValue,
967 wxWindow *parent,
968 wxCoord x, wxCoord y, bool centre )
969 {
970 wxString str;
971 long style = wxTextEntryDialogStyle;
972
973 if (centre)
974 style |= wxCENTRE;
975 else
976 style &= ~wxCENTRE;
977
978 wxPasswordEntryDialog dialog(parent, message, caption, defaultValue,
979 style, wxPoint(x, y));
980 if ( dialog.ShowModal() == wxID_OK )
981 {
982 str = dialog.GetValue();
983 }
984
985 return str;
986 }
987
988 #endif // wxUSE_TEXTDLG
989
990 #if wxUSE_COLOURDLG
991
992 wxColour wxGetColourFromUser(wxWindow *parent, const wxColour& colInit, const wxString& caption)
993 {
994 wxColourData data;
995 data.SetChooseFull(true);
996 if ( colInit.Ok() )
997 {
998 data.SetColour((wxColour &)colInit); // const_cast
999 }
1000
1001 wxColour colRet;
1002 wxColourDialog dialog(parent, &data);
1003 if (!caption.IsEmpty())
1004 dialog.SetTitle(caption);
1005 if ( dialog.ShowModal() == wxID_OK )
1006 {
1007 colRet = dialog.GetColourData().GetColour();
1008 }
1009 //else: leave it invalid
1010
1011 return colRet;
1012 }
1013
1014 #endif // wxUSE_COLOURDLG
1015
1016 #if wxUSE_FONTDLG
1017
1018 wxFont wxGetFontFromUser(wxWindow *parent, const wxFont& fontInit, const wxString& caption)
1019 {
1020 wxFontData data;
1021 if ( fontInit.Ok() )
1022 {
1023 data.SetInitialFont(fontInit);
1024 }
1025
1026 wxFont fontRet;
1027 wxFontDialog dialog(parent, data);
1028 if (!caption.IsEmpty())
1029 dialog.SetTitle(caption);
1030 if ( dialog.ShowModal() == wxID_OK )
1031 {
1032 fontRet = dialog.GetFontData().GetChosenFont();
1033 }
1034 //else: leave it invalid
1035
1036 return fontRet;
1037 }
1038
1039 #endif // wxUSE_FONTDLG
1040
1041 // ----------------------------------------------------------------------------
1042 // wxSafeYield and supporting functions
1043 // ----------------------------------------------------------------------------
1044
1045 void wxEnableTopLevelWindows(bool enable)
1046 {
1047 wxWindowList::compatibility_iterator node;
1048 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1049 node->GetData()->Enable(enable);
1050 }
1051
1052 wxWindowDisabler::wxWindowDisabler(wxWindow *winToSkip)
1053 {
1054 // remember the top level windows which were already disabled, so that we
1055 // don't reenable them later
1056 m_winDisabled = NULL;
1057
1058 wxWindowList::compatibility_iterator node;
1059 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1060 {
1061 wxWindow *winTop = node->GetData();
1062 if ( winTop == winToSkip )
1063 continue;
1064
1065 // we don't need to disable the hidden or already disabled windows
1066 if ( winTop->IsEnabled() && winTop->IsShown() )
1067 {
1068 winTop->Disable();
1069 }
1070 else
1071 {
1072 if ( !m_winDisabled )
1073 {
1074 m_winDisabled = new wxWindowList;
1075 }
1076
1077 m_winDisabled->Append(winTop);
1078 }
1079 }
1080 }
1081
1082 wxWindowDisabler::~wxWindowDisabler()
1083 {
1084 wxWindowList::compatibility_iterator node;
1085 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1086 {
1087 wxWindow *winTop = node->GetData();
1088 if ( !m_winDisabled || !m_winDisabled->Find(winTop) )
1089 {
1090 winTop->Enable();
1091 }
1092 //else: had been already disabled, don't reenable
1093 }
1094
1095 delete m_winDisabled;
1096 }
1097
1098 // Yield to other apps/messages and disable user input to all windows except
1099 // the given one
1100 bool wxSafeYield(wxWindow *win, bool onlyIfNeeded)
1101 {
1102 wxWindowDisabler wd(win);
1103
1104 bool rc;
1105 if (onlyIfNeeded)
1106 rc = wxYieldIfNeeded();
1107 else
1108 rc = wxYield();
1109
1110 return rc;
1111 }
1112
1113 // Don't synthesize KeyUp events holding down a key and producing KeyDown
1114 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
1115 // in utilsgtk.cpp.
1116 #ifndef __WXGTK__
1117 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag) )
1118 {
1119 return true; // detectable auto-repeat is the only mode MSW supports
1120 }
1121 #endif // !wxGTK
1122
1123 #endif // wxUSE_GUI