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