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