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