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