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