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