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