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