]> git.saurik.com Git - wxWidgets.git/blob - src/common/filefn.cpp
0783aa903d3285a874dfd9094f9e29b1ae785f88
[wxWidgets.git] / src / common / filefn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: filefn.cpp
3 // Purpose: File- and directory-related functions
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 "filefn.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26 #include "wx/defs.h"
27
28 #ifdef __BORLANDC__
29 #pragma hdrstop
30 #endif
31
32 #ifndef WX_PRECOMP
33 #include "wx/defs.h"
34 #endif
35
36 #include "wx/utils.h"
37 #include "wx/intl.h"
38
39 // there are just too many of those...
40 #ifdef __VISUALC__
41 #pragma warning(disable:4706) // assignment within conditional expression
42 #endif // VC++
43
44 #include <ctype.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #if !defined(__WATCOMC__)
49 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
50 #include <errno.h>
51 #endif
52 #endif
53
54 #include <time.h>
55
56 #ifndef __MWERKS__
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #else
60 #include <stat.h>
61 #include <unistd.h>
62 #endif
63
64 #ifdef __UNIX__
65 #include <unistd.h>
66 #include <dirent.h>
67 #endif
68
69 #ifdef __OS2__
70 #include <direct.h>
71 #include <process.h>
72 #endif
73 #ifdef __WINDOWS__
74 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
75 #include <direct.h>
76 #include <dos.h>
77 #endif // __WINDOWS__
78 #endif // native Win compiler
79
80 #ifdef __GNUWIN32__
81 #ifndef __TWIN32__
82 #include <sys/unistd.h>
83 #endif
84 #endif
85
86 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
87 // this (3.1 I believe) and how to test for it.
88 // If this works for Borland 4.0 as well, then no worries.
89 #include <dir.h>
90 #endif
91
92 #ifdef __SALFORDC__
93 #include <dir.h>
94 #include <unix.h>
95 #endif
96
97 #include "wx/setup.h"
98 #include "wx/log.h"
99
100 // No, Cygwin doesn't appear to have fnmatch.h after all.
101 #if defined(HAVE_FNMATCH_H)
102 #include "fnmatch.h"
103 #endif
104
105 #ifdef __WINDOWS__
106 #include "windows.h"
107 #endif
108
109 // ----------------------------------------------------------------------------
110 // constants
111 // ----------------------------------------------------------------------------
112
113 #define _MAXPATHLEN 500
114
115 #ifdef __WXMAC__
116 extern wxChar gwxMacFileName[] ;
117 extern wxChar gwxMacFileName2[] ;
118 extern wxChar gwxMacFileName3[] ;
119 #endif
120
121 #if !USE_SHARED_LIBRARIES
122 IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
123 #endif
124
125 // ----------------------------------------------------------------------------
126 // private globals
127 // ----------------------------------------------------------------------------
128
129 static wxChar wxFileFunctionsBuffer[4*_MAXPATHLEN];
130
131 // ============================================================================
132 // implementation
133 // ============================================================================
134
135 void wxPathList::Add (const wxString& path)
136 {
137 wxStringList::Add (WXSTRINGCAST path);
138 }
139
140 // Add paths e.g. from the PATH environment variable
141 void wxPathList::AddEnvList (const wxString& envVariable)
142 {
143 static const wxChar PATH_TOKS[] =
144 #ifdef __WINDOWS__
145 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
146 #else
147 wxT(" :;");
148 #endif
149
150 wxChar *val = wxGetenv (WXSTRINGCAST envVariable);
151 if (val && *val)
152 {
153 wxChar *s = copystring (val);
154 wxChar *save_ptr, *token = wxStrtok (s, PATH_TOKS, &save_ptr);
155
156 if (token)
157 {
158 Add (copystring (token));
159 while (token)
160 {
161 if ((token = wxStrtok ((wxChar *) NULL, PATH_TOKS, &save_ptr)) != NULL)
162 Add (wxString(token));
163 }
164 }
165
166 // suppress warning about unused variable save_ptr when wxStrtok() is a
167 // macro which throws away its third argument
168 save_ptr = token;
169
170 delete [] s;
171 }
172 }
173
174 // Given a full filename (with path), ensure that that file can
175 // be accessed again USING FILENAME ONLY by adding the path
176 // to the list if not already there.
177 void wxPathList::EnsureFileAccessible (const wxString& path)
178 {
179 wxString path_only(wxPathOnly(path));
180 if ( !path_only.IsEmpty() )
181 {
182 if ( !Member(path_only) )
183 Add(path_only);
184 }
185 }
186
187 bool wxPathList::Member (const wxString& path)
188 {
189 for (wxNode * node = First (); node != NULL; node = node->Next ())
190 {
191 wxString path2((wxChar *) node->Data ());
192 if (
193 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
194 // Case INDEPENDENT
195 path.CompareTo (path2, wxString::ignoreCase) == 0
196 #else
197 // Case sensitive File System
198 path.CompareTo (path2) == 0
199 #endif
200 )
201 return TRUE;
202 }
203 return FALSE;
204 }
205
206 wxString wxPathList::FindValidPath (const wxString& file)
207 {
208 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer, file)))
209 return wxString(wxFileFunctionsBuffer);
210
211 wxChar buf[_MAXPATHLEN];
212 wxStrcpy(buf, wxFileFunctionsBuffer);
213
214 wxChar *filename = (wxChar*) NULL; /* shut up buggy egcs warning */
215 filename = IsAbsolutePath (buf) ? wxFileNameFromPath (buf) : (wxChar *)buf;
216
217 for (wxNode * node = First (); node; node = node->Next ())
218 {
219 wxChar *path = (wxChar *) node->Data ();
220 wxStrcpy (wxFileFunctionsBuffer, path);
221 wxChar ch = wxFileFunctionsBuffer[wxStrlen(wxFileFunctionsBuffer)-1];
222 if (ch != wxT('\\') && ch != wxT('/'))
223 wxStrcat (wxFileFunctionsBuffer, wxT("/"));
224 wxStrcat (wxFileFunctionsBuffer, filename);
225 #ifdef __WINDOWS__
226 Unix2DosFilename (wxFileFunctionsBuffer);
227 #endif
228 if (wxFileExists (wxFileFunctionsBuffer))
229 {
230 return wxString(wxFileFunctionsBuffer); // Found!
231 }
232 } // for()
233
234 return wxString(wxT("")); // Not found
235 }
236
237 wxString wxPathList::FindAbsoluteValidPath (const wxString& file)
238 {
239 wxString f = FindValidPath(file);
240 if ( wxIsAbsolutePath(f) )
241 return f;
242
243 wxString buf;
244 wxGetWorkingDirectory(buf.GetWriteBuf(_MAXPATHLEN), _MAXPATHLEN - 1);
245 buf.UngetWriteBuf();
246 if ( !wxEndsWithPathSeparator(buf) )
247 {
248 buf += wxFILE_SEP_PATH;
249 }
250 buf += f;
251
252 return buf;
253 }
254
255 bool
256 wxFileExists (const wxString& filename)
257 {
258 #ifdef __GNUWIN32__ // (fix a B20 bug)
259 if (GetFileAttributes(filename) == 0xFFFFFFFF)
260 return FALSE;
261 else
262 return TRUE;
263 #elif defined(__WXMAC__)
264 struct stat stbuf;
265 wxStrcpy( gwxMacFileName , filename ) ;
266 wxUnix2MacFilename( gwxMacFileName ) ;
267 if (gwxMacFileName && stat (WXSTRINGCAST gwxMacFileName, &stbuf) == 0)
268 return TRUE;
269 return FALSE ;
270 #else
271
272 #ifdef __SALFORDC__
273 struct _stat stbuf;
274 #else
275 struct stat stbuf;
276 #endif
277
278 if ((filename != wxT("")) && stat (wxFNSTRINGCAST filename.fn_str(), &stbuf) == 0)
279 return TRUE;
280 return FALSE;
281 #endif
282 }
283
284 /* Vadim's alternative implementation
285
286 // does the file exist?
287 bool wxFileExists(const char *pszFileName)
288 {
289 struct stat st;
290 return !access(pszFileName, 0) &&
291 !stat(pszFileName, &st) &&
292 (st.st_mode & S_IFREG);
293 }
294 */
295
296 bool
297 wxIsAbsolutePath (const wxString& filename)
298 {
299 if (filename != wxT(""))
300 {
301 if (filename[0] == wxT('/')
302 #ifdef __VMS__
303 || (filename[0] == wxT('[') && filename[1] != wxT('.'))
304 #endif
305 #ifdef __WINDOWS__
306 /* MSDOS */
307 || filename[0] == wxT('\\') || (wxIsalpha (filename[0]) && filename[1] == wxT(':'))
308 #endif
309 )
310 return TRUE;
311 }
312 return FALSE;
313 }
314
315 /*
316 * Strip off any extension (dot something) from end of file,
317 * IF one exists. Inserts zero into buffer.
318 *
319 */
320
321 void wxStripExtension(wxChar *buffer)
322 {
323 int len = wxStrlen(buffer);
324 int i = len-1;
325 while (i > 0)
326 {
327 if (buffer[i] == wxT('.'))
328 {
329 buffer[i] = 0;
330 break;
331 }
332 i --;
333 }
334 }
335
336 void wxStripExtension(wxString& buffer)
337 {
338 size_t len = buffer.Length();
339 size_t i = len-1;
340 while (i > 0)
341 {
342 if (buffer.GetChar(i) == wxT('.'))
343 {
344 buffer = buffer.Left(i);
345 break;
346 }
347 i --;
348 }
349 }
350
351 // Destructive removal of /./ and /../ stuff
352 wxChar *wxRealPath (wxChar *path)
353 {
354 #ifdef __WXMSW__
355 static const wxChar SEP = wxT('\\');
356 Unix2DosFilename(path);
357 #else
358 static const wxChar SEP = wxT('/');
359 #endif
360 if (path[0] && path[1]) {
361 /* MATTHEW: special case "/./x" */
362 wxChar *p;
363 if (path[2] == SEP && path[1] == wxT('.'))
364 p = &path[0];
365 else
366 p = &path[2];
367 for (; *p; p++)
368 {
369 if (*p == SEP)
370 {
371 if (p[1] == wxT('.') && p[2] == wxT('.') && (p[3] == SEP || p[3] == wxT('\0')))
372 {
373 wxChar *q;
374 for (q = p - 1; q >= path && *q != SEP; q--);
375 if (q[0] == SEP && (q[1] != wxT('.') || q[2] != wxT('.') || q[3] != SEP)
376 && (q - 1 <= path || q[-1] != SEP))
377 {
378 wxStrcpy (q, p + 3);
379 if (path[0] == wxT('\0'))
380 {
381 path[0] = SEP;
382 path[1] = wxT('\0');
383 }
384 #ifdef __WXMSW__
385 /* Check that path[2] is NULL! */
386 else if (path[1] == wxT(':') && !path[2])
387 {
388 path[2] = SEP;
389 path[3] = wxT('\0');
390 }
391 #endif
392 p = q - 1;
393 }
394 }
395 else if (p[1] == wxT('.') && (p[2] == SEP || p[2] == wxT('\0')))
396 wxStrcpy (p, p + 2);
397 }
398 }
399 }
400 return path;
401 }
402
403 // Must be destroyed
404 wxChar *wxCopyAbsolutePath(const wxString& filename)
405 {
406 if (filename == wxT(""))
407 return (wxChar *) NULL;
408
409 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer, filename))) {
410 wxChar buf[_MAXPATHLEN];
411 buf[0] = wxT('\0');
412 wxGetWorkingDirectory(buf, WXSIZEOF(buf));
413 wxChar ch = buf[wxStrlen(buf) - 1];
414 #ifdef __WXMSW__
415 if (ch != wxT('\\') && ch != wxT('/'))
416 wxStrcat(buf, wxT("\\"));
417 #else
418 if (ch != wxT('/'))
419 wxStrcat(buf, wxT("/"));
420 #endif
421 wxStrcat(buf, wxFileFunctionsBuffer);
422 return copystring( wxRealPath(buf) );
423 }
424 return copystring( wxFileFunctionsBuffer );
425 }
426
427 /*-
428 Handles:
429 ~/ => home dir
430 ~user/ => user's home dir
431 If the environment variable a = "foo" and b = "bar" then:
432 Unix:
433 $a => foo
434 $a$b => foobar
435 $a.c => foo.c
436 xxx$a => xxxfoo
437 ${a}! => foo!
438 $(b)! => bar!
439 \$a => \$a
440 MSDOS:
441 $a ==> $a
442 $(a) ==> foo
443 $(a)$b ==> foo$b
444 $(a)$(b)==> foobar
445 test.$$ ==> test.$$
446 */
447
448 /* input name in name, pathname output to buf. */
449
450 wxChar *wxExpandPath(wxChar *buf, const wxChar *name)
451 {
452 register wxChar *d, *s, *nm;
453 wxChar lnm[_MAXPATHLEN];
454 int q;
455
456 // Some compilers don't like this line.
457 // const wxChar trimchars[] = wxT("\n \t");
458
459 wxChar trimchars[4];
460 trimchars[0] = wxT('\n');
461 trimchars[1] = wxT(' ');
462 trimchars[2] = wxT('\t');
463 trimchars[3] = 0;
464
465 #ifdef __WXMSW__
466 const wxChar SEP = wxT('\\');
467 #else
468 const wxChar SEP = wxT('/');
469 #endif
470 buf[0] = wxT('\0');
471 if (name == NULL || *name == wxT('\0'))
472 return buf;
473 nm = copystring(name); // Make a scratch copy
474 wxChar *nm_tmp = nm;
475
476 /* Skip leading whitespace and cr */
477 while (wxStrchr((wxChar *)trimchars, *nm) != NULL)
478 nm++;
479 /* And strip off trailing whitespace and cr */
480 s = nm + (q = wxStrlen(nm)) - 1;
481 while (q-- && wxStrchr((wxChar *)trimchars, *s) != NULL)
482 *s = wxT('\0');
483
484 s = nm;
485 d = lnm;
486 #ifdef __WXMSW__
487 q = FALSE;
488 #else
489 q = nm[0] == wxT('\\') && nm[1] == wxT('~');
490 #endif
491
492 /* Expand inline environment variables */
493 #ifdef __VISAGECPP__
494 while (*d)
495 {
496 *d++ = *s;
497 if(*s == wxT('\\'))
498 {
499 *(d - 1) = *++s;
500 if (*d)
501 {
502 s++;
503 continue;
504 }
505 else
506 break;
507 }
508 else
509 #else
510 while ((*d++ = *s)) {
511 # ifndef __WXMSW__
512 if (*s == wxT('\\')) {
513 if ((*(d - 1) = *++s)) {
514 s++;
515 continue;
516 } else
517 break;
518 } else
519 # endif
520 #endif
521 #ifdef __WXMSW__
522 if (*s++ == wxT('$') && (*s == wxT('{') || *s == wxT(')')))
523 #else
524 if (*s++ == wxT('$'))
525 #endif
526 {
527 register wxChar *start = d;
528 register int braces = (*s == wxT('{') || *s == wxT('('));
529 register wxChar *value;
530 #ifdef __VISAGECPP__
531 // VA gives assignment in logical expr warning
532 while (*d)
533 *d++ = *s;
534 #else
535 while ((*d++ = *s))
536 #endif
537 if (braces ? (*s == wxT('}') || *s == wxT(')')) : !(wxIsalnum(*s) || *s == wxT('_')) )
538 break;
539 else
540 s++;
541 *--d = 0;
542 value = wxGetenv(braces ? start + 1 : start);
543 if (value) {
544 #ifdef __VISAGECPP__
545 // VA gives assignment in logical expr warning
546 for ((d = start - 1); (*d); *d++ = *value++);
547 #else
548 for ((d = start - 1); (*d++ = *value++););
549 #endif
550 d--;
551 if (braces && *s)
552 s++;
553 }
554 }
555 }
556
557 /* Expand ~ and ~user */
558 nm = lnm;
559 s = wxT("");
560 if (nm[0] == wxT('~') && !q)
561 {
562 /* prefix ~ */
563 if (nm[1] == SEP || nm[1] == 0)
564 { /* ~/filename */
565 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
566 if ((s = WXSTRINGCAST wxGetUserHome(wxT(""))) != NULL) {
567 if (*++nm)
568 nm++;
569 }
570 } else
571 { /* ~user/filename */
572 register wxChar *nnm;
573 register wxChar *home;
574 for (s = nm; *s && *s != SEP; s++);
575 int was_sep; /* MATTHEW: Was there a separator, or NULL? */
576 was_sep = (*s == SEP);
577 nnm = *s ? s + 1 : s;
578 *s = 0;
579 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
580 if ((home = WXSTRINGCAST wxGetUserHome(wxString(nm + 1))) == NULL) {
581 if (was_sep) /* replace only if it was there: */
582 *s = SEP;
583 s = wxT("");
584 } else {
585 nm = nnm;
586 s = home;
587 }
588 }
589 }
590
591 d = buf;
592 if (s && *s) { /* MATTHEW: s could be NULL if user '~' didn't exist */
593 /* Copy home dir */
594 while (wxT('\0') != (*d++ = *s++))
595 /* loop */;
596 // Handle root home
597 if (d - 1 > buf && *(d - 2) != SEP)
598 *(d - 1) = SEP;
599 }
600 s = nm;
601 #ifdef __VISAGECPP__
602 // VA gives assignment in logical expr warning
603 while (*d)
604 *d++ = *s++;
605 #else
606 while ((*d++ = *s++));
607 #endif
608 delete[] nm_tmp; // clean up alloc
609 /* Now clean up the buffer */
610 return wxRealPath(buf);
611 }
612
613
614 /* Contract Paths to be build upon an environment variable
615 component:
616
617 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
618
619 The call wxExpandPath can convert these back!
620 */
621 wxChar *
622 wxContractPath (const wxString& filename, const wxString& envname, const wxString& user)
623 {
624 static wxChar dest[_MAXPATHLEN];
625
626 if (filename == wxT(""))
627 return (wxChar *) NULL;
628
629 wxStrcpy (dest, WXSTRINGCAST filename);
630 #ifdef __WXMSW__
631 Unix2DosFilename(dest);
632 #endif
633
634 // Handle environment
635 const wxChar *val = (const wxChar *) NULL;
636 wxChar *tcp = (wxChar *) NULL;
637 if (envname != WXSTRINGCAST NULL && (val = wxGetenv (WXSTRINGCAST envname)) != NULL &&
638 (tcp = wxStrstr (dest, val)) != NULL)
639 {
640 wxStrcpy (wxFileFunctionsBuffer, tcp + wxStrlen (val));
641 *tcp++ = wxT('$');
642 *tcp++ = wxT('{');
643 wxStrcpy (tcp, WXSTRINGCAST envname);
644 wxStrcat (tcp, wxT("}"));
645 wxStrcat (tcp, wxFileFunctionsBuffer);
646 }
647
648 // Handle User's home (ignore root homes!)
649 size_t len = 0;
650 if ((val = wxGetUserHome (user)) != NULL &&
651 (len = wxStrlen(val)) > 2 &&
652 wxStrncmp(dest, val, len) == 0)
653 {
654 wxStrcpy(wxFileFunctionsBuffer, wxT("~"));
655 if (user != wxT(""))
656 wxStrcat(wxFileFunctionsBuffer, (const wxChar*) user);
657 #ifdef __WXMSW__
658 // strcat(wxFileFunctionsBuffer, "\\");
659 #else
660 // strcat(wxFileFunctionsBuffer, "/");
661 #endif
662 wxStrcat(wxFileFunctionsBuffer, dest + len);
663 wxStrcpy (dest, wxFileFunctionsBuffer);
664 }
665
666 return dest;
667 }
668
669 // Return just the filename, not the path
670 // (basename)
671 wxChar *wxFileNameFromPath (wxChar *path)
672 {
673 if (path)
674 {
675 register wxChar *tcp;
676
677 tcp = path + wxStrlen (path);
678 while (--tcp >= path)
679 {
680 if (*tcp == wxT('/') || *tcp == wxT('\\')
681 #ifdef __VMS__
682 || *tcp == wxT(':') || *tcp == wxT(']'))
683 #else
684 )
685 #endif
686 return tcp + 1;
687 } /* while */
688 #if defined(__WXMSW__) || defined(__WXPM__)
689 if (wxIsalpha (*path) && *(path + 1) == wxT(':'))
690 return path + 2;
691 #endif
692 }
693 return path;
694 }
695
696 wxString wxFileNameFromPath (const wxString& path1)
697 {
698 if (path1 != wxT(""))
699 {
700
701 wxChar *path = WXSTRINGCAST path1 ;
702 register wxChar *tcp;
703
704 tcp = path + wxStrlen (path);
705 while (--tcp >= path)
706 {
707 if (*tcp == wxT('/') || *tcp == wxT('\\')
708 #ifdef __VMS__
709 || *tcp == wxT(':') || *tcp == wxT(']'))
710 #else
711 )
712 #endif
713 return wxString(tcp + 1);
714 } /* while */
715 #if defined(__WXMSW__) || defined(__WXPM__)
716 if (wxIsalpha (*path) && *(path + 1) == wxT(':'))
717 return wxString(path + 2);
718 #endif
719 }
720 // Yes, this should return the path, not an empty string, otherwise
721 // we get "thing.txt" -> "".
722 return path1;
723 }
724
725 // Return just the directory, or NULL if no directory
726 wxChar *
727 wxPathOnly (wxChar *path)
728 {
729 if (path && *path)
730 {
731 static wxChar buf[_MAXPATHLEN];
732
733 // Local copy
734 wxStrcpy (buf, path);
735
736 int l = wxStrlen(path);
737 bool done = FALSE;
738
739 int i = l - 1;
740
741 // Search backward for a backward or forward slash
742 while (!done && i > -1)
743 {
744 // ] is for VMS
745 if (path[i] == wxT('/') || path[i] == wxT('\\') || path[i] == wxT(']'))
746 {
747 done = TRUE;
748 #ifdef __VMS__
749 buf[i+1] = 0;
750 #else
751 buf[i] = 0;
752 #endif
753
754 return buf;
755 }
756 else i --;
757 }
758
759 #if defined(__WXMSW__) || defined(__WXPM__)
760 // Try Drive specifier
761 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
762 {
763 // A:junk --> A:. (since A:.\junk Not A:\junk)
764 buf[2] = wxT('.');
765 buf[3] = wxT('\0');
766 return buf;
767 }
768 #endif
769 }
770
771 return (wxChar *) NULL;
772 }
773
774 // Return just the directory, or NULL if no directory
775 wxString wxPathOnly (const wxString& path)
776 {
777 if (path != wxT(""))
778 {
779 wxChar buf[_MAXPATHLEN];
780
781 // Local copy
782 wxStrcpy (buf, WXSTRINGCAST path);
783
784 int l = path.Length();
785 bool done = FALSE;
786
787 int i = l - 1;
788
789 // Search backward for a backward or forward slash
790 while (!done && i > -1)
791 {
792 // ] is for VMS
793 if (path[i] == wxT('/') || path[i] == wxT('\\') || path[i] == wxT(']'))
794 {
795 done = TRUE;
796 #ifdef __VMS__
797 buf[i+1] = 0;
798 #else
799 buf[i] = 0;
800 #endif
801
802 return wxString(buf);
803 }
804 else i --;
805 }
806
807 #if defined(__WXMSW__) || defined(__WXPM__)
808 // Try Drive specifier
809 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
810 {
811 // A:junk --> A:. (since A:.\junk Not A:\junk)
812 buf[2] = wxT('.');
813 buf[3] = wxT('\0');
814 return wxString(buf);
815 }
816 #endif
817 }
818
819 return wxString(wxT(""));
820 }
821
822 // Utility for converting delimiters in DOS filenames to UNIX style
823 // and back again - or we get nasty problems with delimiters.
824 // Also, convert to lower case, since case is significant in UNIX.
825
826 #ifdef __WXMAC__
827 void
828 wxMac2UnixFilename (wxChar *s)
829 {
830 if (s)
831 {
832 memmove( s+1 , s ,(strlen( s ) + 1)*sizeof(wxChar)) ;
833 if ( *s == wxT(':') )
834 *s = wxT('.') ;
835 else
836 *s = wxT('/') ;
837
838 while (*s)
839 {
840 if (*s == wxT(':'))
841 *s = wxT('/');
842 else
843 *s = wxTolower(*s); // Case INDEPENDENT
844 s++;
845 }
846 }
847 }
848
849 void
850 wxUnix2MacFilename (wxChar *s)
851 {
852 if (s)
853 {
854 if ( *s == wxT('.') )
855 {
856 // relative path , since it goes on with slash which is translated to a :
857 memmove( s , s+1 ,strlen( s )*sizeof(wxChar) ) ;
858 }
859 else if ( *s == wxT('/') )
860 {
861 // absolute path -> on mac just start with the drive name
862 memmove( s , s+1 ,strlen( s )*sizeof(wxChar) ) ;
863 }
864 else
865 {
866 wxASSERT_MSG( 1 , wxT("unknown path beginning") ) ;
867 }
868 while (*s)
869 {
870 if (*s == wxT('/') || *s == wxT('\\'))
871 *s = wxT(':');
872
873 s++ ;
874 }
875 }
876 }
877 #endif
878 void
879 wxDos2UnixFilename (wxChar *s)
880 {
881 if (s)
882 while (*s)
883 {
884 if (*s == wxT('\\'))
885 *s = wxT('/');
886 #if defined(__WXMSW__) || defined(__WXPM__)
887 else
888 *s = wxTolower(*s); // Case INDEPENDENT
889 #endif
890 s++;
891 }
892 }
893
894 void
895 #if defined(__WXMSW__) || defined(__WXPM__)
896 wxUnix2DosFilename (wxChar *s)
897 #else
898 wxUnix2DosFilename (wxChar *WXUNUSED(s))
899 #endif
900 {
901 // Yes, I really mean this to happen under DOS only! JACS
902 #if defined(__WXMSW__) || defined(__WXPM__)
903 if (s)
904 while (*s)
905 {
906 if (*s == wxT('/'))
907 *s = wxT('\\');
908 s++;
909 }
910 #endif
911 }
912
913 // Concatenate two files to form third
914 bool
915 wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
916 {
917 wxChar *outfile = wxGetTempFileName("cat");
918
919 FILE *fp1 = (FILE *) NULL;
920 FILE *fp2 = (FILE *) NULL;
921 FILE *fp3 = (FILE *) NULL;
922 // Open the inputs and outputs
923 #ifdef __WXMAC__
924 wxStrcpy( gwxMacFileName , file1 ) ;
925 wxUnix2MacFilename( gwxMacFileName ) ;
926 wxStrcpy( gwxMacFileName2 , file2) ;
927 wxUnix2MacFilename( gwxMacFileName2 ) ;
928 wxStrcpy( gwxMacFileName3 , outfile) ;
929 wxUnix2MacFilename( gwxMacFileName3 ) ;
930
931 if ((fp1 = fopen (gwxMacFileName, "rb")) == NULL ||
932 (fp2 = fopen (gwxMacFileName2, "rb")) == NULL ||
933 (fp3 = fopen (gwxMacFileName3, "wb")) == NULL)
934 #else
935 if ((fp1 = fopen (wxFNSTRINGCAST file1.fn_str(), "rb")) == NULL ||
936 (fp2 = fopen (wxFNSTRINGCAST file2.fn_str(), "rb")) == NULL ||
937 (fp3 = fopen (wxFNCONV(outfile), "wb")) == NULL)
938 #endif
939 {
940 if (fp1)
941 fclose (fp1);
942 if (fp2)
943 fclose (fp2);
944 if (fp3)
945 fclose (fp3);
946 return FALSE;
947 }
948
949 int ch;
950 while ((ch = getc (fp1)) != EOF)
951 (void) putc (ch, fp3);
952 fclose (fp1);
953
954 while ((ch = getc (fp2)) != EOF)
955 (void) putc (ch, fp3);
956 fclose (fp2);
957
958 fclose (fp3);
959 bool result = wxRenameFile(outfile, file3);
960 delete[] outfile;
961 return result;
962 }
963
964 // Copy files
965 bool
966 wxCopyFile (const wxString& file1, const wxString& file2)
967 {
968 FILE *fd1;
969 FILE *fd2;
970 int ch;
971
972 #ifdef __WXMAC__
973 wxStrcpy( gwxMacFileName , file1 ) ;
974 wxUnix2MacFilename( gwxMacFileName ) ;
975 wxStrcpy( gwxMacFileName2 , file2) ;
976 wxUnix2MacFilename( gwxMacFileName2 ) ;
977
978 if ((fd1 = fopen (gwxMacFileName, "rb")) == NULL)
979 return FALSE;
980 if ((fd2 = fopen (gwxMacFileName2, "wb")) == NULL)
981 #else
982 if ((fd1 = fopen (wxFNSTRINGCAST file1.fn_str(), "rb")) == NULL)
983 return FALSE;
984 if ((fd2 = fopen (wxFNSTRINGCAST file2.fn_str(), "wb")) == NULL)
985 #endif
986 {
987 fclose (fd1);
988 return FALSE;
989 }
990
991 while ((ch = getc (fd1)) != EOF)
992 (void) putc (ch, fd2);
993
994 fclose (fd1);
995 fclose (fd2);
996 return TRUE;
997 }
998
999 bool
1000 wxRenameFile (const wxString& file1, const wxString& file2)
1001 {
1002 #ifdef __WXMAC__
1003 wxStrcpy( gwxMacFileName , file1 ) ;
1004 wxUnix2MacFilename( gwxMacFileName ) ;
1005 wxStrcpy( gwxMacFileName2 , file2) ;
1006 wxUnix2MacFilename( gwxMacFileName2 ) ;
1007
1008 if (0 == rename (gwxMacFileName, gwxMacFileName2))
1009 return TRUE;
1010 #else
1011 // Normal system call
1012 if (0 == rename (wxFNSTRINGCAST file1.fn_str(), wxFNSTRINGCAST file2.fn_str()))
1013 return TRUE;
1014 #endif
1015 // Try to copy
1016 if (wxCopyFile(file1, file2)) {
1017 wxRemoveFile(file1);
1018 return TRUE;
1019 }
1020 // Give up
1021 return FALSE;
1022 }
1023
1024 bool wxRemoveFile(const wxString& file)
1025 {
1026 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1027 int flag = remove(wxFNSTRINGCAST file.fn_str());
1028 #elif defined( __WXMAC__ )
1029 wxStrcpy( gwxMacFileName , file ) ;
1030 wxUnix2MacFilename( gwxMacFileName ) ;
1031 int flag = unlink(gwxMacFileName);
1032 #else
1033 int flag = unlink(wxFNSTRINGCAST file.fn_str());
1034 #endif
1035 return (flag == 0) ;
1036 }
1037
1038 bool wxMkdir(const wxString& dir, int perm)
1039 {
1040 #if defined( __WXMAC__ )
1041 wxStrcpy( gwxMacFileName , dir ) ;
1042 wxUnix2MacFilename( gwxMacFileName ) ;
1043 const wxChar *dirname = gwxMacFileName;
1044 #else // !Mac
1045 const wxChar *dirname = dir.c_str();
1046 #endif // Mac/!Mac
1047
1048 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1049 // for the GNU compiler
1050 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1051 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1052 #else // MSW and OS/2
1053 if ( mkdir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1054 #endif // !MSW/MSW
1055 {
1056 wxLogSysError(_("Directory '%s' couldn't be created"), dirname);
1057
1058 return FALSE;
1059 }
1060
1061 return TRUE;
1062 }
1063
1064 bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1065 {
1066 #ifdef __VMS__
1067 return FALSE;
1068 #elif defined( __WXMAC__ )
1069 wxStrcpy( gwxMacFileName , dir ) ;
1070 wxUnix2MacFilename( gwxMacFileName ) ;
1071 return (rmdir(WXSTRINGCAST gwxMacFileName) == 0);
1072 #else
1073
1074 #ifdef __SALFORDC__
1075 return FALSE; // What to do?
1076 #else
1077 return (rmdir(wxFNSTRINGCAST dir.fn_str()) == 0);
1078 #endif
1079
1080 #endif
1081 }
1082
1083 #if 0
1084 bool wxDirExists(const wxString& dir)
1085 {
1086 #ifdef __VMS__
1087 return FALSE;
1088 #elif !defined(__WXMSW__)
1089 struct stat sbuf;
1090 return (stat(dir.fn_str(), &sbuf) != -1) && S_ISDIR(sbuf.st_mode) ? TRUE : FALSE;
1091 #else
1092
1093 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
1094 #if defined(__WIN32__)
1095 WIN32_FIND_DATA fileInfo;
1096 #else
1097 #ifdef __BORLANDC__
1098 struct ffblk fileInfo;
1099 #else
1100 struct find_t fileInfo;
1101 #endif
1102 #endif
1103
1104 #if defined(__WIN32__)
1105 HANDLE h = FindFirstFile((LPTSTR) WXSTRINGCAST dir,(LPWIN32_FIND_DATA)&fileInfo);
1106
1107 if (h==INVALID_HANDLE_VALUE)
1108 return FALSE;
1109 else {
1110 FindClose(h);
1111 return ((fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
1112 }
1113 #else
1114 // In Borland findfirst has a different argument
1115 // ordering from _dos_findfirst. But _dos_findfirst
1116 // _should_ be ok in both MS and Borland... why not?
1117 #ifdef __BORLANDC__
1118 return ((findfirst(WXSTRINGCAST dir, &fileInfo, _A_SUBDIR) == 0 && (fileInfo.ff_attrib & _A_SUBDIR) != 0));
1119 #else
1120 return (((_dos_findfirst(WXSTRINGCAST dir, _A_SUBDIR, &fileInfo) == 0) && (fileInfo.attrib & _A_SUBDIR)) != 0);
1121 #endif
1122 #endif
1123
1124 #endif
1125 }
1126
1127 #endif
1128
1129 // does the path exists? (may have or not '/' or '\\' at the end)
1130 bool wxPathExists(const wxChar *pszPathName)
1131 {
1132 /* Windows API returns -1 from stat for "c:\dir\" if "c:\dir" exists
1133 * OTOH, we should change "d:" to "d:\" and leave "\" as is. */
1134 wxString strPath(pszPathName);
1135 if ( wxEndsWithPathSeparator(pszPathName) && pszPathName[1] != wxT('\0') )
1136 strPath.Last() = wxT('\0');
1137
1138 #ifdef __SALFORDC__
1139 struct _stat st;
1140 #else
1141 struct stat st;
1142 #endif
1143
1144 return stat(wxFNSTRINGCAST strPath.fn_str(), &st) == 0 && (st.st_mode & S_IFDIR);
1145 }
1146
1147 // Get a temporary filename, opening and closing the file.
1148 wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
1149 {
1150 #ifdef __WINDOWS__
1151
1152 #ifndef __WIN32__
1153 wxChar tmp[144];
1154 ::GetTempFileName(0, WXSTRINGCAST prefix, 0, tmp);
1155 #else
1156 wxChar tmp[MAX_PATH];
1157 wxChar tmpPath[MAX_PATH];
1158 ::GetTempPath(MAX_PATH, tmpPath);
1159 ::GetTempFileName(tmpPath, WXSTRINGCAST prefix, 0, tmp);
1160 #endif
1161 if (buf) wxStrcpy(buf, tmp);
1162 else buf = copystring(tmp);
1163 return buf;
1164
1165 #else
1166 static short last_temp = 0; // cache last to speed things a bit
1167 // At most 1000 temp files to a process! We use a ring count.
1168 wxChar tmp[100]; // FIXME static buffer
1169
1170 for (short suffix = last_temp + 1; suffix != last_temp; ++suffix %= 1000)
1171 {
1172 wxSprintf (tmp, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix, (int) getpid (), (int) suffix);
1173 if (!wxFileExists( tmp ))
1174 {
1175 // Touch the file to create it (reserve name)
1176 FILE *fd = fopen (wxFNCONV(tmp), "w");
1177 if (fd)
1178 fclose (fd);
1179 last_temp = suffix;
1180 if (buf)
1181 wxStrcpy( buf, tmp);
1182 else
1183 buf = copystring( tmp );
1184 return buf;
1185 }
1186 }
1187 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1188 if (buf) buf[0] = 0;
1189 return (wxChar *) NULL;
1190 #endif
1191 }
1192
1193 // Get first file name matching given wild card.
1194
1195 #ifdef __UNIX__
1196
1197 // Get first file name matching given wild card.
1198 // Flags are reserved for future use.
1199
1200 #ifndef __VMS__
1201 static DIR *gs_dirStream = (DIR *) NULL;
1202 static wxString gs_strFileSpec;
1203 static int gs_findFlags = 0;
1204 #endif
1205
1206 wxString wxFindFirstFile(const wxChar *spec, int flags)
1207 {
1208 wxString result;
1209
1210 #ifndef __VMS__
1211 if (gs_dirStream)
1212 closedir(gs_dirStream); // edz 941103: better housekeping
1213
1214 gs_findFlags = flags;
1215
1216 gs_strFileSpec = spec;
1217
1218 // Find path only so we can concatenate
1219 // found file onto path
1220 wxString path(wxPathOnly(gs_strFileSpec));
1221
1222 // special case: path is really "/"
1223 if ( !path && gs_strFileSpec[0u] == wxT('/') )
1224 path = wxT('/');
1225 // path is empty => Local directory
1226 if ( !path )
1227 path = wxT('.');
1228
1229 gs_dirStream = opendir(path.fn_str());
1230 if ( !gs_dirStream )
1231 {
1232 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1233 path.c_str());
1234 }
1235 else
1236 {
1237 result = wxFindNextFile();
1238 }
1239 #endif // !VMS
1240
1241 return result;
1242 }
1243
1244 wxString wxFindNextFile()
1245 {
1246 wxString result;
1247
1248 #ifndef __VMS__
1249 wxCHECK_MSG( gs_dirStream, result, wxT("must call wxFindFirstFile first") );
1250
1251 // Find path only so we can concatenate
1252 // found file onto path
1253 wxString path(wxPathOnly(gs_strFileSpec));
1254 wxString name(wxFileNameFromPath(gs_strFileSpec));
1255
1256 /* MATTHEW: special case: path is really "/" */
1257 if ( !path && gs_strFileSpec[0u] == wxT('/'))
1258 path = wxT('/');
1259
1260 // Do the reading
1261 struct dirent *nextDir;
1262 for ( nextDir = readdir(gs_dirStream);
1263 nextDir != NULL;
1264 nextDir = readdir(gs_dirStream) )
1265 {
1266 if (wxMatchWild(name, nextDir->d_name))
1267 {
1268 result.Empty();
1269 if ( !path.IsEmpty() )
1270 {
1271 result = path;
1272 if ( path != wxT('/') )
1273 result += wxT('/');
1274 }
1275
1276 result += nextDir->d_name;
1277
1278 // Only return "." and ".." when they match
1279 bool isdir;
1280 if ( (strcmp(nextDir->d_name, ".") == 0) ||
1281 (strcmp(nextDir->d_name, "..") == 0))
1282 {
1283 if ( (gs_findFlags & wxDIR) != 0 )
1284 isdir = TRUE;
1285 else
1286 continue;
1287 }
1288 else
1289 isdir = wxDirExists(result);
1290
1291 // and only return directories when flags & wxDIR
1292 if ( !gs_findFlags ||
1293 ((gs_findFlags & wxDIR) && isdir) ||
1294 ((gs_findFlags & wxFILE) && !isdir) )
1295 {
1296 return result;
1297 }
1298 }
1299 }
1300
1301 result.Empty(); // not found
1302
1303 closedir(gs_dirStream);
1304 gs_dirStream = (DIR *) NULL;
1305 #endif // !VMS
1306
1307 return result;
1308 }
1309
1310 #elif defined(__WXMSW__)
1311
1312 #ifdef __WIN32__
1313 static HANDLE gs_hFileStruct = INVALID_HANDLE_VALUE;
1314 static WIN32_FIND_DATA gs_findDataStruct;
1315 #else // Win16
1316 #ifdef __BORLANDC__
1317 static struct ffblk gs_findDataStruct;
1318 #else
1319 static struct _find_t gs_findDataStruct;
1320 #endif // Borland
1321 #endif // Win32/16
1322
1323 static wxString gs_strFileSpec;
1324 static int gs_findFlags = 0;
1325
1326 wxString wxFindFirstFile(const wxChar *spec, int flags)
1327 {
1328 wxString result;
1329
1330 gs_strFileSpec = spec;
1331 gs_findFlags = flags; /* MATTHEW: [5] Remember flags */
1332
1333 // Find path only so we can concatenate found file onto path
1334 wxString path(wxPathOnly(gs_strFileSpec));
1335 if ( !path.IsEmpty() )
1336 result << path << wxT('\\');
1337
1338 #ifdef __WIN32__
1339 if ( gs_hFileStruct != INVALID_HANDLE_VALUE )
1340 FindClose(gs_hFileStruct);
1341
1342 gs_hFileStruct = ::FindFirstFile(WXSTRINGCAST spec, &gs_findDataStruct);
1343
1344 if ( gs_hFileStruct == INVALID_HANDLE_VALUE )
1345 {
1346 result.Empty();
1347
1348 return result;
1349 }
1350
1351 bool isdir = !!(gs_findDataStruct.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1352
1353 if (isdir && !(flags & wxDIR))
1354 return wxFindNextFile();
1355 else if (!isdir && flags && !(flags & wxFILE))
1356 return wxFindNextFile();
1357
1358 result += gs_findDataStruct.cFileName;
1359
1360 return result;
1361 #else
1362 int flag = _A_NORMAL;
1363 if (flags & wxDIR) /* MATTHEW: [5] Use & */
1364 flag = _A_SUBDIR;
1365
1366 #ifdef __BORLANDC__
1367 if (findfirst(WXSTRINGCAST spec, &gs_findDataStruct, flag) == 0)
1368 #else
1369 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1370 #endif
1371 {
1372 /* MATTHEW: [5] Check directory flag */
1373 char attrib;
1374
1375 #ifdef __BORLANDC__
1376 attrib = gs_findDataStruct.ff_attrib;
1377 #else
1378 attrib = gs_findDataStruct.attrib;
1379 #endif
1380
1381 if (attrib & _A_SUBDIR) {
1382 if (!(gs_findFlags & wxDIR))
1383 return wxFindNextFile();
1384 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1385 return wxFindNextFile();
1386
1387 result +=
1388 #ifdef __BORLANDC__
1389 gs_findDataStruct.ff_name
1390 #else
1391 gs_findDataStruct.name
1392 #endif
1393 ;
1394 }
1395 #endif // __WIN32__
1396
1397 return result;
1398 }
1399
1400 wxString wxFindNextFile()
1401 {
1402 wxString result;
1403
1404 // Find path only so we can concatenate found file onto path
1405 wxString path(wxPathOnly(gs_strFileSpec));
1406
1407 try_again:
1408
1409 #ifdef __WIN32__
1410 if (gs_hFileStruct == INVALID_HANDLE_VALUE)
1411 return result;
1412
1413 bool success = (FindNextFile(gs_hFileStruct, &gs_findDataStruct) != 0);
1414 if (!success)
1415 {
1416 FindClose(gs_hFileStruct);
1417 gs_hFileStruct = INVALID_HANDLE_VALUE;
1418 }
1419 else
1420 {
1421 bool isdir = !!(gs_findDataStruct.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1422
1423 if (isdir && !(gs_findFlags & wxDIR))
1424 goto try_again;
1425 else if (!isdir && gs_findFlags && !(gs_findFlags & wxFILE))
1426 goto try_again;
1427
1428 if ( !path.IsEmpty() )
1429 result << path << wxT('\\');
1430 result << gs_findDataStruct.cFileName;
1431 }
1432
1433 return result;
1434 #else // Win16
1435
1436 #ifdef __BORLANDC__
1437 if (findnext(&gs_findDataStruct) == 0)
1438 #else
1439 if (_dos_findnext(&gs_findDataStruct) == 0)
1440 #endif
1441 {
1442 /* MATTHEW: [5] Check directory flag */
1443 char attrib;
1444
1445 #ifdef __BORLANDC__
1446 attrib = gs_findDataStruct.ff_attrib;
1447 #else
1448 attrib = gs_findDataStruct.attrib;
1449 #endif
1450
1451 if (attrib & _A_SUBDIR) {
1452 if (!(gs_findFlags & wxDIR))
1453 goto try_again;
1454 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1455 goto try_again;
1456
1457
1458 result +=
1459 #ifdef __BORLANDC__
1460 gs_findDataStruct.ff_name
1461 #else
1462 gs_findDataStruct.name
1463 #endif
1464 ;
1465 }
1466 #endif // Win32/16
1467
1468 return result;
1469 }
1470
1471 #endif // Unix/Windows
1472
1473 // Get current working directory.
1474 // If buf is NULL, allocates space using new, else
1475 // copies into buf.
1476 wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1477 {
1478 if (!buf)
1479 buf = new wxChar[sz+1];
1480 #if wxUSE_UNICODE
1481 char *cbuf = new char[sz+1];
1482 #ifdef _MSC_VER
1483 if (_getcwd(cbuf, sz) == NULL) {
1484 #else
1485 if (getcwd(cbuf, sz) == NULL) {
1486 #endif
1487 delete [] cbuf;
1488 #else
1489 #ifdef _MSC_VER
1490 if (_getcwd(buf, sz) == NULL) {
1491 #else
1492 if (getcwd(buf, sz) == NULL) {
1493 #endif
1494 #endif
1495 buf[0] = wxT('.');
1496 buf[1] = wxT('\0');
1497 }
1498 #if wxUSE_UNICODE
1499 else {
1500 wxConvFile.MB2WC(buf, cbuf, sz);
1501 delete [] cbuf;
1502 }
1503 #endif
1504 return buf;
1505 }
1506
1507 wxString wxGetCwd()
1508 {
1509 static const size_t maxPathLen = 1024;
1510
1511 wxString str;
1512 wxGetWorkingDirectory(str.GetWriteBuf(maxPathLen), maxPathLen);
1513 str.UngetWriteBuf();
1514
1515 return str;
1516 }
1517
1518 bool wxSetWorkingDirectory(const wxString& d)
1519 {
1520 #if defined( __UNIX__ ) || defined( __WXMAC__ ) || defined(__WXPM__)
1521 return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
1522 #elif defined(__WINDOWS__)
1523
1524 #ifdef __WIN32__
1525 return (bool)(SetCurrentDirectory(d) != 0);
1526 #else
1527 // Must change drive, too.
1528 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1529 if (isDriveSpec)
1530 {
1531 wxChar firstChar = d[0];
1532
1533 // To upper case
1534 if (firstChar > 90)
1535 firstChar = firstChar - 32;
1536
1537 // To a drive number
1538 unsigned int driveNo = firstChar - 64;
1539 if (driveNo > 0)
1540 {
1541 unsigned int noDrives;
1542 _dos_setdrive(driveNo, &noDrives);
1543 }
1544 }
1545 bool success = (chdir(WXSTRINGCAST d) == 0);
1546
1547 return success;
1548 #endif
1549
1550 #endif
1551 }
1552
1553 // Get the OS directory if appropriate (such as the Windows directory).
1554 // On non-Windows platform, probably just return the empty string.
1555 wxString wxGetOSDirectory()
1556 {
1557 #ifdef __WINDOWS__
1558 wxChar buf[256];
1559 GetWindowsDirectory(buf, 256);
1560 return wxString(buf);
1561 #else
1562 return wxEmptyString;
1563 #endif
1564 }
1565
1566 bool wxEndsWithPathSeparator(const wxChar *pszFileName)
1567 {
1568 size_t len = wxStrlen(pszFileName);
1569 if ( len == 0 )
1570 return FALSE;
1571 else
1572 return wxIsPathSeparator(pszFileName[len - 1]);
1573 }
1574
1575 // find a file in a list of directories, returns false if not found
1576 bool wxFindFileInPath(wxString *pStr, const wxChar *pszPath, const wxChar *pszFile)
1577 {
1578 // we assume that it's not empty
1579 wxCHECK_MSG( !wxIsEmpty(pszFile), FALSE,
1580 _("empty file name in wxFindFileInPath"));
1581
1582 // skip path separator in the beginning of the file name if present
1583 if ( wxIsPathSeparator(*pszFile) )
1584 pszFile++;
1585
1586 // copy the path (strtok will modify it)
1587 wxChar *szPath = new wxChar[wxStrlen(pszPath) + 1];
1588 wxStrcpy(szPath, pszPath);
1589
1590 wxString strFile;
1591 wxChar *pc, *save_ptr;
1592 for ( pc = wxStrtok(szPath, wxPATH_SEP, &save_ptr);
1593 pc != NULL;
1594 pc = wxStrtok((wxChar *) NULL, wxPATH_SEP, &save_ptr) )
1595 {
1596 // search for the file in this directory
1597 strFile = pc;
1598 if ( !wxEndsWithPathSeparator(pc) )
1599 strFile += wxFILE_SEP_PATH;
1600 strFile += pszFile;
1601
1602 if ( FileExists(strFile) ) {
1603 *pStr = strFile;
1604 break;
1605 }
1606 }
1607
1608 // suppress warning about unused variable save_ptr when wxStrtok() is a
1609 // macro which throws away its third argument
1610 save_ptr = pc;
1611
1612 delete [] szPath;
1613
1614 return pc != NULL; // if true => we breaked from the loop
1615 }
1616
1617 void WXDLLEXPORT wxSplitPath(const wxChar *pszFileName,
1618 wxString *pstrPath,
1619 wxString *pstrName,
1620 wxString *pstrExt)
1621 {
1622 // it can be empty, but it shouldn't be NULL
1623 wxCHECK_RET( pszFileName, wxT("NULL file name in wxSplitPath") );
1624
1625 const wxChar *pDot = wxStrrchr(pszFileName, wxFILE_SEP_EXT);
1626
1627 #ifdef __WXMSW__
1628 // under Windows we understand both separators
1629 const wxChar *pSepUnix = wxStrrchr(pszFileName, wxFILE_SEP_PATH_UNIX);
1630 const wxChar *pSepDos = wxStrrchr(pszFileName, wxFILE_SEP_PATH_DOS);
1631 const wxChar *pLastSeparator = pSepUnix > pSepDos ? pSepUnix : pSepDos;
1632 #else // assume Unix
1633 const wxChar *pLastSeparator = wxStrrchr(pszFileName, wxFILE_SEP_PATH_UNIX);
1634
1635 if ( pDot == pszFileName )
1636 {
1637 // under Unix files like .profile are treated in a special way
1638 pDot = NULL;
1639 }
1640 #endif // MSW/Unix
1641
1642 if ( pDot < pLastSeparator )
1643 {
1644 // the dot is part of the path, not the start of the extension
1645 pDot = NULL;
1646 }
1647
1648 if ( pstrPath )
1649 {
1650 if ( pLastSeparator )
1651 *pstrPath = wxString(pszFileName, pLastSeparator - pszFileName);
1652 else
1653 pstrPath->Empty();
1654 }
1655
1656 if ( pstrName )
1657 {
1658 const wxChar *start = pLastSeparator ? pLastSeparator + 1 : pszFileName;
1659 const wxChar *end = pDot ? pDot : pszFileName + wxStrlen(pszFileName);
1660
1661 *pstrName = wxString(start, end - start);
1662 }
1663
1664 if ( pstrExt )
1665 {
1666 if ( pDot )
1667 *pstrExt = wxString(pDot + 1);
1668 else
1669 pstrExt->Empty();
1670 }
1671 }
1672
1673 //------------------------------------------------------------------------
1674 // wild character routines
1675 //------------------------------------------------------------------------
1676
1677 bool wxIsWild( const wxString& pattern )
1678 {
1679 wxString tmp = pattern;
1680 wxChar *pat = WXSTRINGCAST(tmp);
1681 while (*pat) {
1682 switch (*pat++) {
1683 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1684 return TRUE;
1685 case wxT('\\'):
1686 if (!*pat++)
1687 return FALSE;
1688 }
1689 }
1690 return FALSE;
1691 };
1692
1693 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1694
1695 #if defined(HAVE_FNMATCH_H)
1696 {
1697 // this probably won't work well for multibyte chars in Unicode mode?
1698 if(dot_special)
1699 return fnmatch(pat.fn_str(), text.fn_str(), FNM_PERIOD) == 0;
1700 else
1701 return fnmatch(pat.fn_str(), text.fn_str(), 0) == 0;
1702 }
1703 #else
1704
1705 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1706
1707 /*
1708 * WARNING: this code is broken!
1709 */
1710 {
1711 wxString tmp1 = pat;
1712 wxChar *pattern = WXSTRINGCAST(tmp1);
1713 wxString tmp2 = text;
1714 wxChar *str = WXSTRINGCAST(tmp2);
1715 wxChar c;
1716 wxChar *cp;
1717 bool done = FALSE, ret_code, ok;
1718 // Below is for vi fans
1719 const wxChar OB = wxT('{'), CB = wxT('}');
1720
1721 // dot_special means '.' only matches '.'
1722 if (dot_special && *str == wxT('.') && *pattern != *str)
1723 return FALSE;
1724
1725 while ((*pattern != wxT('\0')) && (!done)
1726 && (((*str==wxT('\0'))&&((*pattern==OB)||(*pattern==wxT('*'))))||(*str!=wxT('\0')))) {
1727 switch (*pattern) {
1728 case wxT('\\'):
1729 pattern++;
1730 if (*pattern != wxT('\0'))
1731 pattern++;
1732 break;
1733 case wxT('*'):
1734 pattern++;
1735 ret_code = FALSE;
1736 while ((*str!=wxT('\0'))
1737 && (!(ret_code=wxMatchWild(pattern, str++, FALSE))))
1738 /*loop*/;
1739 if (ret_code) {
1740 while (*str != wxT('\0'))
1741 str++;
1742 while (*pattern != wxT('\0'))
1743 pattern++;
1744 }
1745 break;
1746 case wxT('['):
1747 pattern++;
1748 repeat:
1749 if ((*pattern == wxT('\0')) || (*pattern == wxT(']'))) {
1750 done = TRUE;
1751 break;
1752 }
1753 if (*pattern == wxT('\\')) {
1754 pattern++;
1755 if (*pattern == wxT('\0')) {
1756 done = TRUE;
1757 break;
1758 }
1759 }
1760 if (*(pattern + 1) == wxT('-')) {
1761 c = *pattern;
1762 pattern += 2;
1763 if (*pattern == wxT(']')) {
1764 done = TRUE;
1765 break;
1766 }
1767 if (*pattern == wxT('\\')) {
1768 pattern++;
1769 if (*pattern == wxT('\0')) {
1770 done = TRUE;
1771 break;
1772 }
1773 }
1774 if ((*str < c) || (*str > *pattern)) {
1775 pattern++;
1776 goto repeat;
1777 }
1778 } else if (*pattern != *str) {
1779 pattern++;
1780 goto repeat;
1781 }
1782 pattern++;
1783 while ((*pattern != wxT(']')) && (*pattern != wxT('\0'))) {
1784 if ((*pattern == wxT('\\')) && (*(pattern + 1) != wxT('\0')))
1785 pattern++;
1786 pattern++;
1787 }
1788 if (*pattern != wxT('\0')) {
1789 pattern++, str++;
1790 }
1791 break;
1792 case wxT('?'):
1793 pattern++;
1794 str++;
1795 break;
1796 case OB:
1797 pattern++;
1798 while ((*pattern != CB) && (*pattern != wxT('\0'))) {
1799 cp = str;
1800 ok = TRUE;
1801 while (ok && (*cp != wxT('\0')) && (*pattern != wxT('\0'))
1802 && (*pattern != wxT(',')) && (*pattern != CB)) {
1803 if (*pattern == wxT('\\'))
1804 pattern++;
1805 ok = (*pattern++ == *cp++);
1806 }
1807 if (*pattern == wxT('\0')) {
1808 ok = FALSE;
1809 done = TRUE;
1810 break;
1811 } else if (ok) {
1812 str = cp;
1813 while ((*pattern != CB) && (*pattern != wxT('\0'))) {
1814 if (*++pattern == wxT('\\')) {
1815 if (*++pattern == CB)
1816 pattern++;
1817 }
1818 }
1819 } else {
1820 while (*pattern!=CB && *pattern!=wxT(',') && *pattern!=wxT('\0')) {
1821 if (*++pattern == wxT('\\')) {
1822 if (*++pattern == CB || *pattern == wxT(','))
1823 pattern++;
1824 }
1825 }
1826 }
1827 if (*pattern != wxT('\0'))
1828 pattern++;
1829 }
1830 break;
1831 default:
1832 if (*str == *pattern) {
1833 str++, pattern++;
1834 } else {
1835 done = TRUE;
1836 }
1837 }
1838 }
1839 while (*pattern == wxT('*'))
1840 pattern++;
1841 return ((*str == wxT('\0')) && (*pattern == wxT('\0')));
1842 };
1843
1844 #endif
1845
1846 #ifdef __VISUALC__
1847 #pragma warning(default:4706) // assignment within conditional expression
1848 #endif // VC++