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
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
268 wxDateTime now
= wxDateTime::Now();
271 return wxEmptyString
;
274 time_t now
= time((time_t *) NULL
);
275 char *date
= ctime(&now
);
277 return wxString::FromAscii(date
);
281 const wxChar
*wxGetInstallPrefix()
285 if ( wxGetEnv(wxT("WXPREFIX"), &prefix
) )
286 return prefix
.c_str();
288 #ifdef wxINSTALL_PREFIX
289 return wxT(wxINSTALL_PREFIX
);
295 wxString
wxGetDataDir()
297 wxString format
= wxGetInstallPrefix();
298 format
<< wxFILE_SEP_PATH
299 << wxT("share") << wxFILE_SEP_PATH
300 << wxT("wx") << wxFILE_SEP_PATH
303 dir
.Printf(format
.c_str(), wxMAJOR_VERSION
, wxMINOR_VERSION
);
307 int wxGetOsVersion(int *verMaj
, int *verMin
)
309 // we want this function to work even if there is no wxApp
310 wxConsoleAppTraits traitsConsole
;
311 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
313 traits
= &traitsConsole
;
315 return traits
->GetOSVersion(verMaj
, verMin
);
318 // ----------------------------------------------------------------------------
319 // network and user id functions
320 // ----------------------------------------------------------------------------
322 // Get Full RFC822 style email address
323 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
325 wxString email
= wxGetEmailAddress();
329 wxStrncpy(address
, email
, maxSize
- 1);
330 address
[maxSize
- 1] = wxT('\0');
335 wxString
wxGetEmailAddress()
339 wxString host
= wxGetFullHostName();
342 wxString user
= wxGetUserId();
345 email
<< user
<< wxT('@') << host
;
352 wxString
wxGetUserId()
354 static const int maxLoginLen
= 256; // FIXME arbitrary number
357 bool ok
= wxGetUserId(buf
.GetWriteBuf(maxLoginLen
), maxLoginLen
);
366 wxString
wxGetUserName()
368 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
371 bool ok
= wxGetUserName(buf
.GetWriteBuf(maxUserNameLen
), maxUserNameLen
);
380 wxString
wxGetHostName()
382 static const size_t hostnameSize
= 257;
385 bool ok
= wxGetHostName(buf
.GetWriteBuf(hostnameSize
), hostnameSize
);
395 wxString
wxGetFullHostName()
397 static const size_t hostnameSize
= 257;
400 bool ok
= wxGetFullHostName(buf
.GetWriteBuf(hostnameSize
), hostnameSize
);
410 wxString
wxGetHomeDir()
420 wxString
wxGetCurrentDir()
427 ok
= getcwd(dir
.GetWriteBuf(len
+ 1), len
) != NULL
;
432 if ( errno
!= ERANGE
)
434 wxLogSysError(_T("Failed to get current directory"));
436 return wxEmptyString
;
440 // buffer was too small, retry with a larger one
452 // ----------------------------------------------------------------------------
454 // ----------------------------------------------------------------------------
456 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
458 // returns TRUE if ok, FALSE if error
460 static bool ReadAll(wxInputStream
*is
, wxArrayString
& output
)
462 wxCHECK_MSG( is
, FALSE
, _T("NULL stream in wxExecute()?") );
464 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
467 wxTextInputStream
tis(*is
);
472 wxString line
= tis
.ReadLine();
488 #endif // wxUSE_STREAMS
490 // this is a private function because it hasn't a clean interface: the first
491 // array is passed by reference, the second by pointer - instead we have 2
492 // public versions of wxExecute() below
493 static long wxDoExecuteWithCapture(const wxString
& command
,
494 wxArrayString
& output
,
495 wxArrayString
* error
)
497 // create a wxProcess which will capture the output
498 wxProcess
*process
= new wxProcess
;
501 long rc
= wxExecute(command
, wxEXEC_SYNC
, process
);
506 if ( !ReadAll(process
->GetInputStream(), output
) )
511 if ( !ReadAll(process
->GetErrorStream(), *error
) )
516 #endif // wxUSE_STREAMS
523 long wxExecute(const wxString
& command
, wxArrayString
& output
)
525 return wxDoExecuteWithCapture(command
, output
, NULL
);
528 long wxExecute(const wxString
& command
,
529 wxArrayString
& output
,
530 wxArrayString
& error
)
532 return wxDoExecuteWithCapture(command
, output
, &error
);
535 // ----------------------------------------------------------------------------
536 // wxApp::Yield() wrappers for backwards compatibility
537 // ----------------------------------------------------------------------------
541 return wxTheApp
&& wxTheApp
->Yield();
544 bool wxYieldIfNeeded()
546 return wxTheApp
&& wxTheApp
->Yield(TRUE
);
551 // ============================================================================
552 // GUI-only functions from now on
553 // ============================================================================
559 // ----------------------------------------------------------------------------
560 // Menu accelerators related functions
561 // ----------------------------------------------------------------------------
563 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
565 wxString s
= wxMenuItem::GetLabelFromText(in
);
568 // go smash their buffer if it's not big enough - I love char * params
569 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
573 // MYcopystring - for easier search...
574 out
= new wxChar
[s
.length() + 1];
575 wxStrcpy(out
, s
.c_str());
581 wxString
wxStripMenuCodes(const wxString
& in
)
585 size_t len
= in
.length();
588 for ( size_t n
= 0; n
< len
; n
++ )
593 // skip it, it is used to introduce the accel char (or to quote
594 // itself in which case it should still be skipped): note that it
595 // can't be the last character of the string
598 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
602 // use the next char instead
606 else if ( ch
== _T('\t') )
608 // everything after TAB is accel string, exit the loop
618 #endif // wxUSE_MENUS
620 // ----------------------------------------------------------------------------
621 // Window search functions
622 // ----------------------------------------------------------------------------
625 * If parent is non-NULL, look through children for a label or title
626 * matching the specified string. If NULL, look through all top-level windows.
631 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
633 return wxWindow::FindWindowByLabel( title
, parent
);
638 * If parent is non-NULL, look through children for a name
639 * matching the specified string. If NULL, look through all top-level windows.
644 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
646 return wxWindow::FindWindowByName( name
, parent
);
649 // Returns menu item id or -1 if none.
651 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
654 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
656 return menuBar
->FindMenuItem (menuString
, itemString
);
657 #endif // wxUSE_MENUS
662 // Try to find the deepest child that contains 'pt'.
663 // We go backwards, to try to allow for controls that are spacially
664 // within other controls, but are still siblings (e.g. buttons within
665 // static boxes). Static boxes are likely to be created _before_ controls
666 // that sit inside them.
667 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
672 // Hack for wxNotebook case: at least in wxGTK, all pages
673 // claim to be shown, so we must only deal with the selected one.
675 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
677 wxNotebook
* nb
= (wxNotebook
*) win
;
678 int sel
= nb
->GetSelection();
681 wxWindow
* child
= nb
->GetPage(sel
);
682 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
689 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetLast();
692 wxWindow
* child
= node
->GetData();
693 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
696 node
= node
->GetPrevious();
699 wxPoint pos
= win
->GetPosition();
700 wxSize sz
= win
->GetSize();
701 if (win
->GetParent())
703 pos
= win
->GetParent()->ClientToScreen(pos
);
706 wxRect
rect(pos
, sz
);
713 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
715 // Go backwards through the list since windows
716 // on top are likely to have been appended most
718 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetLast();
721 wxWindow
* win
= node
->GetData();
722 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
725 node
= node
->GetPrevious();
730 // ----------------------------------------------------------------------------
732 // ----------------------------------------------------------------------------
735 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
736 * since otherwise the generic code may be pulled in unnecessarily.
741 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
742 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
744 wxMessageDialog
dialog(parent
, message
, caption
, style
);
746 int ans
= dialog
.ShowModal();
759 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
764 #endif // wxUSE_MSGDLG
768 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
769 const wxString
& defaultValue
, wxWindow
*parent
,
770 int x
, int y
, bool WXUNUSED(centre
) )
773 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, wxOK
|wxCANCEL
, wxPoint(x
, y
));
774 if (dialog
.ShowModal() == wxID_OK
)
776 str
= dialog
.GetValue();
782 wxString
wxGetPasswordFromUser(const wxString
& message
,
783 const wxString
& caption
,
784 const wxString
& defaultValue
,
788 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
789 wxOK
| wxCANCEL
| wxTE_PASSWORD
);
790 if ( dialog
.ShowModal() == wxID_OK
)
792 str
= dialog
.GetValue();
798 #endif // wxUSE_TEXTDLG
802 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
805 data
.SetChooseFull(TRUE
);
808 data
.SetColour((wxColour
&)colInit
); // const_cast
812 wxColourDialog
dialog(parent
, &data
);
813 if ( dialog
.ShowModal() == wxID_OK
)
815 colRet
= dialog
.GetColourData().GetColour();
817 //else: leave it invalid
822 #endif // wxUSE_COLOURDLG
826 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
831 data
.SetInitialFont(fontInit
);
835 wxFontDialog
dialog(parent
, data
);
836 if ( dialog
.ShowModal() == wxID_OK
)
838 fontRet
= dialog
.GetFontData().GetChosenFont();
840 //else: leave it invalid
845 #endif // wxUSE_FONTDLG
847 // ----------------------------------------------------------------------------
848 // wxSafeYield and supporting functions
849 // ----------------------------------------------------------------------------
851 void wxEnableTopLevelWindows(bool enable
)
853 wxWindowList::compatibility_iterator node
;
854 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
855 node
->GetData()->Enable(enable
);
858 wxWindowDisabler::wxWindowDisabler(wxWindow
*winToSkip
)
860 // remember the top level windows which were already disabled, so that we
861 // don't reenable them later
862 m_winDisabled
= NULL
;
864 wxWindowList::compatibility_iterator node
;
865 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
867 wxWindow
*winTop
= node
->GetData();
868 if ( winTop
== winToSkip
)
871 // we don't need to disable the hidden or already disabled windows
872 if ( winTop
->IsEnabled() && winTop
->IsShown() )
878 if ( !m_winDisabled
)
880 m_winDisabled
= new wxWindowList
;
883 m_winDisabled
->Append(winTop
);
888 wxWindowDisabler::~wxWindowDisabler()
890 wxWindowList::compatibility_iterator node
;
891 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
893 wxWindow
*winTop
= node
->GetData();
894 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
898 //else: had been already disabled, don't reenable
901 delete m_winDisabled
;
904 // Yield to other apps/messages and disable user input to all windows except
906 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
908 wxWindowDisabler
wd(win
);
912 rc
= wxYieldIfNeeded();
919 // Don't synthesize KeyUp events holding down a key and producing KeyDown
920 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
923 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
925 return TRUE
; // detectable auto-repeat is the only mode MSW supports