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