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 // ----------------------------------------------------------------------------
21 #pragma implementation "utils.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
33 #include "wx/string.h"
39 #include "wx/window.h"
42 #include "wx/msgdlg.h"
43 #include "wx/textdlg.h"
44 #include "wx/textctrl.h" // for wxTE_PASSWORD
46 #include "wx/menuitem.h"
52 #include "wx/apptrait.h"
54 #include "wx/process.h"
55 #include "wx/txtstrm.h"
62 #if !defined(__WATCOMC__)
63 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
69 #include "wx/colordlg.h"
70 #include "wx/fontdlg.h"
71 #include "wx/notebook.h"
73 #include "wx/statusbr.h"
79 #include "wx/msw/wince/time.h"
83 #include <sys/types.h>
92 #include "wx/msw/private.h"
97 // ----------------------------------------------------------------------------
99 // ----------------------------------------------------------------------------
101 #if WXWIN_COMPATIBILITY_2_2
102 const wxChar
*wxInternalErrorStr
= wxT("wxWindows Internal Error");
103 const wxChar
*wxFatalErrorStr
= wxT("wxWindows 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
= wxT("");
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
127 static long wxCurrentId
= 100;
132 return wxCurrentId
++;
136 wxGetCurrentId(void) { return wxCurrentId
; }
139 wxRegisterId (long id
)
141 if (id
>= wxCurrentId
)
142 wxCurrentId
= id
+ 1;
145 // ----------------------------------------------------------------------------
146 // String <-> Number conversions (deprecated)
147 // ----------------------------------------------------------------------------
149 #if WXWIN_COMPATIBILITY_2_4
151 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxFloatToStringStr
= wxT("%.2f");
152 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxDoubleToStringStr
= wxT("%.2f");
155 StringToFloat (const wxChar
*s
, float *number
)
157 if (s
&& *s
&& number
)
158 *number
= (float) wxStrtod (s
, (wxChar
**) NULL
);
162 StringToDouble (const wxChar
*s
, double *number
)
164 if (s
&& *s
&& number
)
165 *number
= wxStrtod (s
, (wxChar
**) NULL
);
169 FloatToString (float number
, const wxChar
*fmt
)
171 static wxChar buf
[256];
173 wxSprintf (buf
, fmt
, number
);
178 DoubleToString (double number
, const wxChar
*fmt
)
180 static wxChar buf
[256];
182 wxSprintf (buf
, fmt
, number
);
187 StringToInt (const wxChar
*s
, int *number
)
189 if (s
&& *s
&& number
)
190 *number
= (int) wxStrtol (s
, (wxChar
**) NULL
, 10);
194 StringToLong (const wxChar
*s
, long *number
)
196 if (s
&& *s
&& number
)
197 *number
= wxStrtol (s
, (wxChar
**) NULL
, 10);
201 IntToString (int number
)
203 static wxChar buf
[20];
205 wxSprintf (buf
, wxT("%d"), number
);
210 LongToString (long number
)
212 static wxChar buf
[20];
214 wxSprintf (buf
, wxT("%ld"), number
);
218 #endif // WXWIN_COMPATIBILITY_2_4
220 // Array used in DecToHex conversion routine.
221 static wxChar hexArray
[] = wxT("0123456789ABCDEF");
223 // Convert 2-digit hex number to decimal
224 int wxHexToDec(const wxString
& buf
)
226 int firstDigit
, secondDigit
;
228 if (buf
.GetChar(0) >= wxT('A'))
229 firstDigit
= buf
.GetChar(0) - wxT('A') + 10;
231 firstDigit
= buf
.GetChar(0) - wxT('0');
233 if (buf
.GetChar(1) >= wxT('A'))
234 secondDigit
= buf
.GetChar(1) - wxT('A') + 10;
236 secondDigit
= buf
.GetChar(1) - wxT('0');
238 return (firstDigit
& 0xF) * 16 + (secondDigit
& 0xF );
241 // Convert decimal integer to 2-character hex string
242 void wxDecToHex(int dec
, wxChar
*buf
)
244 int firstDigit
= (int)(dec
/16.0);
245 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
246 buf
[0] = hexArray
[firstDigit
];
247 buf
[1] = hexArray
[secondDigit
];
251 // Convert decimal integer to 2-character hex string
252 wxString
wxDecToHex(int dec
)
255 wxDecToHex(dec
, buf
);
256 return wxString(buf
);
259 // ----------------------------------------------------------------------------
261 // ----------------------------------------------------------------------------
263 // Return the current date/time
266 time_t now
= time((time_t *) NULL
);
267 char *date
= ctime(&now
);
269 return wxString
::FromAscii(date
);
272 const wxChar
*wxGetInstallPrefix()
276 if ( wxGetEnv(wxT("WXPREFIX"), &prefix
) )
277 return prefix
.c_str();
279 #ifdef wxINSTALL_PREFIX
280 return wxT(wxINSTALL_PREFIX
);
286 wxString
wxGetDataDir()
288 wxString format
= wxGetInstallPrefix();
289 format
<< wxFILE_SEP_PATH
290 << wxT("share") << wxFILE_SEP_PATH
291 << wxT("wx") << wxFILE_SEP_PATH
294 dir
.Printf(format
.c_str(), wxMAJOR_VERSION
, wxMINOR_VERSION
);
298 int wxGetOsVersion(int *verMaj
, int *verMin
)
300 // we want this function to work even if there is no wxApp
301 wxConsoleAppTraits traitsConsole
;
302 wxAppTraits
*traits
= wxTheApp ? wxTheApp
->GetTraits() : NULL
;
304 traits
= &traitsConsole
;
306 return traits
->GetOSVersion(verMaj
, verMin
);
309 // ----------------------------------------------------------------------------
310 // network and user id functions
311 // ----------------------------------------------------------------------------
313 // Get Full RFC822 style email address
314 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
316 wxString email
= wxGetEmailAddress();
320 wxStrncpy(address
, email
, maxSize
- 1);
321 address
[maxSize
- 1] = wxT('\0');
326 wxString
wxGetEmailAddress()
330 wxString host
= wxGetFullHostName();
333 wxString user
= wxGetUserId();
336 email
<< user
<< wxT('@') << host
;
343 wxString
wxGetUserId()
345 static const int maxLoginLen
= 256; // FIXME arbitrary number
348 bool ok
= wxGetUserId(buf
.GetWriteBuf(maxLoginLen
), maxLoginLen
);
357 wxString
wxGetUserName()
359 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
362 bool ok
= wxGetUserName(buf
.GetWriteBuf(maxUserNameLen
), maxUserNameLen
);
371 wxString
wxGetHostName()
373 static const size_t hostnameSize
= 257;
376 bool ok
= wxGetHostName(buf
.GetWriteBuf(hostnameSize
), hostnameSize
);
386 wxString
wxGetFullHostName()
388 static const size_t hostnameSize
= 257;
391 bool ok
= wxGetFullHostName(buf
.GetWriteBuf(hostnameSize
), hostnameSize
);
401 wxString
wxGetHomeDir()
411 wxString
wxGetCurrentDir()
418 ok
= getcwd(dir
.GetWriteBuf(len
+ 1), len
) != NULL
;
423 if ( errno
!= ERANGE
)
425 wxLogSysError(_T("Failed to get current directory"));
427 return wxEmptyString
;
431 // buffer was too small, retry with a larger one
443 // ----------------------------------------------------------------------------
445 // ----------------------------------------------------------------------------
447 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
449 // returns TRUE if ok, FALSE if error
451 static bool ReadAll(wxInputStream
*is
, wxArrayString
& output
)
453 wxCHECK_MSG( is
, FALSE
, _T("NULL stream in wxExecute()?") );
455 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
458 wxTextInputStream
tis(*is
);
463 wxString line
= tis
.ReadLine();
479 #endif // wxUSE_STREAMS
481 // this is a private function because it hasn't a clean interface: the first
482 // array is passed by reference, the second by pointer - instead we have 2
483 // public versions of wxExecute() below
484 static long wxDoExecuteWithCapture(const wxString
& command
,
485 wxArrayString
& output
,
486 wxArrayString
* error
)
488 // create a wxProcess which will capture the output
489 wxProcess
*process
= new wxProcess
;
492 long rc
= wxExecute(command
, wxEXEC_SYNC
, process
);
497 if ( !ReadAll(process
->GetInputStream(), output
) )
502 if ( !ReadAll(process
->GetErrorStream(), *error
) )
507 #endif // wxUSE_STREAMS
514 long wxExecute(const wxString
& command
, wxArrayString
& output
)
516 return wxDoExecuteWithCapture(command
, output
, NULL
);
519 long wxExecute(const wxString
& command
,
520 wxArrayString
& output
,
521 wxArrayString
& error
)
523 return wxDoExecuteWithCapture(command
, output
, &error
);
526 // ----------------------------------------------------------------------------
527 // wxApp::Yield() wrappers for backwards compatibility
528 // ----------------------------------------------------------------------------
532 return wxTheApp
&& wxTheApp
->Yield();
535 bool wxYieldIfNeeded()
537 return wxTheApp
&& wxTheApp
->Yield(TRUE
);
542 // ============================================================================
543 // GUI-only functions from now on
544 // ============================================================================
550 // ----------------------------------------------------------------------------
551 // Menu accelerators related functions
552 // ----------------------------------------------------------------------------
554 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
556 wxString s
= wxMenuItem
::GetLabelFromText(in
);
559 // go smash their buffer if it's not big enough - I love char * params
560 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
564 // MYcopystring - for easier search...
565 out
= new wxChar
[s
.length() + 1];
566 wxStrcpy(out
, s
.c_str());
572 wxString
wxStripMenuCodes(const wxString
& in
)
576 size_t len
= in
.length();
579 for ( size_t n
= 0; n
< len
; n
++ )
584 // skip it, it is used to introduce the accel char (or to quote
585 // itself in which case it should still be skipped): note that it
586 // can't be the last character of the string
589 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
593 // use the next char instead
597 else if ( ch
== _T('\t') )
599 // everything after TAB is accel string, exit the loop
609 #endif // wxUSE_MENUS
611 // ----------------------------------------------------------------------------
612 // Window search functions
613 // ----------------------------------------------------------------------------
616 * If parent is non-NULL, look through children for a label or title
617 * matching the specified string. If NULL, look through all top-level windows.
622 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
624 return wxWindow
::FindWindowByLabel( title
, parent
);
629 * If parent is non-NULL, look through children for a name
630 * matching the specified string. If NULL, look through all top-level windows.
635 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
637 return wxWindow
::FindWindowByName( name
, parent
);
640 // Returns menu item id or -1 if none.
642 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
645 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
647 return menuBar
->FindMenuItem (menuString
, itemString
);
648 #endif // wxUSE_MENUS
653 // Try to find the deepest child that contains 'pt'.
654 // We go backwards, to try to allow for controls that are spacially
655 // within other controls, but are still siblings (e.g. buttons within
656 // static boxes). Static boxes are likely to be created _before_ controls
657 // that sit inside them.
658 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
663 // Hack for wxNotebook case: at least in wxGTK, all pages
664 // claim to be shown, so we must only deal with the selected one.
666 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
668 wxNotebook
* nb
= (wxNotebook
*) win
;
669 int sel
= nb
->GetSelection();
672 wxWindow
* child
= nb
->GetPage(sel
);
673 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
680 wxWindowList
::compatibility_iterator node
= win
->GetChildren().GetLast();
683 wxWindow
* child
= node
->GetData();
684 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
687 node
= node
->GetPrevious();
690 wxPoint pos
= win
->GetPosition();
691 wxSize sz
= win
->GetSize();
692 if (win
->GetParent())
694 pos
= win
->GetParent()->ClientToScreen(pos
);
697 wxRect
rect(pos
, sz
);
704 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
706 // Go backwards through the list since windows
707 // on top are likely to have been appended most
709 wxWindowList
::compatibility_iterator node
= wxTopLevelWindows
.GetLast();
712 wxWindow
* win
= node
->GetData();
713 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
716 node
= node
->GetPrevious();
721 // ----------------------------------------------------------------------------
723 // ----------------------------------------------------------------------------
726 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
727 * since otherwise the generic code may be pulled in unnecessarily.
732 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
733 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
735 wxMessageDialog
dialog(parent
, message
, caption
, style
);
737 int ans
= dialog
.ShowModal();
750 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
755 #endif // wxUSE_MSGDLG
759 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
760 const wxString
& defaultValue
, wxWindow
*parent
,
761 int x
, int y
, bool WXUNUSED(centre
) )
764 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, wxOK
|wxCANCEL
, wxPoint(x
, y
));
765 if (dialog
.ShowModal() == wxID_OK
)
767 str
= dialog
.GetValue();
773 wxString
wxGetPasswordFromUser(const wxString
& message
,
774 const wxString
& caption
,
775 const wxString
& defaultValue
,
779 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
780 wxOK
| wxCANCEL
| wxTE_PASSWORD
);
781 if ( dialog
.ShowModal() == wxID_OK
)
783 str
= dialog
.GetValue();
789 #endif // wxUSE_TEXTDLG
793 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
796 data
.SetChooseFull(TRUE
);
799 data
.SetColour((wxColour
&)colInit
); // const_cast
803 wxColourDialog
dialog(parent
, &data
);
804 if ( dialog
.ShowModal() == wxID_OK
)
806 colRet
= dialog
.GetColourData().GetColour();
808 //else: leave it invalid
813 #endif // wxUSE_COLOURDLG
817 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
822 data
.SetInitialFont(fontInit
);
826 wxFontDialog
dialog(parent
, data
);
827 if ( dialog
.ShowModal() == wxID_OK
)
829 fontRet
= dialog
.GetFontData().GetChosenFont();
831 //else: leave it invalid
836 #endif // wxUSE_FONTDLG
838 // ----------------------------------------------------------------------------
839 // wxSafeYield and supporting functions
840 // ----------------------------------------------------------------------------
842 void wxEnableTopLevelWindows(bool enable
)
844 wxWindowList
::compatibility_iterator node
;
845 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
846 node
->GetData()->Enable(enable
);
849 wxWindowDisabler
::wxWindowDisabler(wxWindow
*winToSkip
)
851 // remember the top level windows which were already disabled, so that we
852 // don't reenable them later
853 m_winDisabled
= NULL
;
855 wxWindowList
::compatibility_iterator node
;
856 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
858 wxWindow
*winTop
= node
->GetData();
859 if ( winTop
== winToSkip
)
862 // we don't need to disable the hidden or already disabled windows
863 if ( winTop
->IsEnabled() && winTop
->IsShown() )
869 if ( !m_winDisabled
)
871 m_winDisabled
= new wxWindowList
;
874 m_winDisabled
->Append(winTop
);
879 wxWindowDisabler
::~wxWindowDisabler()
881 wxWindowList
::compatibility_iterator node
;
882 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
884 wxWindow
*winTop
= node
->GetData();
885 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
889 //else: had been already disabled, don't reenable
892 delete m_winDisabled
;
895 // Yield to other apps/messages and disable user input to all windows except
897 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
899 wxWindowDisabler
wd(win
);
903 rc
= wxYieldIfNeeded();
910 // Don't synthesize KeyUp events holding down a key and producing KeyDown
911 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
914 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
916 return TRUE
; // detectable auto-repeat is the only mode MSW supports