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