]> git.saurik.com Git - wxWidgets.git/blob - src/common/filefn.cpp
using common code
[wxWidgets.git] / src / common / filefn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/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 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #include "wx/filefn.h"
28
29 #ifndef WX_PRECOMP
30 #include "wx/intl.h"
31 #include "wx/log.h"
32 #include "wx/utils.h"
33 #include "wx/crt.h"
34 #endif
35
36 #include "wx/dynarray.h"
37 #include "wx/file.h"
38 #include "wx/filename.h"
39 #include "wx/dir.h"
40
41 #include "wx/tokenzr.h"
42
43 // there are just too many of those...
44 #ifdef __VISUALC__
45 #pragma warning(disable:4706) // assignment within conditional expression
46 #endif // VC++
47
48 #include <ctype.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #if !wxONLY_WATCOM_EARLIER_THAN(1,4)
53 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
54 #include <errno.h>
55 #endif
56 #endif
57
58 #if defined(__WXMAC__)
59 #include "wx/osx/private.h" // includes mac headers
60 #endif
61
62 #ifdef __WINDOWS__
63 #include "wx/msw/private.h"
64 #include "wx/msw/mslu.h"
65
66 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
67 // and for cygwin_conv_path()
68 //
69 // note that it must be included after <windows.h>
70 #ifdef __GNUWIN32__
71 #ifdef __CYGWIN__
72 #include <sys/cygwin.h>
73 #include <cygwin/version.h>
74 #endif
75 #endif // __GNUWIN32__
76
77 // io.h is needed for _get_osfhandle()
78 // Already included by filefn.h for many Windows compilers
79 #if defined __CYGWIN__
80 #include <io.h>
81 #endif
82 #endif // __WINDOWS__
83
84 #if defined(__VMS__)
85 #include <fab.h>
86 #endif
87
88 // TODO: Borland probably has _wgetcwd as well?
89 #ifdef _MSC_VER
90 #define HAVE_WGETCWD
91 #endif
92
93 // ----------------------------------------------------------------------------
94 // constants
95 // ----------------------------------------------------------------------------
96
97 #ifndef _MAXPATHLEN
98 #define _MAXPATHLEN 1024
99 #endif
100
101 // ----------------------------------------------------------------------------
102 // private globals
103 // ----------------------------------------------------------------------------
104
105 #if WXWIN_COMPATIBILITY_2_8
106 static wxChar wxFileFunctionsBuffer[4*_MAXPATHLEN];
107 #endif
108
109 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
110 //
111 // VisualAge C++ V4.0 cannot have any external linkage const decs
112 // in headers included by more than one primary source
113 //
114 const int wxInvalidOffset = -1;
115 #endif
116
117 // ============================================================================
118 // implementation
119 // ============================================================================
120
121 // ----------------------------------------------------------------------------
122 // wrappers around standard POSIX functions
123 // ----------------------------------------------------------------------------
124
125 #if wxUSE_UNICODE && defined __BORLANDC__ \
126 && __BORLANDC__ >= 0x550 && __BORLANDC__ <= 0x551
127
128 // BCC 5.5 and 5.5.1 have a bug in _wopen where files are created read only
129 // regardless of the mode parameter. This hack works around the problem by
130 // setting the mode with _wchmod.
131 //
132 int wxCRT_OpenW(const wchar_t *pathname, int flags, mode_t mode)
133 {
134 int moreflags = 0;
135
136 // we only want to fix the mode when the file is actually created, so
137 // when creating first try doing it O_EXCL so we can tell if the file
138 // was already there.
139 if ((flags & O_CREAT) && !(flags & O_EXCL) && (mode & wxS_IWUSR) != 0)
140 moreflags = O_EXCL;
141
142 int fd = _wopen(pathname, flags | moreflags, mode);
143
144 // the file was actually created and needs fixing
145 if (fd != -1 && (flags & O_CREAT) != 0 && (mode & wxS_IWUSR) != 0)
146 {
147 close(fd);
148 _wchmod(pathname, mode);
149 fd = _wopen(pathname, flags & ~(O_EXCL | O_CREAT));
150 }
151 // the open failed, but it may have been because the added O_EXCL stopped
152 // the opening of an existing file, so try again without.
153 else if (fd == -1 && moreflags != 0)
154 {
155 fd = _wopen(pathname, flags & ~O_CREAT);
156 }
157
158 return fd;
159 }
160
161 #endif
162
163 // ----------------------------------------------------------------------------
164 // wxPathList
165 // ----------------------------------------------------------------------------
166
167 bool wxPathList::Add(const wxString& path)
168 {
169 // add a path separator to force wxFileName to interpret it always as a directory
170 // (i.e. if we are called with '/home/user' we want to consider it a folder and
171 // not, as wxFileName would consider, a filename).
172 wxFileName fn(path + wxFileName::GetPathSeparator());
173
174 // add only normalized relative/absolute paths
175 // NB: we won't do wxPATH_NORM_DOTS in order to avoid problems when trying to
176 // normalize paths which starts with ".." (which can be normalized only if
177 // we use also wxPATH_NORM_ABSOLUTE - which we don't want to use).
178 if (!fn.Normalize(wxPATH_NORM_TILDE|wxPATH_NORM_LONG|wxPATH_NORM_ENV_VARS))
179 return false;
180
181 wxString toadd = fn.GetPath();
182 if (Index(toadd) == wxNOT_FOUND)
183 wxArrayString::Add(toadd); // do not add duplicates
184
185 return true;
186 }
187
188 void wxPathList::Add(const wxArrayString &arr)
189 {
190 for (size_t j=0; j < arr.GetCount(); j++)
191 Add(arr[j]);
192 }
193
194 // Add paths e.g. from the PATH environment variable
195 void wxPathList::AddEnvList (const wxString& WXUNUSED_IN_WINCE(envVariable))
196 {
197 // No environment variables on WinCE
198 #ifndef __WXWINCE__
199
200 // The space has been removed from the tokenizers, otherwise a
201 // path such as "C:\Program Files" would be split into 2 paths:
202 // "C:\Program" and "Files"; this is true for both Windows and Unix.
203
204 static const wxChar PATH_TOKS[] =
205 #if defined(__WINDOWS__) || defined(__OS2__)
206 wxT(";"); // Don't separate with colon in DOS (used for drive)
207 #else
208 wxT(":;");
209 #endif
210
211 wxString val;
212 if ( wxGetEnv(envVariable, &val) )
213 {
214 // split into an array of string the value of the env var
215 wxArrayString arr = wxStringTokenize(val, PATH_TOKS);
216 WX_APPEND_ARRAY(*this, arr);
217 }
218 #endif // !__WXWINCE__
219 }
220
221 // Given a full filename (with path), ensure that that file can
222 // be accessed again USING FILENAME ONLY by adding the path
223 // to the list if not already there.
224 bool wxPathList::EnsureFileAccessible (const wxString& path)
225 {
226 return Add(wxPathOnly(path));
227 }
228
229 #if WXWIN_COMPATIBILITY_2_6
230 bool wxPathList::Member (const wxString& path) const
231 {
232 return Index(path) != wxNOT_FOUND;
233 }
234 #endif
235
236 wxString wxPathList::FindValidPath (const wxString& file) const
237 {
238 // normalize the given string as it could be a path + a filename
239 // and not only a filename
240 wxFileName fn(file);
241 wxString strend;
242
243 // NB: normalize without making absolute otherwise calling this function with
244 // e.g. "b/c.txt" would result in removing the directory 'b' and the for loop
245 // below would only add to the paths of this list the 'c.txt' part when doing
246 // the existence checks...
247 // NB: we don't use wxPATH_NORM_DOTS here, too (see wxPathList::Add for more info)
248 if (!fn.Normalize(wxPATH_NORM_TILDE|wxPATH_NORM_LONG|wxPATH_NORM_ENV_VARS))
249 return wxEmptyString;
250
251 wxASSERT_MSG(!fn.IsDir(), wxT("Cannot search for directories; only for files"));
252 if (fn.IsAbsolute())
253 strend = fn.GetFullName(); // search for the file name and ignore the path part
254 else
255 strend = fn.GetFullPath();
256
257 for (size_t i=0; i<GetCount(); i++)
258 {
259 wxString strstart = Item(i);
260 if (!strstart.IsEmpty() && strstart.Last() != wxFileName::GetPathSeparator())
261 strstart += wxFileName::GetPathSeparator();
262
263 if (wxFileExists(strstart + strend))
264 return strstart + strend; // Found!
265 }
266
267 return wxEmptyString; // Not found
268 }
269
270 wxString wxPathList::FindAbsoluteValidPath (const wxString& file) const
271 {
272 wxString f = FindValidPath(file);
273 if ( f.empty() || wxIsAbsolutePath(f) )
274 return f;
275
276 wxString buf = ::wxGetCwd();
277
278 if ( !wxEndsWithPathSeparator(buf) )
279 {
280 buf += wxFILE_SEP_PATH;
281 }
282 buf += f;
283
284 return buf;
285 }
286
287 // ----------------------------------------------------------------------------
288 // miscellaneous global functions
289 // ----------------------------------------------------------------------------
290
291 #if WXWIN_COMPATIBILITY_2_8
292 static inline wxChar* MYcopystring(const wxString& s)
293 {
294 wxChar* copy = new wxChar[s.length() + 1];
295 return wxStrcpy(copy, s.c_str());
296 }
297
298 template<typename CharType>
299 static inline CharType* MYcopystring(const CharType* s)
300 {
301 CharType* copy = new CharType[wxStrlen(s) + 1];
302 return wxStrcpy(copy, s);
303 }
304 #endif
305
306
307 bool
308 wxFileExists (const wxString& filename)
309 {
310 return wxFileName::FileExists(filename);
311 }
312
313 bool
314 wxIsAbsolutePath (const wxString& filename)
315 {
316 if (!filename.empty())
317 {
318 // Unix like or Windows
319 if (filename[0] == wxT('/'))
320 return true;
321 #ifdef __VMS__
322 if ((filename[0] == wxT('[') && filename[1] != wxT('.')))
323 return true;
324 #endif
325 #if defined(__WINDOWS__) || defined(__OS2__)
326 // MSDOS like
327 if (filename[0] == wxT('\\') || (wxIsalpha (filename[0]) && filename[1] == wxT(':')))
328 return true;
329 #endif
330 }
331 return false ;
332 }
333
334 #if WXWIN_COMPATIBILITY_2_8
335 /*
336 * Strip off any extension (dot something) from end of file,
337 * IF one exists. Inserts zero into buffer.
338 *
339 */
340
341 template<typename T>
342 static void wxDoStripExtension(T *buffer)
343 {
344 int len = wxStrlen(buffer);
345 int i = len-1;
346 while (i > 0)
347 {
348 if (buffer[i] == wxT('.'))
349 {
350 buffer[i] = 0;
351 break;
352 }
353 i --;
354 }
355 }
356
357 void wxStripExtension(char *buffer) { wxDoStripExtension(buffer); }
358 void wxStripExtension(wchar_t *buffer) { wxDoStripExtension(buffer); }
359
360 void wxStripExtension(wxString& buffer)
361 {
362 buffer = wxFileName::StripExtension(buffer);
363 }
364
365 // Destructive removal of /./ and /../ stuff
366 template<typename CharType>
367 static CharType *wxDoRealPath (CharType *path)
368 {
369 static const CharType SEP = wxFILE_SEP_PATH;
370 #ifdef __WINDOWS__
371 wxUnix2DosFilename(path);
372 #endif
373 if (path[0] && path[1]) {
374 /* MATTHEW: special case "/./x" */
375 CharType *p;
376 if (path[2] == SEP && path[1] == wxT('.'))
377 p = &path[0];
378 else
379 p = &path[2];
380 for (; *p; p++)
381 {
382 if (*p == SEP)
383 {
384 if (p[1] == wxT('.') && p[2] == wxT('.') && (p[3] == SEP || p[3] == wxT('\0')))
385 {
386 CharType *q;
387 for (q = p - 1; q >= path && *q != SEP; q--)
388 {
389 // Empty
390 }
391
392 if (q[0] == SEP && (q[1] != wxT('.') || q[2] != wxT('.') || q[3] != SEP)
393 && (q - 1 <= path || q[-1] != SEP))
394 {
395 wxStrcpy (q, p + 3);
396 if (path[0] == wxT('\0'))
397 {
398 path[0] = SEP;
399 path[1] = wxT('\0');
400 }
401 #if defined(__WINDOWS__) || defined(__OS2__)
402 /* Check that path[2] is NULL! */
403 else if (path[1] == wxT(':') && !path[2])
404 {
405 path[2] = SEP;
406 path[3] = wxT('\0');
407 }
408 #endif
409 p = q - 1;
410 }
411 }
412 else if (p[1] == wxT('.') && (p[2] == SEP || p[2] == wxT('\0')))
413 wxStrcpy (p, p + 2);
414 }
415 }
416 }
417 return path;
418 }
419
420 char *wxRealPath(char *path)
421 {
422 return wxDoRealPath(path);
423 }
424
425 wchar_t *wxRealPath(wchar_t *path)
426 {
427 return wxDoRealPath(path);
428 }
429
430 wxString wxRealPath(const wxString& path)
431 {
432 wxChar *buf1=MYcopystring(path);
433 wxChar *buf2=wxRealPath(buf1);
434 wxString buf(buf2);
435 delete [] buf1;
436 return buf;
437 }
438
439
440 // Must be destroyed
441 wxChar *wxCopyAbsolutePath(const wxString& filename)
442 {
443 if (filename.empty())
444 return NULL;
445
446 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer, filename)))
447 {
448 wxString buf = ::wxGetCwd();
449 wxChar ch = buf.Last();
450 #ifdef __WINDOWS__
451 if (ch != wxT('\\') && ch != wxT('/'))
452 buf << wxT("\\");
453 #else
454 if (ch != wxT('/'))
455 buf << wxT("/");
456 #endif
457 buf << wxFileFunctionsBuffer;
458 buf = wxRealPath( buf );
459 return MYcopystring( buf );
460 }
461 return MYcopystring( wxFileFunctionsBuffer );
462 }
463
464 /*-
465 Handles:
466 ~/ => home dir
467 ~user/ => user's home dir
468 If the environment variable a = "foo" and b = "bar" then:
469 Unix:
470 $a => foo
471 $a$b => foobar
472 $a.c => foo.c
473 xxx$a => xxxfoo
474 ${a}! => foo!
475 $(b)! => bar!
476 \$a => \$a
477 MSDOS:
478 $a ==> $a
479 $(a) ==> foo
480 $(a)$b ==> foo$b
481 $(a)$(b)==> foobar
482 test.$$ ==> test.$$
483 */
484
485 /* input name in name, pathname output to buf. */
486
487 template<typename CharType>
488 static CharType *wxDoExpandPath(CharType *buf, const wxString& name)
489 {
490 register CharType *d, *s, *nm;
491 CharType lnm[_MAXPATHLEN];
492 int q;
493
494 // Some compilers don't like this line.
495 // const CharType trimchars[] = wxT("\n \t");
496
497 CharType trimchars[4];
498 trimchars[0] = wxT('\n');
499 trimchars[1] = wxT(' ');
500 trimchars[2] = wxT('\t');
501 trimchars[3] = 0;
502
503 static const CharType SEP = wxFILE_SEP_PATH;
504 #ifdef __WINDOWS__
505 //wxUnix2DosFilename(path);
506 #endif
507
508 buf[0] = wxT('\0');
509 if (name.empty())
510 return buf;
511 nm = ::MYcopystring(static_cast<const CharType*>(name.c_str())); // Make a scratch copy
512 CharType *nm_tmp = nm;
513
514 /* Skip leading whitespace and cr */
515 while (wxStrchr(trimchars, *nm) != NULL)
516 nm++;
517 /* And strip off trailing whitespace and cr */
518 s = nm + (q = wxStrlen(nm)) - 1;
519 while (q-- && wxStrchr(trimchars, *s) != NULL)
520 *s = wxT('\0');
521
522 s = nm;
523 d = lnm;
524 #ifdef __WINDOWS__
525 q = FALSE;
526 #else
527 q = nm[0] == wxT('\\') && nm[1] == wxT('~');
528 #endif
529
530 /* Expand inline environment variables */
531 #ifdef __VISAGECPP__
532 while (*d)
533 {
534 *d++ = *s;
535 if(*s == wxT('\\'))
536 {
537 *(d - 1) = *++s;
538 if (*d)
539 {
540 s++;
541 continue;
542 }
543 else
544 break;
545 }
546 else
547 #else
548 while ((*d++ = *s) != 0) {
549 # ifndef __WINDOWS__
550 if (*s == wxT('\\')) {
551 if ((*(d - 1) = *++s)!=0) {
552 s++;
553 continue;
554 } else
555 break;
556 } else
557 # endif
558 #endif
559 // No env variables on WinCE
560 #ifndef __WXWINCE__
561 #ifdef __WINDOWS__
562 if (*s++ == wxT('$') && (*s == wxT('{') || *s == wxT(')')))
563 #else
564 if (*s++ == wxT('$'))
565 #endif
566 {
567 register CharType *start = d;
568 register int braces = (*s == wxT('{') || *s == wxT('('));
569 register CharType *value;
570 while ((*d++ = *s) != 0)
571 if (braces ? (*s == wxT('}') || *s == wxT(')')) : !(wxIsalnum(*s) || *s == wxT('_')) )
572 break;
573 else
574 s++;
575 *--d = 0;
576 value = wxGetenv(braces ? start + 1 : start);
577 if (value) {
578 for ((d = start - 1); (*d++ = *value++) != 0;)
579 {
580 // Empty
581 }
582
583 d--;
584 if (braces && *s)
585 s++;
586 }
587 }
588 #endif
589 // __WXWINCE__
590 }
591
592 /* Expand ~ and ~user */
593 wxString homepath;
594 nm = lnm;
595 if (nm[0] == wxT('~') && !q)
596 {
597 /* prefix ~ */
598 if (nm[1] == SEP || nm[1] == 0)
599 { /* ~/filename */
600 homepath = wxGetUserHome(wxEmptyString);
601 if (!homepath.empty()) {
602 s = (CharType*)(const CharType*)homepath.c_str();
603 if (*++nm)
604 nm++;
605 }
606 } else
607 { /* ~user/filename */
608 register CharType *nnm;
609 for (s = nm; *s && *s != SEP; s++)
610 {
611 // Empty
612 }
613 int was_sep; /* MATTHEW: Was there a separator, or NULL? */
614 was_sep = (*s == SEP);
615 nnm = *s ? s + 1 : s;
616 *s = 0;
617 homepath = wxGetUserHome(wxString(nm + 1));
618 if (homepath.empty())
619 {
620 if (was_sep) /* replace only if it was there: */
621 *s = SEP;
622 s = NULL;
623 }
624 else
625 {
626 nm = nnm;
627 s = (CharType*)(const CharType*)homepath.c_str();
628 }
629 }
630 }
631
632 d = buf;
633 if (s && *s) { /* MATTHEW: s could be NULL if user '~' didn't exist */
634 /* Copy home dir */
635 while (wxT('\0') != (*d++ = *s++))
636 /* loop */;
637 // Handle root home
638 if (d - 1 > buf && *(d - 2) != SEP)
639 *(d - 1) = SEP;
640 }
641 s = nm;
642 while ((*d++ = *s++) != 0)
643 {
644 // Empty
645 }
646 delete[] nm_tmp; // clean up alloc
647 /* Now clean up the buffer */
648 return wxRealPath(buf);
649 }
650
651 char *wxExpandPath(char *buf, const wxString& name)
652 {
653 return wxDoExpandPath(buf, name);
654 }
655
656 wchar_t *wxExpandPath(wchar_t *buf, const wxString& name)
657 {
658 return wxDoExpandPath(buf, name);
659 }
660
661
662 /* Contract Paths to be build upon an environment variable
663 component:
664
665 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
666
667 The call wxExpandPath can convert these back!
668 */
669 wxChar *
670 wxContractPath (const wxString& filename,
671 const wxString& WXUNUSED_IN_WINCE(envname),
672 const wxString& user)
673 {
674 static wxChar dest[_MAXPATHLEN];
675
676 if (filename.empty())
677 return NULL;
678
679 wxStrcpy (dest, filename);
680 #ifdef __WINDOWS__
681 wxUnix2DosFilename(dest);
682 #endif
683
684 // Handle environment
685 wxString val;
686 #ifndef __WXWINCE__
687 wxChar *tcp;
688 if (!envname.empty() && !(val = wxGetenv (envname)).empty() &&
689 (tcp = wxStrstr (dest, val)) != NULL)
690 {
691 wxStrcpy (wxFileFunctionsBuffer, tcp + val.length());
692 *tcp++ = wxT('$');
693 *tcp++ = wxT('{');
694 wxStrcpy (tcp, envname);
695 wxStrcat (tcp, wxT("}"));
696 wxStrcat (tcp, wxFileFunctionsBuffer);
697 }
698 #endif
699
700 // Handle User's home (ignore root homes!)
701 val = wxGetUserHome (user);
702 if (val.empty())
703 return dest;
704
705 const size_t len = val.length();
706 if (len <= 2)
707 return dest;
708
709 if (wxStrncmp(dest, val, len) == 0)
710 {
711 wxStrcpy(wxFileFunctionsBuffer, wxT("~"));
712 if (!user.empty())
713 wxStrcat(wxFileFunctionsBuffer, user);
714 wxStrcat(wxFileFunctionsBuffer, dest + len);
715 wxStrcpy (dest, wxFileFunctionsBuffer);
716 }
717
718 return dest;
719 }
720
721 #endif // #if WXWIN_COMPATIBILITY_2_8
722
723 // Return just the filename, not the path (basename)
724 wxChar *wxFileNameFromPath (wxChar *path)
725 {
726 wxString p = path;
727 wxString n = wxFileNameFromPath(p);
728
729 return path + p.length() - n.length();
730 }
731
732 wxString wxFileNameFromPath (const wxString& path)
733 {
734 return wxFileName(path).GetFullName();
735 }
736
737 // Return just the directory, or NULL if no directory
738 wxChar *
739 wxPathOnly (wxChar *path)
740 {
741 if (path && *path)
742 {
743 static wxChar buf[_MAXPATHLEN];
744
745 // Local copy
746 wxStrcpy (buf, path);
747
748 int l = wxStrlen(path);
749 int i = l - 1;
750
751 // Search backward for a backward or forward slash
752 while (i > -1)
753 {
754 // Unix like or Windows
755 if (path[i] == wxT('/') || path[i] == wxT('\\'))
756 {
757 buf[i] = 0;
758 return buf;
759 }
760 #ifdef __VMS__
761 if (path[i] == wxT(']'))
762 {
763 buf[i+1] = 0;
764 return buf;
765 }
766 #endif
767 i --;
768 }
769
770 #if defined(__WINDOWS__) || defined(__OS2__)
771 // Try Drive specifier
772 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
773 {
774 // A:junk --> A:. (since A:.\junk Not A:\junk)
775 buf[2] = wxT('.');
776 buf[3] = wxT('\0');
777 return buf;
778 }
779 #endif
780 }
781 return NULL;
782 }
783
784 // Return just the directory, or NULL if no directory
785 wxString wxPathOnly (const wxString& path)
786 {
787 if (!path.empty())
788 {
789 wxChar buf[_MAXPATHLEN];
790
791 // Local copy
792 wxStrcpy(buf, path);
793
794 int l = path.length();
795 int i = l - 1;
796
797 // Search backward for a backward or forward slash
798 while (i > -1)
799 {
800 // Unix like or Windows
801 if (path[i] == wxT('/') || path[i] == wxT('\\'))
802 {
803 // Don't return an empty string
804 if (i == 0)
805 i ++;
806 buf[i] = 0;
807 return wxString(buf);
808 }
809 #ifdef __VMS__
810 if (path[i] == wxT(']'))
811 {
812 buf[i+1] = 0;
813 return wxString(buf);
814 }
815 #endif
816 i --;
817 }
818
819 #if defined(__WINDOWS__) || defined(__OS2__)
820 // Try Drive specifier
821 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
822 {
823 // A:junk --> A:. (since A:.\junk Not A:\junk)
824 buf[2] = wxT('.');
825 buf[3] = wxT('\0');
826 return wxString(buf);
827 }
828 #endif
829 }
830 return wxEmptyString;
831 }
832
833 // Utility for converting delimiters in DOS filenames to UNIX style
834 // and back again - or we get nasty problems with delimiters.
835 // Also, convert to lower case, since case is significant in UNIX.
836
837 #if defined(__WXMAC__) && !defined(__WXOSX_IPHONE__)
838
839 #define kDefaultPathStyle kCFURLPOSIXPathStyle
840
841 wxString wxMacFSRefToPath( const FSRef *fsRef , CFStringRef additionalPathComponent )
842 {
843 CFURLRef fullURLRef;
844 fullURLRef = CFURLCreateFromFSRef(NULL, fsRef);
845 if ( additionalPathComponent )
846 {
847 CFURLRef parentURLRef = fullURLRef ;
848 fullURLRef = CFURLCreateCopyAppendingPathComponent(NULL, parentURLRef,
849 additionalPathComponent,false);
850 CFRelease( parentURLRef ) ;
851 }
852 wxCFStringRef cfString( CFURLCopyFileSystemPath(fullURLRef, kDefaultPathStyle ));
853 CFRelease( fullURLRef ) ;
854
855 return wxCFStringRef::AsStringWithNormalizationFormC(cfString);
856 }
857
858 OSStatus wxMacPathToFSRef( const wxString&path , FSRef *fsRef )
859 {
860 OSStatus err = noErr ;
861 CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, wxCFStringRef(path));
862 CFStringNormalize(cfMutableString,kCFStringNormalizationFormD);
863 CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfMutableString , kDefaultPathStyle, false);
864 CFRelease( cfMutableString );
865 if ( NULL != url )
866 {
867 if ( CFURLGetFSRef(url, fsRef) == false )
868 err = fnfErr ;
869 CFRelease( url ) ;
870 }
871 else
872 {
873 err = fnfErr ;
874 }
875 return err ;
876 }
877
878 wxString wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname )
879 {
880 wxCFStringRef cfname( CFStringCreateWithCharacters( kCFAllocatorDefault,
881 uniname->unicode,
882 uniname->length ) );
883 return wxCFStringRef::AsStringWithNormalizationFormC(cfname);
884 }
885
886 #ifndef __LP64__
887
888 wxString wxMacFSSpec2MacFilename( const FSSpec *spec )
889 {
890 FSRef fsRef ;
891 if ( FSpMakeFSRef( spec , &fsRef) == noErr )
892 {
893 return wxMacFSRefToPath( &fsRef ) ;
894 }
895 return wxEmptyString ;
896 }
897
898 void wxMacFilename2FSSpec( const wxString& path , FSSpec *spec )
899 {
900 OSStatus err = noErr;
901 FSRef fsRef;
902 wxMacPathToFSRef( path , &fsRef );
903 err = FSGetCatalogInfo(&fsRef, kFSCatInfoNone, NULL, NULL, spec, NULL);
904 verify_noerr( err );
905 }
906 #endif
907
908 #endif // __WXMAC__
909
910
911 #if WXWIN_COMPATIBILITY_2_8
912
913 template<typename T>
914 static void wxDoDos2UnixFilename(T *s)
915 {
916 if (s)
917 while (*s)
918 {
919 if (*s == wxT('\\'))
920 *s = wxT('/');
921 #ifdef __WINDOWS__
922 else
923 *s = wxTolower(*s); // Case INDEPENDENT
924 #endif
925 s++;
926 }
927 }
928
929 void wxDos2UnixFilename(char *s) { wxDoDos2UnixFilename(s); }
930 void wxDos2UnixFilename(wchar_t *s) { wxDoDos2UnixFilename(s); }
931
932 template<typename T>
933 static void
934 #if defined(__WINDOWS__) || defined(__OS2__)
935 wxDoUnix2DosFilename(T *s)
936 #else
937 wxDoUnix2DosFilename(T *WXUNUSED(s) )
938 #endif
939 {
940 // Yes, I really mean this to happen under DOS only! JACS
941 #if defined(__WINDOWS__) || defined(__OS2__)
942 if (s)
943 while (*s)
944 {
945 if (*s == wxT('/'))
946 *s = wxT('\\');
947 s++;
948 }
949 #endif
950 }
951
952 void wxUnix2DosFilename(char *s) { wxDoUnix2DosFilename(s); }
953 void wxUnix2DosFilename(wchar_t *s) { wxDoUnix2DosFilename(s); }
954
955 #endif // #if WXWIN_COMPATIBILITY_2_8
956
957 // Concatenate two files to form third
958 bool
959 wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
960 {
961 #if wxUSE_FILE
962
963 wxFile in1(file1), in2(file2);
964 wxTempFile out(file3);
965
966 if ( !in1.IsOpened() || !in2.IsOpened() || !out.IsOpened() )
967 return false;
968
969 ssize_t ofs;
970 unsigned char buf[1024];
971
972 for( int i=0; i<2; i++)
973 {
974 wxFile *in = i==0 ? &in1 : &in2;
975 do{
976 if ( (ofs = in->Read(buf,WXSIZEOF(buf))) == wxInvalidOffset ) return false;
977 if ( ofs > 0 )
978 if ( !out.Write(buf,ofs) )
979 return false;
980 } while ( ofs == (ssize_t)WXSIZEOF(buf) );
981 }
982
983 return out.Commit();
984
985 #else
986
987 wxUnusedVar(file1);
988 wxUnusedVar(file2);
989 wxUnusedVar(file3);
990 return false;
991
992 #endif
993 }
994
995 // helper of generic implementation of wxCopyFile()
996 #if !(defined(__WIN32__) || defined(__OS2__)) && wxUSE_FILE
997
998 static bool
999 wxDoCopyFile(wxFile& fileIn,
1000 const wxStructStat& fbuf,
1001 const wxString& filenameDst,
1002 bool overwrite)
1003 {
1004 // reset the umask as we want to create the file with exactly the same
1005 // permissions as the original one
1006 wxCHANGE_UMASK(0);
1007
1008 // create file2 with the same permissions than file1 and open it for
1009 // writing
1010
1011 wxFile fileOut;
1012 if ( !fileOut.Create(filenameDst, overwrite, fbuf.st_mode & 0777) )
1013 return false;
1014
1015 // copy contents of file1 to file2
1016 char buf[4096];
1017 for ( ;; )
1018 {
1019 ssize_t count = fileIn.Read(buf, WXSIZEOF(buf));
1020 if ( count == wxInvalidOffset )
1021 return false;
1022
1023 // end of file?
1024 if ( !count )
1025 break;
1026
1027 if ( fileOut.Write(buf, count) < (size_t)count )
1028 return false;
1029 }
1030
1031 // we can expect fileIn to be closed successfully, but we should ensure
1032 // that fileOut was closed as some write errors (disk full) might not be
1033 // detected before doing this
1034 return fileIn.Close() && fileOut.Close();
1035 }
1036
1037 #endif // generic implementation of wxCopyFile
1038
1039 // Copy files
1040 bool
1041 wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
1042 {
1043 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1044 // CopyFile() copies file attributes and modification time too, so use it
1045 // instead of our code if available
1046 //
1047 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1048 if ( !::CopyFile(file1.t_str(), file2.t_str(), !overwrite) )
1049 {
1050 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1051 file1.c_str(), file2.c_str());
1052
1053 return false;
1054 }
1055 #elif defined(__OS2__)
1056 if ( ::DosCopy(file1.c_str(), file2.c_str(), overwrite ? DCPY_EXISTING : 0) != 0 )
1057 return false;
1058 #elif wxUSE_FILE // !Win32
1059
1060 wxStructStat fbuf;
1061 // get permissions of file1
1062 if ( wxStat( file1, &fbuf) != 0 )
1063 {
1064 // the file probably doesn't exist or we haven't the rights to read
1065 // from it anyhow
1066 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1067 file1.c_str());
1068 return false;
1069 }
1070
1071 // open file1 for reading
1072 wxFile fileIn(file1, wxFile::read);
1073 if ( !fileIn.IsOpened() )
1074 return false;
1075
1076 // remove file2, if it exists. This is needed for creating
1077 // file2 with the correct permissions in the next step
1078 if ( wxFileExists(file2) && (!overwrite || !wxRemoveFile(file2)))
1079 {
1080 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1081 file2.c_str());
1082 return false;
1083 }
1084
1085 wxDoCopyFile(fileIn, fbuf, file2, overwrite);
1086
1087 #if defined(__WXMAC__) || defined(__WXCOCOA__)
1088 // copy the resource fork of the file too if it's present
1089 wxString pathRsrcOut;
1090 wxFile fileRsrcIn;
1091
1092 {
1093 // suppress error messages from this block as resource forks don't have
1094 // to exist
1095 wxLogNull noLog;
1096
1097 // it's not enough to check for file existence: it always does on HFS
1098 // but is empty for files without resources
1099 if ( fileRsrcIn.Open(file1 + wxT("/..namedfork/rsrc")) &&
1100 fileRsrcIn.Length() > 0 )
1101 {
1102 // we must be using HFS or another filesystem with resource fork
1103 // support, suppose that destination file system also is HFS[-like]
1104 pathRsrcOut = file2 + wxT("/..namedfork/rsrc");
1105 }
1106 else // check if we have resource fork in separate file (non-HFS case)
1107 {
1108 wxFileName fnRsrc(file1);
1109 fnRsrc.SetName(wxT("._") + fnRsrc.GetName());
1110
1111 fileRsrcIn.Close();
1112 if ( fileRsrcIn.Open( fnRsrc.GetFullPath() ) )
1113 {
1114 fnRsrc = file2;
1115 fnRsrc.SetName(wxT("._") + fnRsrc.GetName());
1116
1117 pathRsrcOut = fnRsrc.GetFullPath();
1118 }
1119 }
1120 }
1121
1122 if ( !pathRsrcOut.empty() )
1123 {
1124 if ( !wxDoCopyFile(fileRsrcIn, fbuf, pathRsrcOut, overwrite) )
1125 return false;
1126 }
1127 #endif // wxMac || wxCocoa
1128
1129 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1130 // no chmod in VA. Should be some permission API for HPFS386 partitions
1131 // however
1132 if ( chmod(file2.fn_str(), fbuf.st_mode) != 0 )
1133 {
1134 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1135 file2.c_str());
1136 return false;
1137 }
1138 #endif // OS/2 || Mac
1139
1140 #else // !Win32 && ! wxUSE_FILE
1141
1142 // impossible to simulate with wxWidgets API
1143 wxUnusedVar(file1);
1144 wxUnusedVar(file2);
1145 wxUnusedVar(overwrite);
1146 return false;
1147
1148 #endif // __WINDOWS__ && __WIN32__
1149
1150 return true;
1151 }
1152
1153 bool
1154 wxRenameFile(const wxString& file1, const wxString& file2, bool overwrite)
1155 {
1156 if ( !overwrite && wxFileExists(file2) )
1157 {
1158 wxLogSysError
1159 (
1160 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1161 file1.c_str(), file2.c_str()
1162 );
1163
1164 return false;
1165 }
1166
1167 #if !defined(__WXWINCE__)
1168 // Normal system call
1169 if ( wxRename (file1, file2) == 0 )
1170 return true;
1171 #endif
1172
1173 // Try to copy
1174 if (wxCopyFile(file1, file2, overwrite)) {
1175 wxRemoveFile(file1);
1176 return true;
1177 }
1178 // Give up
1179 wxLogSysError(_("File '%s' couldn't be renamed '%s'"), file1, file2);
1180 return false;
1181 }
1182
1183 bool wxRemoveFile(const wxString& file)
1184 {
1185 #if defined(__VISUALC__) \
1186 || defined(__BORLANDC__) \
1187 || defined(__WATCOMC__) \
1188 || defined(__DMC__) \
1189 || defined(__GNUWIN32__)
1190 int res = wxRemove(file);
1191 #elif defined(__WXMAC__)
1192 int res = unlink(file.fn_str());
1193 #else
1194 int res = unlink(file.fn_str());
1195 #endif
1196 if ( res )
1197 {
1198 wxLogSysError(_("File '%s' couldn't be removed"), file);
1199 }
1200 return res == 0;
1201 }
1202
1203 bool wxMkdir(const wxString& dir, int perm)
1204 {
1205 #if defined(__WXMAC__) && !defined(__UNIX__)
1206 if ( mkdir(dir.fn_str(), 0) != 0 )
1207
1208 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1209 // for the GNU compiler
1210 #elif (!(defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__))) || \
1211 (defined(__GNUWIN32__) && !defined(__MINGW32__)) || \
1212 defined(__WINE__) || defined(__WXMICROWIN__)
1213 const wxChar *dirname = dir.c_str();
1214 #if defined(MSVCRT)
1215 wxUnusedVar(perm);
1216 if ( mkdir(wxFNCONV(dirname)) != 0 )
1217 #else
1218 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1219 #endif
1220 #elif defined(__OS2__)
1221 wxUnusedVar(perm);
1222 if (::DosCreateDir(dir.c_str(), NULL) != 0) // enhance for EAB's??
1223 #elif defined(__DOS__)
1224 const wxChar *dirname = dir.c_str();
1225 #if defined(__WATCOMC__)
1226 (void)perm;
1227 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1228 #elif defined(__DJGPP__)
1229 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1230 #else
1231 #error "Unsupported DOS compiler!"
1232 #endif
1233 #else // !MSW, !DOS and !OS/2 VAC++
1234 wxUnusedVar(perm);
1235 #ifdef __WXWINCE__
1236 if ( CreateDirectory(dir.fn_str(), NULL) == 0 )
1237 #else
1238 if ( wxMkDir(dir.fn_str()) != 0 )
1239 #endif
1240 #endif // !MSW/MSW
1241 {
1242 wxLogSysError(_("Directory '%s' couldn't be created"), dir);
1243 return false;
1244 }
1245
1246 return true;
1247 }
1248
1249 bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1250 {
1251 #if defined(__VMS__)
1252 return false; //to be changed since rmdir exists in VMS7.x
1253 #else
1254 #if defined(__OS2__)
1255 if ( ::DosDeleteDir(dir.c_str()) != 0 )
1256 #elif defined(__WXWINCE__)
1257 if ( RemoveDirectory(dir.fn_str()) == 0 )
1258 #else
1259 if ( wxRmDir(dir.fn_str()) != 0 )
1260 #endif
1261 {
1262 wxLogSysError(_("Directory '%s' couldn't be deleted"), dir);
1263 return false;
1264 }
1265
1266 return true;
1267 #endif
1268 }
1269
1270 // does the path exists? (may have or not '/' or '\\' at the end)
1271 bool wxDirExists(const wxString& pathName)
1272 {
1273 return wxFileName::DirExists(pathName);
1274 }
1275
1276 #if WXWIN_COMPATIBILITY_2_8
1277
1278 // Get a temporary filename, opening and closing the file.
1279 wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
1280 {
1281 wxString filename;
1282 if ( !wxGetTempFileName(prefix, filename) )
1283 return NULL;
1284
1285 if ( buf )
1286 wxStrcpy(buf, filename);
1287 else
1288 buf = MYcopystring(filename);
1289
1290 return buf;
1291 }
1292
1293 bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1294 {
1295 #if wxUSE_FILE
1296 buf = wxFileName::CreateTempFileName(prefix);
1297
1298 return !buf.empty();
1299 #else // !wxUSE_FILE
1300 wxUnusedVar(prefix);
1301 wxUnusedVar(buf);
1302
1303 return false;
1304 #endif // wxUSE_FILE/!wxUSE_FILE
1305 }
1306
1307 #endif // #if WXWIN_COMPATIBILITY_2_8
1308
1309 // Get first file name matching given wild card.
1310
1311 static wxDir *gs_dir = NULL;
1312 static wxString gs_dirPath;
1313
1314 wxString wxFindFirstFile(const wxString& spec, int flags)
1315 {
1316 wxFileName::SplitPath(spec, &gs_dirPath, NULL, NULL);
1317 if ( gs_dirPath.empty() )
1318 gs_dirPath = wxT(".");
1319 if ( !wxEndsWithPathSeparator(gs_dirPath ) )
1320 gs_dirPath << wxFILE_SEP_PATH;
1321
1322 delete gs_dir; // can be NULL, this is ok
1323 gs_dir = new wxDir(gs_dirPath);
1324
1325 if ( !gs_dir->IsOpened() )
1326 {
1327 wxLogSysError(_("Cannot enumerate files '%s'"), spec);
1328 return wxEmptyString;
1329 }
1330
1331 int dirFlags;
1332 switch (flags)
1333 {
1334 case wxDIR: dirFlags = wxDIR_DIRS; break;
1335 case wxFILE: dirFlags = wxDIR_FILES; break;
1336 default: dirFlags = wxDIR_DIRS | wxDIR_FILES; break;
1337 }
1338
1339 wxString result;
1340 gs_dir->GetFirst(&result, wxFileNameFromPath(spec), dirFlags);
1341 if ( result.empty() )
1342 {
1343 wxDELETE(gs_dir);
1344 return result;
1345 }
1346
1347 return gs_dirPath + result;
1348 }
1349
1350 wxString wxFindNextFile()
1351 {
1352 wxCHECK_MSG( gs_dir, "", "You must call wxFindFirstFile before!" );
1353
1354 wxString result;
1355 gs_dir->GetNext(&result);
1356
1357 if ( result.empty() )
1358 {
1359 wxDELETE(gs_dir);
1360 return result;
1361 }
1362
1363 return gs_dirPath + result;
1364 }
1365
1366
1367 // Get current working directory.
1368 // If buf is NULL, allocates space using new, else copies into buf.
1369 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1370 // wxDoGetCwd() is their common core to be moved
1371 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1372 // Do not expose wxDoGetCwd in headers!
1373
1374 wxChar *wxDoGetCwd(wxChar *buf, int sz)
1375 {
1376 #if defined(__WXWINCE__)
1377 // TODO
1378 if(buf && sz>0) buf[0] = wxT('\0');
1379 return buf;
1380 #else
1381 if ( !buf )
1382 {
1383 buf = new wxChar[sz + 1];
1384 }
1385
1386 bool ok wxDUMMY_INITIALIZE(false);
1387
1388 // for the compilers which have Unicode version of _getcwd(), call it
1389 // directly, for the others call the ANSI version and do the translation
1390 #if !wxUSE_UNICODE
1391 #define cbuf buf
1392 #else // wxUSE_UNICODE
1393 bool needsANSI = true;
1394
1395 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1396 char cbuf[_MAXPATHLEN];
1397 #endif
1398
1399 #ifdef HAVE_WGETCWD
1400 #if wxUSE_UNICODE_MSLU
1401 if ( wxGetOsVersion() != wxOS_WINDOWS_9X )
1402 #else
1403 char *cbuf = NULL; // never really used because needsANSI will always be false
1404 #endif
1405 {
1406 ok = _wgetcwd(buf, sz) != NULL;
1407 needsANSI = false;
1408 }
1409 #endif
1410
1411 if ( needsANSI )
1412 #endif // wxUSE_UNICODE
1413 {
1414 #if defined(_MSC_VER) || defined(__MINGW32__)
1415 ok = _getcwd(cbuf, sz) != NULL;
1416 #elif defined(__OS2__)
1417 APIRET rc;
1418 ULONG ulDriveNum = 0;
1419 ULONG ulDriveMap = 0;
1420 rc = ::DosQueryCurrentDisk(&ulDriveNum, &ulDriveMap);
1421 ok = rc == 0;
1422 if (ok)
1423 {
1424 sz -= 3;
1425 rc = ::DosQueryCurrentDir( 0 // current drive
1426 ,(PBYTE)cbuf + 3
1427 ,(PULONG)&sz
1428 );
1429 cbuf[0] = char('A' + (ulDriveNum - 1));
1430 cbuf[1] = ':';
1431 cbuf[2] = '\\';
1432 ok = rc == 0;
1433 }
1434 #else // !Win32/VC++ !Mac !OS2
1435 ok = getcwd(cbuf, sz) != NULL;
1436 #endif // platform
1437
1438 #if wxUSE_UNICODE
1439 // finally convert the result to Unicode if needed
1440 wxConvFile.MB2WC(buf, cbuf, sz);
1441 #endif // wxUSE_UNICODE
1442 }
1443
1444 if ( !ok )
1445 {
1446 wxLogSysError(_("Failed to get the working directory"));
1447
1448 // VZ: the old code used to return "." on error which didn't make any
1449 // sense at all to me - empty string is a better error indicator
1450 // (NULL might be even better but I'm afraid this could lead to
1451 // problems with the old code assuming the return is never NULL)
1452 buf[0] = wxT('\0');
1453 }
1454 else // ok, but we might need to massage the path into the right format
1455 {
1456 #ifdef __DJGPP__
1457 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1458 // with / deliminers. We don't like that.
1459 for (wxChar *ch = buf; *ch; ch++)
1460 {
1461 if (*ch == wxT('/'))
1462 *ch = wxT('\\');
1463 }
1464 #endif // __DJGPP__
1465
1466 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1467 // he needs Unix as opposed to Win32 pathnames
1468 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1469 // another example of DOS/Unix mix (Cygwin)
1470 wxString pathUnix = buf;
1471 #if wxUSE_UNICODE
1472 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1473 cygwin_conv_path(CCP_POSIX_TO_WIN_W, pathUnix.mb_str(wxConvFile), buf, sz);
1474 #else
1475 char bufA[_MAXPATHLEN];
1476 cygwin_conv_to_full_win32_path(pathUnix.mb_str(wxConvFile), bufA);
1477 wxConvFile.MB2WC(buf, bufA, sz);
1478 #endif
1479 #else
1480 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1481 cygwin_conv_path(CCP_POSIX_TO_WIN_A, pathUnix, buf, sz);
1482 #else
1483 cygwin_conv_to_full_win32_path(pathUnix, buf);
1484 #endif
1485 #endif // wxUSE_UNICODE
1486 #endif // __CYGWIN__
1487 }
1488
1489 return buf;
1490
1491 #if !wxUSE_UNICODE
1492 #undef cbuf
1493 #endif
1494
1495 #endif
1496 // __WXWINCE__
1497 }
1498
1499 #if WXWIN_COMPATIBILITY_2_6
1500 wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1501 {
1502 return wxDoGetCwd(buf,sz);
1503 }
1504 #endif // WXWIN_COMPATIBILITY_2_6
1505
1506 wxString wxGetCwd()
1507 {
1508 wxString str;
1509 wxDoGetCwd(wxStringBuffer(str, _MAXPATHLEN), _MAXPATHLEN);
1510 return str;
1511 }
1512
1513 bool wxSetWorkingDirectory(const wxString& d)
1514 {
1515 bool success = false;
1516 #if defined(__OS2__)
1517 if (d[1] == ':')
1518 {
1519 ::DosSetDefaultDisk(wxToupper(d[0]) - wxT('A') + 1);
1520 // do not call DosSetCurrentDir when just changing drive,
1521 // since it requires e.g. "d:." instead of "d:"!
1522 if (d.length() == 2)
1523 return true;
1524 }
1525 success = (::DosSetCurrentDir(d.c_str()) == 0);
1526 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1527 success = (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
1528 #elif defined(__WINDOWS__)
1529
1530 #ifdef __WIN32__
1531 #ifdef __WXWINCE__
1532 // No equivalent in WinCE
1533 wxUnusedVar(d);
1534 #else
1535 success = (SetCurrentDirectory(d.t_str()) != 0);
1536 #endif
1537 #else
1538 // Must change drive, too.
1539 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1540 if (isDriveSpec)
1541 {
1542 wxChar firstChar = d[0];
1543
1544 // To upper case
1545 if (firstChar > 90)
1546 firstChar = firstChar - 32;
1547
1548 // To a drive number
1549 unsigned int driveNo = firstChar - 64;
1550 if (driveNo > 0)
1551 {
1552 unsigned int noDrives;
1553 _dos_setdrive(driveNo, &noDrives);
1554 }
1555 }
1556 success = (chdir(WXSTRINGCAST d) == 0);
1557 #endif
1558
1559 #endif
1560 if ( !success )
1561 {
1562 wxLogSysError(_("Could not set current working directory"));
1563 }
1564 return success;
1565 }
1566
1567 // Get the OS directory if appropriate (such as the Windows directory).
1568 // On non-Windows platform, probably just return the empty string.
1569 wxString wxGetOSDirectory()
1570 {
1571 #ifdef __WXWINCE__
1572 return wxString(wxT("\\Windows"));
1573 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1574 wxChar buf[256];
1575 GetWindowsDirectory(buf, 256);
1576 return wxString(buf);
1577 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1578 return wxMacFindFolderNoSeparator(kOnSystemDisk, 'macs', false);
1579 #else
1580 return wxEmptyString;
1581 #endif
1582 }
1583
1584 bool wxEndsWithPathSeparator(const wxString& filename)
1585 {
1586 return !filename.empty() && wxIsPathSeparator(filename.Last());
1587 }
1588
1589 // find a file in a list of directories, returns false if not found
1590 bool wxFindFileInPath(wxString *pStr, const wxString& szPath, const wxString& szFile)
1591 {
1592 // we assume that it's not empty
1593 wxCHECK_MSG( !szFile.empty(), false,
1594 wxT("empty file name in wxFindFileInPath"));
1595
1596 // skip path separator in the beginning of the file name if present
1597 wxString szFile2;
1598 if ( wxIsPathSeparator(szFile[0u]) )
1599 szFile2 = szFile.Mid(1);
1600 else
1601 szFile2 = szFile;
1602
1603 wxStringTokenizer tkn(szPath, wxPATH_SEP);
1604
1605 while ( tkn.HasMoreTokens() )
1606 {
1607 wxString strFile = tkn.GetNextToken();
1608 if ( !wxEndsWithPathSeparator(strFile) )
1609 strFile += wxFILE_SEP_PATH;
1610 strFile += szFile2;
1611
1612 if ( wxFileExists(strFile) )
1613 {
1614 *pStr = strFile;
1615 return true;
1616 }
1617 }
1618
1619 return false;
1620 }
1621
1622 #if WXWIN_COMPATIBILITY_2_8
1623 void WXDLLIMPEXP_BASE wxSplitPath(const wxString& fileName,
1624 wxString *pstrPath,
1625 wxString *pstrName,
1626 wxString *pstrExt)
1627 {
1628 wxFileName::SplitPath(fileName, pstrPath, pstrName, pstrExt);
1629 }
1630 #endif // #if WXWIN_COMPATIBILITY_2_8
1631
1632 #if wxUSE_DATETIME
1633
1634 time_t WXDLLIMPEXP_BASE wxFileModificationTime(const wxString& filename)
1635 {
1636 wxDateTime mtime;
1637 if ( !wxFileName(filename).GetTimes(NULL, &mtime, NULL) )
1638 return (time_t)-1;
1639
1640 return mtime.GetTicks();
1641 }
1642
1643 #endif // wxUSE_DATETIME
1644
1645
1646 // Parses the filterStr, returning the number of filters.
1647 // Returns 0 if none or if there's a problem.
1648 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1649
1650 int WXDLLIMPEXP_BASE wxParseCommonDialogsFilter(const wxString& filterStr,
1651 wxArrayString& descriptions,
1652 wxArrayString& filters)
1653 {
1654 descriptions.Clear();
1655 filters.Clear();
1656
1657 wxString str(filterStr);
1658
1659 wxString description, filter;
1660 int pos = 0;
1661 while( pos != wxNOT_FOUND )
1662 {
1663 pos = str.Find(wxT('|'));
1664 if ( pos == wxNOT_FOUND )
1665 {
1666 // if there are no '|'s at all in the string just take the entire
1667 // string as filter and make description empty for later autocompletion
1668 if ( filters.IsEmpty() )
1669 {
1670 descriptions.Add(wxEmptyString);
1671 filters.Add(filterStr);
1672 }
1673 else
1674 {
1675 wxFAIL_MSG( wxT("missing '|' in the wildcard string!") );
1676 }
1677
1678 break;
1679 }
1680
1681 description = str.Left(pos);
1682 str = str.Mid(pos + 1);
1683 pos = str.Find(wxT('|'));
1684 if ( pos == wxNOT_FOUND )
1685 {
1686 filter = str;
1687 }
1688 else
1689 {
1690 filter = str.Left(pos);
1691 str = str.Mid(pos + 1);
1692 }
1693
1694 descriptions.Add(description);
1695 filters.Add(filter);
1696 }
1697
1698 #if defined(__WXMOTIF__)
1699 // split it so there is one wildcard per entry
1700 for( size_t i = 0 ; i < descriptions.GetCount() ; i++ )
1701 {
1702 pos = filters[i].Find(wxT(';'));
1703 if (pos != wxNOT_FOUND)
1704 {
1705 // first split only filters
1706 descriptions.Insert(descriptions[i],i+1);
1707 filters.Insert(filters[i].Mid(pos+1),i+1);
1708 filters[i]=filters[i].Left(pos);
1709
1710 // autoreplace new filter in description with pattern:
1711 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1712 // cause split into:
1713 // C/C++ Files(*.cpp)|*.cpp
1714 // C/C++ Files(*.c;*.h)|*.c;*.h
1715 // and next iteration cause another split into:
1716 // C/C++ Files(*.cpp)|*.cpp
1717 // C/C++ Files(*.c)|*.c
1718 // C/C++ Files(*.h)|*.h
1719 for ( size_t k=i;k<i+2;k++ )
1720 {
1721 pos = descriptions[k].Find(filters[k]);
1722 if (pos != wxNOT_FOUND)
1723 {
1724 wxString before = descriptions[k].Left(pos);
1725 wxString after = descriptions[k].Mid(pos+filters[k].Len());
1726 pos = before.Find(wxT('('),true);
1727 if (pos>before.Find(wxT(')'),true))
1728 {
1729 before = before.Left(pos+1);
1730 before << filters[k];
1731 pos = after.Find(wxT(')'));
1732 int pos1 = after.Find(wxT('('));
1733 if (pos != wxNOT_FOUND && (pos<pos1 || pos1==wxNOT_FOUND))
1734 {
1735 before << after.Mid(pos);
1736 descriptions[k] = before;
1737 }
1738 }
1739 }
1740 }
1741 }
1742 }
1743 #endif
1744
1745 // autocompletion
1746 for( size_t j = 0 ; j < descriptions.GetCount() ; j++ )
1747 {
1748 if ( descriptions[j].empty() && !filters[j].empty() )
1749 {
1750 descriptions[j].Printf(_("Files (%s)"), filters[j].c_str());
1751 }
1752 }
1753
1754 return filters.GetCount();
1755 }
1756
1757 #if defined(__WINDOWS__) && !(defined(__UNIX__) || defined(__OS2__))
1758 static bool wxCheckWin32Permission(const wxString& path, DWORD access)
1759 {
1760 // quoting the MSDN: "To obtain a handle to a directory, call the
1761 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag", but this
1762 // doesn't work under Win9x/ME but then it's not needed there anyhow
1763 const DWORD dwAttr = ::GetFileAttributes(path.t_str());
1764 if ( dwAttr == INVALID_FILE_ATTRIBUTES )
1765 {
1766 // file probably doesn't exist at all
1767 return false;
1768 }
1769
1770 if ( wxGetOsVersion() == wxOS_WINDOWS_9X )
1771 {
1772 // FAT directories always allow all access, even if they have the
1773 // readonly flag set, and FAT files can only be read-only
1774 return (dwAttr & FILE_ATTRIBUTE_DIRECTORY) ||
1775 (access != GENERIC_WRITE ||
1776 !(dwAttr & FILE_ATTRIBUTE_READONLY));
1777 }
1778
1779 HANDLE h = ::CreateFile
1780 (
1781 path.t_str(),
1782 access,
1783 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1784 NULL,
1785 OPEN_EXISTING,
1786 dwAttr & FILE_ATTRIBUTE_DIRECTORY
1787 ? FILE_FLAG_BACKUP_SEMANTICS
1788 : 0,
1789 NULL
1790 );
1791 if ( h != INVALID_HANDLE_VALUE )
1792 CloseHandle(h);
1793
1794 return h != INVALID_HANDLE_VALUE;
1795 }
1796 #endif // __WINDOWS__
1797
1798 bool wxIsWritable(const wxString &path)
1799 {
1800 #if defined( __UNIX__ ) || defined(__OS2__)
1801 // access() will take in count also symbolic links
1802 return wxAccess(path.c_str(), W_OK) == 0;
1803 #elif defined( __WINDOWS__ )
1804 return wxCheckWin32Permission(path, GENERIC_WRITE);
1805 #else
1806 wxUnusedVar(path);
1807 // TODO
1808 return false;
1809 #endif
1810 }
1811
1812 bool wxIsReadable(const wxString &path)
1813 {
1814 #if defined( __UNIX__ ) || defined(__OS2__)
1815 // access() will take in count also symbolic links
1816 return wxAccess(path.c_str(), R_OK) == 0;
1817 #elif defined( __WINDOWS__ )
1818 return wxCheckWin32Permission(path, GENERIC_READ);
1819 #else
1820 wxUnusedVar(path);
1821 // TODO
1822 return false;
1823 #endif
1824 }
1825
1826 bool wxIsExecutable(const wxString &path)
1827 {
1828 #if defined( __UNIX__ ) || defined(__OS2__)
1829 // access() will take in count also symbolic links
1830 return wxAccess(path.c_str(), X_OK) == 0;
1831 #elif defined( __WINDOWS__ )
1832 return wxCheckWin32Permission(path, GENERIC_EXECUTE);
1833 #else
1834 wxUnusedVar(path);
1835 // TODO
1836 return false;
1837 #endif
1838 }
1839
1840 // Return the type of an open file
1841 //
1842 // Some file types on some platforms seem seekable but in fact are not.
1843 // The main use of this function is to allow such cases to be detected
1844 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1845 //
1846 // This is important for the archive streams, which benefit greatly from
1847 // being able to seek on a stream, but which will produce corrupt archives
1848 // if they unknowingly seek on a non-seekable stream.
1849 //
1850 // wxFILE_KIND_DISK is a good catch all return value, since other values
1851 // disable features of the archive streams. Some other value must be returned
1852 // for a file type that appears seekable but isn't.
1853 //
1854 // Known examples:
1855 // * Pipes on Windows
1856 // * Files on VMS with a record format other than StreamLF
1857 //
1858 wxFileKind wxGetFileKind(int fd)
1859 {
1860 #if defined __WINDOWS__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1861 switch (::GetFileType(wxGetOSFHandle(fd)) & ~FILE_TYPE_REMOTE)
1862 {
1863 case FILE_TYPE_CHAR:
1864 return wxFILE_KIND_TERMINAL;
1865 case FILE_TYPE_DISK:
1866 return wxFILE_KIND_DISK;
1867 case FILE_TYPE_PIPE:
1868 return wxFILE_KIND_PIPE;
1869 }
1870
1871 return wxFILE_KIND_UNKNOWN;
1872
1873 #elif defined(__UNIX__)
1874 if (isatty(fd))
1875 return wxFILE_KIND_TERMINAL;
1876
1877 struct stat st;
1878 fstat(fd, &st);
1879
1880 if (S_ISFIFO(st.st_mode))
1881 return wxFILE_KIND_PIPE;
1882 if (!S_ISREG(st.st_mode))
1883 return wxFILE_KIND_UNKNOWN;
1884
1885 #if defined(__VMS__)
1886 if (st.st_fab_rfm != FAB$C_STMLF)
1887 return wxFILE_KIND_UNKNOWN;
1888 #endif
1889
1890 return wxFILE_KIND_DISK;
1891
1892 #else
1893 #define wxFILEKIND_STUB
1894 (void)fd;
1895 return wxFILE_KIND_DISK;
1896 #endif
1897 }
1898
1899 wxFileKind wxGetFileKind(FILE *fp)
1900 {
1901 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1902 // Should be fixed in version 1.4.
1903 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
1904 (void)fp;
1905 return wxFILE_KIND_DISK;
1906 #elif defined(__WINDOWS__) && !defined(__CYGWIN__) && !defined(__WATCOMC__) && !defined(__WINE__)
1907 return fp ? wxGetFileKind(_fileno(fp)) : wxFILE_KIND_UNKNOWN;
1908 #else
1909 return fp ? wxGetFileKind(fileno(fp)) : wxFILE_KIND_UNKNOWN;
1910 #endif
1911 }
1912
1913
1914 //------------------------------------------------------------------------
1915 // wild character routines
1916 //------------------------------------------------------------------------
1917
1918 bool wxIsWild( const wxString& pattern )
1919 {
1920 for ( wxString::const_iterator p = pattern.begin(); p != pattern.end(); ++p )
1921 {
1922 switch ( (*p).GetValue() )
1923 {
1924 case wxT('?'):
1925 case wxT('*'):
1926 case wxT('['):
1927 case wxT('{'):
1928 return true;
1929
1930 case wxT('\\'):
1931 if ( ++p == pattern.end() )
1932 return false;
1933 }
1934 }
1935 return false;
1936 }
1937
1938 /*
1939 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1940 *
1941 * The match procedure is public domain code (from ircII's reg.c)
1942 * but modified to suit our tastes (RN: No "%" syntax I guess)
1943 */
1944
1945 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1946 {
1947 if (text.empty())
1948 {
1949 /* Match if both are empty. */
1950 return pat.empty();
1951 }
1952
1953 const wxChar *m = pat.c_str(),
1954 *n = text.c_str(),
1955 *ma = NULL,
1956 *na = NULL;
1957 int just = 0,
1958 acount = 0,
1959 count = 0;
1960
1961 if (dot_special && (*n == wxT('.')))
1962 {
1963 /* Never match so that hidden Unix files
1964 * are never found. */
1965 return false;
1966 }
1967
1968 for (;;)
1969 {
1970 if (*m == wxT('*'))
1971 {
1972 ma = ++m;
1973 na = n;
1974 just = 1;
1975 acount = count;
1976 }
1977 else if (*m == wxT('?'))
1978 {
1979 m++;
1980 if (!*n++)
1981 return false;
1982 }
1983 else
1984 {
1985 if (*m == wxT('\\'))
1986 {
1987 m++;
1988 /* Quoting "nothing" is a bad thing */
1989 if (!*m)
1990 return false;
1991 }
1992 if (!*m)
1993 {
1994 /*
1995 * If we are out of both strings or we just
1996 * saw a wildcard, then we can say we have a
1997 * match
1998 */
1999 if (!*n)
2000 return true;
2001 if (just)
2002 return true;
2003 just = 0;
2004 goto not_matched;
2005 }
2006 /*
2007 * We could check for *n == NULL at this point, but
2008 * since it's more common to have a character there,
2009 * check to see if they match first (m and n) and
2010 * then if they don't match, THEN we can check for
2011 * the NULL of n
2012 */
2013 just = 0;
2014 if (*m == *n)
2015 {
2016 m++;
2017 count++;
2018 n++;
2019 }
2020 else
2021 {
2022
2023 not_matched:
2024
2025 /*
2026 * If there are no more characters in the
2027 * string, but we still need to find another
2028 * character (*m != NULL), then it will be
2029 * impossible to match it
2030 */
2031 if (!*n)
2032 return false;
2033
2034 if (ma)
2035 {
2036 m = ma;
2037 n = ++na;
2038 count = acount;
2039 }
2040 else
2041 return false;
2042 }
2043 }
2044 }
2045 }
2046
2047 #ifdef __VISUALC__
2048 #pragma warning(default:4706) // assignment within conditional expression
2049 #endif // VC++