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 <sys/types.h>
88 #include "wx/msw/private.h"
93 // ----------------------------------------------------------------------------
95 // ----------------------------------------------------------------------------
97 #if WXWIN_COMPATIBILITY_2_2
98 const wxChar
*wxInternalErrorStr
= wxT("wxWindows Internal Error");
99 const wxChar
*wxFatalErrorStr
= wxT("wxWindows Fatal Error");
100 #endif // WXWIN_COMPATIBILITY_2_2
102 // ============================================================================
104 // ============================================================================
106 #if WXWIN_COMPATIBILITY_2_4
109 copystring (const wxChar
*s
)
111 if (s
== NULL
) s
= wxT("");
112 size_t len
= wxStrlen (s
) + 1;
114 wxChar
*news
= new wxChar
[len
];
115 memcpy (news
, s
, len
* sizeof(wxChar
)); // Should be the fastest
120 #endif // WXWIN_COMPATIBILITY_2_4
123 static long wxCurrentId
= 100;
128 return wxCurrentId
++;
132 wxGetCurrentId(void) { return wxCurrentId
; }
135 wxRegisterId (long id
)
137 if (id
>= wxCurrentId
)
138 wxCurrentId
= id
+ 1;
141 // ----------------------------------------------------------------------------
142 // String <-> Number conversions (deprecated)
143 // ----------------------------------------------------------------------------
145 #if WXWIN_COMPATIBILITY_2_4
147 WXDLLEXPORT_DATA(const wxChar
*) wxFloatToStringStr
= wxT("%.2f");
148 WXDLLEXPORT_DATA(const wxChar
*) wxDoubleToStringStr
= wxT("%.2f");
151 StringToFloat (const wxChar
*s
, float *number
)
153 if (s
&& *s
&& number
)
154 *number
= (float) wxStrtod (s
, (wxChar
**) NULL
);
158 StringToDouble (const wxChar
*s
, double *number
)
160 if (s
&& *s
&& number
)
161 *number
= wxStrtod (s
, (wxChar
**) NULL
);
165 FloatToString (float number
, const wxChar
*fmt
)
167 static wxChar buf
[256];
169 wxSprintf (buf
, fmt
, number
);
174 DoubleToString (double number
, const wxChar
*fmt
)
176 static wxChar buf
[256];
178 wxSprintf (buf
, fmt
, number
);
183 StringToInt (const wxChar
*s
, int *number
)
185 if (s
&& *s
&& number
)
186 *number
= (int) wxStrtol (s
, (wxChar
**) NULL
, 10);
190 StringToLong (const wxChar
*s
, long *number
)
192 if (s
&& *s
&& number
)
193 *number
= wxStrtol (s
, (wxChar
**) NULL
, 10);
197 IntToString (int number
)
199 static wxChar buf
[20];
201 wxSprintf (buf
, wxT("%d"), number
);
206 LongToString (long number
)
208 static wxChar buf
[20];
210 wxSprintf (buf
, wxT("%ld"), number
);
214 #endif // WXWIN_COMPATIBILITY_2_4
216 // Array used in DecToHex conversion routine.
217 static wxChar hexArray
[] = wxT("0123456789ABCDEF");
219 // Convert 2-digit hex number to decimal
220 int wxHexToDec(const wxString
& buf
)
222 int firstDigit
, secondDigit
;
224 if (buf
.GetChar(0) >= wxT('A'))
225 firstDigit
= buf
.GetChar(0) - wxT('A') + 10;
227 firstDigit
= buf
.GetChar(0) - wxT('0');
229 if (buf
.GetChar(1) >= wxT('A'))
230 secondDigit
= buf
.GetChar(1) - wxT('A') + 10;
232 secondDigit
= buf
.GetChar(1) - wxT('0');
234 return (firstDigit
& 0xF) * 16 + (secondDigit
& 0xF );
237 // Convert decimal integer to 2-character hex string
238 void wxDecToHex(int dec
, wxChar
*buf
)
240 int firstDigit
= (int)(dec
/16.0);
241 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
242 buf
[0] = hexArray
[firstDigit
];
243 buf
[1] = hexArray
[secondDigit
];
247 // Convert decimal integer to 2-character hex string
248 wxString
wxDecToHex(int dec
)
251 wxDecToHex(dec
, buf
);
252 return wxString(buf
);
255 // ----------------------------------------------------------------------------
257 // ----------------------------------------------------------------------------
259 // Return the current date/time
262 time_t now
= time((time_t *) NULL
);
263 char *date
= ctime(&now
);
265 return wxString::FromAscii(date
);
268 const wxChar
*wxGetInstallPrefix()
272 if ( wxGetEnv(wxT("WXPREFIX"), &prefix
) )
273 return prefix
.c_str();
275 #ifdef wxINSTALL_PREFIX
276 return wxT(wxINSTALL_PREFIX
);
282 wxString
wxGetDataDir()
284 wxString format
= wxGetInstallPrefix();
285 format
<< wxFILE_SEP_PATH
286 << wxT("share") << wxFILE_SEP_PATH
287 << wxT("wx") << wxFILE_SEP_PATH
290 dir
.Printf(format
.c_str(), wxMAJOR_VERSION
, wxMINOR_VERSION
);
294 int wxGetOsVersion(int *verMaj
, int *verMin
)
296 // we want this function to work even if there is no wxApp
297 wxConsoleAppTraits traitsConsole
;
298 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
300 traits
= &traitsConsole
;
302 return traits
->GetOSVersion(verMaj
, verMin
);
305 // ----------------------------------------------------------------------------
306 // network and user id functions
307 // ----------------------------------------------------------------------------
309 // Get Full RFC822 style email address
310 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
312 wxString email
= wxGetEmailAddress();
316 wxStrncpy(address
, email
, maxSize
- 1);
317 address
[maxSize
- 1] = wxT('\0');
322 wxString
wxGetEmailAddress()
326 wxString host
= wxGetFullHostName();
329 wxString user
= wxGetUserId();
332 email
<< user
<< wxT('@') << host
;
339 wxString
wxGetUserId()
341 static const int maxLoginLen
= 256; // FIXME arbitrary number
344 bool ok
= wxGetUserId(buf
.GetWriteBuf(maxLoginLen
), maxLoginLen
);
353 wxString
wxGetUserName()
355 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
358 bool ok
= wxGetUserName(buf
.GetWriteBuf(maxUserNameLen
), maxUserNameLen
);
367 wxString
wxGetHostName()
369 static const size_t hostnameSize
= 257;
372 bool ok
= wxGetHostName(buf
.GetWriteBuf(hostnameSize
), hostnameSize
);
382 wxString
wxGetFullHostName()
384 static const size_t hostnameSize
= 257;
387 bool ok
= wxGetFullHostName(buf
.GetWriteBuf(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 // ============================================================================
546 // ----------------------------------------------------------------------------
547 // Menu accelerators related functions
548 // ----------------------------------------------------------------------------
550 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
552 wxString s
= wxMenuItem::GetLabelFromText(in
);
555 // go smash their buffer if it's not big enough - I love char * params
556 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
566 wxString
wxStripMenuCodes(const wxString
& in
)
570 size_t len
= in
.length();
573 for ( size_t n
= 0; n
< len
; n
++ )
578 // skip it, it is used to introduce the accel char (or to quote
579 // itself in which case it should still be skipped): note that it
580 // can't be the last character of the string
583 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
587 // use the next char instead
591 else if ( ch
== _T('\t') )
593 // everything after TAB is accel string, exit the loop
603 #endif // wxUSE_MENUS
605 // ----------------------------------------------------------------------------
606 // Window search functions
607 // ----------------------------------------------------------------------------
610 * If parent is non-NULL, look through children for a label or title
611 * matching the specified string. If NULL, look through all top-level windows.
616 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
618 return wxWindow::FindWindowByLabel( title
, parent
);
623 * If parent is non-NULL, look through children for a name
624 * matching the specified string. If NULL, look through all top-level windows.
629 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
631 return wxWindow::FindWindowByName( name
, parent
);
634 // Returns menu item id or -1 if none.
636 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
639 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
641 return menuBar
->FindMenuItem (menuString
, itemString
);
642 #endif // wxUSE_MENUS
647 // Try to find the deepest child that contains 'pt'.
648 // We go backwards, to try to allow for controls that are spacially
649 // within other controls, but are still siblings (e.g. buttons within
650 // static boxes). Static boxes are likely to be created _before_ controls
651 // that sit inside them.
652 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
657 // Hack for wxNotebook case: at least in wxGTK, all pages
658 // claim to be shown, so we must only deal with the selected one.
660 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
662 wxNotebook
* nb
= (wxNotebook
*) win
;
663 int sel
= nb
->GetSelection();
666 wxWindow
* child
= nb
->GetPage(sel
);
667 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
674 wxWindowList::Node
*node
= win
->GetChildren().GetLast();
677 wxWindow
* child
= node
->GetData();
678 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
681 node
= node
->GetPrevious();
684 wxPoint pos
= win
->GetPosition();
685 wxSize sz
= win
->GetSize();
686 if (win
->GetParent())
688 pos
= win
->GetParent()->ClientToScreen(pos
);
691 wxRect
rect(pos
, sz
);
698 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
700 // Go backwards through the list since windows
701 // on top are likely to have been appended most
703 wxWindowList::Node
*node
= wxTopLevelWindows
.GetLast();
706 wxWindow
* win
= node
->GetData();
707 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
710 node
= node
->GetPrevious();
715 // ----------------------------------------------------------------------------
717 // ----------------------------------------------------------------------------
720 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
721 * since otherwise the generic code may be pulled in unnecessarily.
726 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
727 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
729 wxMessageDialog
dialog(parent
, message
, caption
, style
);
731 int ans
= dialog
.ShowModal();
744 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
749 #endif // wxUSE_MSGDLG
753 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
754 const wxString
& defaultValue
, wxWindow
*parent
,
755 int x
, int y
, bool WXUNUSED(centre
) )
758 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, wxOK
|wxCANCEL
, wxPoint(x
, y
));
759 if (dialog
.ShowModal() == wxID_OK
)
761 str
= dialog
.GetValue();
767 wxString
wxGetPasswordFromUser(const wxString
& message
,
768 const wxString
& caption
,
769 const wxString
& defaultValue
,
773 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
774 wxOK
| wxCANCEL
| wxTE_PASSWORD
);
775 if ( dialog
.ShowModal() == wxID_OK
)
777 str
= dialog
.GetValue();
783 #endif // wxUSE_TEXTDLG
787 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
790 data
.SetChooseFull(TRUE
);
793 data
.SetColour((wxColour
&)colInit
); // const_cast
797 wxColourDialog
dialog(parent
, &data
);
798 if ( dialog
.ShowModal() == wxID_OK
)
800 colRet
= dialog
.GetColourData().GetColour();
802 //else: leave it invalid
807 #endif // wxUSE_COLOURDLG
811 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
816 data
.SetInitialFont(fontInit
);
820 wxFontDialog
dialog(parent
, data
);
821 if ( dialog
.ShowModal() == wxID_OK
)
823 fontRet
= dialog
.GetFontData().GetChosenFont();
825 //else: leave it invalid
830 #endif // wxUSE_FONTDLG
831 // ----------------------------------------------------------------------------
832 // missing C RTL functions (FIXME shouldn't be here at all)
833 // ----------------------------------------------------------------------------
835 #if defined( __MWERKS__ ) && !defined(__MACH__)
836 char *strdup(const char *s
)
838 return strcpy( (char*) malloc( strlen( s
) + 1 ) , s
) ;
842 return ( c
>= 0 && c
< 128 ) ;
846 // ----------------------------------------------------------------------------
847 // wxSafeYield and supporting functions
848 // ----------------------------------------------------------------------------
850 void wxEnableTopLevelWindows(bool enable
)
852 wxWindowList::Node
*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::Node
*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::Node
*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