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