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