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