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