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