]> git.saurik.com Git - wxWidgets.git/blob - src/common/utilscmn.cpp
Ignore failure when deleting something that might not exist
[wxWidgets.git] / src / common / utilscmn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: utilscmn.cpp
3 // Purpose: Miscellaneous utility functions and classes
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 29/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "utils.h"
14 #endif
15
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 #ifndef WX_PRECOMP
24 #include "wx/defs.h"
25 #include "wx/utils.h"
26 #include "wx/window.h"
27 #include "wx/menu.h"
28 #include "wx/frame.h"
29 #include "wx/msgdlg.h"
30 #include "wx/textdlg.h"
31 #endif
32
33 #include "wx/ioswrap.h"
34
35 #if wxUSE_IOSTREAMH
36 #include <fstream.h>
37 #else
38 #include <fstream>
39 #endif
40
41 #include <ctype.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #if !defined(__WATCOMC__)
46 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
47 #include <errno.h>
48 #endif
49 #endif
50 #include <time.h>
51 #ifndef __MWERKS__
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #endif
55
56 #ifdef __SALFORDC__
57 #include <clib.h>
58 #endif
59
60 // Pattern matching code.
61 // Yes, this path is deliberate (for Borland compilation)
62 #ifdef wx_mac /* MATTHEW: [5] Mac doesn't like paths with "/" */
63 #include "glob.inc"
64 #else
65 #include "../common/glob.inc"
66 #endif
67
68 #ifdef __WXMSW__
69 #include "windows.h"
70 #endif
71
72 #define _MAXPATHLEN 500
73
74 extern char *wxBuffer;
75
76 #ifdef __WXMAC__
77 int strcasecmp(const char *str_1, const char *str_2)
78 {
79 register char c1, c2;
80 do {
81 c1 = tolower(*str_1++);
82 c2 = tolower(*str_2++);
83 } while ( c1 && (c1 == c2) );
84
85 return c1 - c2;
86 }
87
88 int strncasecmp(const char *str_1, const char *str_2, size_t maxchar)
89 {
90
91 register char c1, c2;
92 while( maxchar--)
93 {
94 c1 = tolower(*str_1++);
95 c2 = tolower(*str_2++);
96
97 if ( !c1 || c1!=c2 )
98 return c1 - c2;
99
100 } ;
101
102 return 0 ;
103
104 }
105 #endif
106 #ifdef __VMS__
107 // we have no strI functions under VMS, therefore I have implemented
108 // an inefficient but portable version: convert copies of strings to lowercase
109 // and then use the normal comparison
110 static void myLowerString(char *s)
111 {
112 while(*s){
113 if(isalpha(*s)) *s = (char)tolower(*s);
114 s++;
115 }
116 }
117
118 int strcasecmp(const char *str_1, const char *str_2)
119 {
120 char *temp1 = new char[strlen(str_1)+1];
121 char *temp2 = new char[strlen(str_2)+1];
122 strcpy(temp1,str_1);
123 strcpy(temp2,str_2);
124 myLowerString(temp1);
125 myLowerString(temp2);
126
127 int result = strcmp(temp1,temp2);
128 delete[] temp1;
129 delete[] temp2;
130
131 return(result);
132 }
133
134 int strncasecmp(const char *str_1, const char *str_2, size_t maxchar)
135 {
136 char *temp1 = new char[strlen(str_1)+1];
137 char *temp2 = new char[strlen(str_2)+1];
138 strcpy(temp1,str_1);
139 strcpy(temp2,str_2);
140 myLowerString(temp1);
141 myLowerString(temp2);
142
143 int result = strncmp(temp1,temp2,maxchar);
144 delete[] temp1;
145 delete[] temp2;
146
147 return(result);
148 }
149 #endif
150
151 #ifdef __WINDOWS__
152
153 #ifndef __GNUWIN32__
154 #ifndef __MWERKS__
155 #define strcasecmp stricmp
156 #define strncasecmp strnicmp
157 #else
158 #define strcasecmp _stricmp
159 #define strncasecmp _strnicmp
160 #endif
161 #endif
162
163 #else
164 // This declaration is missing in SunOS!
165 // (Yes, I know it is NOT ANSI-C but its in BSD libc)
166 #if defined(__xlC) || defined(__AIX__) || defined(__GNUG__)
167 extern "C"
168 {
169 int strcasecmp (const char *, const char *);
170 int strncasecmp (const char *, const char *, size_t);
171 }
172 #endif
173 #endif /* __WXMSW__ */
174
175
176 char *
177 copystring (const char *s)
178 {
179 if (s == NULL) s = "";
180 size_t len = strlen (s) + 1;
181
182 char *news = new char[len];
183 memcpy (news, s, len); // Should be the fastest
184
185 return news;
186 }
187
188 // Id generation
189 static long wxCurrentId = 100;
190
191 long
192 wxNewId (void)
193 {
194 return wxCurrentId++;
195 }
196
197 long
198 wxGetCurrentId(void) { return wxCurrentId; }
199
200 void
201 wxRegisterId (long id)
202 {
203 if (id >= wxCurrentId)
204 wxCurrentId = id + 1;
205 }
206
207 void
208 StringToFloat (char *s, float *number)
209 {
210 if (s && *s && number)
211 *number = (float) strtod (s, (char **) NULL);
212 }
213
214 void
215 StringToDouble (char *s, double *number)
216 {
217 if (s && *s && number)
218 *number = strtod (s, (char **) NULL);
219 }
220
221 char *
222 FloatToString (float number, const char *fmt)
223 {
224 static char buf[256];
225
226 // sprintf (buf, "%.2f", number);
227 sprintf (buf, fmt, number);
228 return buf;
229 }
230
231 char *
232 DoubleToString (double number, const char *fmt)
233 {
234 static char buf[256];
235
236 sprintf (buf, fmt, number);
237 return buf;
238 }
239
240 void
241 StringToInt (char *s, int *number)
242 {
243 if (s && *s && number)
244 *number = (int) strtol (s, (char **) NULL, 10);
245 }
246
247 void
248 StringToLong (char *s, long *number)
249 {
250 if (s && *s && number)
251 *number = strtol (s, (char **) NULL, 10);
252 }
253
254 char *
255 IntToString (int number)
256 {
257 static char buf[20];
258
259 sprintf (buf, "%d", number);
260 return buf;
261 }
262
263 char *
264 LongToString (long number)
265 {
266 static char buf[20];
267
268 sprintf (buf, "%ld", number);
269 return buf;
270 }
271
272 // Array used in DecToHex conversion routine.
273 static char hexArray[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
274 'C', 'D', 'E', 'F' };
275
276 // Convert 2-digit hex number to decimal
277 int wxHexToDec(const wxString& buf)
278 {
279 int firstDigit, secondDigit;
280
281 if (buf.GetChar(0) >= 'A')
282 firstDigit = buf.GetChar(0) - 'A' + 10;
283 else
284 firstDigit = buf.GetChar(0) - '0';
285
286 if (buf.GetChar(1) >= 'A')
287 secondDigit = buf.GetChar(1) - 'A' + 10;
288 else
289 secondDigit = buf.GetChar(1) - '0';
290
291 return firstDigit * 16 + secondDigit;
292 }
293
294 // Convert decimal integer to 2-character hex string
295 void wxDecToHex(int dec, char *buf)
296 {
297 int firstDigit = (int)(dec/16.0);
298 int secondDigit = (int)(dec - (firstDigit*16.0));
299 buf[0] = hexArray[firstDigit];
300 buf[1] = hexArray[secondDigit];
301 buf[2] = 0;
302 }
303
304 // Convert decimal integer to 2-character hex string
305 wxString wxDecToHex(int dec)
306 {
307 char buf[3];
308 wxDecToHex(dec, buf);
309 return wxString(buf);
310 }
311
312 // Match a string INDEPENDENT OF CASE
313 bool
314 StringMatch (char *str1, char *str2, bool subString, bool exact)
315 {
316 if (str1 == NULL || str2 == NULL)
317 return FALSE;
318 if (str1 == str2)
319 return TRUE;
320
321 if (subString)
322 {
323 int len1 = strlen (str1);
324 int len2 = strlen (str2);
325 int i;
326
327 // Search for str1 in str2
328 // Slow .... but acceptable for short strings
329 for (i = 0; i <= len2 - len1; i++)
330 {
331 if (strncasecmp (str1, str2 + i, len1) == 0)
332 return TRUE;
333 }
334 }
335 else if (exact)
336 {
337 if (strcasecmp (str1, str2) == 0)
338 return TRUE;
339 }
340 else
341 {
342 int len1 = strlen (str1);
343 int len2 = strlen (str2);
344
345 if (strncasecmp (str1, str2, wxMin (len1, len2)) == 0)
346 return TRUE;
347 }
348
349 return FALSE;
350 }
351
352 // Return the current date/time
353 // [volatile]
354 wxString wxNow( void )
355 {
356 time_t now = time((time_t *) NULL);
357 char *date = ctime(&now);
358 date[24] = '\0';
359 return wxString(date);
360 }
361
362 /*
363 * Strip out any menu codes
364 */
365
366 char *wxStripMenuCodes (char *in, char *out)
367 {
368 if (!in)
369 return (char *) NULL;
370
371 if (!out)
372 out = copystring(in);
373
374 char *tmpOut = out;
375
376 while (*in)
377 {
378 if (*in == '&')
379 {
380 // Check && -> &, &x -> x
381 if (*++in == '&')
382 *out++ = *in++;
383 }
384 else if (*in == '\t')
385 {
386 // Remove all stuff after \t in X mode, and let the stuff as is
387 // in Windows mode.
388 // Accelerators are handled in wx_item.cc for Motif, and are not
389 // YET supported in XView
390 break;
391 }
392 else
393 *out++ = *in++;
394 } // while
395
396 *out = '\0';
397
398 return tmpOut;
399 }
400
401 wxString wxStripMenuCodes(const wxString& str)
402 {
403 char *buf = new char[str.Length() + 1];
404 wxStripMenuCodes((char*) (const char*) str, buf);
405 wxString str1(buf);
406 delete[] buf;
407 return str1;
408 }
409
410 /*
411 * Window search functions
412 *
413 */
414
415 /*
416 * If parent is non-NULL, look through children for a label or title
417 * matching the specified string. If NULL, look through all top-level windows.
418 *
419 */
420
421 static wxWindow *wxFindWindowByLabel1 (const wxString& title, wxWindow * parent);
422
423 wxWindow *
424 wxFindWindowByLabel (const wxString& title, wxWindow * parent)
425 {
426 if (parent)
427 {
428 return wxFindWindowByLabel1 (title, parent);
429 }
430 else
431 {
432 for (wxNode * node = wxTopLevelWindows.First (); node; node = node->Next ())
433 {
434 wxWindow *win = (wxWindow *) node->Data ();
435 wxWindow *retwin = wxFindWindowByLabel1 (title, win);
436 if (retwin)
437 return retwin;
438 } // for()
439
440 }
441 return (wxWindow *) NULL;
442 }
443
444 // Recursive
445 static wxWindow *
446 wxFindWindowByLabel1 (const wxString& title, wxWindow * parent)
447 {
448 if (parent)
449 {
450 if (parent->GetLabel() == title)
451 return parent;
452 }
453
454 if (parent)
455 {
456 for (wxNode * node = parent->GetChildren().First (); node; node = node->Next ())
457 {
458 wxWindow *win = (wxWindow *) node->Data ();
459 wxWindow *retwin = wxFindWindowByLabel1 (title, win);
460 if (retwin)
461 return retwin;
462 } // for()
463
464 }
465
466 return (wxWindow *) NULL; // Not found
467
468 }
469
470 /*
471 * If parent is non-NULL, look through children for a name
472 * matching the specified string. If NULL, look through all top-level windows.
473 *
474 */
475
476 static wxWindow *wxFindWindowByName1 (const wxString& title, wxWindow * parent);
477
478 wxWindow *
479 wxFindWindowByName (const wxString& title, wxWindow * parent)
480 {
481 if (parent)
482 {
483 return wxFindWindowByName1 (title, parent);
484 }
485 else
486 {
487 for (wxNode * node = wxTopLevelWindows.First (); node; node = node->Next ())
488 {
489 wxWindow *win = (wxWindow *) node->Data ();
490 wxWindow *retwin = wxFindWindowByName1 (title, win);
491 if (retwin)
492 return retwin;
493 } // for()
494
495 }
496 // Failed? Try by label instead.
497 return wxFindWindowByLabel(title, parent);
498 }
499
500 // Recursive
501 static wxWindow *
502 wxFindWindowByName1 (const wxString& title, wxWindow * parent)
503 {
504 if (parent)
505 {
506 if ( parent->GetName() == title )
507 return parent;
508 }
509
510 if (parent)
511 {
512 for (wxNode * node = parent->GetChildren().First (); node; node = node->Next ())
513 {
514 wxWindow *win = (wxWindow *) node->Data ();
515 wxWindow *retwin = wxFindWindowByName1 (title, win);
516 if (retwin)
517 return retwin;
518 } // for()
519
520 }
521
522 return (wxWindow *) NULL; // Not found
523
524 }
525
526 // Returns menu item id or -1 if none.
527 int
528 wxFindMenuItemId (wxFrame * frame, const wxString& menuString, const wxString& itemString)
529 {
530 wxMenuBar *menuBar = frame->GetMenuBar ();
531 if (!menuBar)
532 return -1;
533 return menuBar->FindMenuItem (menuString, itemString);
534 }
535
536 /*
537 On Fri, 21 Jul 1995, Paul Craven wrote:
538
539 > Is there a way to find the path of running program's executable? I can get
540 > my home directory, and the current directory, but I don't know how to get the
541 > executable directory.
542 >
543
544 The code below (warty as it is), does what you want on most Unix,
545 DOS, and Mac platforms (it's from the ALS Prolog main).
546
547 || Ken Bowen Applied Logic Systems, Inc. PO Box 180,
548 ||==== Voice: +1 (617)965-9191 Newton Centre,
549 || FAX: +1 (617)965-1636 MA 02159 USA
550 Email: ken@als.com WWW: http://www.als.com
551 ------------------------------------------------------------------------
552 */
553
554 // This code is commented out but it may be integrated with wxWin at
555 // a later date, after testing. Thanks Ken!
556 #if 0
557
558 /*--------------------------------------------------------------------*
559 | whereami is given a filename f in the form: whereami(argv[0])
560 | It returns the directory in which the executable file (containing
561 | this code [main.c] ) may be found. A dot will be returned to indicate
562 | the current directory.
563 *--------------------------------------------------------------------*/
564
565 static void
566 whereami(name)
567 char *name;
568 {
569 register char *cutoff = NULL; /* stifle -Wall */
570 register char *s;
571 register char *t;
572 int cc;
573 char ebuf[4096];
574
575 /*
576 * See if the file is accessible either through the current directory
577 * or through an absolute path.
578 */
579
580 if (access(name, R_OK) == 0) {
581
582 /*-------------------------------------------------------------*
583 * The file was accessible without any other work. But the current
584 * working directory might change on us, so if it was accessible
585 * through the cwd, then we should get it for later accesses.
586 *-------------------------------------------------------------*/
587
588 t = imagedir;
589 if (!absolute_pathname(name)) {
590 #if defined(DOS) || defined(__WIN32__)
591 int drive;
592 char *newrbuf;
593
594 newrbuf = imagedir;
595 #ifndef __DJGPP__
596 if (*(name + 1) == ':') {
597 if (*name >= 'a' && *name <= 'z')
598 drive = (int) (*name - 'a' + 1);
599 else
600 drive = (int) (*name - 'A' + 1);
601 *newrbuf++ = *name;
602 *newrbuf++ = *(name + 1);
603 *newrbuf++ = DIR_SEPARATOR;
604 }
605 else {
606 drive = 0;
607 *newrbuf++ = DIR_SEPARATOR;
608 }
609 if (getcwd(newrbuf, drive) == 0) { /* } */
610 #else
611 if (getcwd(newrbuf, 1024) == 0) { /* } */
612 #endif
613 #else /* DOS */
614 #ifdef HAVE_GETWD
615 if (getwd(imagedir) == 0) { /* } */
616 #else /* !HAVE_GETWD */
617 if (getcwd(imagedir, 1024) == 0) {
618 #endif /* !HAVE_GETWD */
619 #endif /* DOS */
620 fatal_error(FE_GETCWD, 0);
621 }
622 for (; *t; t++) /* Set t to end of buffer */
623 ;
624 if (*(t - 1) == DIR_SEPARATOR) /* leave slash if already
625 * last char
626 */
627 cutoff = t - 1;
628 else {
629 cutoff = t; /* otherwise put one in */
630 *t++ = DIR_SEPARATOR;
631 }
632 }
633 #if (!defined(__MAC__) && !defined(__DJGPP__) && !defined(__GO32__) && !defined(__WIN32__))
634 else
635 (*t++ = DIR_SEPARATOR);
636 #endif
637
638 /*-------------------------------------------------------------*
639 * Copy the rest of the string and set the cutoff if it was not
640 * already set. If the first character of name is a slash, cutoff
641 * is not presently set but will be on the first iteration of the
642 * loop below.
643 *-------------------------------------------------------------*/
644
645 for ((*name == DIR_SEPARATOR ? (s = name+1) : (s = name));;) {
646 if (*s == DIR_SEPARATOR)
647 cutoff = t;
648 if (!(*t++ = *s++))
649 break;
650 }
651
652 }
653 else {
654
655 /*-------------------------------------------------------------*
656 * Get the path list from the environment. If the path list is
657 * inaccessible for any reason, leave with fatal error.
658 *-------------------------------------------------------------*/
659
660 #ifdef __MAC__
661 if ((s = getenv("Commands")) == (char *) 0)
662 #else
663 if ((s = getenv("PATH")) == (char *) 0)
664 #endif
665 fatal_error(FE_PATH, 0);
666
667 /*
668 * Copy path list into ebuf and set the source pointer to the
669 * beginning of this buffer.
670 */
671
672 strcpy(ebuf, s);
673 s = ebuf;
674
675 for (;;) {
676 t = imagedir;
677 while (*s && *s != PATH_SEPARATOR)
678 *t++ = *s++;
679 if (t > imagedir && *(t - 1) == DIR_SEPARATOR)
680 ; /* do nothing -- slash already is in place */
681 else
682 *t++ = DIR_SEPARATOR; /* put in the slash */
683 cutoff = t - 1; /* set cutoff */
684 strcpy(t, name);
685 if (access(imagedir, R_OK) == 0)
686 break;
687
688 if (*s)
689 s++; /* advance source pointer */
690 else
691 fatal_error(FE_INFND, 0);
692 }
693
694 }
695
696 /*-------------------------------------------------------------*
697 | At this point the full pathname should exist in imagedir and
698 | cutoff should be set to the final slash. We must now determine
699 | whether the file name is a symbolic link or not and chase it down
700 | if it is. Note that we reuse ebuf for getting the link.
701 *-------------------------------------------------------------*/
702
703 #ifdef HAVE_SYMLINK
704 while ((cc = readlink(imagedir, ebuf, 512)) != -1) {
705 ebuf[cc] = 0;
706 s = ebuf;
707 if (*s == DIR_SEPARATOR) {
708 t = imagedir;
709 }
710 else {
711 t = cutoff + 1;
712 }
713 for (;;) {
714 if (*s == DIR_SEPARATOR)
715 cutoff = t; /* mark the last slash seen */
716 if (!(*t++ = *s++)) /* copy the character */
717 break;
718 }
719 }
720
721 #endif /* HAVE_SYMLINK */
722
723 strcpy(imagename, cutoff + 1); /* keep the image name */
724 *(cutoff + 1) = 0; /* chop off the filename part */
725 }
726
727 #endif
728
729
730 // Yield to other apps/messages and disable user input
731 bool wxSafeYield(wxWindow *win)
732 {
733 wxNode *node;
734 for ( node = wxTopLevelWindows.GetFirst();
735 node;
736 node = node->GetNext() )
737 ((wxWindow*)node->GetData())->Enable(FALSE);
738
739 // always enable ourselves
740 if(win) win->Enable(true);
741 bool rc = wxYield();
742
743 for ( node = wxTopLevelWindows.GetFirst();
744 node;
745 node = node->GetNext() )
746 ((wxWindow*)node->GetData())->Enable(TRUE);
747 return rc;
748 }
749
750 /*
751 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
752 * since otherwise the generic code may be pulled in unnecessarily.
753 */
754
755 int wxMessageBox(const wxString& message, const wxString& caption, long style,
756 wxWindow *parent, int WXUNUSED(x), int WXUNUSED(y) )
757 {
758 wxMessageDialog dialog(parent, message, caption, style);
759
760 int ans = dialog.ShowModal();
761 switch ( ans )
762 {
763 case wxID_OK:
764 return wxOK;
765 break;
766 case wxID_YES:
767 return wxYES;
768 break;
769 case wxID_NO:
770 return wxNO;
771 break;
772 default:
773 case wxID_CANCEL:
774 return wxCANCEL;
775 break;
776 }
777 return ans;
778 }
779
780 wxString wxGetTextFromUser(const wxString& message, const wxString& caption,
781 const wxString& defaultValue, wxWindow *parent,
782 int x, int y, bool WXUNUSED(centre) )
783 {
784 wxTextEntryDialog dialog(parent, message, caption, defaultValue, wxOK|wxCANCEL, wxPoint(x, y));
785 if (dialog.ShowModal() == wxID_OK)
786 return dialog.GetValue();
787 else
788 return wxString("");
789 }
790
791 #ifdef __MWERKS__
792 char *strdup(const char *s)
793 {
794 return strcpy( (char*) malloc( strlen( s ) + 1 ) , s ) ;
795 }
796
797 int isascii( int c )
798 {
799 return ( c >= 0 && c < 128 ) ;
800 }
801 #endif
802
803 // ----------------------------------------------------------------------------
804 // network and user id functions
805 // ----------------------------------------------------------------------------
806
807 // Get Full RFC822 style email address
808 bool wxGetEmailAddress(char *address, int maxSize)
809 {
810 wxString email = wxGetEmailAddress();
811 if ( !email )
812 return FALSE;
813
814 strncpy(address, email, maxSize - 1);
815 address[maxSize - 1] = '\0';
816
817 return TRUE;
818 }
819
820 wxString wxGetEmailAddress()
821 {
822 wxString email;
823
824 wxString host = wxGetHostName();
825 if ( !!host )
826 {
827 wxString user = wxGetUserId();
828 if ( !!user )
829 {
830 wxString email(user);
831 email << '@' << host;
832 }
833 }
834
835 return email;
836 }
837
838 wxString wxGetUserId()
839 {
840 static const int maxLoginLen = 256; // FIXME arbitrary number
841
842 wxString buf;
843 bool ok = wxGetUserId(buf.GetWriteBuf(maxLoginLen), maxLoginLen);
844 buf.UngetWriteBuf();
845
846 if ( !ok )
847 buf.Empty();
848
849 return buf;
850 }
851
852 wxString wxGetUserName()
853 {
854 static const int maxUserNameLen = 1024; // FIXME arbitrary number
855
856 wxString buf;
857 bool ok = wxGetUserName(buf.GetWriteBuf(maxUserNameLen), maxUserNameLen);
858 buf.UngetWriteBuf();
859
860 if ( !ok )
861 buf.Empty();
862
863 return buf;
864 }
865
866 wxString wxGetHostName()
867 {
868 static const size_t hostnameSize = 257;
869
870 wxString buf;
871 bool ok = wxGetHostName(buf.GetWriteBuf(hostnameSize), hostnameSize);
872
873 buf.UngetWriteBuf();
874
875 if ( !ok )
876 buf.Empty();
877
878 return buf;
879 }
880