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