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