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
)
525 // set the scheme of url to http if it does not have one
526 wxString
url(urlOrig
);
527 if ( !wxURI(url
).HasScheme() )
528 url
.Prepend(wxT("http://"));
530 #if defined(__WXMSW__)
531 WinStruct
<SHELLEXECUTEINFO
> sei
;
532 sei
.lpFile
= url
.c_str();
533 sei
.lpVerb
= _T("open");
534 sei
.nShow
= SW_SHOWNORMAL
;
536 ::ShellExecuteEx(&sei
);
538 const int nResult
= (int) sei
.hInstApp
;
540 // Firefox returns file not found for some reason, so make an exception
542 if ( nResult
> 32 || nResult
== SE_ERR_FNF
)
545 // Log something if SE_ERR_FNF happens
546 if ( nResult
== SE_ERR_FNF
)
547 wxLogDebug(wxT("SE_ERR_FNF from ShellExecute -- maybe FireFox?"));
548 #endif // __WXDEBUG__
553 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension (_T("html"));
557 ft
->GetMimeType(&mt
);
560 bool ok
= ft
->GetOpenCommand(&cmd
, wxFileType::MessageParameters(url
));
563 if ( !ok
|| cmd
.empty() )
565 // fallback to checking for the BROWSER environment variable
566 cmd
= wxGetenv(wxT("BROWSER"));
568 cmd
<< _T(' ') << url
;
571 if ( !cmd
.empty() && wxExecute(cmd
) )
574 else // no file type for html extension
576 wxLogError(_T("No default application configured for HTML files."));
578 #endif // !wxUSE_MIMETYPE && !__WXMSW__
580 wxLogSysError(_T("Failed to open URL \"%s\" in default browser."),
586 // ----------------------------------------------------------------------------
587 // wxApp::Yield() wrappers for backwards compatibility
588 // ----------------------------------------------------------------------------
592 return wxTheApp
&& wxTheApp
->Yield();
595 bool wxYieldIfNeeded()
597 return wxTheApp
&& wxTheApp
->Yield(true);
602 // ============================================================================
603 // GUI-only functions from now on
604 // ============================================================================
609 static long wxCurrentId
= 100;
613 // skip the part of IDs space that contains hard-coded values:
614 if (wxCurrentId
== wxID_LOWEST
)
615 wxCurrentId
= wxID_HIGHEST
+ 1;
617 return wxCurrentId
++;
621 wxGetCurrentId(void) { return wxCurrentId
; }
624 wxRegisterId (long id
)
626 if (id
>= wxCurrentId
)
627 wxCurrentId
= id
+ 1;
632 // ----------------------------------------------------------------------------
633 // Menu accelerators related functions
634 // ----------------------------------------------------------------------------
636 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
638 wxString s
= wxMenuItem::GetLabelFromText(in
);
641 // go smash their buffer if it's not big enough - I love char * params
642 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
646 // MYcopystring - for easier search...
647 out
= new wxChar
[s
.length() + 1];
648 wxStrcpy(out
, s
.c_str());
654 wxString
wxStripMenuCodes(const wxString
& in
)
658 size_t len
= in
.length();
661 for ( size_t n
= 0; n
< len
; n
++ )
666 // skip it, it is used to introduce the accel char (or to quote
667 // itself in which case it should still be skipped): note that it
668 // can't be the last character of the string
671 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
675 // use the next char instead
679 else if ( ch
== _T('\t') )
681 // everything after TAB is accel string, exit the loop
691 #endif // wxUSE_MENUS
693 // ----------------------------------------------------------------------------
694 // Window search functions
695 // ----------------------------------------------------------------------------
698 * If parent is non-NULL, look through children for a label or title
699 * matching the specified string. If NULL, look through all top-level windows.
704 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
706 return wxWindow::FindWindowByLabel( title
, parent
);
711 * If parent is non-NULL, look through children for a name
712 * matching the specified string. If NULL, look through all top-level windows.
717 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
719 return wxWindow::FindWindowByName( name
, parent
);
722 // Returns menu item id or wxNOT_FOUND if none.
724 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
727 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
729 return menuBar
->FindMenuItem (menuString
, itemString
);
730 #endif // wxUSE_MENUS
735 // Try to find the deepest child that contains 'pt'.
736 // We go backwards, to try to allow for controls that are spacially
737 // within other controls, but are still siblings (e.g. buttons within
738 // static boxes). Static boxes are likely to be created _before_ controls
739 // that sit inside them.
740 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
745 // Hack for wxNotebook case: at least in wxGTK, all pages
746 // claim to be shown, so we must only deal with the selected one.
748 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
750 wxNotebook
* nb
= (wxNotebook
*) win
;
751 int sel
= nb
->GetSelection();
754 wxWindow
* child
= nb
->GetPage(sel
);
755 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
762 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetLast();
765 wxWindow
* child
= node
->GetData();
766 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
769 node
= node
->GetPrevious();
772 wxPoint pos
= win
->GetPosition();
773 wxSize sz
= win
->GetSize();
774 if (win
->GetParent())
776 pos
= win
->GetParent()->ClientToScreen(pos
);
779 wxRect
rect(pos
, sz
);
786 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
788 // Go backwards through the list since windows
789 // on top are likely to have been appended most
791 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetLast();
794 wxWindow
* win
= node
->GetData();
795 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
798 node
= node
->GetPrevious();
803 // ----------------------------------------------------------------------------
805 // ----------------------------------------------------------------------------
808 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
809 * since otherwise the generic code may be pulled in unnecessarily.
814 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
815 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
817 long decorated_style
= style
;
819 if ( ( style
& ( wxICON_EXCLAMATION
| wxICON_HAND
| wxICON_INFORMATION
| wxICON_QUESTION
) ) == 0 )
821 decorated_style
|= ( style
& wxYES
) ? wxICON_QUESTION
: wxICON_INFORMATION
;
824 wxMessageDialog
dialog(parent
, message
, caption
, decorated_style
);
826 int ans
= dialog
.ShowModal();
839 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
844 #endif // wxUSE_MSGDLG
848 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
849 const wxString
& defaultValue
, wxWindow
*parent
,
850 wxCoord x
, wxCoord y
, bool centre
)
853 long style
= wxTextEntryDialogStyle
;
860 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, style
, wxPoint(x
, y
));
862 if (dialog
.ShowModal() == wxID_OK
)
864 str
= dialog
.GetValue();
870 wxString
wxGetPasswordFromUser(const wxString
& message
,
871 const wxString
& caption
,
872 const wxString
& defaultValue
,
874 wxCoord x
, wxCoord y
, bool centre
)
877 long style
= wxTextEntryDialogStyle
;
884 wxPasswordEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
885 style
, wxPoint(x
, y
));
886 if ( dialog
.ShowModal() == wxID_OK
)
888 str
= dialog
.GetValue();
894 #endif // wxUSE_TEXTDLG
898 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
901 data
.SetChooseFull(true);
904 data
.SetColour((wxColour
&)colInit
); // const_cast
908 wxColourDialog
dialog(parent
, &data
);
909 if ( dialog
.ShowModal() == wxID_OK
)
911 colRet
= dialog
.GetColourData().GetColour();
913 //else: leave it invalid
918 #endif // wxUSE_COLOURDLG
922 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
927 data
.SetInitialFont(fontInit
);
931 wxFontDialog
dialog(parent
, data
);
932 if ( dialog
.ShowModal() == wxID_OK
)
934 fontRet
= dialog
.GetFontData().GetChosenFont();
936 //else: leave it invalid
941 #endif // wxUSE_FONTDLG
943 // ----------------------------------------------------------------------------
944 // wxSafeYield and supporting functions
945 // ----------------------------------------------------------------------------
947 void wxEnableTopLevelWindows(bool enable
)
949 wxWindowList::compatibility_iterator node
;
950 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
951 node
->GetData()->Enable(enable
);
954 wxWindowDisabler::wxWindowDisabler(wxWindow
*winToSkip
)
956 // remember the top level windows which were already disabled, so that we
957 // don't reenable them later
958 m_winDisabled
= NULL
;
960 wxWindowList::compatibility_iterator node
;
961 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
963 wxWindow
*winTop
= node
->GetData();
964 if ( winTop
== winToSkip
)
967 // we don't need to disable the hidden or already disabled windows
968 if ( winTop
->IsEnabled() && winTop
->IsShown() )
974 if ( !m_winDisabled
)
976 m_winDisabled
= new wxWindowList
;
979 m_winDisabled
->Append(winTop
);
984 wxWindowDisabler::~wxWindowDisabler()
986 wxWindowList::compatibility_iterator node
;
987 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
989 wxWindow
*winTop
= node
->GetData();
990 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
994 //else: had been already disabled, don't reenable
997 delete m_winDisabled
;
1000 // Yield to other apps/messages and disable user input to all windows except
1002 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
1004 wxWindowDisabler
wd(win
);
1008 rc
= wxYieldIfNeeded();
1015 // Don't synthesize KeyUp events holding down a key and producing KeyDown
1016 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
1019 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
1021 return true; // detectable auto-repeat is the only mode MSW supports