]> git.saurik.com Git - wxWidgets.git/blame - src/common/filefn.cpp
Include more information in assert in wxNumberFormatter.
[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{
30d6c59b 738 return wxFileName(path).GetFullName();
c801d85f
KB
739}
740
741// Return just the directory, or NULL if no directory
50920146
OK
742wxChar *
743wxPathOnly (wxChar *path)
c801d85f 744{
e8e1d09e 745 if (path && *path)
c801d85f 746 {
e8e1d09e 747 static wxChar buf[_MAXPATHLEN];
2db300c6 748
e8e1d09e
GD
749 // Local copy
750 wxStrcpy (buf, path);
2db300c6 751
e8e1d09e
GD
752 int l = wxStrlen(path);
753 int i = l - 1;
2db300c6 754
e8e1d09e
GD
755 // Search backward for a backward or forward slash
756 while (i > -1)
757 {
e8e1d09e
GD
758 // Unix like or Windows
759 if (path[i] == wxT('/') || path[i] == wxT('\\'))
760 {
761 buf[i] = 0;
762 return buf;
763 }
c801d85f 764#ifdef __VMS__
e8e1d09e
GD
765 if (path[i] == wxT(']'))
766 {
767 buf[i+1] = 0;
768 return buf;
769 }
a339970a 770#endif
e8e1d09e 771 i --;
c801d85f 772 }
2db300c6 773
5a3912f2 774#if defined(__WXMSW__) || defined(__OS2__)
e8e1d09e
GD
775 // Try Drive specifier
776 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
3f4a0c5b 777 {
e8e1d09e
GD
778 // A:junk --> A:. (since A:.\junk Not A:\junk)
779 buf[2] = wxT('.');
780 buf[3] = wxT('\0');
781 return buf;
3f4a0c5b 782 }
c801d85f
KB
783#endif
784 }
d3b9f782 785 return NULL;
c801d85f
KB
786}
787
788// Return just the directory, or NULL if no directory
789wxString wxPathOnly (const wxString& path)
790{
b494c48b 791 if (!path.empty())
c801d85f 792 {
e8e1d09e 793 wxChar buf[_MAXPATHLEN];
2db300c6 794
e8e1d09e 795 // Local copy
52de37c7 796 wxStrcpy(buf, path);
2db300c6 797
ce045aed 798 int l = path.length();
e8e1d09e
GD
799 int i = l - 1;
800
801 // Search backward for a backward or forward slash
802 while (i > -1)
803 {
e8e1d09e
GD
804 // Unix like or Windows
805 if (path[i] == wxT('/') || path[i] == wxT('\\'))
806 {
5c760b84
JS
807 // Don't return an empty string
808 if (i == 0)
809 i ++;
e8e1d09e
GD
810 buf[i] = 0;
811 return wxString(buf);
812 }
c801d85f 813#ifdef __VMS__
e8e1d09e
GD
814 if (path[i] == wxT(']'))
815 {
816 buf[i+1] = 0;
817 return wxString(buf);
818 }
a339970a 819#endif
e8e1d09e 820 i --;
c801d85f 821 }
2db300c6 822
5a3912f2 823#if defined(__WXMSW__) || defined(__OS2__)
e8e1d09e
GD
824 // Try Drive specifier
825 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
3f4a0c5b 826 {
e8e1d09e
GD
827 // A:junk --> A:. (since A:.\junk Not A:\junk)
828 buf[2] = wxT('.');
829 buf[3] = wxT('\0');
830 return wxString(buf);
3f4a0c5b 831 }
c801d85f
KB
832#endif
833 }
b494c48b 834 return wxEmptyString;
c801d85f
KB
835}
836
837// Utility for converting delimiters in DOS filenames to UNIX style
838// and back again - or we get nasty problems with delimiters.
839// Also, convert to lower case, since case is significant in UNIX.
840
c933e267 841#if defined(__WXMAC__) && !defined(__WXOSX_IPHONE__)
b0091f58 842
a2b77260 843#define kDefaultPathStyle kCFURLPOSIXPathStyle
a1c34a78 844
a62848fd 845wxString wxMacFSRefToPath( const FSRef *fsRef , CFStringRef additionalPathComponent )
a2b77260 846{
a62848fd 847 CFURLRef fullURLRef;
a2b77260
SC
848 fullURLRef = CFURLCreateFromFSRef(NULL, fsRef);
849 if ( additionalPathComponent )
850 {
851 CFURLRef parentURLRef = fullURLRef ;
852 fullURLRef = CFURLCreateCopyAppendingPathComponent(NULL, parentURLRef,
853 additionalPathComponent,false);
854 CFRelease( parentURLRef ) ;
855 }
a62848fd
WS
856 CFStringRef cfString = CFURLCopyFileSystemPath(fullURLRef, kDefaultPathStyle);
857 CFRelease( fullURLRef ) ;
739cb14a
SC
858 CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, cfString);
859 CFRelease( cfString );
a8d69700 860 CFStringNormalize(cfMutableString,kCFStringNormalizationFormC);
80539f04 861 return wxCFStringRef(cfMutableString).AsString();
bedaf53e 862}
e7549107 863
a62848fd 864OSStatus wxMacPathToFSRef( const wxString&path , FSRef *fsRef )
bedaf53e 865{
b1d4dd7a 866 OSStatus err = noErr ;
80539f04 867 CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, wxCFStringRef(path));
a8d69700 868 CFStringNormalize(cfMutableString,kCFStringNormalizationFormD);
739cb14a
SC
869 CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfMutableString , kDefaultPathStyle, false);
870 CFRelease( cfMutableString );
a62848fd
WS
871 if ( NULL != url )
872 {
873 if ( CFURLGetFSRef(url, fsRef) == false )
874 err = fnfErr ;
a2b77260 875 CFRelease( url ) ;
bfc2bf62
SC
876 }
877 else
878 {
a2b77260 879 err = fnfErr ;
bfc2bf62 880 }
a2b77260 881 return err ;
bedaf53e
SC
882}
883
a62848fd 884wxString wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname )
c4e41ce3 885{
a2b77260
SC
886 CFStringRef cfname = CFStringCreateWithCharacters( kCFAllocatorDefault,
887 uniname->unicode,
888 uniname->length );
739cb14a
SC
889 CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, cfname);
890 CFRelease( cfname );
a8d69700 891 CFStringNormalize(cfMutableString,kCFStringNormalizationFormC);
80539f04 892 return wxCFStringRef(cfMutableString).AsString() ;
c4e41ce3 893}
e7549107 894
fb743cab
SC
895#ifndef __LP64__
896
a2b77260 897wxString wxMacFSSpec2MacFilename( const FSSpec *spec )
17dff81c 898{
a2b77260
SC
899 FSRef fsRef ;
900 if ( FSpMakeFSRef( spec , &fsRef) == noErr )
e7549107 901 {
a2b77260 902 return wxMacFSRefToPath( &fsRef ) ;
e7549107 903 }
a2b77260 904 return wxEmptyString ;
17dff81c 905}
e7549107 906
a2b77260 907void wxMacFilename2FSSpec( const wxString& path , FSSpec *spec )
e7549107 908{
0ad76eea
SC
909 OSStatus err = noErr;
910 FSRef fsRef;
911 wxMacPathToFSRef( path , &fsRef );
47d281e6 912 err = FSGetCatalogInfo(&fsRef, kFSCatInfoNone, NULL, NULL, spec, NULL);
0ad76eea 913 verify_noerr( err );
e7549107 914}
fb743cab 915#endif
12d67f8a 916
e8e1d09e
GD
917#endif // __WXMAC__
918
47d281e6
FM
919
920#if WXWIN_COMPATIBILITY_2_8
921
52de37c7
VS
922template<typename T>
923static void wxDoDos2UnixFilename(T *s)
c801d85f
KB
924{
925 if (s)
926 while (*s)
927 {
9a83f860
VZ
928 if (*s == wxT('\\'))
929 *s = wxT('/');
e7549107 930#ifdef __WXMSW__
3f4a0c5b 931 else
52de37c7 932 *s = wxTolower(*s); // Case INDEPENDENT
c801d85f 933#endif
3f4a0c5b 934 s++;
c801d85f
KB
935 }
936}
937
52de37c7
VS
938void wxDos2UnixFilename(char *s) { wxDoDos2UnixFilename(s); }
939void wxDos2UnixFilename(wchar_t *s) { wxDoDos2UnixFilename(s); }
940
941template<typename T>
942static void
5a3912f2 943#if defined(__WXMSW__) || defined(__OS2__)
52de37c7 944wxDoUnix2DosFilename(T *s)
46dc76ba 945#else
52de37c7 946wxDoUnix2DosFilename(T *WXUNUSED(s) )
46dc76ba 947#endif
c801d85f
KB
948{
949// Yes, I really mean this to happen under DOS only! JACS
5a3912f2 950#if defined(__WXMSW__) || defined(__OS2__)
c801d85f
KB
951 if (s)
952 while (*s)
953 {
223d09f6
KB
954 if (*s == wxT('/'))
955 *s = wxT('\\');
3f4a0c5b 956 s++;
c801d85f
KB
957 }
958#endif
959}
960
52de37c7
VS
961void wxUnix2DosFilename(char *s) { wxDoUnix2DosFilename(s); }
962void wxUnix2DosFilename(wchar_t *s) { wxDoUnix2DosFilename(s); }
963
47d281e6
FM
964#endif // #if WXWIN_COMPATIBILITY_2_8
965
c801d85f 966// Concatenate two files to form third
3f4a0c5b 967bool
c801d85f
KB
968wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
969{
b0c5cd0f
WS
970#if wxUSE_FILE
971
972 wxFile in1(file1), in2(file2);
973 wxTempFile out(file3);
974
975 if ( !in1.IsOpened() || !in2.IsOpened() || !out.IsOpened() )
976 return false;
977
978 ssize_t ofs;
979 unsigned char buf[1024];
980
981 for( int i=0; i<2; i++)
c801d85f 982 {
b0c5cd0f
WS
983 wxFile *in = i==0 ? &in1 : &in2;
984 do{
985 if ( (ofs = in->Read(buf,WXSIZEOF(buf))) == wxInvalidOffset ) return false;
986 if ( ofs > 0 )
987 if ( !out.Write(buf,ofs) )
988 return false;
989 } while ( ofs == (ssize_t)WXSIZEOF(buf) );
c801d85f
KB
990 }
991
b0c5cd0f
WS
992 return out.Commit();
993
994#else
c801d85f 995
b0c5cd0f
WS
996 wxUnusedVar(file1);
997 wxUnusedVar(file2);
998 wxUnusedVar(file3);
999 return false;
c801d85f 1000
b0c5cd0f 1001#endif
c801d85f
KB
1002}
1003
0597e7f9
VZ
1004// helper of generic implementation of wxCopyFile()
1005#if !(defined(__WIN32__) || defined(__OS2__) || defined(__PALMOS__)) && \
1006 wxUSE_FILE
1007
1008static bool
1009wxDoCopyFile(wxFile& fileIn,
1010 const wxStructStat& fbuf,
1011 const wxString& filenameDst,
1012 bool overwrite)
1013{
1014 // reset the umask as we want to create the file with exactly the same
1015 // permissions as the original one
1016 wxCHANGE_UMASK(0);
1017
1018 // create file2 with the same permissions than file1 and open it for
1019 // writing
1020
1021 wxFile fileOut;
1022 if ( !fileOut.Create(filenameDst, overwrite, fbuf.st_mode & 0777) )
1023 return false;
1024
1025 // copy contents of file1 to file2
1026 char buf[4096];
1027 for ( ;; )
1028 {
1029 ssize_t count = fileIn.Read(buf, WXSIZEOF(buf));
1030 if ( count == wxInvalidOffset )
1031 return false;
1032
1033 // end of file?
1034 if ( !count )
1035 break;
1036
1037 if ( fileOut.Write(buf, count) < (size_t)count )
1038 return false;
1039 }
1040
1041 // we can expect fileIn to be closed successfully, but we should ensure
1042 // that fileOut was closed as some write errors (disk full) might not be
1043 // detected before doing this
1044 return fileIn.Close() && fileOut.Close();
1045}
1046
1047#endif // generic implementation of wxCopyFile
1048
c801d85f 1049// Copy files
3f4a0c5b 1050bool
4658c44e 1051wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
c801d85f 1052{
04ef50df 1053#if defined(__WIN32__) && !defined(__WXMICROWIN__)
4658c44e
VZ
1054 // CopyFile() copies file attributes and modification time too, so use it
1055 // instead of our code if available
1056 //
1057 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
715e4f7e 1058 if ( !::CopyFile(file1.t_str(), file2.t_str(), !overwrite) )
564225a1
VZ
1059 {
1060 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1061 file1.c_str(), file2.c_str());
1062
79e162f5 1063 return false;
564225a1 1064 }
5a3912f2 1065#elif defined(__OS2__)
1f3d9911 1066 if ( ::DosCopy(file1.c_str(), file2.c_str(), overwrite ? DCPY_EXISTING : 0) != 0 )
79e162f5 1067 return false;
68351053
WS
1068#elif defined(__PALMOS__)
1069 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1070 return false;
98438730 1071#elif wxUSE_FILE // !Win32
32f31043 1072
b1ac3b56 1073 wxStructStat fbuf;
32f31043 1074 // get permissions of file1
766fc092 1075 if ( wxStat( file1, &fbuf) != 0 )
32f31043
VZ
1076 {
1077 // the file probably doesn't exist or we haven't the rights to read
1078 // from it anyhow
1079 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1080 file1.c_str());
79e162f5 1081 return false;
32f31043
VZ
1082 }
1083
1084 // open file1 for reading
1085 wxFile fileIn(file1, wxFile::read);
a339970a 1086 if ( !fileIn.IsOpened() )
79e162f5 1087 return false;
c801d85f 1088
32f31043
VZ
1089 // remove file2, if it exists. This is needed for creating
1090 // file2 with the correct permissions in the next step
4658c44e 1091 if ( wxFileExists(file2) && (!overwrite || !wxRemoveFile(file2)))
32f31043
VZ
1092 {
1093 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1094 file2.c_str());
79e162f5 1095 return false;
32f31043
VZ
1096 }
1097
0597e7f9 1098 wxDoCopyFile(fileIn, fbuf, file2, overwrite);
32f31043 1099
0597e7f9
VZ
1100#if defined(__WXMAC__) || defined(__WXCOCOA__)
1101 // copy the resource fork of the file too if it's present
1102 wxString pathRsrcOut;
1103 wxFile fileRsrcIn;
c801d85f 1104
c7386783 1105 {
0597e7f9
VZ
1106 // suppress error messages from this block as resource forks don't have
1107 // to exist
1108 wxLogNull noLog;
1109
1110 // it's not enough to check for file existence: it always does on HFS
1111 // but is empty for files without resources
1112 if ( fileRsrcIn.Open(file1 + wxT("/..namedfork/rsrc")) &&
1113 fileRsrcIn.Length() > 0 )
1114 {
1115 // we must be using HFS or another filesystem with resource fork
1116 // support, suppose that destination file system also is HFS[-like]
1117 pathRsrcOut = file2 + wxT("/..namedfork/rsrc");
1118 }
1119 else // check if we have resource fork in separate file (non-HFS case)
1120 {
1121 wxFileName fnRsrc(file1);
1122 fnRsrc.SetName(wxT("._") + fnRsrc.GetName());
a339970a 1123
0597e7f9
VZ
1124 fileRsrcIn.Close();
1125 if ( fileRsrcIn.Open( fnRsrc.GetFullPath() ) )
1126 {
1127 fnRsrc = file2;
1128 fnRsrc.SetName(wxT("._") + fnRsrc.GetName());
a339970a 1129
0597e7f9
VZ
1130 pathRsrcOut = fnRsrc.GetFullPath();
1131 }
1132 }
c7386783 1133 }
c801d85f 1134
0597e7f9
VZ
1135 if ( !pathRsrcOut.empty() )
1136 {
1137 if ( !wxDoCopyFile(fileRsrcIn, fbuf, pathRsrcOut, overwrite) )
1138 return false;
1139 }
1140#endif // wxMac || wxCocoa
abb74e97 1141
5fde6fcc 1142#if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
abb74e97
VZ
1143 // no chmod in VA. Should be some permission API for HPFS386 partitions
1144 // however
4a3c54bf 1145 if ( chmod(file2.fn_str(), fbuf.st_mode) != 0 )
32f31043
VZ
1146 {
1147 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1148 file2.c_str());
79e162f5 1149 return false;
32f31043 1150 }
4658c44e 1151#endif // OS/2 || Mac
98438730
WS
1152
1153#else // !Win32 && ! wxUSE_FILE
1154
1155 // impossible to simulate with wxWidgets API
1156 wxUnusedVar(file1);
1157 wxUnusedVar(file2);
1158 wxUnusedVar(overwrite);
1159 return false;
1160
564225a1 1161#endif // __WXMSW__ && __WIN32__
4658c44e 1162
79e162f5 1163 return true;
c801d85f
KB
1164}
1165
3f4a0c5b 1166bool
57e988b8 1167wxRenameFile(const wxString& file1, const wxString& file2, bool overwrite)
c801d85f 1168{
57e988b8
VZ
1169 if ( !overwrite && wxFileExists(file2) )
1170 {
1171 wxLogSysError
1172 (
1173 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1174 file1.c_str(), file2.c_str()
1175 );
1176
1177 return false;
1178 }
1179
68351053 1180#if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1c193821 1181 // Normal system call
c3396917 1182 if ( wxRename (file1, file2) == 0 )
79e162f5 1183 return true;
1c193821 1184#endif
a339970a 1185
c801d85f 1186 // Try to copy
57e988b8 1187 if (wxCopyFile(file1, file2, overwrite)) {
c801d85f 1188 wxRemoveFile(file1);
79e162f5 1189 return true;
c801d85f
KB
1190 }
1191 // Give up
79e162f5 1192 return false;
c801d85f
KB
1193}
1194
1195bool wxRemoveFile(const wxString& file)
1196{
161f4f73
VZ
1197#if defined(__VISUALC__) \
1198 || defined(__BORLANDC__) \
1199 || defined(__WATCOMC__) \
ba1e9d6c 1200 || defined(__DMC__) \
e874f867
SC
1201 || defined(__GNUWIN32__) \
1202 || (defined(__MWERKS__) && defined(__MSL__))
68351053 1203 int res = wxRemove(file);
c4e41ce3 1204#elif defined(__WXMAC__)
e0a050e3 1205 int res = unlink(file.fn_str());
68351053
WS
1206#elif defined(__WXPALMOS__)
1207 int res = 1;
1208 // TODO with VFSFileDelete()
c801d85f 1209#else
4a3c54bf 1210 int res = unlink(file.fn_str());
c801d85f 1211#endif
a339970a 1212
68351053 1213 return res == 0;
c801d85f
KB
1214}
1215
1a33c3ba 1216bool wxMkdir(const wxString& dir, int perm)
c801d85f 1217{
68351053
WS
1218#if defined(__WXPALMOS__)
1219 return false;
4a3c54bf
VZ
1220#else
1221#if defined(__WXMAC__) && !defined(__UNIX__)
1222 if ( mkdir(dir.fn_str(), 0) != 0 )
1a33c3ba 1223
c2ff79b1 1224 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
7708abe9 1225 // for the GNU compiler
4a3c54bf
VZ
1226#elif (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || \
1227 (defined(__GNUWIN32__) && !defined(__MINGW32__)) || \
1228 defined(__WINE__) || defined(__WXMICROWIN__)
1229 const wxChar *dirname = dir.c_str();
9c8cd106 1230 #if defined(MSVCRT)
79e162f5 1231 wxUnusedVar(perm);
2e38557f 1232 if ( mkdir(wxFNCONV(dirname)) != 0 )
9c8cd106
WS
1233 #else
1234 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
2e38557f 1235 #endif
5a3912f2 1236#elif defined(__OS2__)
7a893a31 1237 wxUnusedVar(perm);
4a3c54bf 1238 if (::DosCreateDir(dir.c_str(), NULL) != 0) // enhance for EAB's??
b916f809 1239#elif defined(__DOS__)
4a3c54bf 1240 const wxChar *dirname = dir.c_str();
b916f809
VS
1241 #if defined(__WATCOMC__)
1242 (void)perm;
1243 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1244 #elif defined(__DJGPP__)
1245 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1246 #else
1247 #error "Unsupported DOS compiler!"
1248 #endif
1249#else // !MSW, !DOS and !OS/2 VAC++
a6f4dbbd 1250 wxUnusedVar(perm);
4a3c54bf 1251 #ifdef __WXWINCE__
592954dd 1252 if ( CreateDirectory(dir.fn_str(), NULL) == 0 )
4a3c54bf 1253 #else
a6f4dbbd 1254 if ( wxMkDir(dir.fn_str()) != 0 )
4a3c54bf 1255 #endif
7708abe9 1256#endif // !MSW/MSW
1a33c3ba 1257 {
4a3c54bf 1258 wxLogSysError(_("Directory '%s' couldn't be created"), dir);
79e162f5 1259 return false;
1a33c3ba
VZ
1260 }
1261
79e162f5 1262 return true;
4a3c54bf 1263#endif // PALMOS/!PALMOS
c801d85f
KB
1264}
1265
1266bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1267{
68351053 1268#if defined(__VMS__)
79e162f5 1269 return false; //to be changed since rmdir exists in VMS7.x
68351053
WS
1270#elif defined(__WXPALMOS__)
1271 // TODO with VFSFileRename()
1272 return false;
a3ef5bf5 1273#else
4a3c54bf
VZ
1274 #if defined(__OS2__)
1275 if ( ::DosDeleteDir(dir.c_str()) != 0 )
1276 #elif defined(__WXWINCE__)
592954dd 1277 if ( RemoveDirectory(dir.fn_str()) == 0 )
4a3c54bf
VZ
1278 #else
1279 if ( wxRmDir(dir.fn_str()) != 0 )
1280 #endif
1281 {
1282 wxLogSysError(_("Directory '%s' couldn't be deleted"), dir);
1283 return false;
1284 }
1285
1286 return true;
1287#endif // PALMOS/!PALMOS
c801d85f
KB
1288}
1289
c801d85f 1290// does the path exists? (may have or not '/' or '\\' at the end)
e960c20e 1291bool wxDirExists(const wxString& pathName)
c801d85f 1292{
5bb59666 1293 return wxFileName::DirExists(pathName);
c801d85f
KB
1294}
1295
47d281e6
FM
1296#if WXWIN_COMPATIBILITY_2_8
1297
c801d85f 1298// Get a temporary filename, opening and closing the file.
50920146 1299wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
c801d85f 1300{
e44d5a58
VZ
1301 wxString filename;
1302 if ( !wxGetTempFileName(prefix, filename) )
ade35f11 1303 return NULL;
c801d85f 1304
ade35f11 1305 if ( buf )
fcb9fb91
VZ
1306#ifdef _PACC_VER
1307 // work around the PalmOS pacc compiler bug
1308 wxStrcpy(buf, filename.data());
1309#else
ade35f11 1310 wxStrcpy(buf, filename);
fcb9fb91 1311#endif
ade35f11 1312 else
f526f752 1313 buf = MYcopystring(filename);
c801d85f 1314
ade35f11 1315 return buf;
c801d85f
KB
1316}
1317
c0ab6adf
JS
1318bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1319{
e44d5a58 1320#if wxUSE_FILE
522d32e5 1321 buf = wxFileName::CreateTempFileName(prefix);
ade35f11
VZ
1322
1323 return !buf.empty();
e44d5a58
VZ
1324#else // !wxUSE_FILE
1325 wxUnusedVar(prefix);
1326 wxUnusedVar(buf);
1327
1328 return false;
1329#endif // wxUSE_FILE/!wxUSE_FILE
c0ab6adf
JS
1330}
1331
47d281e6
FM
1332#endif // #if WXWIN_COMPATIBILITY_2_8
1333
c801d85f
KB
1334// Get first file name matching given wild card.
1335
8ff12342
VS
1336static wxDir *gs_dir = NULL;
1337static wxString gs_dirPath;
1338
52de37c7 1339wxString wxFindFirstFile(const wxString& spec, int flags)
8ff12342 1340{
47d281e6 1341 wxFileName::SplitPath(spec, &gs_dirPath, NULL, NULL);
a6f4dbbd 1342 if ( gs_dirPath.empty() )
8ff12342 1343 gs_dirPath = wxT(".");
083f7497 1344 if ( !wxEndsWithPathSeparator(gs_dirPath ) )
8ff12342
VS
1345 gs_dirPath << wxFILE_SEP_PATH;
1346
31004b74 1347 delete gs_dir; // can be NULL, this is ok
8ff12342 1348 gs_dir = new wxDir(gs_dirPath);
2db300c6 1349
8ff12342
VS
1350 if ( !gs_dir->IsOpened() )
1351 {
1352 wxLogSysError(_("Can not enumerate files '%s'"), spec);
1353 return wxEmptyString;
1354 }
2db300c6 1355
999836aa 1356 int dirFlags;
8ff12342
VS
1357 switch (flags)
1358 {
1359 case wxDIR: dirFlags = wxDIR_DIRS; break;
1360 case wxFILE: dirFlags = wxDIR_FILES; break;
1361 default: dirFlags = wxDIR_DIRS | wxDIR_FILES; break;
1362 }
2db300c6 1363
8ff12342 1364 wxString result;
52de37c7 1365 gs_dir->GetFirst(&result, wxFileNameFromPath(spec), dirFlags);
a6f4dbbd 1366 if ( result.empty() )
e168b6ac 1367 {
8ff12342 1368 wxDELETE(gs_dir);
e168b6ac
VS
1369 return result;
1370 }
8ff12342
VS
1371
1372 return gs_dirPath + result;
1373}
1374
1375wxString wxFindNextFile()
1376{
31004b74 1377 wxCHECK_MSG( gs_dir, "", "You must call wxFindFirstFile before!" );
8ff12342
VS
1378
1379 wxString result;
1380 gs_dir->GetNext(&result);
2db300c6 1381
a6f4dbbd 1382 if ( result.empty() )
e168b6ac 1383 {
8ff12342 1384 wxDELETE(gs_dir);
e168b6ac
VS
1385 return result;
1386 }
2db300c6 1387
8ff12342
VS
1388 return gs_dirPath + result;
1389}
1390
c801d85f
KB
1391
1392// Get current working directory.
ce045aed
WS
1393// If buf is NULL, allocates space using new, else copies into buf.
1394// wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1395// wxDoGetCwd() is their common core to be moved
1396// to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1397// Do not expose wxDoGetCwd in headers!
1398
1399wxChar *wxDoGetCwd(wxChar *buf, int sz)
c801d85f 1400{
68351053 1401#if defined(__WXPALMOS__)
ce045aed 1402 // TODO
9a83f860 1403 if(buf && sz>0) buf[0] = wxT('\0');
cdc05919 1404 return buf;
68351053 1405#elif defined(__WXWINCE__)
abf912c5 1406 // TODO
9a83f860 1407 if(buf && sz>0) buf[0] = wxT('\0');
cdc05919 1408 return buf;
1c193821 1409#else
13b1f8a7 1410 if ( !buf )
f6bcfd97 1411 {
13b1f8a7
VZ
1412 buf = new wxChar[sz + 1];
1413 }
1414
79e162f5 1415 bool ok wxDUMMY_INITIALIZE(false);
13b1f8a7
VZ
1416
1417 // for the compilers which have Unicode version of _getcwd(), call it
1418 // directly, for the others call the ANSI version and do the translation
dbc38199 1419#if !wxUSE_UNICODE
247f8a77 1420 #define cbuf buf
dbc38199 1421#else // wxUSE_UNICODE
79e162f5 1422 bool needsANSI = true;
dbc38199 1423
247f8a77 1424 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
c35c94f6 1425 char cbuf[_MAXPATHLEN];
247f8a77 1426 #endif
dbc38199 1427
13b1f8a7 1428 #ifdef HAVE_WGETCWD
247f8a77 1429 #if wxUSE_UNICODE_MSLU
406d283a 1430 if ( wxGetOsVersion() != wxOS_WINDOWS_9X )
f5c0e657 1431 #else
79e162f5 1432 char *cbuf = NULL; // never really used because needsANSI will always be false
247f8a77
VS
1433 #endif
1434 {
1435 ok = _wgetcwd(buf, sz) != NULL;
79e162f5 1436 needsANSI = false;
247f8a77 1437 }
13b1f8a7 1438 #endif
13b1f8a7 1439
247f8a77 1440 if ( needsANSI )
dbc38199 1441#endif // wxUSE_UNICODE
247f8a77 1442 {
29d0a26e 1443 #if defined(_MSC_VER) || defined(__MINGW32__)
dbc38199 1444 ok = _getcwd(cbuf, sz) != NULL;
5a3912f2 1445 #elif defined(__OS2__)
13b1f8a7 1446 APIRET rc;
5a3912f2
SN
1447 ULONG ulDriveNum = 0;
1448 ULONG ulDriveMap = 0;
a62848fd 1449 rc = ::DosQueryCurrentDisk(&ulDriveNum, &ulDriveMap);
5a3912f2 1450 ok = rc == 0;
a62848fd
WS
1451 if (ok)
1452 {
1453 sz -= 3;
1454 rc = ::DosQueryCurrentDir( 0 // current drive
089e9521 1455 ,(PBYTE)cbuf + 3
5a3912f2
SN
1456 ,(PULONG)&sz
1457 );
7a893a31 1458 cbuf[0] = char('A' + (ulDriveNum - 1));
5a3912f2
SN
1459 cbuf[1] = ':';
1460 cbuf[2] = '\\';
1461 ok = rc == 0;
1462 }
13b1f8a7 1463 #else // !Win32/VC++ !Mac !OS2
dbc38199 1464 ok = getcwd(cbuf, sz) != NULL;
13b1f8a7 1465 #endif // platform
247f8a77 1466
0ad76eea 1467 #if wxUSE_UNICODE
247f8a77
VS
1468 // finally convert the result to Unicode if needed
1469 wxConvFile.MB2WC(buf, cbuf, sz);
1470 #endif // wxUSE_UNICODE
1471 }
13b1f8a7
VZ
1472
1473 if ( !ok )
19193a2c 1474 {
13b1f8a7 1475 wxLogSysError(_("Failed to get the working directory"));
19193a2c 1476
13b1f8a7
VZ
1477 // VZ: the old code used to return "." on error which didn't make any
1478 // sense at all to me - empty string is a better error indicator
1479 // (NULL might be even better but I'm afraid this could lead to
1480 // problems with the old code assuming the return is never NULL)
9a83f860 1481 buf[0] = wxT('\0');
19193a2c 1482 }
13b1f8a7 1483 else // ok, but we might need to massage the path into the right format
19193a2c 1484 {
4b00a538 1485#ifdef __DJGPP__
13b1f8a7
VZ
1486 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1487 // with / deliminers. We don't like that.
1488 for (wxChar *ch = buf; *ch; ch++)
1489 {
1490 if (*ch == wxT('/'))
1491 *ch = wxT('\\');
1492 }
1493#endif // __DJGPP__
1494
17234b26
MB
1495// MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1496// he needs Unix as opposed to Win32 pathnames
1497#if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
3ffbc733 1498 // another example of DOS/Unix mix (Cygwin)
13b1f8a7 1499 wxString pathUnix = buf;
7682e22e 1500#if wxUSE_UNICODE
715e4f7e
VZ
1501 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1502 cygwin_conv_path(CCP_POSIX_TO_WIN_W, pathUnix.mb_str(wxConvFile), buf, sz);
1503 #else
7682e22e
VZ
1504 char bufA[_MAXPATHLEN];
1505 cygwin_conv_to_full_win32_path(pathUnix.mb_str(wxConvFile), bufA);
1506 wxConvFile.MB2WC(buf, bufA, sz);
715e4f7e 1507 #endif
7682e22e 1508#else
715e4f7e
VZ
1509 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1510 cygwin_conv_path(CCP_POSIX_TO_WIN_A, pathUnix, buf, sz);
1511 #else
13b1f8a7 1512 cygwin_conv_to_full_win32_path(pathUnix, buf);
715e4f7e 1513 #endif
7682e22e 1514#endif // wxUSE_UNICODE
e02e8816 1515#endif // __CYGWIN__
13b1f8a7 1516 }
4b00a538 1517
13b1f8a7 1518 return buf;
dbc38199
VS
1519
1520#if !wxUSE_UNICODE
247f8a77 1521 #undef cbuf
dbc38199 1522#endif
1c193821
JS
1523
1524#endif
1525 // __WXWINCE__
c801d85f
KB
1526}
1527
2587df2c
VS
1528#if WXWIN_COMPATIBILITY_2_6
1529wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1530{
1531 return wxDoGetCwd(buf,sz);
1532}
1533#endif // WXWIN_COMPATIBILITY_2_6
1534
ce045aed
WS
1535wxString wxGetCwd()
1536{
1537 wxString str;
1538 wxDoGetCwd(wxStringBuffer(str, _MAXPATHLEN), _MAXPATHLEN);
eac2aeb0 1539 return str;
7af89395
VZ
1540}
1541
c801d85f
KB
1542bool wxSetWorkingDirectory(const wxString& d)
1543{
5a3912f2 1544#if defined(__OS2__)
43c97407
SN
1545 if (d[1] == ':')
1546 {
9a83f860 1547 ::DosSetDefaultDisk(wxToupper(d[0]) - wxT('A') + 1);
2b2883a5
JS
1548 // do not call DosSetCurrentDir when just changing drive,
1549 // since it requires e.g. "d:." instead of "d:"!
1550 if (d.length() == 2)
1551 return true;
43c97407 1552 }
1f3d9911 1553 return (::DosSetCurrentDir(d.c_str()) == 0);
5a3912f2
SN
1554#elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1555 return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
34138703 1556#elif defined(__WINDOWS__)
a62848fd 1557
c801d85f 1558#ifdef __WIN32__
1c193821
JS
1559#ifdef __WXWINCE__
1560 // No equivalent in WinCE
abf912c5 1561 wxUnusedVar(d);
79e162f5 1562 return false;
c801d85f 1563#else
e0a050e3 1564 return (bool)(SetCurrentDirectory(d.fn_str()) != 0);
1c193821
JS
1565#endif
1566#else
1567 // Must change drive, too.
1568 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1569 if (isDriveSpec)
c801d85f 1570 {
1c193821 1571 wxChar firstChar = d[0];
a62848fd 1572
1c193821
JS
1573 // To upper case
1574 if (firstChar > 90)
1575 firstChar = firstChar - 32;
a62848fd 1576
1c193821
JS
1577 // To a drive number
1578 unsigned int driveNo = firstChar - 64;
1579 if (driveNo > 0)
1580 {
1581 unsigned int noDrives;
1582 _dos_setdrive(driveNo, &noDrives);
1583 }
c801d85f 1584 }
1c193821 1585 bool success = (chdir(WXSTRINGCAST d) == 0);
a62848fd 1586
1c193821 1587 return success;
c801d85f 1588#endif
a62848fd 1589
c801d85f
KB
1590#endif
1591}
1592
631f1bfe
JS
1593// Get the OS directory if appropriate (such as the Windows directory).
1594// On non-Windows platform, probably just return the empty string.
1595wxString wxGetOSDirectory()
1596{
1c193821
JS
1597#ifdef __WXWINCE__
1598 return wxString(wxT("\\Windows"));
1599#elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
50920146 1600 wxChar buf[256];
631f1bfe
JS
1601 GetWindowsDirectory(buf, 256);
1602 return wxString(buf);
26eef304 1603#elif defined(__WXMAC__) && wxOSX_USE_CARBON
8478eff5 1604 return wxMacFindFolderNoSeparator(kOnSystemDisk, 'macs', false);
631f1bfe
JS
1605#else
1606 return wxEmptyString;
1607#endif
1608}
1609
52de37c7 1610bool wxEndsWithPathSeparator(const wxString& filename)
c801d85f 1611{
52de37c7 1612 return !filename.empty() && wxIsPathSeparator(filename.Last());
c801d85f
KB
1613}
1614
79e162f5 1615// find a file in a list of directories, returns false if not found
52de37c7 1616bool wxFindFileInPath(wxString *pStr, const wxString& szPath, const wxString& szFile)
c801d85f 1617{
a17e237f 1618 // we assume that it's not empty
52de37c7 1619 wxCHECK_MSG( !szFile.empty(), false,
9a83f860 1620 wxT("empty file name in wxFindFileInPath"));
a17e237f
VZ
1621
1622 // skip path separator in the beginning of the file name if present
52de37c7
VS
1623 wxString szFile2;
1624 if ( wxIsPathSeparator(szFile[0u]) )
1625 szFile2 = szFile.Mid(1);
1626 else
1627 szFile2 = szFile;
1628
1629 wxStringTokenizer tkn(szPath, wxPATH_SEP);
1630
1631 while ( tkn.HasMoreTokens() )
a17e237f 1632 {
52de37c7
VS
1633 wxString strFile = tkn.GetNextToken();
1634 if ( !wxEndsWithPathSeparator(strFile) )
a17e237f 1635 strFile += wxFILE_SEP_PATH;
52de37c7 1636 strFile += szFile2;
a17e237f 1637
52de37c7
VS
1638 if ( wxFileExists(strFile) )
1639 {
a17e237f 1640 *pStr = strFile;
52de37c7 1641 return true;
a17e237f 1642 }
c801d85f 1643 }
c801d85f 1644
52de37c7 1645 return false;
c801d85f
KB
1646}
1647
47d281e6 1648#if WXWIN_COMPATIBILITY_2_8
163b3ad7 1649void WXDLLIMPEXP_BASE wxSplitPath(const wxString& fileName,
3826db3e
VZ
1650 wxString *pstrPath,
1651 wxString *pstrName,
1652 wxString *pstrExt)
1653{
52de37c7 1654 wxFileName::SplitPath(fileName, pstrPath, pstrName, pstrExt);
3826db3e 1655}
47d281e6 1656#endif // #if WXWIN_COMPATIBILITY_2_8
7f555861 1657
2c5e5cbd
VS
1658#if wxUSE_DATETIME
1659
163b3ad7 1660time_t WXDLLIMPEXP_BASE wxFileModificationTime(const wxString& filename)
a47ce4a7 1661{
2936a6b1
VZ
1662 wxDateTime mtime;
1663 if ( !wxFileName(filename).GetTimes(NULL, &mtime, NULL) )
1664 return (time_t)-1;
a62848fd 1665
2936a6b1 1666 return mtime.GetTicks();
a47ce4a7
VS
1667}
1668
2c5e5cbd
VS
1669#endif // wxUSE_DATETIME
1670
a47ce4a7 1671
9e152a55
WS
1672// Parses the filterStr, returning the number of filters.
1673// Returns 0 if none or if there's a problem.
daf32463 1674// filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
9e152a55 1675
163b3ad7 1676int WXDLLIMPEXP_BASE wxParseCommonDialogsFilter(const wxString& filterStr,
7bea7b91
WS
1677 wxArrayString& descriptions,
1678 wxArrayString& filters)
9e152a55
WS
1679{
1680 descriptions.Clear();
1681 filters.Clear();
1682
1683 wxString str(filterStr);
1684
1685 wxString description, filter;
1686 int pos = 0;
1687 while( pos != wxNOT_FOUND )
1688 {
1689 pos = str.Find(wxT('|'));
1690 if ( pos == wxNOT_FOUND )
1691 {
1692 // if there are no '|'s at all in the string just take the entire
daf32463 1693 // string as filter and make description empty for later autocompletion
9e152a55
WS
1694 if ( filters.IsEmpty() )
1695 {
daf32463 1696 descriptions.Add(wxEmptyString);
9e152a55
WS
1697 filters.Add(filterStr);
1698 }
1699 else
1700 {
9a83f860 1701 wxFAIL_MSG( wxT("missing '|' in the wildcard string!") );
9e152a55
WS
1702 }
1703
1704 break;
1705 }
1706
1707 description = str.Left(pos);
1708 str = str.Mid(pos + 1);
1709 pos = str.Find(wxT('|'));
1710 if ( pos == wxNOT_FOUND )
1711 {
1712 filter = str;
1713 }
1714 else
1715 {
1716 filter = str.Left(pos);
1717 str = str.Mid(pos + 1);
1718 }
1719
1720 descriptions.Add(description);
1721 filters.Add(filter);
1722 }
1723
daf32463
WS
1724#if defined(__WXMOTIF__)
1725 // split it so there is one wildcard per entry
1726 for( size_t i = 0 ; i < descriptions.GetCount() ; i++ )
1727 {
1728 pos = filters[i].Find(wxT(';'));
1729 if (pos != wxNOT_FOUND)
1730 {
1731 // first split only filters
1732 descriptions.Insert(descriptions[i],i+1);
1733 filters.Insert(filters[i].Mid(pos+1),i+1);
1734 filters[i]=filters[i].Left(pos);
1735
1736 // autoreplace new filter in description with pattern:
1737 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1738 // cause split into:
1739 // C/C++ Files(*.cpp)|*.cpp
1740 // C/C++ Files(*.c;*.h)|*.c;*.h
1741 // and next iteration cause another split into:
1742 // C/C++ Files(*.cpp)|*.cpp
1743 // C/C++ Files(*.c)|*.c
1744 // C/C++ Files(*.h)|*.h
1745 for ( size_t k=i;k<i+2;k++ )
1746 {
1747 pos = descriptions[k].Find(filters[k]);
1748 if (pos != wxNOT_FOUND)
1749 {
1750 wxString before = descriptions[k].Left(pos);
1751 wxString after = descriptions[k].Mid(pos+filters[k].Len());
9a83f860
VZ
1752 pos = before.Find(wxT('('),true);
1753 if (pos>before.Find(wxT(')'),true))
daf32463
WS
1754 {
1755 before = before.Left(pos+1);
1756 before << filters[k];
9a83f860
VZ
1757 pos = after.Find(wxT(')'));
1758 int pos1 = after.Find(wxT('('));
daf32463
WS
1759 if (pos != wxNOT_FOUND && (pos<pos1 || pos1==wxNOT_FOUND))
1760 {
1761 before << after.Mid(pos);
1762 descriptions[k] = before;
1763 }
1764 }
1765 }
1766 }
1767 }
1768 }
1769#endif
1770
1771 // autocompletion
1772 for( size_t j = 0 ; j < descriptions.GetCount() ; j++ )
1773 {
489f6cf7 1774 if ( descriptions[j].empty() && !filters[j].empty() )
daf32463
WS
1775 {
1776 descriptions[j].Printf(_("Files (%s)"), filters[j].c_str());
1777 }
1778 }
1779
9e152a55
WS
1780 return filters.GetCount();
1781}
1782
968956aa 1783#if defined(__WINDOWS__) && !(defined(__UNIX__) || defined(__OS2__))
f2346d3f 1784static bool wxCheckWin32Permission(const wxString& path, DWORD access)
3ff07edb
RR
1785{
1786 // quoting the MSDN: "To obtain a handle to a directory, call the
f2346d3f
VZ
1787 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag", but this
1788 // doesn't work under Win9x/ME but then it's not needed there anyhow
c9c023dd
VZ
1789 const DWORD dwAttr = ::GetFileAttributes(path.fn_str());
1790 if ( dwAttr == INVALID_FILE_ATTRIBUTES )
1791 {
1792 // file probably doesn't exist at all
1793 return false;
1794 }
1795
1796 if ( wxGetOsVersion() == wxOS_WINDOWS_9X )
3ff07edb 1797 {
f2346d3f 1798 // FAT directories always allow all access, even if they have the
c9c023dd
VZ
1799 // readonly flag set, and FAT files can only be read-only
1800 return (dwAttr & FILE_ATTRIBUTE_DIRECTORY) ||
1801 (access != GENERIC_WRITE ||
1802 !(dwAttr & FILE_ATTRIBUTE_READONLY));
3ff07edb 1803 }
3ff07edb 1804
f2346d3f
VZ
1805 HANDLE h = ::CreateFile
1806 (
6ad68ad8 1807 path.t_str(),
f2346d3f
VZ
1808 access,
1809 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1810 NULL,
1811 OPEN_EXISTING,
c9c023dd
VZ
1812 dwAttr & FILE_ATTRIBUTE_DIRECTORY
1813 ? FILE_FLAG_BACKUP_SEMANTICS
1814 : 0,
f2346d3f
VZ
1815 NULL
1816 );
1817 if ( h != INVALID_HANDLE_VALUE )
1818 CloseHandle(h);
1819
1820 return h != INVALID_HANDLE_VALUE;
3ff07edb 1821}
f2346d3f 1822#endif // __WINDOWS__
3ff07edb
RR
1823
1824bool wxIsWritable(const wxString &path)
1825{
2203a185 1826#if defined( __UNIX__ ) || defined(__OS2__)
3ff07edb 1827 // access() will take in count also symbolic links
0d4ba4ef 1828 return wxAccess(path.c_str(), W_OK) == 0;
3ff07edb 1829#elif defined( __WINDOWS__ )
f2346d3f 1830 return wxCheckWin32Permission(path, GENERIC_WRITE);
3ff07edb 1831#else
a8b6a1b1 1832 wxUnusedVar(path);
3ff07edb
RR
1833 // TODO
1834 return false;
1835#endif
1836}
1837
1838bool wxIsReadable(const wxString &path)
1839{
2203a185 1840#if defined( __UNIX__ ) || defined(__OS2__)
3ff07edb 1841 // access() will take in count also symbolic links
0d4ba4ef 1842 return wxAccess(path.c_str(), R_OK) == 0;
3ff07edb 1843#elif defined( __WINDOWS__ )
f2346d3f 1844 return wxCheckWin32Permission(path, GENERIC_READ);
3ff07edb 1845#else
a8b6a1b1 1846 wxUnusedVar(path);
3ff07edb
RR
1847 // TODO
1848 return false;
1849#endif
1850}
1851
1852bool wxIsExecutable(const wxString &path)
1853{
2203a185 1854#if defined( __UNIX__ ) || defined(__OS2__)
3ff07edb 1855 // access() will take in count also symbolic links
0d4ba4ef 1856 return wxAccess(path.c_str(), X_OK) == 0;
3ff07edb 1857#elif defined( __WINDOWS__ )
f2346d3f 1858 return wxCheckWin32Permission(path, GENERIC_EXECUTE);
3ff07edb 1859#else
a8b6a1b1 1860 wxUnusedVar(path);
3ff07edb
RR
1861 // TODO
1862 return false;
1863#endif
1864}
1865
693b31be
MW
1866// Return the type of an open file
1867//
1868// Some file types on some platforms seem seekable but in fact are not.
1869// The main use of this function is to allow such cases to be detected
1870// (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1871//
1872// This is important for the archive streams, which benefit greatly from
1873// being able to seek on a stream, but which will produce corrupt archives
1874// if they unknowingly seek on a non-seekable stream.
1875//
1876// wxFILE_KIND_DISK is a good catch all return value, since other values
1877// disable features of the archive streams. Some other value must be returned
1878// for a file type that appears seekable but isn't.
1879//
1880// Known examples:
1881// * Pipes on Windows
1882// * Files on VMS with a record format other than StreamLF
1883//
1884wxFileKind wxGetFileKind(int fd)
1885{
1886#if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1887 switch (::GetFileType(wxGetOSFHandle(fd)) & ~FILE_TYPE_REMOTE)
1888 {
1889 case FILE_TYPE_CHAR:
1890 return wxFILE_KIND_TERMINAL;
1891 case FILE_TYPE_DISK:
1892 return wxFILE_KIND_DISK;
1893 case FILE_TYPE_PIPE:
1894 return wxFILE_KIND_PIPE;
1895 }
1896
1897 return wxFILE_KIND_UNKNOWN;
1898
1899#elif defined(__UNIX__)
1900 if (isatty(fd))
1901 return wxFILE_KIND_TERMINAL;
1902
1903 struct stat st;
1904 fstat(fd, &st);
1905
1906 if (S_ISFIFO(st.st_mode))
1907 return wxFILE_KIND_PIPE;
1908 if (!S_ISREG(st.st_mode))
1909 return wxFILE_KIND_UNKNOWN;
1910
1911 #if defined(__VMS__)
1912 if (st.st_fab_rfm != FAB$C_STMLF)
1913 return wxFILE_KIND_UNKNOWN;
1914 #endif
1915
1916 return wxFILE_KIND_DISK;
1917
1918#else
1919 #define wxFILEKIND_STUB
1920 (void)fd;
1921 return wxFILE_KIND_DISK;
1922#endif
1923}
1924
1925wxFileKind wxGetFileKind(FILE *fp)
1926{
1927 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1928 // Should be fixed in version 1.4.
1929#if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
1930 (void)fp;
1931 return wxFILE_KIND_DISK;
bade0251 1932#elif defined(__WINDOWS__) && !defined(__CYGWIN__) && !defined(__WATCOMC__) && !defined(__WINE__)
693b31be
MW
1933 return fp ? wxGetFileKind(_fileno(fp)) : wxFILE_KIND_UNKNOWN;
1934#else
1935 return fp ? wxGetFileKind(fileno(fp)) : wxFILE_KIND_UNKNOWN;
1936#endif
1937}
1938
9e152a55 1939
7f555861
JS
1940//------------------------------------------------------------------------
1941// wild character routines
1942//------------------------------------------------------------------------
1943
1944bool wxIsWild( const wxString& pattern )
1945{
52de37c7 1946 for ( wxString::const_iterator p = pattern.begin(); p != pattern.end(); ++p )
2b5f62a0 1947 {
52de37c7 1948 switch ( (*p).GetValue() )
2b5f62a0 1949 {
52de37c7
VS
1950 case wxT('?'):
1951 case wxT('*'):
1952 case wxT('['):
1953 case wxT('{'):
1954 return true;
1955
1956 case wxT('\\'):
1957 if ( ++p == pattern.end() )
1958 return false;
3f4a0c5b 1959 }
7f555861 1960 }
79e162f5 1961 return false;
dfcb1ae0 1962}
dfcb1ae0 1963
2b5f62a0
VZ
1964/*
1965* Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1966*
1967* The match procedure is public domain code (from ircII's reg.c)
b931e275 1968* but modified to suit our tastes (RN: No "%" syntax I guess)
2b5f62a0 1969*/
7be1f0d9 1970
2b5f62a0 1971bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
7f555861 1972{
7448de8d
WS
1973 if (text.empty())
1974 {
1975 /* Match if both are empty. */
1976 return pat.empty();
1977 }
1978
1979 const wxChar *m = pat.c_str(),
1980 *n = text.c_str(),
1981 *ma = NULL,
b931e275 1982 *na = NULL;
7448de8d 1983 int just = 0,
7448de8d
WS
1984 acount = 0,
1985 count = 0;
1986
1987 if (dot_special && (*n == wxT('.')))
1988 {
1989 /* Never match so that hidden Unix files
1990 * are never found. */
1991 return false;
1992 }
1993
1994 for (;;)
1995 {
1996 if (*m == wxT('*'))
2b5f62a0 1997 {
7448de8d
WS
1998 ma = ++m;
1999 na = n;
2000 just = 1;
7448de8d 2001 acount = count;
2b5f62a0 2002 }
7448de8d 2003 else if (*m == wxT('?'))
2b5f62a0 2004 {
7448de8d
WS
2005 m++;
2006 if (!*n++)
79e162f5 2007 return false;
2b5f62a0 2008 }
7448de8d 2009 else
2b5f62a0 2010 {
7448de8d
WS
2011 if (*m == wxT('\\'))
2012 {
2013 m++;
2014 /* Quoting "nothing" is a bad thing */
2015 if (!*m)
2016 return false;
2017 }
2018 if (!*m)
2019 {
2020 /*
2021 * If we are out of both strings or we just
2022 * saw a wildcard, then we can say we have a
2023 * match
2024 */
2025 if (!*n)
2026 return true;
2027 if (just)
2028 return true;
2029 just = 0;
2030 goto not_matched;
2031 }
2032 /*
2033 * We could check for *n == NULL at this point, but
2034 * since it's more common to have a character there,
2035 * check to see if they match first (m and n) and
2036 * then if they don't match, THEN we can check for
2037 * the NULL of n
2038 */
2039 just = 0;
2040 if (*m == *n)
2041 {
2042 m++;
7448de8d
WS
2043 count++;
2044 n++;
2045 }
2046 else
2047 {
2048
2049 not_matched:
2050
2051 /*
2052 * If there are no more characters in the
2053 * string, but we still need to find another
2054 * character (*m != NULL), then it will be
2055 * impossible to match it
2056 */
2057 if (!*n)
2058 return false;
2b5f62a0 2059
7448de8d
WS
2060 if (ma)
2061 {
2062 m = ma;
2063 n = ++na;
2064 count = acount;
3f4a0c5b 2065 }
7448de8d
WS
2066 else
2067 return false;
2068 }
3f4a0c5b 2069 }
7448de8d 2070 }
2b5f62a0 2071}
fd3f686c 2072
3f4a0c5b 2073#ifdef __VISUALC__
fd3f686c 2074 #pragma warning(default:4706) // assignment within conditional expression
53c6e7cc 2075#endif // VC++