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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) && !defined(__EMX__)
21 // Some older compilers (such as EMX) cannot handle
22 // #pragma interface/implementation correctly, iff
23 // #pragma implementation is used in _two_ translation
24 // units (as created by e.g. event.cpp compiled for
25 // libwx_base and event.cpp compiled for libwx_gui_core).
26 // So we must not use those pragmas for those compilers in
28 #pragma implementation "utils.h"
31 // For compilers that support precompilation, includes "wx.h".
32 #include "wx/wxprec.h"
40 #include "wx/string.h"
46 #include "wx/window.h"
49 #include "wx/msgdlg.h"
50 #include "wx/textdlg.h"
51 #include "wx/textctrl.h" // for wxTE_PASSWORD
53 #include "wx/menuitem.h"
59 #include "wx/apptrait.h"
61 #include "wx/process.h"
62 #include "wx/txtstrm.h"
64 #if defined(__WXWINCE__) && wxUSE_DATETIME
65 #include "wx/datetime.h"
73 #if !defined(__WATCOMC__)
74 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
80 #include "wx/colordlg.h"
81 #include "wx/fontdlg.h"
82 #include "wx/notebook.h"
84 #include "wx/statusbr.h"
90 #include "wx/msw/wince/time.h"
93 #if !defined(__MWERKS__) && !defined(__WXWINCE__)
94 #include <sys/types.h>
99 #include "wx/msw/private.h"
104 // ----------------------------------------------------------------------------
106 // ----------------------------------------------------------------------------
108 #if WXWIN_COMPATIBILITY_2_2
109 const wxChar
*wxInternalErrorStr
= wxT("wxWidgets Internal Error");
110 const wxChar
*wxFatalErrorStr
= wxT("wxWidgets Fatal Error");
111 #endif // WXWIN_COMPATIBILITY_2_2
113 // ============================================================================
115 // ============================================================================
117 #if WXWIN_COMPATIBILITY_2_4
120 copystring (const wxChar
*s
)
122 if (s
== NULL
) s
= wxT("");
123 size_t len
= wxStrlen (s
) + 1;
125 wxChar
*news
= new wxChar
[len
];
126 memcpy (news
, s
, len
* sizeof(wxChar
)); // Should be the fastest
131 #endif // WXWIN_COMPATIBILITY_2_4
133 // ----------------------------------------------------------------------------
134 // String <-> Number conversions (deprecated)
135 // ----------------------------------------------------------------------------
137 #if WXWIN_COMPATIBILITY_2_4
139 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxFloatToStringStr
= wxT("%.2f");
140 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxDoubleToStringStr
= wxT("%.2f");
143 StringToFloat (const wxChar
*s
, float *number
)
145 if (s
&& *s
&& number
)
146 *number
= (float) wxStrtod (s
, (wxChar
**) NULL
);
150 StringToDouble (const wxChar
*s
, double *number
)
152 if (s
&& *s
&& number
)
153 *number
= wxStrtod (s
, (wxChar
**) NULL
);
157 FloatToString (float number
, const wxChar
*fmt
)
159 static wxChar buf
[256];
161 wxSprintf (buf
, fmt
, number
);
166 DoubleToString (double number
, const wxChar
*fmt
)
168 static wxChar buf
[256];
170 wxSprintf (buf
, fmt
, number
);
175 StringToInt (const wxChar
*s
, int *number
)
177 if (s
&& *s
&& number
)
178 *number
= (int) wxStrtol (s
, (wxChar
**) NULL
, 10);
182 StringToLong (const wxChar
*s
, long *number
)
184 if (s
&& *s
&& number
)
185 *number
= wxStrtol (s
, (wxChar
**) NULL
, 10);
189 IntToString (int number
)
191 static wxChar buf
[20];
193 wxSprintf (buf
, wxT("%d"), number
);
198 LongToString (long number
)
200 static wxChar buf
[20];
202 wxSprintf (buf
, wxT("%ld"), number
);
206 #endif // WXWIN_COMPATIBILITY_2_4
208 // Array used in DecToHex conversion routine.
209 static wxChar hexArray
[] = wxT("0123456789ABCDEF");
211 // Convert 2-digit hex number to decimal
212 int wxHexToDec(const wxString
& buf
)
214 int firstDigit
, secondDigit
;
216 if (buf
.GetChar(0) >= wxT('A'))
217 firstDigit
= buf
.GetChar(0) - wxT('A') + 10;
219 firstDigit
= buf
.GetChar(0) - wxT('0');
221 if (buf
.GetChar(1) >= wxT('A'))
222 secondDigit
= buf
.GetChar(1) - wxT('A') + 10;
224 secondDigit
= buf
.GetChar(1) - wxT('0');
226 return (firstDigit
& 0xF) * 16 + (secondDigit
& 0xF );
229 // Convert decimal integer to 2-character hex string
230 void wxDecToHex(int dec
, wxChar
*buf
)
232 int firstDigit
= (int)(dec
/16.0);
233 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
234 buf
[0] = hexArray
[firstDigit
];
235 buf
[1] = hexArray
[secondDigit
];
239 // Convert decimal integer to 2-character hex string
240 wxString
wxDecToHex(int dec
)
243 wxDecToHex(dec
, buf
);
244 return wxString(buf
);
247 // ----------------------------------------------------------------------------
249 // ----------------------------------------------------------------------------
251 // Return the current date/time
256 wxDateTime now
= wxDateTime::Now();
259 return wxEmptyString
;
262 time_t now
= time((time_t *) NULL
);
263 char *date
= ctime(&now
);
265 return wxString::FromAscii(date
);
269 void wxUsleep(unsigned long milliseconds
)
271 wxMilliSleep(milliseconds
);
274 const wxChar
*wxGetInstallPrefix()
278 if ( wxGetEnv(wxT("WXPREFIX"), &prefix
) )
279 return prefix
.c_str();
281 #ifdef wxINSTALL_PREFIX
282 return wxT(wxINSTALL_PREFIX
);
288 wxString
wxGetDataDir()
290 wxString format
= wxGetInstallPrefix();
291 format
<< wxFILE_SEP_PATH
292 << wxT("share") << wxFILE_SEP_PATH
293 << wxT("wx") << wxFILE_SEP_PATH
296 dir
.Printf(format
.c_str(), wxMAJOR_VERSION
, wxMINOR_VERSION
);
300 int wxGetOsVersion(int *verMaj
, int *verMin
)
302 // we want this function to work even if there is no wxApp
303 wxConsoleAppTraits traitsConsole
;
304 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
306 traits
= &traitsConsole
;
308 wxToolkitInfo
& info
= traits
->GetToolkitInfo();
310 *verMaj
= info
.versionMajor
;
312 *verMin
= info
.versionMinor
;
316 // ----------------------------------------------------------------------------
317 // network and user id functions
318 // ----------------------------------------------------------------------------
320 // Get Full RFC822 style email address
321 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
323 wxString email
= wxGetEmailAddress();
327 wxStrncpy(address
, email
, maxSize
- 1);
328 address
[maxSize
- 1] = wxT('\0');
333 wxString
wxGetEmailAddress()
337 wxString host
= wxGetFullHostName();
340 wxString user
= wxGetUserId();
343 email
<< user
<< wxT('@') << host
;
350 wxString
wxGetUserId()
352 static const int maxLoginLen
= 256; // FIXME arbitrary number
355 bool ok
= wxGetUserId(wxStringBuffer(buf
, maxLoginLen
), maxLoginLen
);
363 wxString
wxGetUserName()
365 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
368 bool ok
= wxGetUserName(wxStringBuffer(buf
, maxUserNameLen
), maxUserNameLen
);
376 wxString
wxGetHostName()
378 static const size_t hostnameSize
= 257;
381 bool ok
= wxGetHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
389 wxString
wxGetFullHostName()
391 static const size_t hostnameSize
= 257;
394 bool ok
= wxGetFullHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
402 wxString
wxGetHomeDir()
412 wxString
wxGetCurrentDir()
419 ok
= getcwd(dir
.GetWriteBuf(len
+ 1), len
) != NULL
;
424 if ( errno
!= ERANGE
)
426 wxLogSysError(_T("Failed to get current directory"));
428 return wxEmptyString
;
432 // buffer was too small, retry with a larger one
444 // ----------------------------------------------------------------------------
446 // ----------------------------------------------------------------------------
448 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
450 // returns TRUE if ok, FALSE if error
452 static bool ReadAll(wxInputStream
*is
, wxArrayString
& output
)
454 wxCHECK_MSG( is
, FALSE
, _T("NULL stream in wxExecute()?") );
456 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
459 wxTextInputStream
tis(*is
);
464 wxString line
= tis
.ReadLine();
480 #endif // wxUSE_STREAMS
482 // this is a private function because it hasn't a clean interface: the first
483 // array is passed by reference, the second by pointer - instead we have 2
484 // public versions of wxExecute() below
485 static long wxDoExecuteWithCapture(const wxString
& command
,
486 wxArrayString
& output
,
487 wxArrayString
* error
)
489 // create a wxProcess which will capture the output
490 wxProcess
*process
= new wxProcess
;
493 long rc
= wxExecute(command
, wxEXEC_SYNC
, process
);
498 if ( !ReadAll(process
->GetInputStream(), output
) )
503 if ( !ReadAll(process
->GetErrorStream(), *error
) )
508 #endif // wxUSE_STREAMS
515 long wxExecute(const wxString
& command
, wxArrayString
& output
)
517 return wxDoExecuteWithCapture(command
, output
, NULL
);
520 long wxExecute(const wxString
& command
,
521 wxArrayString
& output
,
522 wxArrayString
& error
)
524 return wxDoExecuteWithCapture(command
, output
, &error
);
527 // ----------------------------------------------------------------------------
528 // wxApp::Yield() wrappers for backwards compatibility
529 // ----------------------------------------------------------------------------
533 return wxTheApp
&& wxTheApp
->Yield();
536 bool wxYieldIfNeeded()
538 return wxTheApp
&& wxTheApp
->Yield(TRUE
);
543 // ============================================================================
544 // GUI-only functions from now on
545 // ============================================================================
550 static long wxCurrentId
= 100;
555 return wxCurrentId
++;
559 wxGetCurrentId(void) { return wxCurrentId
; }
562 wxRegisterId (long id
)
564 if (id
>= wxCurrentId
)
565 wxCurrentId
= id
+ 1;
570 // ----------------------------------------------------------------------------
571 // Menu accelerators related functions
572 // ----------------------------------------------------------------------------
574 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
576 wxString s
= wxMenuItem::GetLabelFromText(in
);
579 // go smash their buffer if it's not big enough - I love char * params
580 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
584 // MYcopystring - for easier search...
585 out
= new wxChar
[s
.length() + 1];
586 wxStrcpy(out
, s
.c_str());
592 wxString
wxStripMenuCodes(const wxString
& in
)
596 size_t len
= in
.length();
599 for ( size_t n
= 0; n
< len
; n
++ )
604 // skip it, it is used to introduce the accel char (or to quote
605 // itself in which case it should still be skipped): note that it
606 // can't be the last character of the string
609 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
613 // use the next char instead
617 else if ( ch
== _T('\t') )
619 // everything after TAB is accel string, exit the loop
629 #endif // wxUSE_MENUS
631 // ----------------------------------------------------------------------------
632 // Window search functions
633 // ----------------------------------------------------------------------------
636 * If parent is non-NULL, look through children for a label or title
637 * matching the specified string. If NULL, look through all top-level windows.
642 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
644 return wxWindow::FindWindowByLabel( title
, parent
);
649 * If parent is non-NULL, look through children for a name
650 * matching the specified string. If NULL, look through all top-level windows.
655 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
657 return wxWindow::FindWindowByName( name
, parent
);
660 // Returns menu item id or -1 if none.
662 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
665 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
667 return menuBar
->FindMenuItem (menuString
, itemString
);
668 #endif // wxUSE_MENUS
673 // Try to find the deepest child that contains 'pt'.
674 // We go backwards, to try to allow for controls that are spacially
675 // within other controls, but are still siblings (e.g. buttons within
676 // static boxes). Static boxes are likely to be created _before_ controls
677 // that sit inside them.
678 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
683 // Hack for wxNotebook case: at least in wxGTK, all pages
684 // claim to be shown, so we must only deal with the selected one.
686 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
688 wxNotebook
* nb
= (wxNotebook
*) win
;
689 int sel
= nb
->GetSelection();
692 wxWindow
* child
= nb
->GetPage(sel
);
693 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
700 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetLast();
703 wxWindow
* child
= node
->GetData();
704 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
707 node
= node
->GetPrevious();
710 wxPoint pos
= win
->GetPosition();
711 wxSize sz
= win
->GetSize();
712 if (win
->GetParent())
714 pos
= win
->GetParent()->ClientToScreen(pos
);
717 wxRect
rect(pos
, sz
);
724 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
726 // Go backwards through the list since windows
727 // on top are likely to have been appended most
729 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetLast();
732 wxWindow
* win
= node
->GetData();
733 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
736 node
= node
->GetPrevious();
741 // ----------------------------------------------------------------------------
743 // ----------------------------------------------------------------------------
746 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
747 * since otherwise the generic code may be pulled in unnecessarily.
752 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
753 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
755 long decorated_style
= style
;
757 if ( ( style
& ( wxICON_EXCLAMATION
| wxICON_HAND
| wxICON_INFORMATION
| wxICON_QUESTION
) ) == 0 )
759 decorated_style
|= ( style
& wxYES
) ? wxICON_QUESTION
: wxICON_INFORMATION
;
762 wxMessageDialog
dialog(parent
, message
, caption
, decorated_style
);
764 int ans
= dialog
.ShowModal();
777 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
782 #endif // wxUSE_MSGDLG
786 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
787 const wxString
& defaultValue
, wxWindow
*parent
,
788 int x
, int y
, bool WXUNUSED(centre
) )
791 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, wxOK
|wxCANCEL
, wxPoint(x
, y
));
792 if (dialog
.ShowModal() == wxID_OK
)
794 str
= dialog
.GetValue();
800 wxString
wxGetPasswordFromUser(const wxString
& message
,
801 const wxString
& caption
,
802 const wxString
& defaultValue
,
806 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
807 wxOK
| wxCANCEL
| wxTE_PASSWORD
);
808 if ( dialog
.ShowModal() == wxID_OK
)
810 str
= dialog
.GetValue();
816 #endif // wxUSE_TEXTDLG
820 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
823 data
.SetChooseFull(TRUE
);
826 data
.SetColour((wxColour
&)colInit
); // const_cast
830 wxColourDialog
dialog(parent
, &data
);
831 if ( dialog
.ShowModal() == wxID_OK
)
833 colRet
= dialog
.GetColourData().GetColour();
835 //else: leave it invalid
840 #endif // wxUSE_COLOURDLG
844 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
849 data
.SetInitialFont(fontInit
);
853 wxFontDialog
dialog(parent
, data
);
854 if ( dialog
.ShowModal() == wxID_OK
)
856 fontRet
= dialog
.GetFontData().GetChosenFont();
858 //else: leave it invalid
863 #endif // wxUSE_FONTDLG
865 // ----------------------------------------------------------------------------
866 // wxSafeYield and supporting functions
867 // ----------------------------------------------------------------------------
869 void wxEnableTopLevelWindows(bool enable
)
871 wxWindowList::compatibility_iterator node
;
872 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
873 node
->GetData()->Enable(enable
);
876 wxWindowDisabler::wxWindowDisabler(wxWindow
*winToSkip
)
878 // remember the top level windows which were already disabled, so that we
879 // don't reenable them later
880 m_winDisabled
= NULL
;
882 wxWindowList::compatibility_iterator node
;
883 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
885 wxWindow
*winTop
= node
->GetData();
886 if ( winTop
== winToSkip
)
889 // we don't need to disable the hidden or already disabled windows
890 if ( winTop
->IsEnabled() && winTop
->IsShown() )
896 if ( !m_winDisabled
)
898 m_winDisabled
= new wxWindowList
;
901 m_winDisabled
->Append(winTop
);
906 wxWindowDisabler::~wxWindowDisabler()
908 wxWindowList::compatibility_iterator node
;
909 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
911 wxWindow
*winTop
= node
->GetData();
912 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
916 //else: had been already disabled, don't reenable
919 delete m_winDisabled
;
922 // Yield to other apps/messages and disable user input to all windows except
924 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
926 wxWindowDisabler
wd(win
);
930 rc
= wxYieldIfNeeded();
937 // Don't synthesize KeyUp events holding down a key and producing KeyDown
938 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
941 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
943 return TRUE
; // detectable auto-repeat is the only mode MSW supports