1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Miscellaneous utility functions and classes
4 // Author: Julian Smart
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
29 #include "wx/string.h"
35 #include "wx/window.h"
38 #include "wx/msgdlg.h"
39 #include "wx/textdlg.h"
40 #include "wx/textctrl.h" // for wxTE_PASSWORD
42 #include "wx/menuitem.h"
48 #include "wx/apptrait.h"
50 #include "wx/process.h"
51 #include "wx/txtstrm.h"
53 #include "wx/mimetype.h"
54 #include "wx/config.h"
56 #if defined(__WXWINCE__) && wxUSE_DATETIME
57 #include "wx/datetime.h"
65 #if !defined(__WATCOMC__)
66 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
72 #include "wx/colordlg.h"
73 #include "wx/fontdlg.h"
74 #include "wx/notebook.h"
76 #include "wx/statusbr.h"
82 #include "wx/msw/wince/time.h"
85 #if !defined(__MWERKS__) && !defined(__WXWINCE__)
86 #include <sys/types.h>
90 #if defined(__WXMSW__)
91 #include "wx/msw/private.h"
96 // ----------------------------------------------------------------------------
98 // ----------------------------------------------------------------------------
100 #if WXWIN_COMPATIBILITY_2_2
101 const wxChar
*wxInternalErrorStr
= wxT("wxWidgets Internal Error");
102 const wxChar
*wxFatalErrorStr
= wxT("wxWidgets Fatal Error");
103 #endif // WXWIN_COMPATIBILITY_2_2
105 // ============================================================================
107 // ============================================================================
109 #if WXWIN_COMPATIBILITY_2_4
112 copystring (const wxChar
*s
)
114 if (s
== NULL
) s
= wxEmptyString
;
115 size_t len
= wxStrlen (s
) + 1;
117 wxChar
*news
= new wxChar
[len
];
118 memcpy (news
, s
, len
* sizeof(wxChar
)); // Should be the fastest
123 #endif // WXWIN_COMPATIBILITY_2_4
125 // ----------------------------------------------------------------------------
126 // String <-> Number conversions (deprecated)
127 // ----------------------------------------------------------------------------
129 #if WXWIN_COMPATIBILITY_2_4
131 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxFloatToStringStr
= wxT("%.2f");
132 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxDoubleToStringStr
= wxT("%.2f");
135 StringToFloat (const wxChar
*s
, float *number
)
137 if (s
&& *s
&& number
)
138 *number
= (float) wxStrtod (s
, (wxChar
**) NULL
);
142 StringToDouble (const wxChar
*s
, double *number
)
144 if (s
&& *s
&& number
)
145 *number
= wxStrtod (s
, (wxChar
**) NULL
);
149 FloatToString (float number
, const wxChar
*fmt
)
151 static wxChar buf
[256];
153 wxSprintf (buf
, fmt
, number
);
158 DoubleToString (double number
, const wxChar
*fmt
)
160 static wxChar buf
[256];
162 wxSprintf (buf
, fmt
, number
);
167 StringToInt (const wxChar
*s
, int *number
)
169 if (s
&& *s
&& number
)
170 *number
= (int) wxStrtol (s
, (wxChar
**) NULL
, 10);
174 StringToLong (const wxChar
*s
, long *number
)
176 if (s
&& *s
&& number
)
177 *number
= wxStrtol (s
, (wxChar
**) NULL
, 10);
181 IntToString (int number
)
183 static wxChar buf
[20];
185 wxSprintf (buf
, wxT("%d"), number
);
190 LongToString (long number
)
192 static wxChar buf
[20];
194 wxSprintf (buf
, wxT("%ld"), number
);
198 #endif // WXWIN_COMPATIBILITY_2_4
200 // Array used in DecToHex conversion routine.
201 static wxChar hexArray
[] = wxT("0123456789ABCDEF");
203 // Convert 2-digit hex number to decimal
204 int wxHexToDec(const wxString
& buf
)
206 int firstDigit
, secondDigit
;
208 if (buf
.GetChar(0) >= wxT('A'))
209 firstDigit
= buf
.GetChar(0) - wxT('A') + 10;
211 firstDigit
= buf
.GetChar(0) - wxT('0');
213 if (buf
.GetChar(1) >= wxT('A'))
214 secondDigit
= buf
.GetChar(1) - wxT('A') + 10;
216 secondDigit
= buf
.GetChar(1) - wxT('0');
218 return (firstDigit
& 0xF) * 16 + (secondDigit
& 0xF );
221 // Convert decimal integer to 2-character hex string
222 void wxDecToHex(int dec
, wxChar
*buf
)
224 int firstDigit
= (int)(dec
/16.0);
225 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
226 buf
[0] = hexArray
[firstDigit
];
227 buf
[1] = hexArray
[secondDigit
];
231 // Convert decimal integer to 2-character hex string
232 wxString
wxDecToHex(int dec
)
235 wxDecToHex(dec
, buf
);
236 return wxString(buf
);
239 // ----------------------------------------------------------------------------
241 // ----------------------------------------------------------------------------
243 // Return the current date/time
248 wxDateTime now
= wxDateTime::Now();
251 return wxEmptyString
;
254 time_t now
= time((time_t *) NULL
);
255 char *date
= ctime(&now
);
257 return wxString::FromAscii(date
);
261 void wxUsleep(unsigned long milliseconds
)
263 wxMilliSleep(milliseconds
);
266 const wxChar
*wxGetInstallPrefix()
270 if ( wxGetEnv(wxT("WXPREFIX"), &prefix
) )
271 return prefix
.c_str();
273 #ifdef wxINSTALL_PREFIX
274 return wxT(wxINSTALL_PREFIX
);
276 return wxEmptyString
;
280 wxString
wxGetDataDir()
282 wxString dir
= wxGetInstallPrefix();
283 dir
<< wxFILE_SEP_PATH
<< wxT("share") << wxFILE_SEP_PATH
<< wxT("wx");
287 int wxGetOsVersion(int *verMaj
, int *verMin
)
289 // we want this function to work even if there is no wxApp
290 wxConsoleAppTraits traitsConsole
;
291 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
293 traits
= &traitsConsole
;
295 wxToolkitInfo
& info
= traits
->GetToolkitInfo();
297 *verMaj
= info
.versionMajor
;
299 *verMin
= info
.versionMinor
;
303 // ----------------------------------------------------------------------------
304 // network and user id functions
305 // ----------------------------------------------------------------------------
307 // Get Full RFC822 style email address
308 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
310 wxString email
= wxGetEmailAddress();
314 wxStrncpy(address
, email
, maxSize
- 1);
315 address
[maxSize
- 1] = wxT('\0');
320 wxString
wxGetEmailAddress()
324 wxString host
= wxGetFullHostName();
327 wxString user
= wxGetUserId();
330 email
<< user
<< wxT('@') << host
;
337 wxString
wxGetUserId()
339 static const int maxLoginLen
= 256; // FIXME arbitrary number
342 bool ok
= wxGetUserId(wxStringBuffer(buf
, maxLoginLen
), maxLoginLen
);
350 wxString
wxGetUserName()
352 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
355 bool ok
= wxGetUserName(wxStringBuffer(buf
, maxUserNameLen
), maxUserNameLen
);
363 wxString
wxGetHostName()
365 static const size_t hostnameSize
= 257;
368 bool ok
= wxGetHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
376 wxString
wxGetFullHostName()
378 static const size_t hostnameSize
= 257;
381 bool ok
= wxGetFullHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
389 wxString
wxGetHomeDir()
399 wxString
wxGetCurrentDir()
406 ok
= getcwd(dir
.GetWriteBuf(len
+ 1), len
) != NULL
;
411 if ( errno
!= ERANGE
)
413 wxLogSysError(_T("Failed to get current directory"));
415 return wxEmptyString
;
419 // buffer was too small, retry with a larger one
431 // ----------------------------------------------------------------------------
433 // ----------------------------------------------------------------------------
435 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
437 // returns true if ok, false if error
439 static bool ReadAll(wxInputStream
*is
, wxArrayString
& output
)
441 wxCHECK_MSG( is
, false, _T("NULL stream in wxExecute()?") );
443 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
446 wxTextInputStream
tis(*is
);
451 wxString line
= tis
.ReadLine();
467 #endif // wxUSE_STREAMS
469 // this is a private function because it hasn't a clean interface: the first
470 // array is passed by reference, the second by pointer - instead we have 2
471 // public versions of wxExecute() below
472 static long wxDoExecuteWithCapture(const wxString
& command
,
473 wxArrayString
& output
,
474 wxArrayString
* error
,
477 // create a wxProcess which will capture the output
478 wxProcess
*process
= new wxProcess
;
481 long rc
= wxExecute(command
, wxEXEC_SYNC
| flags
, process
);
486 if ( !ReadAll(process
->GetInputStream(), output
) )
491 if ( !ReadAll(process
->GetErrorStream(), *error
) )
499 #endif // wxUSE_STREAMS/!wxUSE_STREAMS
506 long wxExecute(const wxString
& command
, wxArrayString
& output
, int flags
)
508 return wxDoExecuteWithCapture(command
, output
, NULL
, flags
);
511 long wxExecute(const wxString
& command
,
512 wxArrayString
& output
,
513 wxArrayString
& error
,
516 return wxDoExecuteWithCapture(command
, output
, &error
, flags
);
519 // ----------------------------------------------------------------------------
520 // Launch default browser
521 // ----------------------------------------------------------------------------
523 bool wxLaunchDefaultBrowser(const wxString
& urlOrig
, int flags
)
527 // set the scheme of url to http if it does not have one
528 wxString
url(urlOrig
);
529 if ( !wxURI(url
).HasScheme() )
530 url
.Prepend(wxT("http://"));
532 #if defined(__WXMSW__)
533 if ( flags
& wxBROWSER_NEW_WINDOW
)
535 // ShellExecuteEx() opens the URL in an existing window by default so
536 // we can't use it if we need a new window
537 wxRegKey
key(wxRegKey::HKCR
, url
.BeforeFirst(':') + _T("\\shell\\open"));
540 wxRegKey
keyDDE(key
, wxT("DDEExec"));
541 if ( keyDDE
.Exists() )
543 const wxString ddeTopic
= wxRegKey(keyDDE
, wxT("topic"));
545 // we only know the syntax of WWW_OpenURL DDE request for IE,
546 // optimistically assume that all other browsers are compatible
549 bool ok
= ddeTopic
== wxT("WWW_OpenURL");
552 ddeCmd
= keyDDE
.QueryDefaultValue();
553 ok
= !ddeCmd
.empty();
558 // for WWW_OpenURL, the index of the window to open the URL
559 // in is -1 (meaning "current") by default, replace it with
560 // 0 which means "new" (see KB article 160957)
561 ok
= ddeCmd
.Replace(wxT("-1"), wxT("0"),
562 false /* only first occurence */) == 1;
567 // and also replace the parameters: the topic should
568 // contain a placeholder for the URL
569 ok
= ddeCmd
.Replace(wxT("%1"), url
, false) == 1;
574 // try to send it the DDE request now but ignore the errors
577 const wxString ddeServer
= wxRegKey(keyDDE
, wxT("application"));
578 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCmd
) )
581 // this is not necessarily an error: maybe browser is
582 // simply not running, but no matter, in any case we're
583 // going to launch it using ShellExecuteEx() below now and
584 // we shouldn't try to open a new window if we open a new
591 WinStruct
<SHELLEXECUTEINFO
> sei
;
592 sei
.lpFile
= url
.c_str();
593 sei
.lpVerb
= _T("open");
594 sei
.nShow
= SW_SHOWNORMAL
;
596 ::ShellExecuteEx(&sei
);
598 const int nResult
= (int) sei
.hInstApp
;
600 // Firefox returns file not found for some reason, so make an exception
602 if ( nResult
> 32 || nResult
== SE_ERR_FNF
)
605 // Log something if SE_ERR_FNF happens
606 if ( nResult
== SE_ERR_FNF
)
607 wxLogDebug(wxT("SE_ERR_FNF from ShellExecute -- maybe FireFox?"));
608 #endif // __WXDEBUG__
613 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension (_T("html"));
617 ft
->GetMimeType(&mt
);
620 bool ok
= ft
->GetOpenCommand(&cmd
, wxFileType::MessageParameters(url
));
623 if ( !ok
|| cmd
.empty() )
625 // fallback to checking for the BROWSER environment variable
626 cmd
= wxGetenv(wxT("BROWSER"));
628 cmd
<< _T(' ') << url
;
631 if ( !cmd
.empty() && wxExecute(cmd
) )
634 else // no file type for html extension
636 wxLogError(_T("No default application configured for HTML files."));
638 #endif // !wxUSE_MIMETYPE && !__WXMSW__
640 wxLogSysError(_T("Failed to open URL \"%s\" in default browser."),
646 // ----------------------------------------------------------------------------
647 // wxApp::Yield() wrappers for backwards compatibility
648 // ----------------------------------------------------------------------------
652 return wxTheApp
&& wxTheApp
->Yield();
655 bool wxYieldIfNeeded()
657 return wxTheApp
&& wxTheApp
->Yield(true);
662 // ============================================================================
663 // GUI-only functions from now on
664 // ============================================================================
669 static long wxCurrentId
= 100;
673 // skip the part of IDs space that contains hard-coded values:
674 if (wxCurrentId
== wxID_LOWEST
)
675 wxCurrentId
= wxID_HIGHEST
+ 1;
677 return wxCurrentId
++;
681 wxGetCurrentId(void) { return wxCurrentId
; }
684 wxRegisterId (long id
)
686 if (id
>= wxCurrentId
)
687 wxCurrentId
= id
+ 1;
692 // ----------------------------------------------------------------------------
693 // Menu accelerators related functions
694 // ----------------------------------------------------------------------------
696 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
698 wxString s
= wxMenuItem::GetLabelFromText(in
);
701 // go smash their buffer if it's not big enough - I love char * params
702 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
706 // MYcopystring - for easier search...
707 out
= new wxChar
[s
.length() + 1];
708 wxStrcpy(out
, s
.c_str());
714 wxString
wxStripMenuCodes(const wxString
& in
)
718 size_t len
= in
.length();
721 for ( size_t n
= 0; n
< len
; n
++ )
726 // skip it, it is used to introduce the accel char (or to quote
727 // itself in which case it should still be skipped): note that it
728 // can't be the last character of the string
731 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
735 // use the next char instead
739 else if ( ch
== _T('\t') )
741 // everything after TAB is accel string, exit the loop
751 #endif // wxUSE_MENUS
753 // ----------------------------------------------------------------------------
754 // Window search functions
755 // ----------------------------------------------------------------------------
758 * If parent is non-NULL, look through children for a label or title
759 * matching the specified string. If NULL, look through all top-level windows.
764 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
766 return wxWindow::FindWindowByLabel( title
, parent
);
771 * If parent is non-NULL, look through children for a name
772 * matching the specified string. If NULL, look through all top-level windows.
777 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
779 return wxWindow::FindWindowByName( name
, parent
);
782 // Returns menu item id or wxNOT_FOUND if none.
784 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
787 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
789 return menuBar
->FindMenuItem (menuString
, itemString
);
790 #endif // wxUSE_MENUS
795 // Try to find the deepest child that contains 'pt'.
796 // We go backwards, to try to allow for controls that are spacially
797 // within other controls, but are still siblings (e.g. buttons within
798 // static boxes). Static boxes are likely to be created _before_ controls
799 // that sit inside them.
800 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
805 // Hack for wxNotebook case: at least in wxGTK, all pages
806 // claim to be shown, so we must only deal with the selected one.
808 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
810 wxNotebook
* nb
= (wxNotebook
*) win
;
811 int sel
= nb
->GetSelection();
814 wxWindow
* child
= nb
->GetPage(sel
);
815 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
822 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetLast();
825 wxWindow
* child
= node
->GetData();
826 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
829 node
= node
->GetPrevious();
832 wxPoint pos
= win
->GetPosition();
833 wxSize sz
= win
->GetSize();
834 if (win
->GetParent())
836 pos
= win
->GetParent()->ClientToScreen(pos
);
839 wxRect
rect(pos
, sz
);
846 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
848 // Go backwards through the list since windows
849 // on top are likely to have been appended most
851 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetLast();
854 wxWindow
* win
= node
->GetData();
855 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
858 node
= node
->GetPrevious();
863 // ----------------------------------------------------------------------------
865 // ----------------------------------------------------------------------------
868 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
869 * since otherwise the generic code may be pulled in unnecessarily.
874 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
875 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
877 long decorated_style
= style
;
879 if ( ( style
& ( wxICON_EXCLAMATION
| wxICON_HAND
| wxICON_INFORMATION
| wxICON_QUESTION
) ) == 0 )
881 decorated_style
|= ( style
& wxYES
) ? wxICON_QUESTION
: wxICON_INFORMATION
;
884 wxMessageDialog
dialog(parent
, message
, caption
, decorated_style
);
886 int ans
= dialog
.ShowModal();
899 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
904 #endif // wxUSE_MSGDLG
908 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
909 const wxString
& defaultValue
, wxWindow
*parent
,
910 wxCoord x
, wxCoord y
, bool centre
)
913 long style
= wxTextEntryDialogStyle
;
920 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, style
, wxPoint(x
, y
));
922 if (dialog
.ShowModal() == wxID_OK
)
924 str
= dialog
.GetValue();
930 wxString
wxGetPasswordFromUser(const wxString
& message
,
931 const wxString
& caption
,
932 const wxString
& defaultValue
,
934 wxCoord x
, wxCoord y
, bool centre
)
937 long style
= wxTextEntryDialogStyle
;
944 wxPasswordEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
945 style
, wxPoint(x
, y
));
946 if ( dialog
.ShowModal() == wxID_OK
)
948 str
= dialog
.GetValue();
954 #endif // wxUSE_TEXTDLG
958 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
961 data
.SetChooseFull(true);
964 data
.SetColour((wxColour
&)colInit
); // const_cast
968 wxColourDialog
dialog(parent
, &data
);
969 if ( dialog
.ShowModal() == wxID_OK
)
971 colRet
= dialog
.GetColourData().GetColour();
973 //else: leave it invalid
978 #endif // wxUSE_COLOURDLG
982 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
987 data
.SetInitialFont(fontInit
);
991 wxFontDialog
dialog(parent
, data
);
992 if ( dialog
.ShowModal() == wxID_OK
)
994 fontRet
= dialog
.GetFontData().GetChosenFont();
996 //else: leave it invalid
1001 #endif // wxUSE_FONTDLG
1003 // ----------------------------------------------------------------------------
1004 // wxSafeYield and supporting functions
1005 // ----------------------------------------------------------------------------
1007 void wxEnableTopLevelWindows(bool enable
)
1009 wxWindowList::compatibility_iterator node
;
1010 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1011 node
->GetData()->Enable(enable
);
1014 wxWindowDisabler::wxWindowDisabler(wxWindow
*winToSkip
)
1016 // remember the top level windows which were already disabled, so that we
1017 // don't reenable them later
1018 m_winDisabled
= NULL
;
1020 wxWindowList::compatibility_iterator node
;
1021 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1023 wxWindow
*winTop
= node
->GetData();
1024 if ( winTop
== winToSkip
)
1027 // we don't need to disable the hidden or already disabled windows
1028 if ( winTop
->IsEnabled() && winTop
->IsShown() )
1034 if ( !m_winDisabled
)
1036 m_winDisabled
= new wxWindowList
;
1039 m_winDisabled
->Append(winTop
);
1044 wxWindowDisabler::~wxWindowDisabler()
1046 wxWindowList::compatibility_iterator node
;
1047 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1049 wxWindow
*winTop
= node
->GetData();
1050 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
1054 //else: had been already disabled, don't reenable
1057 delete m_winDisabled
;
1060 // Yield to other apps/messages and disable user input to all windows except
1062 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
1064 wxWindowDisabler
wd(win
);
1068 rc
= wxYieldIfNeeded();
1075 // Don't synthesize KeyUp events holding down a key and producing KeyDown
1076 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
1079 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
1081 return true; // detectable auto-repeat is the only mode MSW supports