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