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