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