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