]>
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 license
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"
45 #include "wx/menuitem.h"
56 #if !defined(__WATCOMC__)
57 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
65 #include <sys/types.h>
77 // ----------------------------------------------------------------------------
79 // ----------------------------------------------------------------------------
82 static wxWindow
*wxFindWindowByLabel1(const wxString
& title
, wxWindow
*parent
);
83 static wxWindow
*wxFindWindowByName1 (const wxString
& title
, wxWindow
*parent
);
86 // ============================================================================
88 // ============================================================================
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
95 int strcasecmp(const char *str_1
, const char *str_2
)
99 c1
= tolower(*str_1
++);
100 c2
= tolower(*str_2
++);
101 } while ( c1
&& (c1
== c2
) );
106 int strncasecmp(const char *str_1
, const char *str_2
, size_t maxchar
)
109 register char c1
, c2
;
112 c1
= tolower(*str_1
++);
113 c2
= tolower(*str_2
++);
125 #if defined( __VMS__ ) && ( __VMS_VER < 70000000 )
126 // we have no strI functions under VMS, therefore I have implemented
127 // an inefficient but portable version: convert copies of strings to lowercase
128 // and then use the normal comparison
129 static void myLowerString(char *s
)
132 if(isalpha(*s
)) *s
= (char)tolower(*s
);
137 int strcasecmp(const char *str_1
, const char *str_2
)
139 char *temp1
= new char[strlen(str_1
)+1];
140 char *temp2
= new char[strlen(str_2
)+1];
143 myLowerString(temp1
);
144 myLowerString(temp2
);
146 int result
= wxStrcmp(temp1
,temp2
);
153 int strncasecmp(const char *str_1
, const char *str_2
, size_t maxchar
)
155 char *temp1
= new char[strlen(str_1
)+1];
156 char *temp2
= new char[strlen(str_2
)+1];
159 myLowerString(temp1
);
160 myLowerString(temp2
);
162 int result
= strncmp(temp1
,temp2
,maxchar
);
174 #define strcasecmp stricmp
175 #define strncasecmp strnicmp
177 #define strcasecmp _stricmp
178 #define strncasecmp _strnicmp
185 #define strcasecmp stricmp
186 #define strncasecmp strnicmp
189 // This declaration is missing in SunOS!
190 // (Yes, I know it is NOT ANSI-C but its in BSD libc)
191 #if defined(__xlC) || defined(__AIX__) || defined(__GNUG__)
194 int strcasecmp (const char *, const char *);
195 int strncasecmp (const char *, const char *, size_t);
198 #endif /* __WXMSW__ */
201 #define strcasecmp stricmp
202 #define strncasecmp strnicmp
206 copystring (const wxChar
*s
)
208 if (s
== NULL
) s
= wxT("");
209 size_t len
= wxStrlen (s
) + 1;
211 wxChar
*news
= new wxChar
[len
];
212 memcpy (news
, s
, len
* sizeof(wxChar
)); // Should be the fastest
218 static long wxCurrentId
= 100;
223 return wxCurrentId
++;
227 wxGetCurrentId(void) { return wxCurrentId
; }
230 wxRegisterId (long id
)
232 if (id
>= wxCurrentId
)
233 wxCurrentId
= id
+ 1;
237 StringToFloat (wxChar
*s
, float *number
)
239 if (s
&& *s
&& number
)
240 *number
= (float) wxStrtod (s
, (wxChar
**) NULL
);
244 StringToDouble (wxChar
*s
, double *number
)
246 if (s
&& *s
&& number
)
247 *number
= wxStrtod (s
, (wxChar
**) NULL
);
251 FloatToString (float number
, const wxChar
*fmt
)
253 static wxChar buf
[256];
255 // sprintf (buf, "%.2f", number);
256 wxSprintf (buf
, fmt
, number
);
261 DoubleToString (double number
, const wxChar
*fmt
)
263 static wxChar buf
[256];
265 wxSprintf (buf
, fmt
, number
);
270 StringToInt (wxChar
*s
, int *number
)
272 if (s
&& *s
&& number
)
273 *number
= (int) wxStrtol (s
, (wxChar
**) NULL
, 10);
277 StringToLong (wxChar
*s
, long *number
)
279 if (s
&& *s
&& number
)
280 *number
= wxStrtol (s
, (wxChar
**) NULL
, 10);
284 IntToString (int number
)
286 static wxChar buf
[20];
288 wxSprintf (buf
, wxT("%d"), number
);
293 LongToString (long number
)
295 static wxChar buf
[20];
297 wxSprintf (buf
, wxT("%ld"), number
);
301 // Array used in DecToHex conversion routine.
302 static wxChar hexArray
[] = wxT("0123456789ABCDEF");
304 // Convert 2-digit hex number to decimal
305 int wxHexToDec(const wxString
& buf
)
307 int firstDigit
, secondDigit
;
309 if (buf
.GetChar(0) >= wxT('A'))
310 firstDigit
= buf
.GetChar(0) - wxT('A') + 10;
312 firstDigit
= buf
.GetChar(0) - wxT('0');
314 if (buf
.GetChar(1) >= wxT('A'))
315 secondDigit
= buf
.GetChar(1) - wxT('A') + 10;
317 secondDigit
= buf
.GetChar(1) - wxT('0');
319 return firstDigit
* 16 + secondDigit
;
322 // Convert decimal integer to 2-character hex string
323 void wxDecToHex(int dec
, wxChar
*buf
)
325 int firstDigit
= (int)(dec
/16.0);
326 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
327 buf
[0] = hexArray
[firstDigit
];
328 buf
[1] = hexArray
[secondDigit
];
332 // Convert decimal integer to 2-character hex string
333 wxString
wxDecToHex(int dec
)
336 wxDecToHex(dec
, buf
);
337 return wxString(buf
);
340 // Match a string INDEPENDENT OF CASE
342 StringMatch (char *str1
, char *str2
, bool subString
, bool exact
)
344 if (str1
== NULL
|| str2
== NULL
)
351 int len1
= strlen (str1
);
352 int len2
= strlen (str2
);
355 // Search for str1 in str2
356 // Slow .... but acceptable for short strings
357 for (i
= 0; i
<= len2
- len1
; i
++)
359 if (strncasecmp (str1
, str2
+ i
, len1
) == 0)
365 if (strcasecmp (str1
, str2
) == 0)
370 int len1
= strlen (str1
);
371 int len2
= strlen (str2
);
373 if (strncasecmp (str1
, str2
, wxMin (len1
, len2
)) == 0)
380 // Return the current date/time
384 time_t now
= time((time_t *) NULL
);
385 char *date
= ctime(&now
);
387 return wxString(date
);
392 // ----------------------------------------------------------------------------
393 // Menu accelerators related functions
394 // ----------------------------------------------------------------------------
396 wxChar
*wxStripMenuCodes (wxChar
*in
, wxChar
*out
)
399 return (wxChar
*) NULL
;
402 out
= copystring(in
);
404 wxChar
*tmpOut
= out
;
410 // Check && -> &, &x -> x
411 if (*++in
== wxT('&'))
414 else if (*in
== wxT('\t'))
416 // Remove all stuff after \t in X mode, and let the stuff as is
418 // Accelerators are handled in wx_item.cc for Motif, and are not
419 // YET supported in XView
431 wxString
wxStripMenuCodes(const wxString
& str
)
433 wxChar
*buf
= new wxChar
[str
.Length() + 1];
434 wxStripMenuCodes(WXSTRINGCAST str
, buf
);
442 // return wxAcceleratorEntry for the given menu string or NULL if none
444 wxAcceleratorEntry
*wxGetAccelFromString(const wxString
& label
)
446 // check for accelerators: they are given after '\t'
447 int posTab
= label
.Find(wxT('\t'));
448 if ( posTab
!= wxNOT_FOUND
) {
449 // parse the accelerator string
451 int accelFlags
= wxACCEL_NORMAL
;
453 for ( size_t n
= (size_t)posTab
+ 1; n
< label
.Len(); n
++ ) {
454 if ( (label
[n
] == '+') || (label
[n
] == '-') ) {
455 if ( current
== _("ctrl") )
456 accelFlags
|= wxACCEL_CTRL
;
457 else if ( current
== _("alt") )
458 accelFlags
|= wxACCEL_ALT
;
459 else if ( current
== _("shift") )
460 accelFlags
|= wxACCEL_SHIFT
;
462 wxLogDebug(wxT("Unknown accel modifier: '%s'"),
469 current
+= wxTolower(label
[n
]);
473 if ( current
.IsEmpty() ) {
474 wxLogDebug(wxT("No accel key found, accel string ignored."));
477 if ( current
.Len() == 1 ) {
479 keyCode
= wxToupper(current
[0U]);
482 // is it a function key?
483 if ( current
[0U] == 'f' && isdigit(current
[1U]) &&
484 (current
.Len() == 2 ||
485 (current
.Len() == 3 && isdigit(current
[2U]))) ) {
487 wxSscanf(current
.c_str() + 1, wxT("%d"), &n
);
489 keyCode
= WXK_F1
+ n
- 1;
492 #if 0 // this is not supported by GTK+, apparently
493 // several special cases
495 if ( current
== wxT("DEL") ) {
498 else if ( current
== wxT("PGUP") ) {
501 else if ( current
== wxT("PGDN") ) {
507 wxLogDebug(wxT("Unrecognized accel key '%s', accel "
508 "string ignored."), current
.c_str());
515 // we do have something
516 return new wxAcceleratorEntry(accelFlags
, keyCode
);
520 return (wxAcceleratorEntry
*)NULL
;
523 #endif // wxUSE_ACCEL
525 // ----------------------------------------------------------------------------
526 // Window search functions
527 // ----------------------------------------------------------------------------
530 * If parent is non-NULL, look through children for a label or title
531 * matching the specified string. If NULL, look through all top-level windows.
536 wxFindWindowByLabel (const wxString
& title
, wxWindow
* parent
)
540 return wxFindWindowByLabel1(title
, parent
);
544 for ( wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
546 node
= node
->GetNext() )
548 wxWindow
*win
= node
->GetData();
549 wxWindow
*retwin
= wxFindWindowByLabel1 (title
, win
);
555 return (wxWindow
*) NULL
;
560 wxFindWindowByLabel1 (const wxString
& title
, wxWindow
* parent
)
564 if (parent
->GetLabel() == title
)
570 for ( wxWindowList::Node
* node
= parent
->GetChildren().GetFirst();
572 node
= node
->GetNext() )
574 wxWindow
*win
= (wxWindow
*)node
->GetData();
575 wxWindow
*retwin
= wxFindWindowByLabel1 (title
, win
);
582 return (wxWindow
*) NULL
; // Not found
586 * If parent is non-NULL, look through children for a name
587 * matching the specified string. If NULL, look through all top-level windows.
592 wxFindWindowByName (const wxString
& title
, wxWindow
* parent
)
596 return wxFindWindowByName1 (title
, parent
);
600 for ( wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
602 node
= node
->GetNext() )
604 wxWindow
*win
= node
->GetData();
605 wxWindow
*retwin
= wxFindWindowByName1 (title
, win
);
612 // Failed? Try by label instead.
613 return wxFindWindowByLabel(title
, parent
);
618 wxFindWindowByName1 (const wxString
& title
, wxWindow
* parent
)
622 if ( parent
->GetName() == title
)
628 for (wxNode
* node
= parent
->GetChildren().First (); node
; node
= node
->Next ())
630 wxWindow
*win
= (wxWindow
*) node
->Data ();
631 wxWindow
*retwin
= wxFindWindowByName1 (title
, win
);
638 return (wxWindow
*) NULL
; // Not found
642 // Returns menu item id or -1 if none.
644 wxFindMenuItemId (wxFrame
* frame
, const wxString
& menuString
, const wxString
& itemString
)
646 wxMenuBar
*menuBar
= frame
->GetMenuBar ();
649 return menuBar
->FindMenuItem (menuString
, itemString
);
655 On Fri, 21 Jul 1995, Paul Craven wrote:
657 > Is there a way to find the path of running program's executable? I can get
658 > my home directory, and the current directory, but I don't know how to get the
659 > executable directory.
662 The code below (warty as it is), does what you want on most Unix,
663 DOS, and Mac platforms (it's from the ALS Prolog main).
665 || Ken Bowen Applied Logic Systems, Inc. PO Box 180,
666 ||==== Voice: +1 (617)965-9191 Newton Centre,
667 || FAX: +1 (617)965-1636 MA 02159 USA
668 Email: ken@als.com WWW: http://www.als.com
669 ------------------------------------------------------------------------
672 // This code is commented out but it may be integrated with wxWin at
673 // a later date, after testing. Thanks Ken!
676 /*--------------------------------------------------------------------*
677 | whereami is given a filename f in the form: whereami(argv[0])
678 | It returns the directory in which the executable file (containing
679 | this code [main.c] ) may be found. A dot will be returned to indicate
680 | the current directory.
681 *--------------------------------------------------------------------*/
687 register char *cutoff
= NULL
; /* stifle -Wall */
694 * See if the file is accessible either through the current directory
695 * or through an absolute path.
698 if (access(name
, R_OK
) == 0) {
700 /*-------------------------------------------------------------*
701 * The file was accessible without any other work. But the current
702 * working directory might change on us, so if it was accessible
703 * through the cwd, then we should get it for later accesses.
704 *-------------------------------------------------------------*/
707 if (!absolute_pathname(name
)) {
708 #if defined(DOS) || defined(__WIN32__)
714 if (*(name
+ 1) == ':') {
715 if (*name
>= 'a' && *name
<= 'z')
716 drive
= (int) (*name
- 'a' + 1);
718 drive
= (int) (*name
- 'A' + 1);
720 *newrbuf
++ = *(name
+ 1);
721 *newrbuf
++ = DIR_SEPARATOR
;
725 *newrbuf
++ = DIR_SEPARATOR
;
727 if (getcwd(newrbuf
, drive
) == 0) { /* } */
729 if (getcwd(newrbuf
, 1024) == 0) { /* } */
733 if (getwd(imagedir
) == 0) { /* } */
734 #else /* !HAVE_GETWD */
735 if (getcwd(imagedir
, 1024) == 0) {
736 #endif /* !HAVE_GETWD */
738 fatal_error(FE_GETCWD
, 0);
740 for (; *t
; t
++) /* Set t to end of buffer */
742 if (*(t
- 1) == DIR_SEPARATOR
) /* leave slash if already
747 cutoff
= t
; /* otherwise put one in */
748 *t
++ = DIR_SEPARATOR
;
751 #if (!defined(__MAC__) && !defined(__DJGPP__) && !defined(__GO32__) && !defined(__WIN32__))
753 (*t
++ = DIR_SEPARATOR
);
756 /*-------------------------------------------------------------*
757 * Copy the rest of the string and set the cutoff if it was not
758 * already set. If the first character of name is a slash, cutoff
759 * is not presently set but will be on the first iteration of the
761 *-------------------------------------------------------------*/
763 for ((*name
== DIR_SEPARATOR
? (s
= name
+1) : (s
= name
));;) {
764 if (*s
== DIR_SEPARATOR
)
773 /*-------------------------------------------------------------*
774 * Get the path list from the environment. If the path list is
775 * inaccessible for any reason, leave with fatal error.
776 *-------------------------------------------------------------*/
779 if ((s
= getenv("Commands")) == (char *) 0)
781 if ((s
= getenv("PATH")) == (char *) 0)
783 fatal_error(FE_PATH
, 0);
786 * Copy path list into ebuf and set the source pointer to the
787 * beginning of this buffer.
795 while (*s
&& *s
!= PATH_SEPARATOR
)
797 if (t
> imagedir
&& *(t
- 1) == DIR_SEPARATOR
)
798 ; /* do nothing -- slash already is in place */
800 *t
++ = DIR_SEPARATOR
; /* put in the slash */
801 cutoff
= t
- 1; /* set cutoff */
803 if (access(imagedir
, R_OK
) == 0)
807 s
++; /* advance source pointer */
809 fatal_error(FE_INFND
, 0);
814 /*-------------------------------------------------------------*
815 | At this point the full pathname should exist in imagedir and
816 | cutoff should be set to the final slash. We must now determine
817 | whether the file name is a symbolic link or not and chase it down
818 | if it is. Note that we reuse ebuf for getting the link.
819 *-------------------------------------------------------------*/
822 while ((cc
= readlink(imagedir
, ebuf
, 512)) != -1) {
825 if (*s
== DIR_SEPARATOR
) {
832 if (*s
== DIR_SEPARATOR
)
833 cutoff
= t
; /* mark the last slash seen */
834 if (!(*t
++ = *s
++)) /* copy the character */
839 #endif /* HAVE_SYMLINK */
841 strcpy(imagename
, cutoff
+ 1); /* keep the image name */
842 *(cutoff
+ 1) = 0; /* chop off the filename part */
849 // ----------------------------------------------------------------------------
851 // ----------------------------------------------------------------------------
854 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
855 * since otherwise the generic code may be pulled in unnecessarily.
858 int wxMessageBox(const wxString
& message
, const wxString
& caption
, long style
,
859 wxWindow
*parent
, int WXUNUSED(x
), int WXUNUSED(y
) )
861 wxMessageDialog
dialog(parent
, message
, caption
, style
);
863 int ans
= dialog
.ShowModal();
879 wxString
wxGetTextFromUser(const wxString
& message
, const wxString
& caption
,
880 const wxString
& defaultValue
, wxWindow
*parent
,
881 int x
, int y
, bool WXUNUSED(centre
) )
883 wxTextEntryDialog
dialog(parent
, message
, caption
, defaultValue
, wxOK
|wxCANCEL
, wxPoint(x
, y
));
884 if (dialog
.ShowModal() == wxID_OK
)
885 return dialog
.GetValue();
889 #endif // wxUSE_TEXTDLG
892 char *strdup(const char *s
)
894 return strcpy( (char*) malloc( strlen( s
) + 1 ) , s
) ;
899 return ( c
>= 0 && c
< 128 ) ;
903 // ----------------------------------------------------------------------------
905 // ----------------------------------------------------------------------------
907 void wxEnableTopLevelWindows(bool enable
)
909 wxWindowList::Node
*node
;
910 for ( node
= wxTopLevelWindows
.GetFirst(); node
; node
= node
->GetNext() )
911 node
->GetData()->Enable(enable
);
914 // Yield to other apps/messages and disable user input
915 bool wxSafeYield(wxWindow
*win
)
917 wxEnableTopLevelWindows(FALSE
);
918 // always enable ourselves
922 wxEnableTopLevelWindows(TRUE
);
926 // Don't synthesize KeyUp events holding down a key and producing KeyDown
927 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
930 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag
) )
932 return TRUE
; // detectable auto-repeat is the only mode MSW supports
938 // ----------------------------------------------------------------------------
939 // network and user id functions
940 // ----------------------------------------------------------------------------
942 // Get Full RFC822 style email address
943 bool wxGetEmailAddress(wxChar
*address
, int maxSize
)
945 wxString email
= wxGetEmailAddress();
949 wxStrncpy(address
, email
, maxSize
- 1);
950 address
[maxSize
- 1] = wxT('\0');
955 wxString
wxGetEmailAddress()
959 wxString host
= wxGetHostName();
962 wxString user
= wxGetUserId();
965 wxString
email(user
);
966 email
<< wxT('@') << host
;
973 wxString
wxGetUserId()
975 static const int maxLoginLen
= 256; // FIXME arbitrary number
978 bool ok
= wxGetUserId(buf
.GetWriteBuf(maxLoginLen
), maxLoginLen
);
987 wxString
wxGetUserName()
989 static const int maxUserNameLen
= 1024; // FIXME arbitrary number
992 bool ok
= wxGetUserName(buf
.GetWriteBuf(maxUserNameLen
), maxUserNameLen
);
1001 wxString
wxGetHostName()
1003 static const size_t hostnameSize
= 257;
1006 bool ok
= wxGetHostName(buf
.GetWriteBuf(hostnameSize
), hostnameSize
);
1008 buf
.UngetWriteBuf();
1016 wxString
wxGetFullHostName()
1018 static const size_t hostnameSize
= 257;
1021 bool ok
= wxGetFullHostName(buf
.GetWriteBuf(hostnameSize
), hostnameSize
);
1023 buf
.UngetWriteBuf();
1031 wxString
wxGetHomeDir()
1034 wxGetHomeDir(&home
);
1041 wxString
wxGetCurrentDir()
1048 ok
= getcwd(dir
.GetWriteBuf(len
+ 1), len
) != NULL
;
1049 dir
.UngetWriteBuf();
1053 if ( errno
!= ERANGE
)
1055 wxLogSysError(_T("Failed to get current directory"));
1057 return wxEmptyString
;
1061 // buffer was too small, retry with a larger one