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