]>
git.saurik.com Git - wxWidgets.git/blob - src/common/utilscmn.cpp
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"
40 #include "wx/window.h"
43 #include "wx/msgdlg.h"
44 #include "wx/textdlg.h"
45 #include "wx/textctrl.h" // for wxTE_PASSWORD
47 #include "wx/menuitem.h"
54 #include "wx/process.h"
55 #include "wx/txtstrm.h"
63 #if !defined(__WATCOMC__)
64 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
70 #include "wx/colordlg.h"
71 #include "wx/fontdlg.h"
72 #include "wx/notebook.h"
74 #include "wx/statusbr.h"
80 #include <sys/types.h>
89 #include "wx/msw/private.h"
92 #if 1 // def __WXBASE__
94 // ----------------------------------------------------------------------------
96 // ----------------------------------------------------------------------------
98 #if WXWIN_COMPATIBILITY_2_2
99 const wxChar
*wxInternalErrorStr
= wxT("wxWindows Internal Error");
100 const wxChar
*wxFatalErrorStr
= wxT("wxWindows Fatal Error");
101 #endif // WXWIN_COMPATIBILITY_2_2
103 // ============================================================================
105 // ============================================================================
107 #if WXWIN_COMPATIBILITY_2_4
110 copystring (const wxChar
*s
)
112 if (s
== NULL
) s
= wxT("");
113 size_t len
= wxStrlen (s
) + 1;
115 wxChar
*news
= new wxChar
[len
];
116 memcpy (news
, s
, len
* sizeof(wxChar
)); // Should be the fastest
121 #endif // WXWIN_COMPATIBILITY_2_4
124 static long wxCurrentId
= 100;
129 return wxCurrentId
++;
133 wxGetCurrentId(void) { return wxCurrentId
; }
136 wxRegisterId (long id
)
138 if (id
>= wxCurrentId
)
139 wxCurrentId
= id
+ 1;
142 // ----------------------------------------------------------------------------
143 // String <-> Number conversions (deprecated)
144 // ----------------------------------------------------------------------------
146 #if WXWIN_COMPATIBILITY_2_4
148 WXDLLEXPORT_DATA(const wxChar
*) wxFloatToStringStr
= wxT("%.2f");
149 WXDLLEXPORT_DATA(const wxChar
*) wxDoubleToStringStr
= wxT("%.2f");
152 StringToFloat (const wxChar
*s
, float *number
)
154 if (s
&& *s
&& number
)
155 *number
= (float) wxStrtod (s
, (wxChar
**) NULL
);
159 StringToDouble (const wxChar
*s
, double *number
)
161 if (s
&& *s
&& number
)
162 *number
= wxStrtod (s
, (wxChar
**) NULL
);
166 FloatToString (float number
, const wxChar
*fmt
)
168 static wxChar buf
[256];
170 wxSprintf (buf
, fmt
, number
);
175 DoubleToString (double number
, const wxChar
*fmt
)
177 static wxChar buf
[256];
179 wxSprintf (buf
, fmt
, number
);
184 StringToInt (const wxChar
*s
, int *number
)
186 if (s
&& *s
&& number
)
187 *number
= (int) wxStrtol (s
, (wxChar
**) NULL
, 10);
191 StringToLong (const wxChar
*s
, long *number
)
193 if (s
&& *s
&& number
)
194 *number
= wxStrtol (s
, (wxChar
**) NULL
, 10);
198 IntToString (int number
)
200 static wxChar buf
[20];
202 wxSprintf (buf
, wxT("%d"), number
);
207 LongToString (long number
)
209 static wxChar buf
[20];
211 wxSprintf (buf
, wxT("%ld"), number
);
215 #endif // WXWIN_COMPATIBILITY_2_4
217 // Array used in DecToHex conversion routine.
218 static wxChar hexArray
[] = wxT("0123456789ABCDEF");
220 // Convert 2-digit hex number to decimal
221 int wxHexToDec(const wxString
& buf
)
223 int firstDigit
, secondDigit
;
225 if (buf
.GetChar(0) >= wxT('A'))
226 firstDigit
= buf
.GetChar(0) - wxT('A') + 10;
228 firstDigit
= buf
.GetChar(0) - wxT('0');
230 if (buf
.GetChar(1) >= wxT('A'))
231 secondDigit
= buf
.GetChar(1) - wxT('A') + 10;
233 secondDigit
= buf
.GetChar(1) - wxT('0');
235 return (firstDigit
& 0xF) * 16 + (secondDigit
& 0xF );
238 // Convert decimal integer to 2-character hex string
239 void wxDecToHex(int dec
, wxChar
*buf
)
241 int firstDigit
= (int)(dec
/16.0);
242 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
243 buf
[0] = hexArray
[firstDigit
];
244 buf
[1] = hexArray
[secondDigit
];
248 // Convert decimal integer to 2-character hex string
249 wxString
wxDecToHex(int dec
)
252 wxDecToHex(dec
, buf
);
253 return wxString(buf
);
256 // ----------------------------------------------------------------------------
258 // ----------------------------------------------------------------------------
260 // Return the current date/time
263 time_t now
= time((time_t *) NULL
);
264 char *date
= ctime(&now
);
266 return wxString::FromAscii(date
);
269 const wxChar
*wxGetInstallPrefix()
273 if ( wxGetEnv(wxT("WXPREFIX"), &prefix
) )
274 return prefix
.c_str();
276 #ifdef wxINSTALL_PREFIX
277 return wxT(wxINSTALL_PREFIX
);
283 wxString
wxGetDataDir()
285 wxString format
= wxGetInstallPrefix();
286 format
<< wxFILE_SEP_PATH
287 << wxT("share") << wxFILE_SEP_PATH
288 << wxT("wx") << wxFILE_SEP_PATH
291 dir
.Printf(format
.c_str(), wxMAJOR_VERSION
, wxMINOR_VERSION
);
296 // ----------------------------------------------------------------------------
297 // network and user id functions
298 // ----------------------------------------------------------------------------
300 // Get Full RFC822 style email address
301 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
303 wxString email
= wxGetEmailAddress();
307 wxStrncpy(address
, email
, maxSize
- 1);
308 address
[maxSize
- 1] = wxT('\0');
313 wxString
wxGetEmailAddress()
317 wxString host
= wxGetFullHostName();
320 wxString user
= wxGetUserId();
323 email
<< user
<< wxT('@') << host
;
330 wxString
wxGetUserId()
332 static const int maxLoginLen
= 256; // FIXME arbitrary number
335 bool ok
= wxGetUserId(buf
.GetWriteBuf(maxLoginLen
), maxLoginLen
);
344 wxString
wxGetUserName()
346 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
349 bool ok
= wxGetUserName(buf
.GetWriteBuf(maxUserNameLen
), maxUserNameLen
);
358 wxString
wxGetHostName()
360 static const size_t hostnameSize
= 257;
363 bool ok
= wxGetHostName(buf
.GetWriteBuf(hostnameSize
), hostnameSize
);
373 wxString
wxGetFullHostName()
375 static const size_t hostnameSize
= 257;
378 bool ok
= wxGetFullHostName(buf
.GetWriteBuf(hostnameSize
), hostnameSize
);
388 wxString
wxGetHomeDir()
398 wxString
wxGetCurrentDir()
405 ok
= getcwd(dir
.GetWriteBuf(len
+ 1), len
) != NULL
;
410 if ( errno
!= ERANGE
)
412 wxLogSysError(_T("Failed to get current directory"));
414 return wxEmptyString
;
418 // buffer was too small, retry with a larger one
430 // ----------------------------------------------------------------------------
432 // ----------------------------------------------------------------------------
434 // wxDoExecuteWithCapture() helper: reads an entire stream into one array
436 // returns TRUE if ok, FALSE if error
438 static bool ReadAll(wxInputStream
*is
, wxArrayString
& output
)
440 wxCHECK_MSG( is
, FALSE
, _T("NULL stream in wxExecute()?") );
442 // the stream could be already at EOF or in wxSTREAM_BROKEN_PIPE state
445 wxTextInputStream
tis(*is
);
450 wxString line
= tis
.ReadLine();
466 #endif // wxUSE_STREAMS
468 // this is a private function because it hasn't a clean interface: the first
469 // array is passed by reference, the second by pointer - instead we have 2
470 // public versions of wxExecute() below
471 static long wxDoExecuteWithCapture(const wxString
& command
,
472 wxArrayString
& output
,
473 wxArrayString
* error
)
476 wxFAIL_MSG("Sorry, this version of wxExecute not implemented on WIN16.");
480 // create a wxProcess which will capture the output
481 wxProcess
*process
= new wxProcess
;
484 long rc
= wxExecute(command
, wxEXEC_SYNC
, process
);
489 if ( !ReadAll(process
->GetInputStream(), output
) )
494 if ( !ReadAll(process
->GetErrorStream(), *error
) )
499 #endif // wxUSE_STREAMS
504 #endif // IO redirection supported
507 long wxExecute(const wxString
& command
, wxArrayString
& output
)
509 return wxDoExecuteWithCapture(command
, output
, NULL
);
512 long wxExecute(const wxString
& command
,
513 wxArrayString
& output
,
514 wxArrayString
& error
)
516 return wxDoExecuteWithCapture(command
, output
, &error
);
519 // ----------------------------------------------------------------------------
520 // wxApp::Yield() wrappers for backwards compatibility
521 // ----------------------------------------------------------------------------
525 return wxTheApp
&& wxTheApp
->Yield();
528 bool wxYieldIfNeeded()
530 return wxTheApp
&& wxTheApp
->Yield(TRUE
);
535 // ============================================================================
536 // GUI-only functions from now on
537 // ============================================================================
543 // ----------------------------------------------------------------------------
544 // Menu accelerators related functions
545 // ----------------------------------------------------------------------------
547 wxChar
*wxStripMenuCodes(const wxChar
*in
, wxChar
*out
)
549 wxString s
= wxMenuItem::GetLabelFromText(in
);
552 // go smash their buffer if it's not big enough - I love char * params
553 memcpy(out
, s
.c_str(), s
.length() * sizeof(wxChar
));
563 wxString
wxStripMenuCodes(const wxString
& in
)
567 size_t len
= in
.length();
570 for ( size_t n
= 0; n
< len
; n
++ )
575 // skip it, it is used to introduce the accel char (or to quote
576 // itself in which case it should still be skipped): note that it
577 // can't be the last character of the string
580 wxLogDebug(_T("Invalid menu string '%s'"), in
.c_str());
584 // use the next char instead
588 else if ( ch
== _T('\t') )
590 // everything after TAB is accel string, exit the loop
600 #endif // wxUSE_MENUS
602 // ----------------------------------------------------------------------------
603 // Window search functions
604 // ----------------------------------------------------------------------------
607 * If parent is non-NULL, look through children for a label or title
608 * matching the specified string. If NULL, look through all top-level windows.
613 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
615 return wxWindow::FindWindowByLabel( title
, parent
);
620 * If parent is non-NULL, look through children for a name
621 * matching the specified string. If NULL, look through all top-level windows.
626 wxFindWindowByName (const wxString
& name
, wxWindow
* parent
)
628 return wxWindow::FindWindowByName( name
, parent
);
631 // Returns menu item id or -1 if none.
633 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
636 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
638 return menuBar
->FindMenuItem (menuString
, itemString
);
639 #endif // wxUSE_MENUS
644 // Try to find the deepest child that contains 'pt'.
645 // We go backwards, to try to allow for controls that are spacially
646 // within other controls, but are still siblings (e.g. buttons within
647 // static boxes). Static boxes are likely to be created _before_ controls
648 // that sit inside them.
649 wxWindow
* wxFindWindowAtPoint(wxWindow
* win
, const wxPoint
& pt
)
654 // Hack for wxNotebook case: at least in wxGTK, all pages
655 // claim to be shown, so we must only deal with the selected one.
657 if (win
->IsKindOf(CLASSINFO(wxNotebook
)))
659 wxNotebook
* nb
= (wxNotebook
*) win
;
660 int sel
= nb
->GetSelection();
663 wxWindow
* child
= nb
->GetPage(sel
);
664 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
671 wxWindowList::Node
*node
= win
->GetChildren().GetLast();
674 wxWindow
* child
= node
->GetData();
675 wxWindow
* foundWin
= wxFindWindowAtPoint(child
, pt
);
678 node
= node
->GetPrevious();
681 wxPoint pos
= win
->GetPosition();
682 wxSize sz
= win
->GetSize();
683 if (win
->GetParent())
685 pos
= win
->GetParent()->ClientToScreen(pos
);
688 wxRect
rect(pos
, sz
);
695 wxWindow
* wxGenericFindWindowAtPoint(const wxPoint
& pt
)
697 // Go backwards through the list since windows
698 // on top are likely to have been appended most
700 wxWindowList::Node
*node
= wxTopLevelWindows
.GetLast();
703 wxWindow
* win
= node
->GetData();
704 wxWindow
* found
= wxFindWindowAtPoint(win
, pt
);
707 node
= node
->GetPrevious();
712 // ----------------------------------------------------------------------------
714 // ----------------------------------------------------------------------------
717 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
718 * since otherwise the generic code may be pulled in unnecessarily.
723 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
724 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
726 wxMessageDialog
dialog(parent
, message
, caption
, style
);
728 int ans
= dialog
.ShowModal();
741 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
746 #endif // wxUSE_MSGDLG
750 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
751 const wxString
& defaultValue
, wxWindow
*parent
,
752 int x
, int y
, bool WXUNUSED(centre
) )
755 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, wxOK
|wxCANCEL
, wxPoint(x
, y
));
756 if (dialog
.ShowModal() == wxID_OK
)
758 str
= dialog
.GetValue();
764 wxString
wxGetPasswordFromUser(const wxString
& message
,
765 const wxString
& caption
,
766 const wxString
& defaultValue
,
770 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
,
771 wxOK
| wxCANCEL
| wxTE_PASSWORD
);
772 if ( dialog
.ShowModal() == wxID_OK
)
774 str
= dialog
.GetValue();
780 #endif // wxUSE_TEXTDLG
784 wxColour
wxGetColourFromUser(wxWindow
*parent
, const wxColour
& colInit
)
787 data
.SetChooseFull(TRUE
);
790 data
.SetColour((wxColour
&)colInit
); // const_cast
794 wxColourDialog
dialog(parent
, &data
);
795 if ( dialog
.ShowModal() == wxID_OK
)
797 colRet
= dialog
.GetColourData().GetColour();
799 //else: leave it invalid
804 #endif // wxUSE_COLOURDLG
808 wxFont
wxGetFontFromUser(wxWindow
*parent
, const wxFont
& fontInit
)
813 data
.SetInitialFont(fontInit
);
817 wxFontDialog
dialog(parent
, data
);
818 if ( dialog
.ShowModal() == wxID_OK
)
820 fontRet
= dialog
.GetFontData().GetChosenFont();
822 //else: leave it invalid
827 #endif // wxUSE_FONTDLG
828 // ----------------------------------------------------------------------------
829 // missing C RTL functions (FIXME shouldn't be here at all)
830 // ----------------------------------------------------------------------------
832 #if defined( __MWERKS__ ) && !defined(__MACH__)
833 char *strdup(const char *s
)
835 return strcpy( (char*) malloc( strlen( s
) + 1 ) , s
) ;
839 return ( c
>= 0 && c
< 128 ) ;
843 // ----------------------------------------------------------------------------
844 // wxSafeYield and supporting functions
845 // ----------------------------------------------------------------------------
847 void wxEnableTopLevelWindows(bool enable
)
849 wxWindowList::Node
*node
;
850 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
851 node
->GetData()->Enable(enable
);
854 wxWindowDisabler::wxWindowDisabler(wxWindow
*winToSkip
)
856 // remember the top level windows which were already disabled, so that we
857 // don't reenable them later
858 m_winDisabled
= NULL
;
860 wxWindowList::Node
*node
;
861 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
863 wxWindow
*winTop
= node
->GetData();
864 if ( winTop
== winToSkip
)
867 // we don't need to disable the hidden or already disabled windows
868 if ( winTop
->IsEnabled() && winTop
->IsShown() )
874 if ( !m_winDisabled
)
876 m_winDisabled
= new wxWindowList
;
879 m_winDisabled
->Append(winTop
);
884 wxWindowDisabler::~wxWindowDisabler()
886 wxWindowList::Node
*node
;
887 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
889 wxWindow
*winTop
= node
->GetData();
890 if ( !m_winDisabled
|| !m_winDisabled
->Find(winTop
) )
894 //else: had been already disabled, don't reenable
897 delete m_winDisabled
;
900 // Yield to other apps/messages and disable user input to all windows except
902 bool wxSafeYield(wxWindow
*win
, bool onlyIfNeeded
)
904 wxWindowDisabler
wd(win
);
908 rc
= wxYieldIfNeeded();
915 // Don't synthesize KeyUp events holding down a key and producing KeyDown
916 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
919 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
921 return TRUE
; // detectable auto-repeat is the only mode MSW supports