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