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