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