1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/utilscmn.cpp
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 !wxONLY_WATCOM_EARLIER_THAN(1,4)
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"
86 #include "wx/mac/private.h"
88 #include "InternetConfig.h"
92 #if !defined(__MWERKS__) && !defined(__WXWINCE__)
93 #include <sys/types.h>
97 #if defined(__WXMSW__)
98 #include "wx/msw/private.h"
99 #include "wx/msw/registry.h"
104 // ----------------------------------------------------------------------------
106 // ----------------------------------------------------------------------------
108 // ============================================================================
110 // ============================================================================
112 #if WXWIN_COMPATIBILITY_2_4
115 copystring (const wxChar
*s
)
117 if (s
== NULL
) s
= wxEmptyString
;
118 size_t len
= wxStrlen (s
) + 1;
120 wxChar
*news
= new wxChar
[len
];
121 memcpy (news
, s
, len
* sizeof(wxChar
)); // Should be the fastest
126 #endif // WXWIN_COMPATIBILITY_2_4
128 // ----------------------------------------------------------------------------
129 // String <-> Number conversions (deprecated)
130 // ----------------------------------------------------------------------------
132 #if WXWIN_COMPATIBILITY_2_4
134 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxFloatToStringStr
= wxT("%.2f");
135 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxDoubleToStringStr
= wxT("%.2f");
138 StringToFloat (const wxChar
*s
, float *number
)
140 if (s
&& *s
&& number
)
141 *number
= (float) wxStrtod (s
, (wxChar
**) NULL
);
145 StringToDouble (const wxChar
*s
, double *number
)
147 if (s
&& *s
&& number
)
148 *number
= wxStrtod (s
, (wxChar
**) NULL
);
152 FloatToString (float number
, const wxChar
*fmt
)
154 static wxChar buf
[256];
156 wxSprintf (buf
, fmt
, number
);
161 DoubleToString (double number
, const wxChar
*fmt
)
163 static wxChar buf
[256];
165 wxSprintf (buf
, fmt
, number
);
170 StringToInt (const wxChar
*s
, int *number
)
172 if (s
&& *s
&& number
)
173 *number
= (int) wxStrtol (s
, (wxChar
**) NULL
, 10);
177 StringToLong (const wxChar
*s
, long *number
)
179 if (s
&& *s
&& number
)
180 *number
= wxStrtol (s
, (wxChar
**) NULL
, 10);
184 IntToString (int number
)
186 static wxChar buf
[20];
188 wxSprintf (buf
, wxT("%d"), number
);
193 LongToString (long number
)
195 static wxChar buf
[20];
197 wxSprintf (buf
, wxT("%ld"), number
);
201 #endif // WXWIN_COMPATIBILITY_2_4
203 // Array used in DecToHex conversion routine.
204 static wxChar hexArray
[] = wxT("0123456789ABCDEF");
206 // Convert 2-digit hex number to decimal
207 int wxHexToDec(const wxString
& buf
)
209 int firstDigit
, secondDigit
;
211 if (buf
.GetChar(0) >= wxT('A'))
212 firstDigit
= buf
.GetChar(0) - wxT('A') + 10;
214 firstDigit
= buf
.GetChar(0) - wxT('0');
216 if (buf
.GetChar(1) >= wxT('A'))
217 secondDigit
= buf
.GetChar(1) - wxT('A') + 10;
219 secondDigit
= buf
.GetChar(1) - wxT('0');
221 return (firstDigit
& 0xF) * 16 + (secondDigit
& 0xF );
224 // Convert decimal integer to 2-character hex string
225 void wxDecToHex(int dec
, wxChar
*buf
)
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
];
234 // Convert decimal integer to 2-character hex string
235 wxString
wxDecToHex(int dec
)
238 wxDecToHex(dec
, buf
);
239 return wxString(buf
);
242 // ----------------------------------------------------------------------------
244 // ----------------------------------------------------------------------------
246 // Return the current date/time
251 wxDateTime now
= wxDateTime::Now();
254 return wxEmptyString
;
257 time_t now
= time((time_t *) NULL
);
258 char *date
= ctime(&now
);
260 return wxString::FromAscii(date
);
264 void wxUsleep(unsigned long milliseconds
)
266 wxMilliSleep(milliseconds
);
269 const wxChar
*wxGetInstallPrefix()
273 if ( wxGetEnv(wxT("WXPREFIX"), &prefix
) )
274 return prefix
.c_str();
276 #ifdef wxINSTALL_PREFIX
277 return wxT(wxINSTALL_PREFIX
);
279 return wxEmptyString
;
283 wxString
wxGetDataDir()
285 wxString dir
= wxGetInstallPrefix();
286 dir
<< wxFILE_SEP_PATH
<< wxT("share") << wxFILE_SEP_PATH
<< wxT("wx");
290 int wxGetOsVersion(int *verMaj
, int *verMin
)
292 // we want this function to work even if there is no wxApp
293 wxConsoleAppTraits traitsConsole
;
294 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
296 traits
= &traitsConsole
;
298 wxToolkitInfo
& info
= traits
->GetToolkitInfo();
300 *verMaj
= info
.versionMajor
;
302 *verMin
= info
.versionMinor
;
306 // ----------------------------------------------------------------------------
307 // network and user id functions
308 // ----------------------------------------------------------------------------
310 // Get Full RFC822 style email address
311 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
313 wxString email
= wxGetEmailAddress();
317 wxStrncpy(address
, email
, maxSize
- 1);
318 address
[maxSize
- 1] = wxT('\0');
323 wxString
wxGetEmailAddress()
327 wxString host
= wxGetFullHostName();
330 wxString user
= wxGetUserId();
333 email
<< user
<< wxT('@') << host
;
340 wxString
wxGetUserId()
342 static const int maxLoginLen
= 256; // FIXME arbitrary number
345 bool ok
= wxGetUserId(wxStringBuffer(buf
, maxLoginLen
), maxLoginLen
);
353 wxString
wxGetUserName()
355 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
358 bool ok
= wxGetUserName(wxStringBuffer(buf
, maxUserNameLen
), maxUserNameLen
);
366 wxString
wxGetHostName()
368 static const size_t hostnameSize
= 257;
371 bool ok
= wxGetHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
379 wxString
wxGetFullHostName()
381 static const size_t hostnameSize
= 257;
384 bool ok
= wxGetFullHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
392 wxString
wxGetHomeDir()
402 wxString
wxGetCurrentDir()
409 ok
= getcwd(dir
.GetWriteBuf(len
+ 1), len
) != NULL
;
414 if ( errno
!= ERANGE
)
416 wxLogSysError(_T("Failed to get current directory"));
418 return wxEmptyString
;
422 // buffer was too small, retry with a larger one
434 // ----------------------------------------------------------------------------
436 // ----------------------------------------------------------------------------
438 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
440 // returns true if ok, false if error
442 static bool ReadAll(wxInputStream
*is
, wxArrayString
& output
)
444 wxCHECK_MSG( is
, false, _T("NULL stream in wxExecute()?") );
446 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
449 wxTextInputStream
tis(*is
);
454 wxString line
= tis
.ReadLine();
470 #endif // wxUSE_STREAMS
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
,
480 // create a wxProcess which will capture the output
481 wxProcess
*process
= new wxProcess
;
484 long rc
= wxExecute(command
, wxEXEC_SYNC
| flags
, process
);
489 if ( !ReadAll(process
->GetInputStream(), output
) )
494 if ( !ReadAll(process
->GetErrorStream(), *error
) )
502 #endif // wxUSE_STREAMS/!wxUSE_STREAMS
509 long wxExecute(const wxString
& command
, wxArrayString
& output
, int flags
)
511 return wxDoExecuteWithCapture(command
, output
, NULL
, flags
);
514 long wxExecute(const wxString
& command
,
515 wxArrayString
& output
,
516 wxArrayString
& error
,
519 return wxDoExecuteWithCapture(command
, output
, &error
, flags
);
522 // ----------------------------------------------------------------------------
523 // Launch default browser
524 // ----------------------------------------------------------------------------
526 bool wxLaunchDefaultBrowser(const wxString
& urlOrig
, int flags
)
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://"));
535 #if defined(__WXMSW__)
538 if ( flags
& wxBROWSER_NEW_WINDOW
)
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"));
545 wxRegKey
keyDDE(key
, wxT("DDEExec"));
546 if ( keyDDE
.Exists() )
548 const wxString ddeTopic
= wxRegKey(keyDDE
, wxT("topic"));
550 // we only know the syntax of WWW_OpenURL DDE request for IE,
551 // optimistically assume that all other browsers are compatible
554 bool ok
= ddeTopic
== wxT("WWW_OpenURL");
557 ddeCmd
= keyDDE
.QueryDefaultValue();
558 ok
= !ddeCmd
.empty();
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;
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;
579 // try to send it the DDE request now but ignore the errors
582 const wxString ddeServer
= wxRegKey(keyDDE
, wxT("application"));
583 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCmd
) )
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
597 WinStruct
<SHELLEXECUTEINFO
> sei
;
598 sei
.lpFile
= url
.c_str();
599 sei
.lpVerb
= _T("open");
600 sei
.nShow
= SW_SHOWNORMAL
;
602 ::ShellExecuteEx(&sei
);
604 const int nResult
= (int) sei
.hInstApp
;
606 // Firefox returns file not found for some reason, so make an exception
608 if ( nResult
> 32 || nResult
== SE_ERR_FNF
)
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__
617 #elif defined(__WXMAC__)
623 err
= ICStart(&inst
, 'STKA'); // put your app creator code here
627 err
= ICFindConfigFile(inst
, 0, NULL
);
631 ConstStr255Param hint
= 0;
633 endSel
= url
.Length();
634 err
= ICLaunchURL(inst
, hint
, url
.fn_str(), endSel
, &startSel
, &endSel
);
636 wxLogDebug(wxT("ICLaunchURL error %d"), (int) err
);
643 wxLogDebug(wxT("ICStart error %d"), (int) err
);
651 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(_T("html"));
655 ft
->GetMimeType(&mt
);
657 ok
= ft
->GetOpenCommand(&cmd
, wxFileType::MessageParameters(url
));
661 if ( !ok
|| cmd
.empty() )
663 // fallback to checking for the BROWSER environment variable
664 cmd
= wxGetenv(wxT("BROWSER"));
666 cmd
<< _T(' ') << url
;
669 ok
= ( !cmd
.empty() && wxExecute(cmd
) );
673 // no file type for HTML extension
674 wxLogError(_T("No default application configured for HTML files."));
676 #endif // !wxUSE_MIMETYPE && !__WXMSW__
678 wxLogSysError(_T("Failed to open URL \"%s\" in default browser."),
684 // ----------------------------------------------------------------------------
685 // wxApp::Yield() wrappers for backwards compatibility
686 // ----------------------------------------------------------------------------
690 return wxTheApp
&& wxTheApp
->Yield();
693 bool wxYieldIfNeeded()
695 return wxTheApp
&& wxTheApp
->Yield(true);
700 // ============================================================================
701 // GUI-only functions from now on
702 // ============================================================================
707 static long wxCurrentId
= 100;
711 // skip the part of IDs space that contains hard-coded values:
712 if (wxCurrentId
== wxID_LOWEST
)
713 wxCurrentId
= wxID_HIGHEST
+ 1;
715 return wxCurrentId
++;
719 wxGetCurrentId(void) { return wxCurrentId
; }
722 wxRegisterId (long id
)
724 if (id
>= wxCurrentId
)
725 wxCurrentId
= id
+ 1;
730 // ----------------------------------------------------------------------------
731 // Menu accelerators related functions
732 // ----------------------------------------------------------------------------
734 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
736 wxString s
= wxMenuItem::GetLabelFromText(in
);
739 // go smash their buffer if it's not big enough - I love char * params
740 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
744 // MYcopystring - for easier search...
745 out
= new wxChar
[s
.length() + 1];
746 wxStrcpy(out
, s
.c_str());
752 wxString
wxStripMenuCodes(const wxString
& in
)
756 size_t len
= in
.length();
759 for ( size_t n
= 0; n
< len
; n
++ )
764 // skip it, it is used to introduce the accel char (or to quote
765 // itself in which case it should still be skipped): note that it
766 // can't be the last character of the string
769 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
773 // use the next char instead
777 else if ( ch
== _T('\t') )
779 // everything after TAB is accel string, exit the loop
789 #endif // wxUSE_MENUS
791 // ----------------------------------------------------------------------------
792 // Window search functions
793 // ----------------------------------------------------------------------------
796 * If parent is non-NULL, look through children for a label or title
797 * matching the specified string. If NULL, look through all top-level windows.
802 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
804 return wxWindow::FindWindowByLabel( title
, parent
);
809 * If parent is non-NULL, look through children for a name
810 * matching the specified string. If NULL, look through all top-level windows.
815 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
817 return wxWindow::FindWindowByName( name
, parent
);
820 // Returns menu item id or wxNOT_FOUND if none.
822 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
825 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
827 return menuBar
->FindMenuItem (menuString
, itemString
);
828 #endif // wxUSE_MENUS
833 // Try to find the deepest child that contains 'pt'.
834 // We go backwards, to try to allow for controls that are spacially
835 // within other controls, but are still siblings (e.g. buttons within
836 // static boxes). Static boxes are likely to be created _before_ controls
837 // that sit inside them.
838 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
843 // Hack for wxNotebook case: at least in wxGTK, all pages
844 // claim to be shown, so we must only deal with the selected one.
846 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
848 wxNotebook
* nb
= (wxNotebook
*) win
;
849 int sel
= nb
->GetSelection();
852 wxWindow
* child
= nb
->GetPage(sel
);
853 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
860 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetLast();
863 wxWindow
* child
= node
->GetData();
864 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
867 node
= node
->GetPrevious();
870 wxPoint pos
= win
->GetPosition();
871 wxSize sz
= win
->GetSize();
872 if (win
->GetParent())
874 pos
= win
->GetParent()->ClientToScreen(pos
);
877 wxRect
rect(pos
, sz
);
884 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
886 // Go backwards through the list since windows
887 // on top are likely to have been appended most
889 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetLast();
892 wxWindow
* win
= node
->GetData();
893 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
896 node
= node
->GetPrevious();
901 // ----------------------------------------------------------------------------
903 // ----------------------------------------------------------------------------
906 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
907 * since otherwise the generic code may be pulled in unnecessarily.
912 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
913 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
915 long decorated_style
= style
;
917 if ( ( style
& ( wxICON_EXCLAMATION
| wxICON_HAND
| wxICON_INFORMATION
| wxICON_QUESTION
) ) == 0 )
919 decorated_style
|= ( style
& wxYES
) ? wxICON_QUESTION
: wxICON_INFORMATION
;
922 wxMessageDialog
dialog(parent
, message
, caption
, decorated_style
);
924 int ans
= dialog
.ShowModal();
937 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
942 #endif // wxUSE_MSGDLG
946 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
947 const wxString
& defaultValue
, wxWindow
*parent
,
948 wxCoord x
, wxCoord y
, bool centre
)
951 long style
= wxTextEntryDialogStyle
;
958 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, style
, wxPoint(x
, y
));
960 if (dialog
.ShowModal() == wxID_OK
)
962 str
= dialog
.GetValue();
968 wxString
wxGetPasswordFromUser(const wxString
& message
,
969 const wxString
& caption
,
970 const wxString
& defaultValue
,
972 wxCoord x
, wxCoord y
, bool centre
)
975 long style
= wxTextEntryDialogStyle
;
982 wxPasswordEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
983 style
, wxPoint(x
, y
));
984 if ( dialog
.ShowModal() == wxID_OK
)
986 str
= dialog
.GetValue();
992 #endif // wxUSE_TEXTDLG
996 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
, const wxString
& caption
)
999 data
.SetChooseFull(true);
1002 data
.SetColour((wxColour
&)colInit
); // const_cast
1006 wxColourDialog
dialog(parent
, &data
);
1007 if (!caption
.IsEmpty())
1008 dialog
.SetTitle(caption
);
1009 if ( dialog
.ShowModal() == wxID_OK
)
1011 colRet
= dialog
.GetColourData().GetColour();
1013 //else: leave it invalid
1018 #endif // wxUSE_COLOURDLG
1022 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
, const wxString
& caption
)
1025 if ( fontInit
.Ok() )
1027 data
.SetInitialFont(fontInit
);
1031 wxFontDialog
dialog(parent
, data
);
1032 if (!caption
.IsEmpty())
1033 dialog
.SetTitle(caption
);
1034 if ( dialog
.ShowModal() == wxID_OK
)
1036 fontRet
= dialog
.GetFontData().GetChosenFont();
1038 //else: leave it invalid
1043 #endif // wxUSE_FONTDLG
1045 // ----------------------------------------------------------------------------
1046 // wxSafeYield and supporting functions
1047 // ----------------------------------------------------------------------------
1049 void wxEnableTopLevelWindows(bool enable
)
1051 wxWindowList::compatibility_iterator node
;
1052 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1053 node
->GetData()->Enable(enable
);
1056 wxWindowDisabler::wxWindowDisabler(wxWindow
*winToSkip
)
1058 // remember the top level windows which were already disabled, so that we
1059 // don't reenable them later
1060 m_winDisabled
= NULL
;
1062 wxWindowList::compatibility_iterator node
;
1063 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1065 wxWindow
*winTop
= node
->GetData();
1066 if ( winTop
== winToSkip
)
1069 // we don't need to disable the hidden or already disabled windows
1070 if ( winTop
->IsEnabled() && winTop
->IsShown() )
1076 if ( !m_winDisabled
)
1078 m_winDisabled
= new wxWindowList
;
1081 m_winDisabled
->Append(winTop
);
1086 wxWindowDisabler::~wxWindowDisabler()
1088 wxWindowList::compatibility_iterator node
;
1089 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1091 wxWindow
*winTop
= node
->GetData();
1092 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
1096 //else: had been already disabled, don't reenable
1099 delete m_winDisabled
;
1102 // Yield to other apps/messages and disable user input to all windows except
1104 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
1106 wxWindowDisabler
wd(win
);
1110 rc
= wxYieldIfNeeded();
1117 // Don't synthesize KeyUp events holding down a key and producing KeyDown
1118 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
1121 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
1123 return true; // detectable auto-repeat is the only mode MSW supports