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 // ============================================================================
103 // ============================================================================
105 #if WXWIN_COMPATIBILITY_2_4
108 copystring (const wxChar
*s
)
110 if (s
== NULL
) s
= wxEmptyString
;
111 size_t len
= wxStrlen (s
) + 1;
113 wxChar
*news
= new wxChar
[len
];
114 memcpy (news
, s
, len
* sizeof(wxChar
)); // Should be the fastest
119 #endif // WXWIN_COMPATIBILITY_2_4
121 // ----------------------------------------------------------------------------
122 // String <-> Number conversions (deprecated)
123 // ----------------------------------------------------------------------------
125 #if WXWIN_COMPATIBILITY_2_4
127 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxFloatToStringStr
= wxT("%.2f");
128 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxDoubleToStringStr
= wxT("%.2f");
131 StringToFloat (const wxChar
*s
, float *number
)
133 if (s
&& *s
&& number
)
134 *number
= (float) wxStrtod (s
, (wxChar
**) NULL
);
138 StringToDouble (const wxChar
*s
, double *number
)
140 if (s
&& *s
&& number
)
141 *number
= wxStrtod (s
, (wxChar
**) NULL
);
145 FloatToString (float number
, const wxChar
*fmt
)
147 static wxChar buf
[256];
149 wxSprintf (buf
, fmt
, number
);
154 DoubleToString (double number
, const wxChar
*fmt
)
156 static wxChar buf
[256];
158 wxSprintf (buf
, fmt
, number
);
163 StringToInt (const wxChar
*s
, int *number
)
165 if (s
&& *s
&& number
)
166 *number
= (int) wxStrtol (s
, (wxChar
**) NULL
, 10);
170 StringToLong (const wxChar
*s
, long *number
)
172 if (s
&& *s
&& number
)
173 *number
= wxStrtol (s
, (wxChar
**) NULL
, 10);
177 IntToString (int number
)
179 static wxChar buf
[20];
181 wxSprintf (buf
, wxT("%d"), number
);
186 LongToString (long number
)
188 static wxChar buf
[20];
190 wxSprintf (buf
, wxT("%ld"), number
);
194 #endif // WXWIN_COMPATIBILITY_2_4
196 // Array used in DecToHex conversion routine.
197 static wxChar hexArray
[] = wxT("0123456789ABCDEF");
199 // Convert 2-digit hex number to decimal
200 int wxHexToDec(const wxString
& buf
)
202 int firstDigit
, secondDigit
;
204 if (buf
.GetChar(0) >= wxT('A'))
205 firstDigit
= buf
.GetChar(0) - wxT('A') + 10;
207 firstDigit
= buf
.GetChar(0) - wxT('0');
209 if (buf
.GetChar(1) >= wxT('A'))
210 secondDigit
= buf
.GetChar(1) - wxT('A') + 10;
212 secondDigit
= buf
.GetChar(1) - wxT('0');
214 return (firstDigit
& 0xF) * 16 + (secondDigit
& 0xF );
217 // Convert decimal integer to 2-character hex string
218 void wxDecToHex(int dec
, wxChar
*buf
)
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
];
227 // Convert decimal integer to 2-character hex string
228 wxString
wxDecToHex(int dec
)
231 wxDecToHex(dec
, buf
);
232 return wxString(buf
);
235 // ----------------------------------------------------------------------------
237 // ----------------------------------------------------------------------------
239 // Return the current date/time
244 wxDateTime now
= wxDateTime::Now();
247 return wxEmptyString
;
250 time_t now
= time((time_t *) NULL
);
251 char *date
= ctime(&now
);
253 return wxString::FromAscii(date
);
257 void wxUsleep(unsigned long milliseconds
)
259 wxMilliSleep(milliseconds
);
262 const wxChar
*wxGetInstallPrefix()
266 if ( wxGetEnv(wxT("WXPREFIX"), &prefix
) )
267 return prefix
.c_str();
269 #ifdef wxINSTALL_PREFIX
270 return wxT(wxINSTALL_PREFIX
);
272 return wxEmptyString
;
276 wxString
wxGetDataDir()
278 wxString dir
= wxGetInstallPrefix();
279 dir
<< wxFILE_SEP_PATH
<< wxT("share") << wxFILE_SEP_PATH
<< wxT("wx");
283 int wxGetOsVersion(int *verMaj
, int *verMin
)
285 // we want this function to work even if there is no wxApp
286 wxConsoleAppTraits traitsConsole
;
287 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
289 traits
= &traitsConsole
;
291 wxToolkitInfo
& info
= traits
->GetToolkitInfo();
293 *verMaj
= info
.versionMajor
;
295 *verMin
= info
.versionMinor
;
299 // ----------------------------------------------------------------------------
300 // network and user id functions
301 // ----------------------------------------------------------------------------
303 // Get Full RFC822 style email address
304 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
306 wxString email
= wxGetEmailAddress();
310 wxStrncpy(address
, email
, maxSize
- 1);
311 address
[maxSize
- 1] = wxT('\0');
316 wxString
wxGetEmailAddress()
320 wxString host
= wxGetFullHostName();
323 wxString user
= wxGetUserId();
326 email
<< user
<< wxT('@') << host
;
333 wxString
wxGetUserId()
335 static const int maxLoginLen
= 256; // FIXME arbitrary number
338 bool ok
= wxGetUserId(wxStringBuffer(buf
, maxLoginLen
), maxLoginLen
);
346 wxString
wxGetUserName()
348 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
351 bool ok
= wxGetUserName(wxStringBuffer(buf
, maxUserNameLen
), maxUserNameLen
);
359 wxString
wxGetHostName()
361 static const size_t hostnameSize
= 257;
364 bool ok
= wxGetHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
372 wxString
wxGetFullHostName()
374 static const size_t hostnameSize
= 257;
377 bool ok
= wxGetFullHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
385 wxString
wxGetHomeDir()
395 wxString
wxGetCurrentDir()
402 ok
= getcwd(dir
.GetWriteBuf(len
+ 1), len
) != NULL
;
407 if ( errno
!= ERANGE
)
409 wxLogSysError(_T("Failed to get current directory"));
411 return wxEmptyString
;
415 // buffer was too small, retry with a larger one
427 // ----------------------------------------------------------------------------
429 // ----------------------------------------------------------------------------
431 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
433 // returns true if ok, false if error
435 static bool ReadAll(wxInputStream
*is
, wxArrayString
& output
)
437 wxCHECK_MSG( is
, false, _T("NULL stream in wxExecute()?") );
439 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
442 wxTextInputStream
tis(*is
);
447 wxString line
= tis
.ReadLine();
463 #endif // wxUSE_STREAMS
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
,
473 // create a wxProcess which will capture the output
474 wxProcess
*process
= new wxProcess
;
477 long rc
= wxExecute(command
, wxEXEC_SYNC
| flags
, process
);
482 if ( !ReadAll(process
->GetInputStream(), output
) )
487 if ( !ReadAll(process
->GetErrorStream(), *error
) )
495 #endif // wxUSE_STREAMS/!wxUSE_STREAMS
502 long wxExecute(const wxString
& command
, wxArrayString
& output
, int flags
)
504 return wxDoExecuteWithCapture(command
, output
, NULL
, flags
);
507 long wxExecute(const wxString
& command
,
508 wxArrayString
& output
,
509 wxArrayString
& error
,
512 return wxDoExecuteWithCapture(command
, output
, &error
, flags
);
515 // ----------------------------------------------------------------------------
516 // Launch default browser
517 // ----------------------------------------------------------------------------
519 bool wxLaunchDefaultBrowser(const wxString
& urlOrig
, int flags
)
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://"));
528 #if defined(__WXMSW__)
531 if ( flags
& wxBROWSER_NEW_WINDOW
)
533 // ShellExecuteEx() opens the URL in an existing window by default so
534 // we can't use it if we need a new window
535 wxRegKey
key(wxRegKey::HKCR
, url
.BeforeFirst(':') + _T("\\shell\\open"));
538 wxRegKey
keyDDE(key
, wxT("DDEExec"));
539 if ( keyDDE
.Exists() )
541 const wxString ddeTopic
= wxRegKey(keyDDE
, wxT("topic"));
543 // we only know the syntax of WWW_OpenURL DDE request for IE,
544 // optimistically assume that all other browsers are compatible
547 bool ok
= ddeTopic
== wxT("WWW_OpenURL");
550 ddeCmd
= keyDDE
.QueryDefaultValue();
551 ok
= !ddeCmd
.empty();
556 // for WWW_OpenURL, the index of the window to open the URL
557 // in is -1 (meaning "current") by default, replace it with
558 // 0 which means "new" (see KB article 160957)
559 ok
= ddeCmd
.Replace(wxT("-1"), wxT("0"),
560 false /* only first occurence */) == 1;
565 // and also replace the parameters: the topic should
566 // contain a placeholder for the URL
567 ok
= ddeCmd
.Replace(wxT("%1"), url
, false) == 1;
572 // try to send it the DDE request now but ignore the errors
575 const wxString ddeServer
= wxRegKey(keyDDE
, wxT("application"));
576 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCmd
) )
579 // this is not necessarily an error: maybe browser is
580 // simply not running, but no matter, in any case we're
581 // going to launch it using ShellExecuteEx() below now and
582 // we shouldn't try to open a new window if we open a new
590 WinStruct
<SHELLEXECUTEINFO
> sei
;
591 sei
.lpFile
= url
.c_str();
592 sei
.lpVerb
= _T("open");
593 sei
.nShow
= SW_SHOWNORMAL
;
595 ::ShellExecuteEx(&sei
);
597 const int nResult
= (int) sei
.hInstApp
;
599 // Firefox returns file not found for some reason, so make an exception
601 if ( nResult
> 32 || nResult
== SE_ERR_FNF
)
604 // Log something if SE_ERR_FNF happens
605 if ( nResult
== SE_ERR_FNF
)
606 wxLogDebug(wxT("SE_ERR_FNF from ShellExecute -- maybe FireFox?"));
607 #endif // __WXDEBUG__
612 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension (_T("html"));
616 ft
->GetMimeType(&mt
);
619 bool ok
= ft
->GetOpenCommand(&cmd
, wxFileType::MessageParameters(url
));
622 if ( !ok
|| cmd
.empty() )
624 // fallback to checking for the BROWSER environment variable
625 cmd
= wxGetenv(wxT("BROWSER"));
627 cmd
<< _T(' ') << url
;
630 if ( !cmd
.empty() && wxExecute(cmd
) )
633 else // no file type for html extension
635 wxLogError(_T("No default application configured for HTML files."));
637 #endif // !wxUSE_MIMETYPE && !__WXMSW__
639 wxLogSysError(_T("Failed to open URL \"%s\" in default browser."),
645 // ----------------------------------------------------------------------------
646 // wxApp::Yield() wrappers for backwards compatibility
647 // ----------------------------------------------------------------------------
651 return wxTheApp
&& wxTheApp
->Yield();
654 bool wxYieldIfNeeded()
656 return wxTheApp
&& wxTheApp
->Yield(true);
661 // ============================================================================
662 // GUI-only functions from now on
663 // ============================================================================
668 static long wxCurrentId
= 100;
672 // skip the part of IDs space that contains hard-coded values:
673 if (wxCurrentId
== wxID_LOWEST
)
674 wxCurrentId
= wxID_HIGHEST
+ 1;
676 return wxCurrentId
++;
680 wxGetCurrentId(void) { return wxCurrentId
; }
683 wxRegisterId (long id
)
685 if (id
>= wxCurrentId
)
686 wxCurrentId
= id
+ 1;
691 // ----------------------------------------------------------------------------
692 // Menu accelerators related functions
693 // ----------------------------------------------------------------------------
695 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
697 wxString s
= wxMenuItem::GetLabelFromText(in
);
700 // go smash their buffer if it's not big enough - I love char * params
701 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
705 // MYcopystring - for easier search...
706 out
= new wxChar
[s
.length() + 1];
707 wxStrcpy(out
, s
.c_str());
713 wxString
wxStripMenuCodes(const wxString
& in
)
717 size_t len
= in
.length();
720 for ( size_t n
= 0; n
< len
; n
++ )
725 // skip it, it is used to introduce the accel char (or to quote
726 // itself in which case it should still be skipped): note that it
727 // can't be the last character of the string
730 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
734 // use the next char instead
738 else if ( ch
== _T('\t') )
740 // everything after TAB is accel string, exit the loop
750 #endif // wxUSE_MENUS
752 // ----------------------------------------------------------------------------
753 // Window search functions
754 // ----------------------------------------------------------------------------
757 * If parent is non-NULL, look through children for a label or title
758 * matching the specified string. If NULL, look through all top-level windows.
763 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
765 return wxWindow::FindWindowByLabel( title
, parent
);
770 * If parent is non-NULL, look through children for a name
771 * matching the specified string. If NULL, look through all top-level windows.
776 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
778 return wxWindow::FindWindowByName( name
, parent
);
781 // Returns menu item id or wxNOT_FOUND if none.
783 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
786 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
788 return menuBar
->FindMenuItem (menuString
, itemString
);
789 #endif // wxUSE_MENUS
794 // Try to find the deepest child that contains 'pt'.
795 // We go backwards, to try to allow for controls that are spacially
796 // within other controls, but are still siblings (e.g. buttons within
797 // static boxes). Static boxes are likely to be created _before_ controls
798 // that sit inside them.
799 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
804 // Hack for wxNotebook case: at least in wxGTK, all pages
805 // claim to be shown, so we must only deal with the selected one.
807 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
809 wxNotebook
* nb
= (wxNotebook
*) win
;
810 int sel
= nb
->GetSelection();
813 wxWindow
* child
= nb
->GetPage(sel
);
814 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
821 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetLast();
824 wxWindow
* child
= node
->GetData();
825 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
828 node
= node
->GetPrevious();
831 wxPoint pos
= win
->GetPosition();
832 wxSize sz
= win
->GetSize();
833 if (win
->GetParent())
835 pos
= win
->GetParent()->ClientToScreen(pos
);
838 wxRect
rect(pos
, sz
);
845 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
847 // Go backwards through the list since windows
848 // on top are likely to have been appended most
850 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetLast();
853 wxWindow
* win
= node
->GetData();
854 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
857 node
= node
->GetPrevious();
862 // ----------------------------------------------------------------------------
864 // ----------------------------------------------------------------------------
867 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
868 * since otherwise the generic code may be pulled in unnecessarily.
873 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
874 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
876 long decorated_style
= style
;
878 if ( ( style
& ( wxICON_EXCLAMATION
| wxICON_HAND
| wxICON_INFORMATION
| wxICON_QUESTION
) ) == 0 )
880 decorated_style
|= ( style
& wxYES
) ? wxICON_QUESTION
: wxICON_INFORMATION
;
883 wxMessageDialog
dialog(parent
, message
, caption
, decorated_style
);
885 int ans
= dialog
.ShowModal();
898 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
903 #endif // wxUSE_MSGDLG
907 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
908 const wxString
& defaultValue
, wxWindow
*parent
,
909 wxCoord x
, wxCoord y
, bool centre
)
912 long style
= wxTextEntryDialogStyle
;
919 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, style
, wxPoint(x
, y
));
921 if (dialog
.ShowModal() == wxID_OK
)
923 str
= dialog
.GetValue();
929 wxString
wxGetPasswordFromUser(const wxString
& message
,
930 const wxString
& caption
,
931 const wxString
& defaultValue
,
933 wxCoord x
, wxCoord y
, bool centre
)
936 long style
= wxTextEntryDialogStyle
;
943 wxPasswordEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
944 style
, wxPoint(x
, y
));
945 if ( dialog
.ShowModal() == wxID_OK
)
947 str
= dialog
.GetValue();
953 #endif // wxUSE_TEXTDLG
957 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
960 data
.SetChooseFull(true);
963 data
.SetColour((wxColour
&)colInit
); // const_cast
967 wxColourDialog
dialog(parent
, &data
);
968 if ( dialog
.ShowModal() == wxID_OK
)
970 colRet
= dialog
.GetColourData().GetColour();
972 //else: leave it invalid
977 #endif // wxUSE_COLOURDLG
981 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
986 data
.SetInitialFont(fontInit
);
990 wxFontDialog
dialog(parent
, data
);
991 if ( dialog
.ShowModal() == wxID_OK
)
993 fontRet
= dialog
.GetFontData().GetChosenFont();
995 //else: leave it invalid
1000 #endif // wxUSE_FONTDLG
1002 // ----------------------------------------------------------------------------
1003 // wxSafeYield and supporting functions
1004 // ----------------------------------------------------------------------------
1006 void wxEnableTopLevelWindows(bool enable
)
1008 wxWindowList::compatibility_iterator node
;
1009 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1010 node
->GetData()->Enable(enable
);
1013 wxWindowDisabler::wxWindowDisabler(wxWindow
*winToSkip
)
1015 // remember the top level windows which were already disabled, so that we
1016 // don't reenable them later
1017 m_winDisabled
= NULL
;
1019 wxWindowList::compatibility_iterator node
;
1020 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1022 wxWindow
*winTop
= node
->GetData();
1023 if ( winTop
== winToSkip
)
1026 // we don't need to disable the hidden or already disabled windows
1027 if ( winTop
->IsEnabled() && winTop
->IsShown() )
1033 if ( !m_winDisabled
)
1035 m_winDisabled
= new wxWindowList
;
1038 m_winDisabled
->Append(winTop
);
1043 wxWindowDisabler::~wxWindowDisabler()
1045 wxWindowList::compatibility_iterator node
;
1046 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
1048 wxWindow
*winTop
= node
->GetData();
1049 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
1053 //else: had been already disabled, don't reenable
1056 delete m_winDisabled
;
1059 // Yield to other apps/messages and disable user input to all windows except
1061 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
1063 wxWindowDisabler
wd(win
);
1067 rc
= wxYieldIfNeeded();
1074 // Don't synthesize KeyUp events holding down a key and producing KeyDown
1075 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
1078 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
1080 return true; // detectable auto-repeat is the only mode MSW supports