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)
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 wxToolkitInfo
& info
= traits
->GetToolkitInfo();
298 *verMaj
= info
.versionMajor
;
300 *verMin
= info
.versionMinor
;
304 // ----------------------------------------------------------------------------
305 // network and user id functions
306 // ----------------------------------------------------------------------------
308 // Get Full RFC822 style email address
309 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
311 wxString email
= wxGetEmailAddress();
315 wxStrncpy(address
, email
, maxSize
- 1);
316 address
[maxSize
- 1] = wxT('\0');
321 wxString
wxGetEmailAddress()
325 wxString host
= wxGetFullHostName();
328 wxString user
= wxGetUserId();
331 email
<< user
<< wxT('@') << host
;
338 wxString
wxGetUserId()
340 static const int maxLoginLen
= 256; // FIXME arbitrary number
343 bool ok
= wxGetUserId(wxStringBuffer(buf
, maxLoginLen
), maxLoginLen
);
351 wxString
wxGetUserName()
353 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
356 bool ok
= wxGetUserName(wxStringBuffer(buf
, maxUserNameLen
), maxUserNameLen
);
364 wxString
wxGetHostName()
366 static const size_t hostnameSize
= 257;
369 bool ok
= wxGetHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
377 wxString
wxGetFullHostName()
379 static const size_t hostnameSize
= 257;
382 bool ok
= wxGetFullHostName(wxStringBuffer(buf
, hostnameSize
), hostnameSize
);
390 wxString
wxGetHomeDir()
400 wxString
wxGetCurrentDir()
407 ok
= getcwd(dir
.GetWriteBuf(len
+ 1), len
) != NULL
;
412 if ( errno
!= ERANGE
)
414 wxLogSysError(_T("Failed to get current directory"));
416 return wxEmptyString
;
420 // buffer was too small, retry with a larger one
432 // ----------------------------------------------------------------------------
434 // ----------------------------------------------------------------------------
436 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
438 // returns TRUE if ok, FALSE if error
440 static bool ReadAll(wxInputStream
*is
, wxArrayString
& output
)
442 wxCHECK_MSG( is
, FALSE
, _T("NULL stream in wxExecute()?") );
444 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
447 wxTextInputStream
tis(*is
);
452 wxString line
= tis
.ReadLine();
468 #endif // wxUSE_STREAMS
470 // this is a private function because it hasn't a clean interface: the first
471 // array is passed by reference, the second by pointer - instead we have 2
472 // public versions of wxExecute() below
473 static long wxDoExecuteWithCapture(const wxString
& command
,
474 wxArrayString
& output
,
475 wxArrayString
* error
)
477 // create a wxProcess which will capture the output
478 wxProcess
*process
= new wxProcess
;
481 long rc
= wxExecute(command
, wxEXEC_SYNC
, process
);
486 if ( !ReadAll(process
->GetInputStream(), output
) )
491 if ( !ReadAll(process
->GetErrorStream(), *error
) )
496 #endif // wxUSE_STREAMS
503 long wxExecute(const wxString
& command
, wxArrayString
& output
)
505 return wxDoExecuteWithCapture(command
, output
, NULL
);
508 long wxExecute(const wxString
& command
,
509 wxArrayString
& output
,
510 wxArrayString
& error
)
512 return wxDoExecuteWithCapture(command
, output
, &error
);
515 // ----------------------------------------------------------------------------
516 // wxApp::Yield() wrappers for backwards compatibility
517 // ----------------------------------------------------------------------------
521 return wxTheApp
&& wxTheApp
->Yield();
524 bool wxYieldIfNeeded()
526 return wxTheApp
&& wxTheApp
->Yield(TRUE
);
531 // ============================================================================
532 // GUI-only functions from now on
533 // ============================================================================
538 static long wxCurrentId
= 100;
543 return wxCurrentId
++;
547 wxGetCurrentId(void) { return wxCurrentId
; }
550 wxRegisterId (long id
)
552 if (id
>= wxCurrentId
)
553 wxCurrentId
= id
+ 1;
558 // ----------------------------------------------------------------------------
559 // Menu accelerators related functions
560 // ----------------------------------------------------------------------------
562 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
564 wxString s
= wxMenuItem::GetLabelFromText(in
);
567 // go smash their buffer if it's not big enough - I love char * params
568 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
572 // MYcopystring - for easier search...
573 out
= new wxChar
[s
.length() + 1];
574 wxStrcpy(out
, s
.c_str());
580 wxString
wxStripMenuCodes(const wxString
& in
)
584 size_t len
= in
.length();
587 for ( size_t n
= 0; n
< len
; n
++ )
592 // skip it, it is used to introduce the accel char (or to quote
593 // itself in which case it should still be skipped): note that it
594 // can't be the last character of the string
597 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
601 // use the next char instead
605 else if ( ch
== _T('\t') )
607 // everything after TAB is accel string, exit the loop
617 #endif // wxUSE_MENUS
619 // ----------------------------------------------------------------------------
620 // Window search functions
621 // ----------------------------------------------------------------------------
624 * If parent is non-NULL, look through children for a label or title
625 * matching the specified string. If NULL, look through all top-level windows.
630 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
632 return wxWindow::FindWindowByLabel( title
, parent
);
637 * If parent is non-NULL, look through children for a name
638 * matching the specified string. If NULL, look through all top-level windows.
643 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
645 return wxWindow::FindWindowByName( name
, parent
);
648 // Returns menu item id or -1 if none.
650 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
653 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
655 return menuBar
->FindMenuItem (menuString
, itemString
);
656 #endif // wxUSE_MENUS
661 // Try to find the deepest child that contains 'pt'.
662 // We go backwards, to try to allow for controls that are spacially
663 // within other controls, but are still siblings (e.g. buttons within
664 // static boxes). Static boxes are likely to be created _before_ controls
665 // that sit inside them.
666 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
671 // Hack for wxNotebook case: at least in wxGTK, all pages
672 // claim to be shown, so we must only deal with the selected one.
674 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
676 wxNotebook
* nb
= (wxNotebook
*) win
;
677 int sel
= nb
->GetSelection();
680 wxWindow
* child
= nb
->GetPage(sel
);
681 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
688 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetLast();
691 wxWindow
* child
= node
->GetData();
692 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
695 node
= node
->GetPrevious();
698 wxPoint pos
= win
->GetPosition();
699 wxSize sz
= win
->GetSize();
700 if (win
->GetParent())
702 pos
= win
->GetParent()->ClientToScreen(pos
);
705 wxRect
rect(pos
, sz
);
712 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
714 // Go backwards through the list since windows
715 // on top are likely to have been appended most
717 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetLast();
720 wxWindow
* win
= node
->GetData();
721 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
724 node
= node
->GetPrevious();
729 // ----------------------------------------------------------------------------
731 // ----------------------------------------------------------------------------
734 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
735 * since otherwise the generic code may be pulled in unnecessarily.
740 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
741 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
743 wxMessageDialog
dialog(parent
, message
, caption
, style
);
745 int ans
= dialog
.ShowModal();
758 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
763 #endif // wxUSE_MSGDLG
767 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
768 const wxString
& defaultValue
, wxWindow
*parent
,
769 int x
, int y
, bool WXUNUSED(centre
) )
772 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, wxOK
|wxCANCEL
, wxPoint(x
, y
));
773 if (dialog
.ShowModal() == wxID_OK
)
775 str
= dialog
.GetValue();
781 wxString
wxGetPasswordFromUser(const wxString
& message
,
782 const wxString
& caption
,
783 const wxString
& defaultValue
,
787 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
788 wxOK
| wxCANCEL
| wxTE_PASSWORD
);
789 if ( dialog
.ShowModal() == wxID_OK
)
791 str
= dialog
.GetValue();
797 #endif // wxUSE_TEXTDLG
801 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
804 data
.SetChooseFull(TRUE
);
807 data
.SetColour((wxColour
&)colInit
); // const_cast
811 wxColourDialog
dialog(parent
, &data
);
812 if ( dialog
.ShowModal() == wxID_OK
)
814 colRet
= dialog
.GetColourData().GetColour();
816 //else: leave it invalid
821 #endif // wxUSE_COLOURDLG
825 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
830 data
.SetInitialFont(fontInit
);
834 wxFontDialog
dialog(parent
, data
);
835 if ( dialog
.ShowModal() == wxID_OK
)
837 fontRet
= dialog
.GetFontData().GetChosenFont();
839 //else: leave it invalid
844 #endif // wxUSE_FONTDLG
846 // ----------------------------------------------------------------------------
847 // wxSafeYield and supporting functions
848 // ----------------------------------------------------------------------------
850 void wxEnableTopLevelWindows(bool enable
)
852 wxWindowList::compatibility_iterator node
;
853 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
854 node
->GetData()->Enable(enable
);
857 wxWindowDisabler::wxWindowDisabler(wxWindow
*winToSkip
)
859 // remember the top level windows which were already disabled, so that we
860 // don't reenable them later
861 m_winDisabled
= NULL
;
863 wxWindowList::compatibility_iterator node
;
864 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
866 wxWindow
*winTop
= node
->GetData();
867 if ( winTop
== winToSkip
)
870 // we don't need to disable the hidden or already disabled windows
871 if ( winTop
->IsEnabled() && winTop
->IsShown() )
877 if ( !m_winDisabled
)
879 m_winDisabled
= new wxWindowList
;
882 m_winDisabled
->Append(winTop
);
887 wxWindowDisabler::~wxWindowDisabler()
889 wxWindowList::compatibility_iterator node
;
890 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
892 wxWindow
*winTop
= node
->GetData();
893 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
897 //else: had been already disabled, don't reenable
900 delete m_winDisabled
;
903 // Yield to other apps/messages and disable user input to all windows except
905 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
907 wxWindowDisabler
wd(win
);
911 rc
= wxYieldIfNeeded();
918 // Don't synthesize KeyUp events holding down a key and producing KeyDown
919 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
922 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
924 return TRUE
; // detectable auto-repeat is the only mode MSW supports