]> git.saurik.com Git - wxWidgets.git/blob - src/common/filefn.cpp
Prepare wxToolBarSimple for event type change.
[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 #ifndef __VISAGECPP__
1061 // no chmod in VA. SHould be some permission API for HPFS386 partitions however
1062 if ( chmod(file2, fbuf.st_mode) != 0 )
1063 {
1064 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1065 file2.c_str());
1066 return FALSE;
1067 }
1068 #endif
1069 return TRUE;
1070 }
1071
1072 bool
1073 wxRenameFile (const wxString& file1, const wxString& file2)
1074 {
1075 // Normal system call
1076 if ( wxRename (OS_FILENAME(file1), OS_FILENAME(file2)) == 0 )
1077 return TRUE;
1078
1079 // Try to copy
1080 if (wxCopyFile(file1, file2)) {
1081 wxRemoveFile(file1);
1082 return TRUE;
1083 }
1084 // Give up
1085 return FALSE;
1086 }
1087
1088 bool wxRemoveFile(const wxString& file)
1089 {
1090 #if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__)
1091 int res = wxRemove(file);
1092 #else
1093 int res = unlink(OS_FILENAME(file));
1094 #endif
1095
1096 return res == 0;
1097 }
1098
1099 bool wxMkdir(const wxString& dir, int perm)
1100 {
1101 #if defined( __WXMAC__ )
1102 return (mkdir(wxUnix2MacFilename( dir ) , 0 ) == 0);
1103 #else // !Mac
1104 const wxChar *dirname = dir.c_str();
1105
1106 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1107 // for the GNU compiler
1108 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1109 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1110 #elif defined(__WXPM__)
1111 if (::DosCreateDir((PSZ)dirname, NULL) != 0) // enhance for EAB's??
1112 #else // !MSW and !OS/2 VAC++
1113 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1114 #endif // !MSW/MSW
1115 {
1116 wxLogSysError(_("Directory '%s' couldn't be created"), dirname);
1117
1118 return FALSE;
1119 }
1120
1121 return TRUE;
1122 #endif // Mac/!Mac
1123 }
1124
1125 bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1126 {
1127 #ifdef __VMS__
1128 return FALSE; //to be changed since rmdir exists in VMS7.x
1129 #elif defined(__WXPM__)
1130 return (::DosDeleteDir((PSZ)dir.c_str()) == 0);
1131 #else
1132
1133 #ifdef __SALFORDC__
1134 return FALSE; // What to do?
1135 #else
1136 return (wxRmDir(OS_FILENAME(dir)) == 0);
1137 #endif
1138
1139 #endif
1140 }
1141
1142 // does the path exists? (may have or not '/' or '\\' at the end)
1143 bool wxPathExists(const wxChar *pszPathName)
1144 {
1145 wxString strPath(pszPathName);
1146 #ifdef __WINDOWS__
1147 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1148 // so remove all trailing backslashes from the path - but don't do this for
1149 // the pathes "d:\" (which are different from "d:") nor for just "\"
1150 while ( wxEndsWithPathSeparator(strPath) )
1151 {
1152 size_t len = strPath.length();
1153 if ( len == 1 || strPath[len - 1] == _T(':') )
1154 break;
1155
1156 strPath.Truncate(len - 1);
1157 }
1158 #endif // __WINDOWS__
1159
1160 wxStructStat st;
1161 #ifndef __VISAGECPP__
1162 return wxStat(wxFNSTRINGCAST strPath.fn_str(), &st) == 0 &&
1163 ((st.st_mode & S_IFMT) == S_IFDIR);
1164 #else
1165 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1166 return wxStat(wxFNSTRINGCAST strPath.fn_str(), &st) == 0 &&
1167 (st.st_mode == S_IFDIR);
1168 #endif
1169
1170 }
1171
1172 // Get a temporary filename, opening and closing the file.
1173 wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
1174 {
1175 #ifdef __WINDOWS__
1176
1177 #ifndef __WIN32__
1178 wxChar tmp[144];
1179 ::GetTempFileName(0, WXSTRINGCAST prefix, 0, tmp);
1180 #else
1181 wxChar tmp[MAX_PATH];
1182 wxChar tmpPath[MAX_PATH];
1183 ::GetTempPath(MAX_PATH, tmpPath);
1184 ::GetTempFileName(tmpPath, WXSTRINGCAST prefix, 0, tmp);
1185 #endif
1186 if (buf) wxStrcpy(buf, tmp);
1187 else buf = copystring(tmp);
1188 return buf;
1189
1190 #else
1191 static short last_temp = 0; // cache last to speed things a bit
1192 // At most 1000 temp files to a process! We use a ring count.
1193 wxChar tmp[100]; // FIXME static buffer
1194
1195 for (short suffix = last_temp + 1; suffix != last_temp; ++suffix %= 1000)
1196 {
1197 wxSprintf (tmp, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix, (int) getpid (), (int) suffix);
1198 if (!wxFileExists( tmp ))
1199 {
1200 // Touch the file to create it (reserve name)
1201 FILE *fd = fopen (wxFNCONV(tmp), "w");
1202 if (fd)
1203 fclose (fd);
1204 last_temp = suffix;
1205 if (buf)
1206 wxStrcpy( buf, tmp);
1207 else
1208 buf = copystring( tmp );
1209 return buf;
1210 }
1211 }
1212 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1213 if (buf) buf[0] = 0;
1214 return (wxChar *) NULL;
1215 #endif
1216 }
1217
1218 bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1219 {
1220 wxChar buf2[512];
1221 if (wxGetTempFileName(prefix, buf2) != (wxChar*) NULL)
1222 {
1223 buf = buf2;
1224 return TRUE;
1225 }
1226 else
1227 return FALSE;
1228 }
1229
1230 // Get first file name matching given wild card.
1231
1232 #ifdef __UNIX__
1233
1234 // Get first file name matching given wild card.
1235 // Flags are reserved for future use.
1236
1237 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1238 static DIR *gs_dirStream = (DIR *) NULL;
1239 static wxString gs_strFileSpec;
1240 static int gs_findFlags = 0;
1241 #endif
1242
1243 wxString wxFindFirstFile(const wxChar *spec, int flags)
1244 {
1245 wxString result;
1246 #ifdef __VMS
1247 wxChar *specvms = NULL;
1248 #endif
1249
1250 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1251 if (gs_dirStream)
1252 closedir(gs_dirStream); // edz 941103: better housekeping
1253
1254 gs_findFlags = flags;
1255
1256 gs_strFileSpec = spec;
1257
1258 // Find path only so we can concatenate
1259 // found file onto path
1260 wxString path(wxPathOnly(gs_strFileSpec));
1261
1262 // special case: path is really "/"
1263 if ( !path && gs_strFileSpec[0u] == wxT('/') )
1264 #ifdef __VMS
1265 {
1266 wxStrcpy( specvms , wxT( "[000000]" ) );
1267 gs_strFileSpec = specvms;
1268 wxString path_vms(wxPathOnly(gs_strFileSpec));
1269 path = path_vms;
1270 }
1271 #else
1272 path = wxT('/');
1273 #endif
1274 // path is empty => Local directory
1275 if ( !path )
1276 #ifdef __VMS
1277 {
1278 wxStrcpy( specvms , wxT( "[]" ) );
1279 gs_strFileSpec = specvms;
1280 wxString path_vms1(wxPathOnly(gs_strFileSpec));
1281 path = path_vms1;
1282 }
1283 #else
1284 path = wxT('.');
1285 #endif
1286
1287 gs_dirStream = opendir(path.fn_str());
1288 if ( !gs_dirStream )
1289 {
1290 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1291 path.c_str());
1292 }
1293 else
1294 {
1295 result = wxFindNextFile();
1296 }
1297 #endif // !VMS6.x or earlier
1298
1299 return result;
1300 }
1301
1302 wxString wxFindNextFile()
1303 {
1304 wxString result;
1305
1306 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1307 wxCHECK_MSG( gs_dirStream, result, wxT("must call wxFindFirstFile first") );
1308
1309 // Find path only so we can concatenate
1310 // found file onto path
1311 wxString path(wxPathOnly(gs_strFileSpec));
1312 wxString name(wxFileNameFromPath(gs_strFileSpec));
1313
1314 /* MATTHEW: special case: path is really "/" */
1315 if ( !path && gs_strFileSpec[0u] == wxT('/'))
1316 path = wxT('/');
1317
1318 // Do the reading
1319 struct dirent *nextDir;
1320 for ( nextDir = readdir(gs_dirStream);
1321 nextDir != NULL;
1322 nextDir = readdir(gs_dirStream) )
1323 {
1324 if (wxMatchWild(name, nextDir->d_name, FALSE) && // RR: added FALSE to find hidden files
1325 strcmp(nextDir->d_name, ".") &&
1326 strcmp(nextDir->d_name, "..") )
1327 {
1328 result.Empty();
1329 if ( !path.IsEmpty() )
1330 {
1331 result = path;
1332 if ( path != wxT('/') )
1333 result += wxT('/');
1334 }
1335
1336 result += nextDir->d_name;
1337
1338 // Only return "." and ".." when they match
1339 bool isdir;
1340 if ( (strcmp(nextDir->d_name, ".") == 0) ||
1341 (strcmp(nextDir->d_name, "..") == 0))
1342 {
1343 if ( (gs_findFlags & wxDIR) != 0 )
1344 isdir = TRUE;
1345 else
1346 continue;
1347 }
1348 else
1349 isdir = wxDirExists(result);
1350
1351 // and only return directories when flags & wxDIR
1352 if ( !gs_findFlags ||
1353 ((gs_findFlags & wxDIR) && isdir) ||
1354 ((gs_findFlags & wxFILE) && !isdir) )
1355 {
1356 return result;
1357 }
1358 }
1359 }
1360
1361 result.Empty(); // not found
1362
1363 closedir(gs_dirStream);
1364 gs_dirStream = (DIR *) NULL;
1365 #endif // !VMS6.2 or earlier
1366
1367 return result;
1368 }
1369
1370 #elif defined(__WXMAC__)
1371
1372 struct MacDirectoryIterator
1373 {
1374 CInfoPBRec m_CPB ;
1375 wxInt16 m_index ;
1376 long m_dirId ;
1377 Str255 m_name ;
1378 } ;
1379
1380 static int g_iter_flags ;
1381
1382 static MacDirectoryIterator g_iter ;
1383
1384 wxString wxFindFirstFile(const wxChar *spec, int flags)
1385 {
1386 wxString result;
1387
1388 g_iter_flags = flags; /* MATTHEW: [5] Remember flags */
1389
1390 // Find path only so we can concatenate found file onto path
1391 wxString path(wxPathOnly(spec));
1392 if ( !path.IsEmpty() )
1393 result << path << wxT('\\');
1394
1395 FSSpec fsspec ;
1396
1397 wxUnixFilename2FSSpec( result , &fsspec ) ;
1398 g_iter.m_CPB.hFileInfo.ioVRefNum = fsspec.vRefNum ;
1399 g_iter.m_CPB.hFileInfo.ioNamePtr = g_iter.m_name ;
1400 g_iter.m_index = 0 ;
1401
1402 Boolean isDir ;
1403 FSpGetDirectoryID( &fsspec , &g_iter.m_dirId , &isDir ) ;
1404 if ( !isDir )
1405 return wxEmptyString ;
1406
1407 return wxFindNextFile( ) ;
1408 }
1409
1410 wxString wxFindNextFile()
1411 {
1412 wxString result;
1413
1414 short err = noErr ;
1415
1416 while ( err == noErr )
1417 {
1418 g_iter.m_index++ ;
1419 g_iter.m_CPB.dirInfo.ioFDirIndex = g_iter.m_index;
1420 g_iter.m_CPB.dirInfo.ioDrDirID = g_iter.m_dirId; /* we need to do this every time */
1421 err = PBGetCatInfoSync((CInfoPBPtr)&g_iter.m_CPB);
1422 if ( err != noErr )
1423 break ;
1424
1425 if ( ( g_iter.m_CPB.dirInfo.ioFlAttrib & ioDirMask) != 0 && (g_iter_flags & wxDIR) ) // we have a directory
1426 break ;
1427
1428 if ( ( g_iter.m_CPB.dirInfo.ioFlAttrib & ioDirMask) == 0 && !(g_iter_flags & wxFILE ) )
1429 continue ;
1430
1431 // hit !
1432 break ;
1433 }
1434 if ( err != noErr )
1435 {
1436 return wxEmptyString ;
1437 }
1438 FSSpec spec ;
1439
1440 FSMakeFSSpecCompat(g_iter.m_CPB.hFileInfo.ioVRefNum,
1441 g_iter.m_dirId,
1442 g_iter.m_name,
1443 &spec) ;
1444
1445 return wxMacFSSpec2UnixFilename( &spec ) ;
1446 }
1447
1448 #elif defined(__WXMSW__)
1449
1450 #ifdef __WIN32__
1451 static HANDLE gs_hFileStruct = INVALID_HANDLE_VALUE;
1452 static WIN32_FIND_DATA gs_findDataStruct;
1453 #else // Win16
1454 #ifdef __BORLANDC__
1455 static struct ffblk gs_findDataStruct;
1456 #else
1457 static struct _find_t gs_findDataStruct;
1458 #endif // Borland
1459 #endif // Win32/16
1460
1461 static wxString gs_strFileSpec;
1462 static int gs_findFlags = 0;
1463
1464 wxString wxFindFirstFile(const wxChar *spec, int flags)
1465 {
1466 wxString result;
1467
1468 gs_strFileSpec = spec;
1469 gs_findFlags = flags; /* MATTHEW: [5] Remember flags */
1470
1471 // Find path only so we can concatenate found file onto path
1472 wxString path(wxPathOnly(gs_strFileSpec));
1473 if ( !path.IsEmpty() )
1474 result << path << wxT('\\');
1475
1476 #ifdef __WIN32__
1477 if ( gs_hFileStruct != INVALID_HANDLE_VALUE )
1478 FindClose(gs_hFileStruct);
1479
1480 gs_hFileStruct = ::FindFirstFile(WXSTRINGCAST spec, &gs_findDataStruct);
1481
1482 if ( gs_hFileStruct == INVALID_HANDLE_VALUE )
1483 {
1484 result.Empty();
1485
1486 return result;
1487 }
1488
1489 bool isdir = !!(gs_findDataStruct.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1490
1491 if (isdir && !(flags & wxDIR))
1492 return wxFindNextFile();
1493 else if (!isdir && flags && !(flags & wxFILE))
1494 return wxFindNextFile();
1495
1496 result += gs_findDataStruct.cFileName;
1497
1498 return result;
1499 #else // !Win32
1500 int flag = _A_NORMAL;
1501 if (flags & wxDIR)
1502 flag = _A_SUBDIR;
1503
1504 #ifdef __BORLANDC__
1505 if (findfirst(WXSTRINGCAST spec, &gs_findDataStruct, flag) == 0)
1506 #else
1507 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1508 #endif
1509 {
1510 char attrib;
1511
1512 #ifdef __BORLANDC__
1513 attrib = gs_findDataStruct.ff_attrib;
1514 #else
1515 attrib = gs_findDataStruct.attrib;
1516 #endif
1517
1518 if (attrib & _A_SUBDIR) {
1519 if (!(gs_findFlags & wxDIR))
1520 return wxFindNextFile();
1521 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1522 return wxFindNextFile();
1523
1524 result +=
1525 #ifdef __BORLANDC__
1526 gs_findDataStruct.ff_name
1527 #else
1528 gs_findDataStruct.name
1529 #endif
1530 ;
1531 }
1532
1533 return result;
1534 #endif // __WIN32__
1535 }
1536
1537
1538 wxString wxFindNextFile()
1539 {
1540 wxString result;
1541
1542 // Find path only so we can concatenate found file onto path
1543 wxString path(wxPathOnly(gs_strFileSpec));
1544
1545 try_again:
1546
1547 #ifdef __WIN32__
1548 if (gs_hFileStruct == INVALID_HANDLE_VALUE)
1549 return result;
1550
1551 bool success = (FindNextFile(gs_hFileStruct, &gs_findDataStruct) != 0);
1552 if (!success)
1553 {
1554 FindClose(gs_hFileStruct);
1555 gs_hFileStruct = INVALID_HANDLE_VALUE;
1556 }
1557 else
1558 {
1559 bool isdir = !!(gs_findDataStruct.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1560
1561 if (isdir && !(gs_findFlags & wxDIR))
1562 goto try_again;
1563 else if (!isdir && gs_findFlags && !(gs_findFlags & wxFILE))
1564 goto try_again;
1565
1566 if ( !path.IsEmpty() )
1567 result << path << wxT('\\');
1568 result << gs_findDataStruct.cFileName;
1569 }
1570
1571 return result;
1572 #else // Win16
1573
1574 #ifdef __BORLANDC__
1575 if (findnext(&gs_findDataStruct) == 0)
1576 #else
1577 if (_dos_findnext(&gs_findDataStruct) == 0)
1578 #endif
1579 {
1580 /* MATTHEW: [5] Check directory flag */
1581 char attrib;
1582
1583 #ifdef __BORLANDC__
1584 attrib = gs_findDataStruct.ff_attrib;
1585 #else
1586 attrib = gs_findDataStruct.attrib;
1587 #endif
1588
1589 if (attrib & _A_SUBDIR) {
1590 if (!(gs_findFlags & wxDIR))
1591 goto try_again;
1592 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1593 goto try_again;
1594
1595
1596 result +=
1597 #ifdef __BORLANDC__
1598 gs_findDataStruct.ff_name
1599 #else
1600 gs_findDataStruct.name
1601 #endif
1602 ;
1603 }
1604
1605 return result;
1606 #endif // Win32/16
1607 }
1608
1609 #elif defined(__WXPM__)
1610
1611 wxString wxFindFirstFile(const wxChar *spec, int flags)
1612 {
1613 wxString result;
1614
1615 /*
1616 // TODO: figure something out here for OS/2
1617 gs_strFileSpec = spec;
1618 gs_findFlags = flags;
1619
1620 // Find path only so we can concatenate found file onto path
1621 wxString path(wxPathOnly(gs_strFileSpec));
1622 if ( !path.IsEmpty() )
1623 result << path << wxT('\\');
1624
1625 int flag = _A_NORMAL;
1626 if (flags & wxDIR)
1627 flag = _A_SUBDIR;
1628
1629 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1630 {
1631 char attrib;
1632 attrib = gs_findDataStruct.attrib;
1633
1634 if (attrib & _A_SUBDIR) {
1635 if (!(gs_findFlags & wxDIR))
1636 return wxFindNextFile();
1637 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1638 return wxFindNextFile();
1639
1640 result += gs_findDataStruct.name;
1641 }
1642 */
1643 return result;
1644 }
1645
1646 wxString wxFindNextFile()
1647 {
1648 wxString result;
1649 // TODO:
1650 return result;
1651 }
1652
1653 #endif // Unix/Windows/OS/2
1654
1655 // Get current working directory.
1656 // If buf is NULL, allocates space using new, else
1657 // copies into buf.
1658 wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1659 {
1660 if (!buf)
1661 buf = new wxChar[sz+1];
1662 #if wxUSE_UNICODE
1663 char *cbuf = new char[sz+1];
1664 #ifdef _MSC_VER
1665 if (_getcwd(cbuf, sz) == NULL) {
1666 #elif defined( __WXMAC__)
1667 enum
1668 {
1669 SFSaveDisk = 0x214, CurDirStore = 0x398
1670 };
1671 FSSpec cwdSpec ;
1672
1673 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1674 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1675 strcpy( buf , res ) ;
1676 if (0) {
1677 #else
1678 if (getcwd(cbuf, sz) == NULL) {
1679 #endif
1680 delete [] cbuf;
1681 #else // wxUnicode
1682 #ifdef _MSC_VER
1683 if (_getcwd(buf, sz) == NULL) {
1684 #elif defined( __WXMAC__)
1685 enum
1686 {
1687 SFSaveDisk = 0x214, CurDirStore = 0x398
1688 };
1689 FSSpec cwdSpec ;
1690
1691 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1692 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1693 strcpy( buf , res ) ;
1694 if (0) {
1695 #elif(__VISAGECPP__)
1696 APIRET rc;
1697 rc = ::DosQueryCurrentDir( 0 // current drive
1698 ,buf
1699 ,(PULONG)&sz
1700 );
1701 if (rc != 0) {
1702 #else
1703 if (getcwd(buf, sz) == NULL) {
1704 #endif
1705 #endif
1706 buf[0] = wxT('.');
1707 buf[1] = wxT('\0');
1708 }
1709 #if wxUSE_UNICODE
1710 else {
1711 wxConvFile.MB2WC(buf, cbuf, sz);
1712 delete [] cbuf;
1713 }
1714 #endif
1715 return buf;
1716 }
1717
1718 wxString wxGetCwd()
1719 {
1720 static const size_t maxPathLen = 1024;
1721
1722 wxString str;
1723 wxGetWorkingDirectory(str.GetWriteBuf(maxPathLen), maxPathLen);
1724 str.UngetWriteBuf();
1725
1726 return str;
1727 }
1728
1729 bool wxSetWorkingDirectory(const wxString& d)
1730 {
1731 #if defined( __UNIX__ ) || defined( __WXMAC__ )
1732 return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
1733 #elif defined(__WXPM__)
1734 return (::DosSetCurrentDir((PSZ)d.c_str()) == 0);
1735 #elif defined(__WINDOWS__)
1736
1737 #ifdef __WIN32__
1738 return (bool)(SetCurrentDirectory(d) != 0);
1739 #else
1740 // Must change drive, too.
1741 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1742 if (isDriveSpec)
1743 {
1744 wxChar firstChar = d[0];
1745
1746 // To upper case
1747 if (firstChar > 90)
1748 firstChar = firstChar - 32;
1749
1750 // To a drive number
1751 unsigned int driveNo = firstChar - 64;
1752 if (driveNo > 0)
1753 {
1754 unsigned int noDrives;
1755 _dos_setdrive(driveNo, &noDrives);
1756 }
1757 }
1758 bool success = (chdir(WXSTRINGCAST d) == 0);
1759
1760 return success;
1761 #endif
1762
1763 #endif
1764 }
1765
1766 // Get the OS directory if appropriate (such as the Windows directory).
1767 // On non-Windows platform, probably just return the empty string.
1768 wxString wxGetOSDirectory()
1769 {
1770 #ifdef __WINDOWS__
1771 wxChar buf[256];
1772 GetWindowsDirectory(buf, 256);
1773 return wxString(buf);
1774 #else
1775 return wxEmptyString;
1776 #endif
1777 }
1778
1779 bool wxEndsWithPathSeparator(const wxChar *pszFileName)
1780 {
1781 size_t len = wxStrlen(pszFileName);
1782 if ( len == 0 )
1783 return FALSE;
1784 else
1785 return wxIsPathSeparator(pszFileName[len - 1]);
1786 }
1787
1788 // find a file in a list of directories, returns false if not found
1789 bool wxFindFileInPath(wxString *pStr, const wxChar *pszPath, const wxChar *pszFile)
1790 {
1791 // we assume that it's not empty
1792 wxCHECK_MSG( !wxIsEmpty(pszFile), FALSE,
1793 _T("empty file name in wxFindFileInPath"));
1794
1795 // skip path separator in the beginning of the file name if present
1796 if ( wxIsPathSeparator(*pszFile) )
1797 pszFile++;
1798
1799 // copy the path (strtok will modify it)
1800 wxChar *szPath = new wxChar[wxStrlen(pszPath) + 1];
1801 wxStrcpy(szPath, pszPath);
1802
1803 wxString strFile;
1804 wxChar *pc, *save_ptr;
1805 for ( pc = wxStrtok(szPath, wxPATH_SEP, &save_ptr);
1806 pc != NULL;
1807 pc = wxStrtok((wxChar *) NULL, wxPATH_SEP, &save_ptr) )
1808 {
1809 // search for the file in this directory
1810 strFile = pc;
1811 if ( !wxEndsWithPathSeparator(pc) )
1812 strFile += wxFILE_SEP_PATH;
1813 strFile += pszFile;
1814
1815 if ( FileExists(strFile) ) {
1816 *pStr = strFile;
1817 break;
1818 }
1819 }
1820
1821 // suppress warning about unused variable save_ptr when wxStrtok() is a
1822 // macro which throws away its third argument
1823 save_ptr = pc;
1824
1825 delete [] szPath;
1826
1827 return pc != NULL; // if true => we breaked from the loop
1828 }
1829
1830 void WXDLLEXPORT wxSplitPath(const wxChar *pszFileName,
1831 wxString *pstrPath,
1832 wxString *pstrName,
1833 wxString *pstrExt)
1834 {
1835 // it can be empty, but it shouldn't be NULL
1836 wxCHECK_RET( pszFileName, wxT("NULL file name in wxSplitPath") );
1837
1838 wxFileName::SplitPath(pszFileName, pstrPath, pstrName, pstrExt);
1839 }
1840
1841 time_t WXDLLEXPORT wxFileModificationTime(const wxString& filename)
1842 {
1843 wxStructStat buf;
1844
1845 wxStat(filename.fn_str(), &buf);
1846 return buf.st_mtime;
1847 }
1848
1849
1850 //------------------------------------------------------------------------
1851 // wild character routines
1852 //------------------------------------------------------------------------
1853
1854 bool wxIsWild( const wxString& pattern )
1855 {
1856 wxString tmp = pattern;
1857 wxChar *pat = WXSTRINGCAST(tmp);
1858 while (*pat) {
1859 switch (*pat++) {
1860 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1861 return TRUE;
1862 case wxT('\\'):
1863 if (!*pat++)
1864 return FALSE;
1865 }
1866 }
1867 return FALSE;
1868 };
1869
1870 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1871
1872 #if defined(HAVE_FNMATCH_H)
1873 {
1874 // this probably won't work well for multibyte chars in Unicode mode?
1875 if(dot_special)
1876 return fnmatch(pat.fn_str(), text.fn_str(), FNM_PERIOD) == 0;
1877 else
1878 return fnmatch(pat.fn_str(), text.fn_str(), 0) == 0;
1879 }
1880 #else
1881
1882 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1883
1884 /*
1885 * WARNING: this code is broken!
1886 */
1887 {
1888 wxString tmp1 = pat;
1889 wxChar *pattern = WXSTRINGCAST(tmp1);
1890 wxString tmp2 = text;
1891 wxChar *str = WXSTRINGCAST(tmp2);
1892 wxChar c;
1893 wxChar *cp;
1894 bool done = FALSE, ret_code, ok;
1895 // Below is for vi fans
1896 const wxChar OB = wxT('{'), CB = wxT('}');
1897
1898 // dot_special means '.' only matches '.'
1899 if (dot_special && *str == wxT('.') && *pattern != *str)
1900 return FALSE;
1901
1902 while ((*pattern != wxT('\0')) && (!done)
1903 && (((*str==wxT('\0'))&&((*pattern==OB)||(*pattern==wxT('*'))))||(*str!=wxT('\0')))) {
1904 switch (*pattern) {
1905 case wxT('\\'):
1906 pattern++;
1907 if (*pattern != wxT('\0'))
1908 pattern++;
1909 break;
1910 case wxT('*'):
1911 pattern++;
1912 ret_code = FALSE;
1913 while ((*str!=wxT('\0'))
1914 && (!(ret_code=wxMatchWild(pattern, str++, FALSE))))
1915 /*loop*/;
1916 if (ret_code) {
1917 while (*str != wxT('\0'))
1918 str++;
1919 while (*pattern != wxT('\0'))
1920 pattern++;
1921 }
1922 break;
1923 case wxT('['):
1924 pattern++;
1925 repeat:
1926 if ((*pattern == wxT('\0')) || (*pattern == wxT(']'))) {
1927 done = TRUE;
1928 break;
1929 }
1930 if (*pattern == wxT('\\')) {
1931 pattern++;
1932 if (*pattern == wxT('\0')) {
1933 done = TRUE;
1934 break;
1935 }
1936 }
1937 if (*(pattern + 1) == wxT('-')) {
1938 c = *pattern;
1939 pattern += 2;
1940 if (*pattern == wxT(']')) {
1941 done = TRUE;
1942 break;
1943 }
1944 if (*pattern == wxT('\\')) {
1945 pattern++;
1946 if (*pattern == wxT('\0')) {
1947 done = TRUE;
1948 break;
1949 }
1950 }
1951 if ((*str < c) || (*str > *pattern)) {
1952 pattern++;
1953 goto repeat;
1954 }
1955 } else if (*pattern != *str) {
1956 pattern++;
1957 goto repeat;
1958 }
1959 pattern++;
1960 while ((*pattern != wxT(']')) && (*pattern != wxT('\0'))) {
1961 if ((*pattern == wxT('\\')) && (*(pattern + 1) != wxT('\0')))
1962 pattern++;
1963 pattern++;
1964 }
1965 if (*pattern != wxT('\0')) {
1966 pattern++, str++;
1967 }
1968 break;
1969 case wxT('?'):
1970 pattern++;
1971 str++;
1972 break;
1973 case OB:
1974 pattern++;
1975 while ((*pattern != CB) && (*pattern != wxT('\0'))) {
1976 cp = str;
1977 ok = TRUE;
1978 while (ok && (*cp != wxT('\0')) && (*pattern != wxT('\0'))
1979 && (*pattern != wxT(',')) && (*pattern != CB)) {
1980 if (*pattern == wxT('\\'))
1981 pattern++;
1982 ok = (*pattern++ == *cp++);
1983 }
1984 if (*pattern == wxT('\0')) {
1985 ok = FALSE;
1986 done = TRUE;
1987 break;
1988 } else if (ok) {
1989 str = cp;
1990 while ((*pattern != CB) && (*pattern != wxT('\0'))) {
1991 if (*++pattern == wxT('\\')) {
1992 if (*++pattern == CB)
1993 pattern++;
1994 }
1995 }
1996 } else {
1997 while (*pattern!=CB && *pattern!=wxT(',') && *pattern!=wxT('\0')) {
1998 if (*++pattern == wxT('\\')) {
1999 if (*++pattern == CB || *pattern == wxT(','))
2000 pattern++;
2001 }
2002 }
2003 }
2004 if (*pattern != wxT('\0'))
2005 pattern++;
2006 }
2007 break;
2008 default:
2009 if (*str == *pattern) {
2010 str++, pattern++;
2011 } else {
2012 done = TRUE;
2013 }
2014 }
2015 }
2016 while (*pattern == wxT('*'))
2017 pattern++;
2018 return ((*str == wxT('\0')) && (*pattern == wxT('\0')));
2019 };
2020
2021 #endif
2022
2023 #ifdef __VISUALC__
2024 #pragma warning(default:4706) // assignment within conditional expression
2025 #endif // VC++