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