]> git.saurik.com Git - wxWidgets.git/blob - src/common/utilscmn.cpp
fixed bug in parsing filenames without paths, added more/better tests
[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 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "utils.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/defs.h"
33 #include "wx/string.h"
34 #include "wx/utils.h"
35 #include "wx/intl.h"
36 #include "wx/log.h"
37
38 #if wxUSE_GUI
39 #include "wx/window.h"
40 #include "wx/menu.h"
41 #include "wx/frame.h"
42 #include "wx/msgdlg.h"
43 #include "wx/textdlg.h"
44 #if wxUSE_ACCEL
45 #include "wx/menuitem.h"
46 #include "wx/accel.h"
47 #endif // wxUSE_ACCEL
48 #endif // wxUSE_GUI
49 #endif // WX_PRECOMP
50
51 #ifndef __WIN16__
52 #include "wx/process.h"
53 #include "wx/txtstrm.h"
54 #endif
55
56 #include <ctype.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60
61 #if !defined(__WATCOMC__)
62 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
63 #include <errno.h>
64 #endif
65 #endif
66
67 #if wxUSE_GUI
68 #include "wx/colordlg.h"
69 #include "wx/notebook.h"
70 #include "wx/frame.h"
71 #include "wx/statusbr.h"
72 #include "wx/toolbar.h"
73 #endif // wxUSE_GUI
74
75 #include <time.h>
76
77 #ifndef __MWERKS__
78 #include <sys/types.h>
79 #include <sys/stat.h>
80 #endif
81
82 #ifdef __SALFORDC__
83 #include <clib.h>
84 #endif
85
86 #ifdef __WXMSW__
87 #include "wx/msw/private.h"
88 #endif
89
90 // ----------------------------------------------------------------------------
91 // function protoypes
92 // ----------------------------------------------------------------------------
93
94 #if wxUSE_GUI
95 static wxWindow *wxFindWindowByLabel1(const wxString& title, wxWindow *parent);
96 static wxWindow *wxFindWindowByName1 (const wxString& title, wxWindow *parent);
97 #endif // wxUSE_GUI
98
99 // ============================================================================
100 // implementation
101 // ============================================================================
102
103 // ----------------------------------------------------------------------------
104 // string functions
105 // ----------------------------------------------------------------------------
106
107 #ifdef __WXMAC__
108 int strcasecmp(const char *str_1, const char *str_2)
109 {
110 register char c1, c2;
111 do {
112 c1 = tolower(*str_1++);
113 c2 = tolower(*str_2++);
114 } while ( c1 && (c1 == c2) );
115
116 return c1 - c2;
117 }
118
119 int strncasecmp(const char *str_1, const char *str_2, size_t maxchar)
120 {
121
122 register char c1, c2;
123 while( maxchar--)
124 {
125 c1 = tolower(*str_1++);
126 c2 = tolower(*str_2++);
127
128 if ( !c1 || c1!=c2 )
129 return c1 - c2;
130
131 } ;
132
133 return 0 ;
134
135 }
136 #endif // wxMAC
137
138 #if defined( __VMS__ ) && ( __VMS_VER < 70000000 )
139 // we have no strI functions under VMS, therefore I have implemented
140 // an inefficient but portable version: convert copies of strings to lowercase
141 // and then use the normal comparison
142 static void myLowerString(char *s)
143 {
144 while(*s){
145 if(isalpha(*s)) *s = (char)tolower(*s);
146 s++;
147 }
148 }
149
150 int strcasecmp(const char *str_1, const char *str_2)
151 {
152 char *temp1 = new char[strlen(str_1)+1];
153 char *temp2 = new char[strlen(str_2)+1];
154 strcpy(temp1,str_1);
155 strcpy(temp2,str_2);
156 myLowerString(temp1);
157 myLowerString(temp2);
158
159 int result = wxStrcmp(temp1,temp2);
160 delete[] temp1;
161 delete[] temp2;
162
163 return(result);
164 }
165
166 int strncasecmp(const char *str_1, const char *str_2, size_t maxchar)
167 {
168 char *temp1 = new char[strlen(str_1)+1];
169 char *temp2 = new char[strlen(str_2)+1];
170 strcpy(temp1,str_1);
171 strcpy(temp2,str_2);
172 myLowerString(temp1);
173 myLowerString(temp2);
174
175 int result = strncmp(temp1,temp2,maxchar);
176 delete[] temp1;
177 delete[] temp2;
178
179 return(result);
180 }
181 #endif // __VMS__
182
183 #ifdef __WINDOWS__
184
185 #ifndef __GNUWIN32__
186 #ifndef __MWERKS__
187 #define strcasecmp stricmp
188 #define strncasecmp strnicmp
189 #else
190 #define strcasecmp _stricmp
191 #define strncasecmp _strnicmp
192 #endif
193 #endif
194
195 #else
196
197 #ifdef __EMX__
198 #define strcasecmp stricmp
199 #define strncasecmp strnicmp
200 #endif
201
202 // This declaration is missing in SunOS!
203 // (Yes, I know it is NOT ANSI-C but its in BSD libc)
204 #if defined(__xlC) || defined(__AIX__) || defined(__GNUG__)
205 extern "C"
206 {
207 int strcasecmp (const char *, const char *);
208 int strncasecmp (const char *, const char *, size_t);
209 }
210 #endif
211 #endif /* __WXMSW__ */
212
213 #ifdef __WXPM__
214 #define strcasecmp stricmp
215 #define strncasecmp strnicmp
216 #endif
217
218 wxChar *
219 copystring (const wxChar *s)
220 {
221 if (s == NULL) s = wxT("");
222 size_t len = wxStrlen (s) + 1;
223
224 wxChar *news = new wxChar[len];
225 memcpy (news, s, len * sizeof(wxChar)); // Should be the fastest
226
227 return news;
228 }
229
230 // Id generation
231 static long wxCurrentId = 100;
232
233 long
234 wxNewId (void)
235 {
236 return wxCurrentId++;
237 }
238
239 long
240 wxGetCurrentId(void) { return wxCurrentId; }
241
242 void
243 wxRegisterId (long id)
244 {
245 if (id >= wxCurrentId)
246 wxCurrentId = id + 1;
247 }
248
249 void
250 StringToFloat (wxChar *s, float *number)
251 {
252 if (s && *s && number)
253 *number = (float) wxStrtod (s, (wxChar **) NULL);
254 }
255
256 void
257 StringToDouble (wxChar *s, double *number)
258 {
259 if (s && *s && number)
260 *number = wxStrtod (s, (wxChar **) NULL);
261 }
262
263 wxChar *
264 FloatToString (float number, const wxChar *fmt)
265 {
266 static wxChar buf[256];
267
268 // sprintf (buf, "%.2f", number);
269 wxSprintf (buf, fmt, number);
270 return buf;
271 }
272
273 wxChar *
274 DoubleToString (double number, const wxChar *fmt)
275 {
276 static wxChar buf[256];
277
278 wxSprintf (buf, fmt, number);
279 return buf;
280 }
281
282 void
283 StringToInt (wxChar *s, int *number)
284 {
285 if (s && *s && number)
286 *number = (int) wxStrtol (s, (wxChar **) NULL, 10);
287 }
288
289 void
290 StringToLong (wxChar *s, long *number)
291 {
292 if (s && *s && number)
293 *number = wxStrtol (s, (wxChar **) NULL, 10);
294 }
295
296 wxChar *
297 IntToString (int number)
298 {
299 static wxChar buf[20];
300
301 wxSprintf (buf, wxT("%d"), number);
302 return buf;
303 }
304
305 wxChar *
306 LongToString (long number)
307 {
308 static wxChar buf[20];
309
310 wxSprintf (buf, wxT("%ld"), number);
311 return buf;
312 }
313
314 // Array used in DecToHex conversion routine.
315 static wxChar hexArray[] = wxT("0123456789ABCDEF");
316
317 // Convert 2-digit hex number to decimal
318 int wxHexToDec(const wxString& buf)
319 {
320 int firstDigit, secondDigit;
321
322 if (buf.GetChar(0) >= wxT('A'))
323 firstDigit = buf.GetChar(0) - wxT('A') + 10;
324 else
325 firstDigit = buf.GetChar(0) - wxT('0');
326
327 if (buf.GetChar(1) >= wxT('A'))
328 secondDigit = buf.GetChar(1) - wxT('A') + 10;
329 else
330 secondDigit = buf.GetChar(1) - wxT('0');
331
332 return firstDigit * 16 + secondDigit;
333 }
334
335 // Convert decimal integer to 2-character hex string
336 void wxDecToHex(int dec, wxChar *buf)
337 {
338 int firstDigit = (int)(dec/16.0);
339 int secondDigit = (int)(dec - (firstDigit*16.0));
340 buf[0] = hexArray[firstDigit];
341 buf[1] = hexArray[secondDigit];
342 buf[2] = 0;
343 }
344
345 // Convert decimal integer to 2-character hex string
346 wxString wxDecToHex(int dec)
347 {
348 wxChar buf[3];
349 wxDecToHex(dec, buf);
350 return wxString(buf);
351 }
352
353 // Match a string INDEPENDENT OF CASE
354 bool
355 StringMatch (char *str1, char *str2, bool subString, bool exact)
356 {
357 if (str1 == NULL || str2 == NULL)
358 return FALSE;
359 if (str1 == str2)
360 return TRUE;
361
362 if (subString)
363 {
364 int len1 = strlen (str1);
365 int len2 = strlen (str2);
366 int i;
367
368 // Search for str1 in str2
369 // Slow .... but acceptable for short strings
370 for (i = 0; i <= len2 - len1; i++)
371 {
372 if (strncasecmp (str1, str2 + i, len1) == 0)
373 return TRUE;
374 }
375 }
376 else if (exact)
377 {
378 if (strcasecmp (str1, str2) == 0)
379 return TRUE;
380 }
381 else
382 {
383 int len1 = strlen (str1);
384 int len2 = strlen (str2);
385
386 if (strncasecmp (str1, str2, wxMin (len1, len2)) == 0)
387 return TRUE;
388 }
389
390 return FALSE;
391 }
392
393 // Return the current date/time
394 // [volatile]
395 wxString wxNow()
396 {
397 time_t now = time((time_t *) NULL);
398 char *date = ctime(&now);
399 date[24] = '\0';
400 return wxString(date);
401 }
402
403 #if wxUSE_GUI
404
405 // ----------------------------------------------------------------------------
406 // Menu accelerators related functions
407 // ----------------------------------------------------------------------------
408
409 wxChar *wxStripMenuCodes (wxChar *in, wxChar *out)
410 {
411 if (!in)
412 return (wxChar *) NULL;
413
414 if (!out)
415 out = copystring(in);
416
417 wxChar *tmpOut = out;
418
419 while (*in)
420 {
421 if (*in == wxT('&'))
422 {
423 // Check && -> &, &x -> x
424 if (*++in == wxT('&'))
425 *out++ = *in++;
426 }
427 else if (*in == wxT('\t'))
428 {
429 // Remove all stuff after \t in X mode, and let the stuff as is
430 // in Windows mode.
431 // Accelerators are handled in wx_item.cc for Motif, and are not
432 // YET supported in XView
433 break;
434 }
435 else
436 *out++ = *in++;
437 } // while
438
439 *out = wxT('\0');
440
441 return tmpOut;
442 }
443
444 wxString wxStripMenuCodes(const wxString& str)
445 {
446 wxChar *buf = new wxChar[str.Length() + 1];
447 wxStripMenuCodes(WXSTRINGCAST str, buf);
448 wxString str1(buf);
449 delete[] buf;
450 return str1;
451 }
452
453 #if wxUSE_ACCEL
454
455 // return wxAcceleratorEntry for the given menu string or NULL if none
456 // specified
457 wxAcceleratorEntry *wxGetAccelFromString(const wxString& label)
458 {
459 // check for accelerators: they are given after '\t'
460 int posTab = label.Find(wxT('\t'));
461 if ( posTab != wxNOT_FOUND ) {
462 // parse the accelerator string
463 int keyCode = 0;
464 int accelFlags = wxACCEL_NORMAL;
465 wxString current;
466 for ( size_t n = (size_t)posTab + 1; n < label.Len(); n++ ) {
467 if ( (label[n] == '+') || (label[n] == '-') ) {
468 if ( current == _("ctrl") )
469 accelFlags |= wxACCEL_CTRL;
470 else if ( current == _("alt") )
471 accelFlags |= wxACCEL_ALT;
472 else if ( current == _("shift") )
473 accelFlags |= wxACCEL_SHIFT;
474 else {
475 wxLogDebug(wxT("Unknown accel modifier: '%s'"),
476 current.c_str());
477 }
478
479 current.Empty();
480 }
481 else {
482 current += wxTolower(label[n]);
483 }
484 }
485
486 if ( current.IsEmpty() ) {
487 wxLogDebug(wxT("No accel key found, accel string ignored."));
488 }
489 else {
490 if ( current.Len() == 1 ) {
491 // it's a letter
492 keyCode = wxToupper(current[0U]);
493 }
494 else {
495 // is it a function key?
496 if ( current[0U] == 'f' && isdigit(current[1U]) &&
497 (current.Len() == 2 ||
498 (current.Len() == 3 && isdigit(current[2U]))) ) {
499 int n;
500 wxSscanf(current.c_str() + 1, wxT("%d"), &n);
501
502 keyCode = WXK_F1 + n - 1;
503 }
504 else {
505 // several special cases
506 current.MakeUpper();
507 if ( current == wxT("DEL") ) {
508 keyCode = WXK_DELETE;
509 }
510 else if ( current == wxT("DELETE") ) {
511 keyCode = WXK_DELETE;
512 }
513 else if ( current == wxT("INS") ) {
514 keyCode = WXK_INSERT;
515 }
516 else if ( current == wxT("INSERT") ) {
517 keyCode = WXK_INSERT;
518 }
519 #if 0
520 else if ( current == wxT("PGUP") ) {
521 keyCode = VK_PRIOR;
522 }
523 else if ( current == wxT("PGDN") ) {
524 keyCode = VK_NEXT;
525 }
526 #endif
527 else
528 {
529 wxLogDebug(wxT("Unrecognized accel key '%s', accel string ignored."),
530 current.c_str());
531 }
532 }
533 }
534 }
535
536 if ( keyCode ) {
537 // we do have something
538 return new wxAcceleratorEntry(accelFlags, keyCode);
539 }
540 }
541
542 return (wxAcceleratorEntry *)NULL;
543 }
544
545 #endif // wxUSE_ACCEL
546
547 // ----------------------------------------------------------------------------
548 // Window search functions
549 // ----------------------------------------------------------------------------
550
551 /*
552 * If parent is non-NULL, look through children for a label or title
553 * matching the specified string. If NULL, look through all top-level windows.
554 *
555 */
556
557 wxWindow *
558 wxFindWindowByLabel (const wxString& title, wxWindow * parent)
559 {
560 if (parent)
561 {
562 return wxFindWindowByLabel1(title, parent);
563 }
564 else
565 {
566 for ( wxWindowList::Node * node = wxTopLevelWindows.GetFirst();
567 node;
568 node = node->GetNext() )
569 {
570 wxWindow *win = node->GetData();
571 wxWindow *retwin = wxFindWindowByLabel1 (title, win);
572 if (retwin)
573 return retwin;
574 } // for()
575
576 }
577 return (wxWindow *) NULL;
578 }
579
580 // Recursive
581 static wxWindow *
582 wxFindWindowByLabel1 (const wxString& title, wxWindow * parent)
583 {
584 if (parent)
585 {
586 if (parent->GetLabel() == title)
587 return parent;
588 }
589
590 if (parent)
591 {
592 for ( wxWindowList::Node * node = parent->GetChildren().GetFirst();
593 node;
594 node = node->GetNext() )
595 {
596 wxWindow *win = (wxWindow *)node->GetData();
597 wxWindow *retwin = wxFindWindowByLabel1 (title, win);
598 if (retwin)
599 return retwin;
600 }
601
602 }
603
604 return (wxWindow *) NULL; // Not found
605 }
606
607 /*
608 * If parent is non-NULL, look through children for a name
609 * matching the specified string. If NULL, look through all top-level windows.
610 *
611 */
612
613 wxWindow *
614 wxFindWindowByName (const wxString& title, wxWindow * parent)
615 {
616 if (parent)
617 {
618 return wxFindWindowByName1 (title, parent);
619 }
620 else
621 {
622 for ( wxWindowList::Node * node = wxTopLevelWindows.GetFirst();
623 node;
624 node = node->GetNext() )
625 {
626 wxWindow *win = node->GetData();
627 wxWindow *retwin = wxFindWindowByName1 (title, win);
628 if (retwin)
629 return retwin;
630 }
631
632 }
633
634 // Failed? Try by label instead.
635 return wxFindWindowByLabel(title, parent);
636 }
637
638 // Recursive
639 static wxWindow *
640 wxFindWindowByName1 (const wxString& title, wxWindow * parent)
641 {
642 if (parent)
643 {
644 if ( parent->GetName() == title )
645 return parent;
646 }
647
648 if (parent)
649 {
650 for (wxNode * node = parent->GetChildren().First (); node; node = node->Next ())
651 {
652 wxWindow *win = (wxWindow *) node->Data ();
653 wxWindow *retwin = wxFindWindowByName1 (title, win);
654 if (retwin)
655 return retwin;
656 } // for()
657
658 }
659
660 return (wxWindow *) NULL; // Not found
661
662 }
663
664 // Returns menu item id or -1 if none.
665 int
666 wxFindMenuItemId (wxFrame * frame, const wxString& menuString, const wxString& itemString)
667 {
668 wxMenuBar *menuBar = frame->GetMenuBar ();
669 if (!menuBar)
670 return -1;
671 return menuBar->FindMenuItem (menuString, itemString);
672 }
673
674 // Try to find the deepest child that contains 'pt'.
675 // We go backwards, to try to allow for controls that are spacially
676 // within other controls, but are still siblings (e.g. buttons within
677 // static boxes). Static boxes are likely to be created _before_ controls
678 // that sit inside them.
679 wxWindow* wxFindWindowAtPoint(wxWindow* win, const wxPoint& pt)
680 {
681 if (!win->IsShown())
682 return NULL;
683
684 // Hack for wxNotebook case: at least in wxGTK, all pages
685 // claim to be shown, so we must only deal with the selected one.
686 if (win->IsKindOf(CLASSINFO(wxNotebook)))
687 {
688 wxNotebook* nb = (wxNotebook*) win;
689 int sel = nb->GetSelection();
690 if (sel >= 0)
691 {
692 wxWindow* child = nb->GetPage(sel);
693 wxWindow* foundWin = wxFindWindowAtPoint(child, pt);
694 if (foundWin)
695 return foundWin;
696 }
697 }
698 /* Doesn't work
699 // Frame case
700 else if (win->IsKindOf(CLASSINFO(wxFrame)))
701 {
702 // Pseudo-children that may not be mentioned in the child list
703 wxWindowList extraChildren;
704 wxFrame* frame = (wxFrame*) win;
705 if (frame->GetStatusBar())
706 extraChildren.Append(frame->GetStatusBar());
707 if (frame->GetToolBar())
708 extraChildren.Append(frame->GetToolBar());
709
710 wxNode* node = extraChildren.First();
711 while (node)
712 {
713 wxWindow* child = (wxWindow*) node->Data();
714 wxWindow* foundWin = wxFindWindowAtPoint(child, pt);
715 if (foundWin)
716 return foundWin;
717 node = node->Next();
718 }
719 }
720 */
721
722 wxNode* node = win->GetChildren().Last();
723 while (node)
724 {
725 wxWindow* child = (wxWindow*) node->Data();
726 wxWindow* foundWin = wxFindWindowAtPoint(child, pt);
727 if (foundWin)
728 return foundWin;
729 node = node->Previous();
730 }
731
732 wxPoint pos = win->GetPosition();
733 wxSize sz = win->GetSize();
734 if (win->GetParent())
735 {
736 pos = win->GetParent()->ClientToScreen(pos);
737 }
738
739 wxRect rect(pos, sz);
740 if (rect.Inside(pt))
741 return win;
742 else
743 return NULL;
744 }
745
746 wxWindow* wxGenericFindWindowAtPoint(const wxPoint& pt)
747 {
748 // Go backwards through the list since windows
749 // on top are likely to have been appended most
750 // recently.
751 wxNode* node = wxTopLevelWindows.Last();
752 while (node)
753 {
754 wxWindow* win = (wxWindow*) node->Data();
755 wxWindow* found = wxFindWindowAtPoint(win, pt);
756 if (found)
757 return found;
758 node = node->Previous();
759 }
760 return NULL;
761 }
762
763 #endif // wxUSE_GUI
764
765 /*
766 On Fri, 21 Jul 1995, Paul Craven wrote:
767
768 > Is there a way to find the path of running program's executable? I can get
769 > my home directory, and the current directory, but I don't know how to get the
770 > executable directory.
771 >
772
773 The code below (warty as it is), does what you want on most Unix,
774 DOS, and Mac platforms (it's from the ALS Prolog main).
775
776 || Ken Bowen Applied Logic Systems, Inc. PO Box 180,
777 ||==== Voice: +1 (617)965-9191 Newton Centre,
778 || FAX: +1 (617)965-1636 MA 02159 USA
779 Email: ken@als.com WWW: http://www.als.com
780 ------------------------------------------------------------------------
781 */
782
783 // This code is commented out but it may be integrated with wxWin at
784 // a later date, after testing. Thanks Ken!
785 #if 0
786
787 /*--------------------------------------------------------------------*
788 | whereami is given a filename f in the form: whereami(argv[0])
789 | It returns the directory in which the executable file (containing
790 | this code [main.c] ) may be found. A dot will be returned to indicate
791 | the current directory.
792 *--------------------------------------------------------------------*/
793
794 static void
795 whereami(name)
796 char *name;
797 {
798 register char *cutoff = NULL; /* stifle -Wall */
799 register char *s;
800 register char *t;
801 int cc;
802 char ebuf[4096];
803
804 /*
805 * See if the file is accessible either through the current directory
806 * or through an absolute path.
807 */
808
809 if (access(name, R_OK) == 0) {
810
811 /*-------------------------------------------------------------*
812 * The file was accessible without any other work. But the current
813 * working directory might change on us, so if it was accessible
814 * through the cwd, then we should get it for later accesses.
815 *-------------------------------------------------------------*/
816
817 t = imagedir;
818 if (!absolute_pathname(name)) {
819 #if defined(DOS) || defined(__WIN32__)
820 int drive;
821 char *newrbuf;
822
823 newrbuf = imagedir;
824 #ifndef __DJGPP__
825 if (*(name + 1) == ':') {
826 if (*name >= 'a' && *name <= 'z')
827 drive = (int) (*name - 'a' + 1);
828 else
829 drive = (int) (*name - 'A' + 1);
830 *newrbuf++ = *name;
831 *newrbuf++ = *(name + 1);
832 *newrbuf++ = DIR_SEPARATOR;
833 }
834 else {
835 drive = 0;
836 *newrbuf++ = DIR_SEPARATOR;
837 }
838 if (getcwd(newrbuf, drive) == 0) { /* } */
839 #else
840 if (getcwd(newrbuf, 1024) == 0) { /* } */
841 #endif
842 #else /* DOS */
843 #ifdef HAVE_GETWD
844 if (getwd(imagedir) == 0) { /* } */
845 #else /* !HAVE_GETWD */
846 if (getcwd(imagedir, 1024) == 0) {
847 #endif /* !HAVE_GETWD */
848 #endif /* DOS */
849 fatal_error(FE_GETCWD, 0);
850 }
851 for (; *t; t++) /* Set t to end of buffer */
852 ;
853 if (*(t - 1) == DIR_SEPARATOR) /* leave slash if already
854 * last char
855 */
856 cutoff = t - 1;
857 else {
858 cutoff = t; /* otherwise put one in */
859 *t++ = DIR_SEPARATOR;
860 }
861 }
862 #if (!defined(__MAC__) && !defined(__DJGPP__) && !defined(__GO32__) && !defined(__WIN32__))
863 else
864 (*t++ = DIR_SEPARATOR);
865 #endif
866
867 /*-------------------------------------------------------------*
868 * Copy the rest of the string and set the cutoff if it was not
869 * already set. If the first character of name is a slash, cutoff
870 * is not presently set but will be on the first iteration of the
871 * loop below.
872 *-------------------------------------------------------------*/
873
874 for ((*name == DIR_SEPARATOR ? (s = name+1) : (s = name));;) {
875 if (*s == DIR_SEPARATOR)
876 cutoff = t;
877 if (!(*t++ = *s++))
878 break;
879 }
880
881 }
882 else {
883
884 /*-------------------------------------------------------------*
885 * Get the path list from the environment. If the path list is
886 * inaccessible for any reason, leave with fatal error.
887 *-------------------------------------------------------------*/
888
889 #ifdef __MAC__
890 if ((s = getenv("Commands")) == (char *) 0)
891 #else
892 if ((s = getenv("PATH")) == (char *) 0)
893 #endif
894 fatal_error(FE_PATH, 0);
895
896 /*
897 * Copy path list into ebuf and set the source pointer to the
898 * beginning of this buffer.
899 */
900
901 strcpy(ebuf, s);
902 s = ebuf;
903
904 for (;;) {
905 t = imagedir;
906 while (*s && *s != PATH_SEPARATOR)
907 *t++ = *s++;
908 if (t > imagedir && *(t - 1) == DIR_SEPARATOR)
909 ; /* do nothing -- slash already is in place */
910 else
911 *t++ = DIR_SEPARATOR; /* put in the slash */
912 cutoff = t - 1; /* set cutoff */
913 strcpy(t, name);
914 if (access(imagedir, R_OK) == 0)
915 break;
916
917 if (*s)
918 s++; /* advance source pointer */
919 else
920 fatal_error(FE_INFND, 0);
921 }
922
923 }
924
925 /*-------------------------------------------------------------*
926 | At this point the full pathname should exist in imagedir and
927 | cutoff should be set to the final slash. We must now determine
928 | whether the file name is a symbolic link or not and chase it down
929 | if it is. Note that we reuse ebuf for getting the link.
930 *-------------------------------------------------------------*/
931
932 #ifdef HAVE_SYMLINK
933 while ((cc = readlink(imagedir, ebuf, 512)) != -1) {
934 ebuf[cc] = 0;
935 s = ebuf;
936 if (*s == DIR_SEPARATOR) {
937 t = imagedir;
938 }
939 else {
940 t = cutoff + 1;
941 }
942 for (;;) {
943 if (*s == DIR_SEPARATOR)
944 cutoff = t; /* mark the last slash seen */
945 if (!(*t++ = *s++)) /* copy the character */
946 break;
947 }
948 }
949
950 #endif /* HAVE_SYMLINK */
951
952 strcpy(imagename, cutoff + 1); /* keep the image name */
953 *(cutoff + 1) = 0; /* chop off the filename part */
954 }
955
956 #endif
957
958 #if wxUSE_GUI
959
960 // ----------------------------------------------------------------------------
961 // GUI helpers
962 // ----------------------------------------------------------------------------
963
964 /*
965 * N.B. these convenience functions must be separate from msgdlgg.cpp, textdlgg.cpp
966 * since otherwise the generic code may be pulled in unnecessarily.
967 */
968
969 int wxMessageBox(const wxString& message, const wxString& caption, long style,
970 wxWindow *parent, int WXUNUSED(x), int WXUNUSED(y) )
971 {
972 wxMessageDialog dialog(parent, message, caption, style);
973
974 int ans = dialog.ShowModal();
975 switch ( ans )
976 {
977 case wxID_OK:
978 return wxOK;
979 case wxID_YES:
980 return wxYES;
981 case wxID_NO:
982 return wxNO;
983 case wxID_CANCEL:
984 return wxCANCEL;
985 }
986
987 wxFAIL_MSG( _T("unexpected return code from wxMessageDialog") );
988
989 return wxCANCEL;
990 }
991
992 #if wxUSE_TEXTDLG
993 wxString wxGetTextFromUser(const wxString& message, const wxString& caption,
994 const wxString& defaultValue, wxWindow *parent,
995 int x, int y, bool WXUNUSED(centre) )
996 {
997 wxString str;
998 wxTextEntryDialog dialog(parent, message, caption, defaultValue, wxOK|wxCANCEL, wxPoint(x, y));
999 if (dialog.ShowModal() == wxID_OK)
1000 {
1001 str = dialog.GetValue();
1002 }
1003
1004 return str;
1005 }
1006
1007 wxString wxGetPasswordFromUser(const wxString& message,
1008 const wxString& caption,
1009 const wxString& defaultValue,
1010 wxWindow *parent)
1011 {
1012 wxString str;
1013 wxTextEntryDialog dialog(parent, message, caption, defaultValue,
1014 wxOK | wxCANCEL | wxTE_PASSWORD);
1015 if ( dialog.ShowModal() == wxID_OK )
1016 {
1017 str = dialog.GetValue();
1018 }
1019
1020 return str;
1021 }
1022
1023 #endif // wxUSE_TEXTDLG
1024
1025 wxColour wxGetColourFromUser(wxWindow *parent, const wxColour& colInit)
1026 {
1027 wxColourData data;
1028 data.SetChooseFull(TRUE);
1029 if ( colInit.Ok() )
1030 {
1031 data.SetColour((wxColour &)colInit); // const_cast
1032 }
1033
1034 wxColour colRet;
1035 wxColourDialog dialog(parent, &data);
1036 if ( dialog.ShowModal() == wxID_OK )
1037 {
1038 colRet = dialog.GetColourData().GetColour();
1039 }
1040 //else: leave it invalid
1041
1042 return colRet;
1043 }
1044
1045 // ----------------------------------------------------------------------------
1046 // missing C RTL functions (FIXME shouldn't be here at all)
1047 // ----------------------------------------------------------------------------
1048
1049 #ifdef __MWERKS__
1050 char *strdup(const char *s)
1051 {
1052 return strcpy( (char*) malloc( strlen( s ) + 1 ) , s ) ;
1053 }
1054
1055 int isascii( int c )
1056 {
1057 return ( c >= 0 && c < 128 ) ;
1058 }
1059 #endif // __MWERKS__
1060
1061 // ----------------------------------------------------------------------------
1062 // wxSafeYield and supporting functions
1063 // ----------------------------------------------------------------------------
1064
1065 void wxEnableTopLevelWindows(bool enable)
1066 {
1067 wxWindowList::Node *node;
1068 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1069 node->GetData()->Enable(enable);
1070 }
1071
1072 wxWindowDisabler::wxWindowDisabler(wxWindow *winToSkip)
1073 {
1074 // remember the top level windows which were already disabled, so that we
1075 // don't reenable them later
1076 m_winDisabled = NULL;
1077
1078 wxWindowList::Node *node;
1079 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1080 {
1081 wxWindow *winTop = node->GetData();
1082 if ( winTop == winToSkip )
1083 continue;
1084
1085 if ( winTop->IsEnabled() )
1086 {
1087 winTop->Disable();
1088 }
1089 else
1090 {
1091 if ( !m_winDisabled )
1092 {
1093 m_winDisabled = new wxWindowList;
1094 }
1095
1096 m_winDisabled->Append(winTop);
1097 }
1098 }
1099 }
1100
1101 wxWindowDisabler::~wxWindowDisabler()
1102 {
1103 wxWindowList::Node *node;
1104 for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
1105 {
1106 wxWindow *winTop = node->GetData();
1107 if ( !m_winDisabled || !m_winDisabled->Find(winTop) )
1108 {
1109 winTop->Enable();
1110 }
1111 //else: had been already disabled, don't reenable
1112 }
1113
1114 delete m_winDisabled;
1115 }
1116
1117 // Yield to other apps/messages and disable user input to all windows except
1118 // the given one
1119 bool wxSafeYield(wxWindow *win)
1120 {
1121 wxWindowDisabler wd(win);
1122
1123 bool rc = wxYield();
1124
1125 return rc;
1126 }
1127
1128 // ----------------------------------------------------------------------------
1129 // misc functions
1130 // ----------------------------------------------------------------------------
1131
1132 // Don't synthesize KeyUp events holding down a key and producing KeyDown
1133 // events with autorepeat. On by default and always on in wxMSW. wxGTK version
1134 // in utilsgtk.cpp.
1135 #ifndef __WXGTK__
1136 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag) )
1137 {
1138 return TRUE; // detectable auto-repeat is the only mode MSW supports
1139 }
1140 #endif // !wxGTK
1141
1142 #endif // wxUSE_GUI
1143
1144 // ----------------------------------------------------------------------------
1145 // network and user id functions
1146 // ----------------------------------------------------------------------------
1147
1148 // Get Full RFC822 style email address
1149 bool wxGetEmailAddress(wxChar *address, int maxSize)
1150 {
1151 wxString email = wxGetEmailAddress();
1152 if ( !email )
1153 return FALSE;
1154
1155 wxStrncpy(address, email, maxSize - 1);
1156 address[maxSize - 1] = wxT('\0');
1157
1158 return TRUE;
1159 }
1160
1161 wxString wxGetEmailAddress()
1162 {
1163 wxString email;
1164
1165 wxString host = wxGetFullHostName();
1166 if ( !!host )
1167 {
1168 wxString user = wxGetUserId();
1169 if ( !!user )
1170 {
1171 email << user << wxT('@') << host;
1172 }
1173 }
1174
1175 return email;
1176 }
1177
1178 wxString wxGetUserId()
1179 {
1180 static const int maxLoginLen = 256; // FIXME arbitrary number
1181
1182 wxString buf;
1183 bool ok = wxGetUserId(buf.GetWriteBuf(maxLoginLen), maxLoginLen);
1184 buf.UngetWriteBuf();
1185
1186 if ( !ok )
1187 buf.Empty();
1188
1189 return buf;
1190 }
1191
1192 wxString wxGetUserName()
1193 {
1194 static const int maxUserNameLen = 1024; // FIXME arbitrary number
1195
1196 wxString buf;
1197 bool ok = wxGetUserName(buf.GetWriteBuf(maxUserNameLen), maxUserNameLen);
1198 buf.UngetWriteBuf();
1199
1200 if ( !ok )
1201 buf.Empty();
1202
1203 return buf;
1204 }
1205
1206 wxString wxGetHostName()
1207 {
1208 static const size_t hostnameSize = 257;
1209
1210 wxString buf;
1211 bool ok = wxGetHostName(buf.GetWriteBuf(hostnameSize), hostnameSize);
1212
1213 buf.UngetWriteBuf();
1214
1215 if ( !ok )
1216 buf.Empty();
1217
1218 return buf;
1219 }
1220
1221 wxString wxGetFullHostName()
1222 {
1223 static const size_t hostnameSize = 257;
1224
1225 wxString buf;
1226 bool ok = wxGetFullHostName(buf.GetWriteBuf(hostnameSize), hostnameSize);
1227
1228 buf.UngetWriteBuf();
1229
1230 if ( !ok )
1231 buf.Empty();
1232
1233 return buf;
1234 }
1235
1236 wxString wxGetHomeDir()
1237 {
1238 wxString home;
1239 wxGetHomeDir(&home);
1240
1241 return home;
1242 }
1243
1244 #if 0
1245
1246 wxString wxGetCurrentDir()
1247 {
1248 wxString dir;
1249 size_t len = 1024;
1250 bool ok;
1251 do
1252 {
1253 ok = getcwd(dir.GetWriteBuf(len + 1), len) != NULL;
1254 dir.UngetWriteBuf();
1255
1256 if ( !ok )
1257 {
1258 if ( errno != ERANGE )
1259 {
1260 wxLogSysError(_T("Failed to get current directory"));
1261
1262 return wxEmptyString;
1263 }
1264 else
1265 {
1266 // buffer was too small, retry with a larger one
1267 len *= 2;
1268 }
1269 }
1270 //else: ok
1271 } while ( !ok );
1272
1273 return dir;
1274 }
1275
1276 #endif // 0
1277
1278 // ----------------------------------------------------------------------------
1279 // wxExecute
1280 // ----------------------------------------------------------------------------
1281
1282 // this is a private function because it hasn't a clean interface: the first
1283 // array is passed by reference, the second by pointer - instead we have 2
1284 // public versions of wxExecute() below
1285 static long wxDoExecuteWithCapture(const wxString& command,
1286 wxArrayString& output,
1287 wxArrayString* error)
1288 {
1289 #ifdef __WIN16__
1290 wxFAIL_MSG("Sorry, this version of wxExecute not implemented on WIN16.");
1291
1292 return 0;
1293 #else // !Win16
1294 // create a wxProcess which will capture the output
1295 wxProcess *process = new wxProcess;
1296 process->Redirect();
1297
1298 long rc = wxExecute(command, TRUE /* sync */, process);
1299
1300 #if wxUSE_STREAMS
1301 if ( rc != -1 )
1302 {
1303 wxInputStream* is = process->GetInputStream();
1304 wxCHECK_MSG( is, -1, _T("if wxExecute() succeded, stream can't be NULL") );
1305 wxTextInputStream tis(*is);
1306
1307 wxTextInputStream *tes = NULL;
1308 wxInputStream *es = NULL;
1309 if ( error )
1310 {
1311 es = process->GetErrorStream();
1312
1313 wxCHECK_MSG( es, -1, _T("stderr can't be NULL") );
1314
1315 tes = new wxTextInputStream(*es);
1316 }
1317
1318 bool cont;
1319 do
1320 {
1321 cont = FALSE;
1322
1323 if ( !is->Eof() && is->IsOk() )
1324 {
1325 wxString line = tis.ReadLine();
1326 if ( is->LastError() )
1327 break;
1328
1329 cont = TRUE;
1330
1331 output.Add(line);
1332 }
1333
1334 if ( error && !es->Eof() && es->IsOk() )
1335 {
1336 wxString line = tes->ReadLine();
1337 if ( es->LastError() )
1338 break;
1339
1340 cont = TRUE;
1341
1342 error->Add(line);
1343 }
1344 }
1345 while ( cont );
1346
1347 delete tes;
1348 }
1349 #endif // wxUSE_STREAMS
1350
1351 delete process;
1352
1353 return rc;
1354 #endif // IO redirection supoprted
1355 }
1356
1357 long wxExecute(const wxString& command, wxArrayString& output)
1358 {
1359 return wxDoExecuteWithCapture(command, output, NULL);
1360 }
1361
1362 long wxExecute(const wxString& command,
1363 wxArrayString& output,
1364 wxArrayString& error)
1365 {
1366 return wxDoExecuteWithCapture(command, output, &error);
1367 }