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