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