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