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