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