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