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