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