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 const wxChar
*wxGetInstallPrefix()
273 if ( wxGetEnv(wxT("WXPREFIX"), &prefix
) )
274 return prefix
.c_str();
276 #ifdef wxINSTALL_PREFIX
277 return wxT(wxINSTALL_PREFIX
);
283 wxString
wxGetDataDir()
285 wxString format
= wxGetInstallPrefix();
286 format
<< wxFILE_SEP_PATH
287 << wxT("share") << wxFILE_SEP_PATH
288 << wxT("wx") << wxFILE_SEP_PATH
291 dir
.Printf(format
.c_str(), wxMAJOR_VERSION
, wxMINOR_VERSION
);
295 int wxGetOsVersion(int *verMaj
, int *verMin
)
297 // we want this function to work even if there is no wxApp
298 wxConsoleAppTraits traitsConsole
;
299 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
301 traits
= &traitsConsole
;
303 wxToolkitInfo
& info
= traits
->GetToolkitInfo();
305 *verMaj
= info
.versionMajor
;
307 *verMin
= info
.versionMinor
;
311 // ----------------------------------------------------------------------------
312 // network and user id functions
313 // ----------------------------------------------------------------------------
315 // Get Full RFC822 style email address
316 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
318 wxString email
= wxGetEmailAddress();
322 wxStrncpy(address
, email
, maxSize
- 1);
323 address
[maxSize
- 1] = wxT('\0');
328 wxString
wxGetEmailAddress()
332 wxString host
= wxGetFullHostName();
335 wxString user
= wxGetUserId();
338 email
<< user
<< wxT('@') << host
;
345 wxString
wxGetUserId()
347 static const int maxLoginLen
= 256; // FIXME arbitrary number
350 bool ok
= wxGetUserId(wxStringBuffer(buf
, maxLoginLen
), maxLoginLen
);
358 wxString
wxGetUserName()
360 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
363 bool ok
= wxGetUserName(wxStringBuffer(buf
, maxUserNameLen
), maxUserNameLen
);
371 wxString
wxGetHostName()
373 static const size_t hostnameSize
= 257;
376 bool ok
= wxGetHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
384 wxString
wxGetFullHostName()
386 static const size_t hostnameSize
= 257;
389 bool ok
= wxGetFullHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
397 wxString
wxGetHomeDir()
407 wxString
wxGetCurrentDir()
414 ok
= getcwd(dir
.GetWriteBuf(len
+ 1), len
) != NULL
;
419 if ( errno
!= ERANGE
)
421 wxLogSysError(_T("Failed to get current directory"));
423 return wxEmptyString
;
427 // buffer was too small, retry with a larger one
439 // ----------------------------------------------------------------------------
441 // ----------------------------------------------------------------------------
443 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
445 // returns TRUE if ok, FALSE if error
447 static bool ReadAll(wxInputStream
*is
, wxArrayString
& output
)
449 wxCHECK_MSG( is
, FALSE
, _T("NULL stream in wxExecute()?") );
451 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
454 wxTextInputStream
tis(*is
);
459 wxString line
= tis
.ReadLine();
475 #endif // wxUSE_STREAMS
477 // this is a private function because it hasn't a clean interface: the first
478 // array is passed by reference, the second by pointer - instead we have 2
479 // public versions of wxExecute() below
480 static long wxDoExecuteWithCapture(const wxString
& command
,
481 wxArrayString
& output
,
482 wxArrayString
* error
)
484 // create a wxProcess which will capture the output
485 wxProcess
*process
= new wxProcess
;
488 long rc
= wxExecute(command
, wxEXEC_SYNC
, process
);
493 if ( !ReadAll(process
->GetInputStream(), output
) )
498 if ( !ReadAll(process
->GetErrorStream(), *error
) )
503 #endif // wxUSE_STREAMS
510 long wxExecute(const wxString
& command
, wxArrayString
& output
)
512 return wxDoExecuteWithCapture(command
, output
, NULL
);
515 long wxExecute(const wxString
& command
,
516 wxArrayString
& output
,
517 wxArrayString
& error
)
519 return wxDoExecuteWithCapture(command
, output
, &error
);
522 // ----------------------------------------------------------------------------
523 // wxApp::Yield() wrappers for backwards compatibility
524 // ----------------------------------------------------------------------------
528 return wxTheApp
&& wxTheApp
->Yield();
531 bool wxYieldIfNeeded()
533 return wxTheApp
&& wxTheApp
->Yield(TRUE
);
538 // ============================================================================
539 // GUI-only functions from now on
540 // ============================================================================
545 static long wxCurrentId
= 100;
550 return wxCurrentId
++;
554 wxGetCurrentId(void) { return wxCurrentId
; }
557 wxRegisterId (long id
)
559 if (id
>= wxCurrentId
)
560 wxCurrentId
= id
+ 1;
565 // ----------------------------------------------------------------------------
566 // Menu accelerators related functions
567 // ----------------------------------------------------------------------------
569 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
571 wxString s
= wxMenuItem::GetLabelFromText(in
);
574 // go smash their buffer if it's not big enough - I love char * params
575 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
579 // MYcopystring - for easier search...
580 out
= new wxChar
[s
.length() + 1];
581 wxStrcpy(out
, s
.c_str());
587 wxString
wxStripMenuCodes(const wxString
& in
)
591 size_t len
= in
.length();
594 for ( size_t n
= 0; n
< len
; n
++ )
599 // skip it, it is used to introduce the accel char (or to quote
600 // itself in which case it should still be skipped): note that it
601 // can't be the last character of the string
604 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
608 // use the next char instead
612 else if ( ch
== _T('\t') )
614 // everything after TAB is accel string, exit the loop
624 #endif // wxUSE_MENUS
626 // ----------------------------------------------------------------------------
627 // Window search functions
628 // ----------------------------------------------------------------------------
631 * If parent is non-NULL, look through children for a label or title
632 * matching the specified string. If NULL, look through all top-level windows.
637 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
639 return wxWindow::FindWindowByLabel( title
, parent
);
644 * If parent is non-NULL, look through children for a name
645 * matching the specified string. If NULL, look through all top-level windows.
650 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
652 return wxWindow::FindWindowByName( name
, parent
);
655 // Returns menu item id or -1 if none.
657 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
660 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
662 return menuBar
->FindMenuItem (menuString
, itemString
);
663 #endif // wxUSE_MENUS
668 // Try to find the deepest child that contains 'pt'.
669 // We go backwards, to try to allow for controls that are spacially
670 // within other controls, but are still siblings (e.g. buttons within
671 // static boxes). Static boxes are likely to be created _before_ controls
672 // that sit inside them.
673 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
678 // Hack for wxNotebook case: at least in wxGTK, all pages
679 // claim to be shown, so we must only deal with the selected one.
681 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
683 wxNotebook
* nb
= (wxNotebook
*) win
;
684 int sel
= nb
->GetSelection();
687 wxWindow
* child
= nb
->GetPage(sel
);
688 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
695 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetLast();
698 wxWindow
* child
= node
->GetData();
699 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
702 node
= node
->GetPrevious();
705 wxPoint pos
= win
->GetPosition();
706 wxSize sz
= win
->GetSize();
707 if (win
->GetParent())
709 pos
= win
->GetParent()->ClientToScreen(pos
);
712 wxRect
rect(pos
, sz
);
719 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
721 // Go backwards through the list since windows
722 // on top are likely to have been appended most
724 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetLast();
727 wxWindow
* win
= node
->GetData();
728 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
731 node
= node
->GetPrevious();
736 // ----------------------------------------------------------------------------
738 // ----------------------------------------------------------------------------
741 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
742 * since otherwise the generic code may be pulled in unnecessarily.
747 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
748 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
750 wxMessageDialog
dialog(parent
, message
, caption
, style
);
752 int ans
= dialog
.ShowModal();
765 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
770 #endif // wxUSE_MSGDLG
774 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
775 const wxString
& defaultValue
, wxWindow
*parent
,
776 int x
, int y
, bool WXUNUSED(centre
) )
779 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, wxOK
|wxCANCEL
, wxPoint(x
, y
));
780 if (dialog
.ShowModal() == wxID_OK
)
782 str
= dialog
.GetValue();
788 wxString
wxGetPasswordFromUser(const wxString
& message
,
789 const wxString
& caption
,
790 const wxString
& defaultValue
,
794 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
795 wxOK
| wxCANCEL
| wxTE_PASSWORD
);
796 if ( dialog
.ShowModal() == wxID_OK
)
798 str
= dialog
.GetValue();
804 #endif // wxUSE_TEXTDLG
808 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
811 data
.SetChooseFull(TRUE
);
814 data
.SetColour((wxColour
&)colInit
); // const_cast
818 wxColourDialog
dialog(parent
, &data
);
819 if ( dialog
.ShowModal() == wxID_OK
)
821 colRet
= dialog
.GetColourData().GetColour();
823 //else: leave it invalid
828 #endif // wxUSE_COLOURDLG
832 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
837 data
.SetInitialFont(fontInit
);
841 wxFontDialog
dialog(parent
, data
);
842 if ( dialog
.ShowModal() == wxID_OK
)
844 fontRet
= dialog
.GetFontData().GetChosenFont();
846 //else: leave it invalid
851 #endif // wxUSE_FONTDLG
853 // ----------------------------------------------------------------------------
854 // wxSafeYield and supporting functions
855 // ----------------------------------------------------------------------------
857 void wxEnableTopLevelWindows(bool enable
)
859 wxWindowList::compatibility_iterator node
;
860 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
861 node
->GetData()->Enable(enable
);
864 wxWindowDisabler::wxWindowDisabler(wxWindow
*winToSkip
)
866 // remember the top level windows which were already disabled, so that we
867 // don't reenable them later
868 m_winDisabled
= NULL
;
870 wxWindowList::compatibility_iterator node
;
871 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
873 wxWindow
*winTop
= node
->GetData();
874 if ( winTop
== winToSkip
)
877 // we don't need to disable the hidden or already disabled windows
878 if ( winTop
->IsEnabled() && winTop
->IsShown() )
884 if ( !m_winDisabled
)
886 m_winDisabled
= new wxWindowList
;
889 m_winDisabled
->Append(winTop
);
894 wxWindowDisabler::~wxWindowDisabler()
896 wxWindowList::compatibility_iterator node
;
897 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
899 wxWindow
*winTop
= node
->GetData();
900 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
904 //else: had been already disabled, don't reenable
907 delete m_winDisabled
;
910 // Yield to other apps/messages and disable user input to all windows except
912 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
914 wxWindowDisabler
wd(win
);
918 rc
= wxYieldIfNeeded();
925 // Don't synthesize KeyUp events holding down a key and producing KeyDown
926 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
929 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
931 return TRUE
; // detectable auto-repeat is the only mode MSW supports