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"
57 #if defined(__WXWINCE__) && wxUSE_DATETIME
58 #include "wx/datetime.h"
66 #if !defined(__WATCOMC__)
67 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
73 #include "wx/colordlg.h"
74 #include "wx/fontdlg.h"
75 #include "wx/notebook.h"
77 #include "wx/statusbr.h"
83 #include "wx/msw/wince/time.h"
86 #if !defined(__MWERKS__) && !defined(__WXWINCE__)
87 #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
126 // ----------------------------------------------------------------------------
127 // String <-> Number conversions (deprecated)
128 // ----------------------------------------------------------------------------
130 #if WXWIN_COMPATIBILITY_2_4
132 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxFloatToStringStr
= wxT("%.2f");
133 WXDLLIMPEXP_DATA_BASE(const wxChar
*) wxDoubleToStringStr
= wxT("%.2f");
136 StringToFloat (const wxChar
*s
, float *number
)
138 if (s
&& *s
&& number
)
139 *number
= (float) wxStrtod (s
, (wxChar
**) NULL
);
143 StringToDouble (const wxChar
*s
, double *number
)
145 if (s
&& *s
&& number
)
146 *number
= wxStrtod (s
, (wxChar
**) NULL
);
150 FloatToString (float number
, const wxChar
*fmt
)
152 static wxChar buf
[256];
154 wxSprintf (buf
, fmt
, number
);
159 DoubleToString (double number
, const wxChar
*fmt
)
161 static wxChar buf
[256];
163 wxSprintf (buf
, fmt
, number
);
168 StringToInt (const wxChar
*s
, int *number
)
170 if (s
&& *s
&& number
)
171 *number
= (int) wxStrtol (s
, (wxChar
**) NULL
, 10);
175 StringToLong (const wxChar
*s
, long *number
)
177 if (s
&& *s
&& number
)
178 *number
= wxStrtol (s
, (wxChar
**) NULL
, 10);
182 IntToString (int number
)
184 static wxChar buf
[20];
186 wxSprintf (buf
, wxT("%d"), number
);
191 LongToString (long number
)
193 static wxChar buf
[20];
195 wxSprintf (buf
, wxT("%ld"), number
);
199 #endif // WXWIN_COMPATIBILITY_2_4
201 // Array used in DecToHex conversion routine.
202 static wxChar hexArray
[] = wxT("0123456789ABCDEF");
204 // Convert 2-digit hex number to decimal
205 int wxHexToDec(const wxString
& buf
)
207 int firstDigit
, secondDigit
;
209 if (buf
.GetChar(0) >= wxT('A'))
210 firstDigit
= buf
.GetChar(0) - wxT('A') + 10;
212 firstDigit
= buf
.GetChar(0) - wxT('0');
214 if (buf
.GetChar(1) >= wxT('A'))
215 secondDigit
= buf
.GetChar(1) - wxT('A') + 10;
217 secondDigit
= buf
.GetChar(1) - wxT('0');
219 return (firstDigit
& 0xF) * 16 + (secondDigit
& 0xF );
222 // Convert decimal integer to 2-character hex string
223 void wxDecToHex(int dec
, wxChar
*buf
)
225 int firstDigit
= (int)(dec
/16.0);
226 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
227 buf
[0] = hexArray
[firstDigit
];
228 buf
[1] = hexArray
[secondDigit
];
232 // Convert decimal integer to 2-character hex string
233 wxString
wxDecToHex(int dec
)
236 wxDecToHex(dec
, buf
);
237 return wxString(buf
);
240 // ----------------------------------------------------------------------------
242 // ----------------------------------------------------------------------------
244 // Return the current date/time
249 wxDateTime now
= wxDateTime::Now();
252 return wxEmptyString
;
255 time_t now
= time((time_t *) NULL
);
256 char *date
= ctime(&now
);
258 return wxString::FromAscii(date
);
262 const wxChar
*wxGetInstallPrefix()
266 if ( wxGetEnv(wxT("WXPREFIX"), &prefix
) )
267 return prefix
.c_str();
269 #ifdef wxINSTALL_PREFIX
270 return wxT(wxINSTALL_PREFIX
);
276 wxString
wxGetDataDir()
278 wxString format
= wxGetInstallPrefix();
279 format
<< wxFILE_SEP_PATH
280 << wxT("share") << wxFILE_SEP_PATH
281 << wxT("wx") << wxFILE_SEP_PATH
284 dir
.Printf(format
.c_str(), wxMAJOR_VERSION
, wxMINOR_VERSION
);
288 int wxGetOsVersion(int *verMaj
, int *verMin
)
290 // we want this function to work even if there is no wxApp
291 wxConsoleAppTraits traitsConsole
;
292 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
294 traits
= &traitsConsole
;
296 return traits
->GetOSVersion(verMaj
, verMin
);
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
)
472 // create a wxProcess which will capture the output
473 wxProcess
*process
= new wxProcess
;
476 long rc
= wxExecute(command
, wxEXEC_SYNC
, process
);
481 if ( !ReadAll(process
->GetInputStream(), output
) )
486 if ( !ReadAll(process
->GetErrorStream(), *error
) )
491 #endif // wxUSE_STREAMS
498 long wxExecute(const wxString
& command
, wxArrayString
& output
)
500 return wxDoExecuteWithCapture(command
, output
, NULL
);
503 long wxExecute(const wxString
& command
,
504 wxArrayString
& output
,
505 wxArrayString
& error
)
507 return wxDoExecuteWithCapture(command
, output
, &error
);
510 // ----------------------------------------------------------------------------
511 // wxApp::Yield() wrappers for backwards compatibility
512 // ----------------------------------------------------------------------------
516 return wxTheApp
&& wxTheApp
->Yield();
519 bool wxYieldIfNeeded()
521 return wxTheApp
&& wxTheApp
->Yield(TRUE
);
526 // ============================================================================
527 // GUI-only functions from now on
528 // ============================================================================
533 static long wxCurrentId
= 100;
538 return wxCurrentId
++;
542 wxGetCurrentId(void) { return wxCurrentId
; }
545 wxRegisterId (long id
)
547 if (id
>= wxCurrentId
)
548 wxCurrentId
= id
+ 1;
553 // ----------------------------------------------------------------------------
554 // Menu accelerators related functions
555 // ----------------------------------------------------------------------------
557 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
559 wxString s
= wxMenuItem::GetLabelFromText(in
);
562 // go smash their buffer if it's not big enough - I love char * params
563 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
567 // MYcopystring - for easier search...
568 out
= new wxChar
[s
.length() + 1];
569 wxStrcpy(out
, s
.c_str());
575 wxString
wxStripMenuCodes(const wxString
& in
)
579 size_t len
= in
.length();
582 for ( size_t n
= 0; n
< len
; n
++ )
587 // skip it, it is used to introduce the accel char (or to quote
588 // itself in which case it should still be skipped): note that it
589 // can't be the last character of the string
592 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
596 // use the next char instead
600 else if ( ch
== _T('\t') )
602 // everything after TAB is accel string, exit the loop
612 #endif // wxUSE_MENUS
614 // ----------------------------------------------------------------------------
615 // Window search functions
616 // ----------------------------------------------------------------------------
619 * If parent is non-NULL, look through children for a label or title
620 * matching the specified string. If NULL, look through all top-level windows.
625 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
627 return wxWindow::FindWindowByLabel( title
, parent
);
632 * If parent is non-NULL, look through children for a name
633 * matching the specified string. If NULL, look through all top-level windows.
638 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
640 return wxWindow::FindWindowByName( name
, parent
);
643 // Returns menu item id or -1 if none.
645 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
648 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
650 return menuBar
->FindMenuItem (menuString
, itemString
);
651 #endif // wxUSE_MENUS
656 // Try to find the deepest child that contains 'pt'.
657 // We go backwards, to try to allow for controls that are spacially
658 // within other controls, but are still siblings (e.g. buttons within
659 // static boxes). Static boxes are likely to be created _before_ controls
660 // that sit inside them.
661 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
666 // Hack for wxNotebook case: at least in wxGTK, all pages
667 // claim to be shown, so we must only deal with the selected one.
669 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
671 wxNotebook
* nb
= (wxNotebook
*) win
;
672 int sel
= nb
->GetSelection();
675 wxWindow
* child
= nb
->GetPage(sel
);
676 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
683 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetLast();
686 wxWindow
* child
= node
->GetData();
687 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
690 node
= node
->GetPrevious();
693 wxPoint pos
= win
->GetPosition();
694 wxSize sz
= win
->GetSize();
695 if (win
->GetParent())
697 pos
= win
->GetParent()->ClientToScreen(pos
);
700 wxRect
rect(pos
, sz
);
707 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
709 // Go backwards through the list since windows
710 // on top are likely to have been appended most
712 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetLast();
715 wxWindow
* win
= node
->GetData();
716 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
719 node
= node
->GetPrevious();
724 // ----------------------------------------------------------------------------
726 // ----------------------------------------------------------------------------
729 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
730 * since otherwise the generic code may be pulled in unnecessarily.
735 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
736 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
738 wxMessageDialog
dialog(parent
, message
, caption
, style
);
740 int ans
= dialog
.ShowModal();
753 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
758 #endif // wxUSE_MSGDLG
762 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
763 const wxString
& defaultValue
, wxWindow
*parent
,
764 int x
, int y
, bool WXUNUSED(centre
) )
767 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, wxOK
|wxCANCEL
, wxPoint(x
, y
));
768 if (dialog
.ShowModal() == wxID_OK
)
770 str
= dialog
.GetValue();
776 wxString
wxGetPasswordFromUser(const wxString
& message
,
777 const wxString
& caption
,
778 const wxString
& defaultValue
,
782 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
783 wxOK
| wxCANCEL
| wxTE_PASSWORD
);
784 if ( dialog
.ShowModal() == wxID_OK
)
786 str
= dialog
.GetValue();
792 #endif // wxUSE_TEXTDLG
796 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
799 data
.SetChooseFull(TRUE
);
802 data
.SetColour((wxColour
&)colInit
); // const_cast
806 wxColourDialog
dialog(parent
, &data
);
807 if ( dialog
.ShowModal() == wxID_OK
)
809 colRet
= dialog
.GetColourData().GetColour();
811 //else: leave it invalid
816 #endif // wxUSE_COLOURDLG
820 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
825 data
.SetInitialFont(fontInit
);
829 wxFontDialog
dialog(parent
, data
);
830 if ( dialog
.ShowModal() == wxID_OK
)
832 fontRet
= dialog
.GetFontData().GetChosenFont();
834 //else: leave it invalid
839 #endif // wxUSE_FONTDLG
841 // ----------------------------------------------------------------------------
842 // wxSafeYield and supporting functions
843 // ----------------------------------------------------------------------------
845 void wxEnableTopLevelWindows(bool enable
)
847 wxWindowList::compatibility_iterator node
;
848 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
849 node
->GetData()->Enable(enable
);
852 wxWindowDisabler::wxWindowDisabler(wxWindow
*winToSkip
)
854 // remember the top level windows which were already disabled, so that we
855 // don't reenable them later
856 m_winDisabled
= NULL
;
858 wxWindowList::compatibility_iterator node
;
859 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
861 wxWindow
*winTop
= node
->GetData();
862 if ( winTop
== winToSkip
)
865 // we don't need to disable the hidden or already disabled windows
866 if ( winTop
->IsEnabled() && winTop
->IsShown() )
872 if ( !m_winDisabled
)
874 m_winDisabled
= new wxWindowList
;
877 m_winDisabled
->Append(winTop
);
882 wxWindowDisabler::~wxWindowDisabler()
884 wxWindowList::compatibility_iterator node
;
885 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
887 wxWindow
*winTop
= node
->GetData();
888 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
892 //else: had been already disabled, don't reenable
895 delete m_winDisabled
;
898 // Yield to other apps/messages and disable user input to all windows except
900 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
902 wxWindowDisabler
wd(win
);
906 rc
= wxYieldIfNeeded();
913 // Don't synthesize KeyUp events holding down a key and producing KeyDown
914 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
917 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
919 return TRUE
; // detectable auto-repeat is the only mode MSW supports