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 !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"
92 #include "wx/msw/registry.h"
97 // ----------------------------------------------------------------------------
99 // ----------------------------------------------------------------------------
101 #if WXWIN_COMPATIBILITY_2_2
102 const wxChar
*wxInternalErrorStr
= wxT("wxWidgets Internal Error");
103 const wxChar
*wxFatalErrorStr
= wxT("wxWidgets Fatal Error");
104 #endif // WXWIN_COMPATIBILITY_2_2
106 // ============================================================================
108 // ============================================================================
110 #if WXWIN_COMPATIBILITY_2_4
113 copystring (const wxChar
*s
)
115 if (s
== NULL
) s
= wxEmptyString
;
116 size_t len
= wxStrlen (s
) + 1;
118 wxChar
*news
= new wxChar
[len
];
119 memcpy (news
, s
, len
* sizeof(wxChar
)); // Should be the fastest
124 #endif // WXWIN_COMPATIBILITY_2_4
126 // ----------------------------------------------------------------------------
127 // String <-> Number conversions (deprecated)
128 // ----------------------------------------------------------------------------
130 #if WXWIN_COMPATIBILITY_2_4
132 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxFloatToStringStr
= wxT("%.2f");
133 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxDoubleToStringStr
= wxT("%.2f");
136 StringToFloat (const wxChar
*s
, float *number
)
138 if (s
&& *s
&& number
)
139 *number
= (float) wxStrtod (s
, (wxChar
**) NULL
);
143 StringToDouble (const wxChar
*s
, double *number
)
145 if (s
&& *s
&& number
)
146 *number
= wxStrtod (s
, (wxChar
**) NULL
);
150 FloatToString (float number
, const wxChar
*fmt
)
152 static wxChar buf
[256];
154 wxSprintf (buf
, fmt
, number
);
159 DoubleToString (double number
, const wxChar
*fmt
)
161 static wxChar buf
[256];
163 wxSprintf (buf
, fmt
, number
);
168 StringToInt (const wxChar
*s
, int *number
)
170 if (s
&& *s
&& number
)
171 *number
= (int) wxStrtol (s
, (wxChar
**) NULL
, 10);
175 StringToLong (const wxChar
*s
, long *number
)
177 if (s
&& *s
&& number
)
178 *number
= wxStrtol (s
, (wxChar
**) NULL
, 10);
182 IntToString (int number
)
184 static wxChar buf
[20];
186 wxSprintf (buf
, wxT("%d"), number
);
191 LongToString (long number
)
193 static wxChar buf
[20];
195 wxSprintf (buf
, wxT("%ld"), number
);
199 #endif // WXWIN_COMPATIBILITY_2_4
201 // Array used in DecToHex conversion routine.
202 static wxChar hexArray
[] = wxT("0123456789ABCDEF");
204 // Convert 2-digit hex number to decimal
205 int wxHexToDec(const wxString
& buf
)
207 int firstDigit
, secondDigit
;
209 if (buf
.GetChar(0) >= wxT('A'))
210 firstDigit
= buf
.GetChar(0) - wxT('A') + 10;
212 firstDigit
= buf
.GetChar(0) - wxT('0');
214 if (buf
.GetChar(1) >= wxT('A'))
215 secondDigit
= buf
.GetChar(1) - wxT('A') + 10;
217 secondDigit
= buf
.GetChar(1) - wxT('0');
219 return (firstDigit
& 0xF) * 16 + (secondDigit
& 0xF );
222 // Convert decimal integer to 2-character hex string
223 void wxDecToHex(int dec
, wxChar
*buf
)
225 int firstDigit
= (int)(dec
/16.0);
226 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
227 buf
[0] = hexArray
[firstDigit
];
228 buf
[1] = hexArray
[secondDigit
];
232 // Convert decimal integer to 2-character hex string
233 wxString
wxDecToHex(int dec
)
236 wxDecToHex(dec
, buf
);
237 return wxString(buf
);
240 // ----------------------------------------------------------------------------
242 // ----------------------------------------------------------------------------
244 // Return the current date/time
249 wxDateTime now
= wxDateTime::Now();
252 return wxEmptyString
;
255 time_t now
= time((time_t *) NULL
);
256 char *date
= ctime(&now
);
258 return wxString::FromAscii(date
);
262 void wxUsleep(unsigned long milliseconds
)
264 wxMilliSleep(milliseconds
);
267 const wxChar
*wxGetInstallPrefix()
271 if ( wxGetEnv(wxT("WXPREFIX"), &prefix
) )
272 return prefix
.c_str();
274 #ifdef wxINSTALL_PREFIX
275 return wxT(wxINSTALL_PREFIX
);
277 return wxEmptyString
;
281 wxString
wxGetDataDir()
283 wxString dir
= wxGetInstallPrefix();
284 dir
<< wxFILE_SEP_PATH
<< wxT("share") << wxFILE_SEP_PATH
<< wxT("wx");
288 int wxGetOsVersion(int *verMaj
, int *verMin
)
290 // we want this function to work even if there is no wxApp
291 wxConsoleAppTraits traitsConsole
;
292 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
294 traits
= &traitsConsole
;
296 wxToolkitInfo
& info
= traits
->GetToolkitInfo();
298 *verMaj
= info
.versionMajor
;
300 *verMin
= info
.versionMinor
;
304 // ----------------------------------------------------------------------------
305 // network and user id functions
306 // ----------------------------------------------------------------------------
308 // Get Full RFC822 style email address
309 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
311 wxString email
= wxGetEmailAddress();
315 wxStrncpy(address
, email
, maxSize
- 1);
316 address
[maxSize
- 1] = wxT('\0');
321 wxString
wxGetEmailAddress()
325 wxString host
= wxGetFullHostName();
328 wxString user
= wxGetUserId();
331 email
<< user
<< wxT('@') << host
;
338 wxString
wxGetUserId()
340 static const int maxLoginLen
= 256; // FIXME arbitrary number
343 bool ok
= wxGetUserId(wxStringBuffer(buf
, maxLoginLen
), maxLoginLen
);
351 wxString
wxGetUserName()
353 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
356 bool ok
= wxGetUserName(wxStringBuffer(buf
, maxUserNameLen
), maxUserNameLen
);
364 wxString
wxGetHostName()
366 static const size_t hostnameSize
= 257;
369 bool ok
= wxGetHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
377 wxString
wxGetFullHostName()
379 static const size_t hostnameSize
= 257;
382 bool ok
= wxGetFullHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
390 wxString
wxGetHomeDir()
400 wxString
wxGetCurrentDir()
407 ok
= getcwd(dir
.GetWriteBuf(len
+ 1), len
) != NULL
;
412 if ( errno
!= ERANGE
)
414 wxLogSysError(_T("Failed to get current directory"));
416 return wxEmptyString
;
420 // buffer was too small, retry with a larger one
432 // ----------------------------------------------------------------------------
434 // ----------------------------------------------------------------------------
436 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
438 // returns true if ok, false if error
440 static bool ReadAll(wxInputStream
*is
, wxArrayString
& output
)
442 wxCHECK_MSG( is
, false, _T("NULL stream in wxExecute()?") );
444 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
447 wxTextInputStream
tis(*is
);
452 wxString line
= tis
.ReadLine();
468 #endif // wxUSE_STREAMS
470 // this is a private function because it hasn't a clean interface: the first
471 // array is passed by reference, the second by pointer - instead we have 2
472 // public versions of wxExecute() below
473 static long wxDoExecuteWithCapture(const wxString
& command
,
474 wxArrayString
& output
,
475 wxArrayString
* error
,
478 // create a wxProcess which will capture the output
479 wxProcess
*process
= new wxProcess
;
482 long rc
= wxExecute(command
, wxEXEC_SYNC
| flags
, process
);
487 if ( !ReadAll(process
->GetInputStream(), output
) )
492 if ( !ReadAll(process
->GetErrorStream(), *error
) )
500 #endif // wxUSE_STREAMS/!wxUSE_STREAMS
507 long wxExecute(const wxString
& command
, wxArrayString
& output
, int flags
)
509 return wxDoExecuteWithCapture(command
, output
, NULL
, flags
);
512 long wxExecute(const wxString
& command
,
513 wxArrayString
& output
,
514 wxArrayString
& error
,
517 return wxDoExecuteWithCapture(command
, output
, &error
, flags
);
520 // ----------------------------------------------------------------------------
521 // Launch default browser
522 // ----------------------------------------------------------------------------
524 bool wxLaunchDefaultBrowser(const wxString
& urlOrig
, int flags
)
528 // set the scheme of url to http if it does not have one
529 wxString
url(urlOrig
);
530 if ( !wxURI(url
).HasScheme() )
531 url
.Prepend(wxT("http://"));
533 #if defined(__WXMSW__)
534 if ( flags
& wxBROWSER_NEW_WINDOW
)
536 // ShellExecuteEx() opens the URL in an existing window by default so
537 // we can't use it if we need a new window
538 wxRegKey
key(wxRegKey::HKCR
, url
.BeforeFirst(':') + _T("\\shell\\open"));
541 wxRegKey
keyDDE(key
, wxT("DDEExec"));
542 if ( keyDDE
.Exists() )
544 const wxString ddeTopic
= wxRegKey(keyDDE
, wxT("topic"));
546 // we only know the syntax of WWW_OpenURL DDE request for IE,
547 // optimistically assume that all other browsers are compatible
550 bool ok
= ddeTopic
== wxT("WWW_OpenURL");
553 ddeCmd
= keyDDE
.QueryDefaultValue();
554 ok
= !ddeCmd
.empty();
559 // for WWW_OpenURL, the index of the window to open the URL
560 // in is -1 (meaning "current") by default, replace it with
561 // 0 which means "new" (see KB article 160957)
562 ok
= ddeCmd
.Replace(wxT("-1"), wxT("0"),
563 false /* only first occurence */) == 1;
568 // and also replace the parameters: the topic should
569 // contain a placeholder for the URL
570 ok
= ddeCmd
.Replace(wxT("%1"), url
, false) == 1;
575 // try to send it the DDE request now but ignore the errors
578 const wxString ddeServer
= wxRegKey(keyDDE
, wxT("application"));
579 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCmd
) )
582 // this is not necessarily an error: maybe browser is
583 // simply not running, but no matter, in any case we're
584 // going to launch it using ShellExecuteEx() below now and
585 // we shouldn't try to open a new window if we open a new
592 WinStruct
<SHELLEXECUTEINFO
> sei
;
593 sei
.lpFile
= url
.c_str();
594 sei
.lpVerb
= _T("open");
595 sei
.nShow
= SW_SHOWNORMAL
;
597 ::ShellExecuteEx(&sei
);
599 const int nResult
= (int) sei
.hInstApp
;
601 // Firefox returns file not found for some reason, so make an exception
603 if ( nResult
> 32 || nResult
== SE_ERR_FNF
)
606 // Log something if SE_ERR_FNF happens
607 if ( nResult
== SE_ERR_FNF
)
608 wxLogDebug(wxT("SE_ERR_FNF from ShellExecute -- maybe FireFox?"));
609 #endif // __WXDEBUG__
614 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension (_T("html"));
618 ft
->GetMimeType(&mt
);
621 bool ok
= ft
->GetOpenCommand(&cmd
, wxFileType::MessageParameters(url
));
624 if ( !ok
|| cmd
.empty() )
626 // fallback to checking for the BROWSER environment variable
627 cmd
= wxGetenv(wxT("BROWSER"));
629 cmd
<< _T(' ') << url
;
632 if ( !cmd
.empty() && wxExecute(cmd
) )
635 else // no file type for html extension
637 wxLogError(_T("No default application configured for HTML files."));
639 #endif // !wxUSE_MIMETYPE && !__WXMSW__
641 wxLogSysError(_T("Failed to open URL \"%s\" in default browser."),
647 // ----------------------------------------------------------------------------
648 // wxApp::Yield() wrappers for backwards compatibility
649 // ----------------------------------------------------------------------------
653 return wxTheApp
&& wxTheApp
->Yield();
656 bool wxYieldIfNeeded()
658 return wxTheApp
&& wxTheApp
->Yield(true);
663 // ============================================================================
664 // GUI-only functions from now on
665 // ============================================================================
670 static long wxCurrentId
= 100;
674 // skip the part of IDs space that contains hard-coded values:
675 if (wxCurrentId
== wxID_LOWEST
)
676 wxCurrentId
= wxID_HIGHEST
+ 1;
678 return wxCurrentId
++;
682 wxGetCurrentId(void) { return wxCurrentId
; }
685 wxRegisterId (long id
)
687 if (id
>= wxCurrentId
)
688 wxCurrentId
= id
+ 1;
693 // ----------------------------------------------------------------------------
694 // Menu accelerators related functions
695 // ----------------------------------------------------------------------------
697 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
699 wxString s
= wxMenuItem::GetLabelFromText(in
);
702 // go smash their buffer if it's not big enough - I love char * params
703 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
707 // MYcopystring - for easier search...
708 out
= new wxChar
[s
.length() + 1];
709 wxStrcpy(out
, s
.c_str());
715 wxString
wxStripMenuCodes(const wxString
& in
)
719 size_t len
= in
.length();
722 for ( size_t n
= 0; n
< len
; n
++ )
727 // skip it, it is used to introduce the accel char (or to quote
728 // itself in which case it should still be skipped): note that it
729 // can't be the last character of the string
732 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
736 // use the next char instead
740 else if ( ch
== _T('\t') )
742 // everything after TAB is accel string, exit the loop
752 #endif // wxUSE_MENUS
754 // ----------------------------------------------------------------------------
755 // Window search functions
756 // ----------------------------------------------------------------------------
759 * If parent is non-NULL, look through children for a label or title
760 * matching the specified string. If NULL, look through all top-level windows.
765 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
767 return wxWindow::FindWindowByLabel( title
, parent
);
772 * If parent is non-NULL, look through children for a name
773 * matching the specified string. If NULL, look through all top-level windows.
778 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
780 return wxWindow::FindWindowByName( name
, parent
);
783 // Returns menu item id or wxNOT_FOUND if none.
785 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
788 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
790 return menuBar
->FindMenuItem (menuString
, itemString
);
791 #endif // wxUSE_MENUS
796 // Try to find the deepest child that contains 'pt'.
797 // We go backwards, to try to allow for controls that are spacially
798 // within other controls, but are still siblings (e.g. buttons within
799 // static boxes). Static boxes are likely to be created _before_ controls
800 // that sit inside them.
801 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
806 // Hack for wxNotebook case: at least in wxGTK, all pages
807 // claim to be shown, so we must only deal with the selected one.
809 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
811 wxNotebook
* nb
= (wxNotebook
*) win
;
812 int sel
= nb
->GetSelection();
815 wxWindow
* child
= nb
->GetPage(sel
);
816 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
823 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetLast();
826 wxWindow
* child
= node
->GetData();
827 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
830 node
= node
->GetPrevious();
833 wxPoint pos
= win
->GetPosition();
834 wxSize sz
= win
->GetSize();
835 if (win
->GetParent())
837 pos
= win
->GetParent()->ClientToScreen(pos
);
840 wxRect
rect(pos
, sz
);
847 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
849 // Go backwards through the list since windows
850 // on top are likely to have been appended most
852 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetLast();
855 wxWindow
* win
= node
->GetData();
856 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
859 node
= node
->GetPrevious();
864 // ----------------------------------------------------------------------------
866 // ----------------------------------------------------------------------------
869 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
870 * since otherwise the generic code may be pulled in unnecessarily.
875 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
876 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
878 long decorated_style
= style
;
880 if ( ( style
& ( wxICON_EXCLAMATION
| wxICON_HAND
| wxICON_INFORMATION
| wxICON_QUESTION
) ) == 0 )
882 decorated_style
|= ( style
& wxYES
) ? wxICON_QUESTION
: wxICON_INFORMATION
;
885 wxMessageDialog
dialog(parent
, message
, caption
, decorated_style
);
887 int ans
= dialog
.ShowModal();
900 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
905 #endif // wxUSE_MSGDLG
909 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
910 const wxString
& defaultValue
, wxWindow
*parent
,
911 wxCoord x
, wxCoord y
, bool centre
)
914 long style
= wxTextEntryDialogStyle
;
921 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, style
, wxPoint(x
, y
));
923 if (dialog
.ShowModal() == wxID_OK
)
925 str
= dialog
.GetValue();
931 wxString
wxGetPasswordFromUser(const wxString
& message
,
932 const wxString
& caption
,
933 const wxString
& defaultValue
,
935 wxCoord x
, wxCoord y
, bool centre
)
938 long style
= wxTextEntryDialogStyle
;
945 wxPasswordEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
946 style
, wxPoint(x
, y
));
947 if ( dialog
.ShowModal() == wxID_OK
)
949 str
= dialog
.GetValue();
955 #endif // wxUSE_TEXTDLG
959 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
962 data
.SetChooseFull(true);
965 data
.SetColour((wxColour
&)colInit
); // const_cast
969 wxColourDialog
dialog(parent
, &data
);
970 if ( dialog
.ShowModal() == wxID_OK
)
972 colRet
= dialog
.GetColourData().GetColour();
974 //else: leave it invalid
979 #endif // wxUSE_COLOURDLG
983 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
988 data
.SetInitialFont(fontInit
);
992 wxFontDialog
dialog(parent
, data
);
993 if ( dialog
.ShowModal() == wxID_OK
)
995 fontRet
= dialog
.GetFontData().GetChosenFont();
997 //else: leave it invalid
1002 #endif // wxUSE_FONTDLG
1004 // ----------------------------------------------------------------------------
1005 // wxSafeYield and supporting functions
1006 // ----------------------------------------------------------------------------
1008 void wxEnableTopLevelWindows(bool enable
)
1010 wxWindowList::compatibility_iterator node
;
1011 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1012 node
->GetData()->Enable(enable
);
1015 wxWindowDisabler::wxWindowDisabler(wxWindow
*winToSkip
)
1017 // remember the top level windows which were already disabled, so that we
1018 // don't reenable them later
1019 m_winDisabled
= NULL
;
1021 wxWindowList::compatibility_iterator node
;
1022 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1024 wxWindow
*winTop
= node
->GetData();
1025 if ( winTop
== winToSkip
)
1028 // we don't need to disable the hidden or already disabled windows
1029 if ( winTop
->IsEnabled() && winTop
->IsShown() )
1035 if ( !m_winDisabled
)
1037 m_winDisabled
= new wxWindowList
;
1040 m_winDisabled
->Append(winTop
);
1045 wxWindowDisabler::~wxWindowDisabler()
1047 wxWindowList::compatibility_iterator node
;
1048 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1050 wxWindow
*winTop
= node
->GetData();
1051 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
1055 //else: had been already disabled, don't reenable
1058 delete m_winDisabled
;
1061 // Yield to other apps/messages and disable user input to all windows except
1063 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
1065 wxWindowDisabler
wd(win
);
1069 rc
= wxYieldIfNeeded();
1076 // Don't synthesize KeyUp events holding down a key and producing KeyDown
1077 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
1080 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
1082 return true; // detectable auto-repeat is the only mode MSW supports