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