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