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