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