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