]> git.saurik.com Git - wxWidgets.git/blame - src/common/filename.cpp
Don't lock global mutex when deleting wxThread to avoid deadlocks.
[wxWidgets.git] / src / common / filename.cpp
CommitLineData
df5ddbca 1/////////////////////////////////////////////////////////////////////////////
097ead30
VZ
2// Name: src/common/filename.cpp
3// Purpose: wxFileName - encapsulates a file path
844f90fb 4// Author: Robert Roebling, Vadim Zeitlin
df5ddbca
RR
5// Modified by:
6// Created: 28.12.2000
7// RCS-ID: $Id$
8// Copyright: (c) 2000 Robert Roebling
65571936 9// Licence: wxWindows licence
df5ddbca
RR
10/////////////////////////////////////////////////////////////////////////////
11
04c943b1
VZ
12/*
13 Here are brief descriptions of the filename formats supported by this class:
14
2bc60417
RR
15 wxPATH_UNIX: standard Unix format, used under Darwin as well, absolute file
16 names have the form:
04c943b1
VZ
17 /dir1/dir2/.../dirN/filename, "." and ".." stand for the
18 current and parent directory respectively, "~" is parsed as the
19 user HOME and "~username" as the HOME of that user
20
2bc60417 21 wxPATH_DOS: DOS/Windows format, absolute file names have the form:
04c943b1
VZ
22 drive:\dir1\dir2\...\dirN\filename.ext where drive is a single
23 letter. "." and ".." as for Unix but no "~".
24
25 There are also UNC names of the form \\share\fullpath
26
ae4d7004 27 wxPATH_MAC: Mac OS 8/9 and Mac OS X under CodeWarrior 7 format, absolute file
2bc60417 28 names have the form
04c943b1
VZ
29 volume:dir1:...:dirN:filename
30 and the relative file names are either
31 :dir1:...:dirN:filename
32 or just
33 filename
34 (although :filename works as well).
a385b5df 35 Since the volume is just part of the file path, it is not
353f41cb 36 treated like a separate entity as it is done under DOS and
90a68369 37 VMS, it is just treated as another dir.
04c943b1
VZ
38
39 wxPATH_VMS: VMS native format, absolute file names have the form
40 <device>:[dir1.dir2.dir3]file.txt
41 or
42 <device>:[000000.dir1.dir2.dir3]file.txt
43
44 the <device> is the physical device (i.e. disk). 000000 is the
45 root directory on the device which can be omitted.
46
47 Note that VMS uses different separators unlike Unix:
48 : always after the device. If the path does not contain : than
49 the default (the device of the current directory) is assumed.
ba623ba2 50 [ start of directory specification
04c943b1
VZ
51 . separator between directory and subdirectory
52 ] between directory and file
53 */
54
097ead30
VZ
55// ============================================================================
56// declarations
57// ============================================================================
58
59// ----------------------------------------------------------------------------
60// headers
61// ----------------------------------------------------------------------------
62
df5ddbca
RR
63// For compilers that support precompilation, includes "wx.h".
64#include "wx/wxprec.h"
65
66#ifdef __BORLANDC__
0b9ab0bd 67#pragma hdrstop
df5ddbca
RR
68#endif
69
70#ifndef WX_PRECOMP
57bd4c60
WS
71 #ifdef __WXMSW__
72 #include "wx/msw/wrapwin.h" // For GetShort/LongPathName
73 #endif
ad9835c9
WS
74 #include "wx/dynarray.h"
75 #include "wx/intl.h"
76 #include "wx/log.h"
de6185e2 77 #include "wx/utils.h"
0bf751e7 78 #include "wx/crt.h"
df5ddbca
RR
79#endif
80
81#include "wx/filename.h"
b70a2866 82#include "wx/private/filename.h"
df5ddbca 83#include "wx/tokenzr.h"
844f90fb 84#include "wx/config.h" // for wxExpandEnvVars
35a6691a 85#include "wx/dynlib.h"
110c5094 86#include "wx/dir.h"
df5ddbca 87
57bd4c60
WS
88#if defined(__WIN32__) && defined(__MINGW32__)
89 #include "wx/msw/gccpriv.h"
951cd180
VZ
90#endif
91
1c193821
JS
92#ifdef __WXWINCE__
93#include "wx/msw/private.h"
94#endif
95
76a5e5d2 96#if defined(__WXMAC__)
c933e267 97 #include "wx/osx/private.h" // includes mac headers
76a5e5d2
SC
98#endif
99
951cd180
VZ
100// utime() is POSIX so should normally be available on all Unices
101#ifdef __UNIX_LIKE__
0b9ab0bd
RL
102#include <sys/types.h>
103#include <utime.h>
104#include <sys/stat.h>
105#include <unistd.h>
9e9b65c1
JS
106#endif
107
444d61ba
VS
108#ifdef __DJGPP__
109#include <unistd.h>
110#endif
111
01d981ec 112#ifdef __MWERKS__
31907d03
SC
113#ifdef __MACH__
114#include <sys/types.h>
115#include <utime.h>
116#include <sys/stat.h>
117#include <unistd.h>
118#else
0b9ab0bd
RL
119#include <stat.h>
120#include <unistd.h>
121#include <unix.h>
01d981ec 122#endif
31907d03 123#endif
01d981ec 124
d9f54bb0 125#ifdef __WATCOMC__
0b9ab0bd
RL
126#include <io.h>
127#include <sys/utime.h>
128#include <sys/stat.h>
d9f54bb0
VS
129#endif
130
24eb81cb
DW
131#ifdef __VISAGECPP__
132#ifndef MAX_PATH
133#define MAX_PATH 256
134#endif
135#endif
136
01c9a906 137#ifdef __EMX__
5d66debf 138#include <os2.h>
01c9a906
SN
139#define MAX_PATH _MAX_PATH
140#endif
141
23b8a262 142
bd08f2f7 143#if wxUSE_LONGLONG
060668a1 144extern const wxULongLong wxInvalidSize = (unsigned)-1;
bd08f2f7 145#endif // wxUSE_LONGLONG
23b8a262 146
85b1997c
VZ
147#ifdef __WIN32__
148 // this define is missing from VC6 headers
149 #ifndef INVALID_FILE_ATTRIBUTES
150 #define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
151 #endif
152#endif // __WIN32__
153
7b611a3a
VZ
154namespace
155{
23b8a262 156
951cd180
VZ
157// ----------------------------------------------------------------------------
158// private classes
159// ----------------------------------------------------------------------------
160
161// small helper class which opens and closes the file - we use it just to get
162// a file handle for the given file name to pass it to some Win32 API function
c67d6888 163#if defined(__WIN32__) && !defined(__WXMICROWIN__)
951cd180
VZ
164
165class wxFileHandle
166{
167public:
6dbb903b
VZ
168 enum OpenMode
169 {
f3c74c8d
VZ
170 ReadAttr,
171 WriteAttr
6dbb903b
VZ
172 };
173
6bc176b4 174 wxFileHandle(const wxString& filename, OpenMode mode, int flags = 0)
951cd180 175 {
f3c74c8d
VZ
176 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
177 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
178 // be changed when we open it because this class is used for setting
179 // access time (see #10567)
951cd180
VZ
180 m_hFile = ::CreateFile
181 (
e0a050e3 182 filename.fn_str(), // name
f3c74c8d
VZ
183 mode == ReadAttr ? FILE_READ_ATTRIBUTES // access mask
184 : FILE_WRITE_ATTRIBUTES,
54bcff35
VZ
185 FILE_SHARE_READ | // sharing mode
186 FILE_SHARE_WRITE, // (allow everything)
6dbb903b
VZ
187 NULL, // no secutity attr
188 OPEN_EXISTING, // creation disposition
6bc176b4 189 flags, // flags
6dbb903b 190 NULL // no template file
951cd180
VZ
191 );
192
193 if ( m_hFile == INVALID_HANDLE_VALUE )
194 {
f3c74c8d 195 if ( mode == ReadAttr )
43b2d5e7 196 {
49a70977
VS
197 wxLogSysError(_("Failed to open '%s' for reading"),
198 filename.c_str());
43b2d5e7 199 }
49a70977 200 else
43b2d5e7 201 {
49a70977
VS
202 wxLogSysError(_("Failed to open '%s' for writing"),
203 filename.c_str());
43b2d5e7 204 }
951cd180
VZ
205 }
206 }
207
208 ~wxFileHandle()
209 {
210 if ( m_hFile != INVALID_HANDLE_VALUE )
211 {
212 if ( !::CloseHandle(m_hFile) )
213 {
214 wxLogSysError(_("Failed to close file handle"));
215 }
216 }
217 }
218
f363e05c 219 // return true only if the file could be opened successfully
951cd180
VZ
220 bool IsOk() const { return m_hFile != INVALID_HANDLE_VALUE; }
221
222 // get the handle
223 operator HANDLE() const { return m_hFile; }
224
225private:
226 HANDLE m_hFile;
227};
228
229#endif // __WIN32__
230
231// ----------------------------------------------------------------------------
232// private functions
233// ----------------------------------------------------------------------------
234
e2b87f38 235#if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
951cd180
VZ
236
237// convert between wxDateTime and FILETIME which is a 64-bit value representing
238// the number of 100-nanosecond intervals since January 1, 1601.
239
d56e2b97 240static void ConvertFileTimeToWx(wxDateTime *dt, const FILETIME &ft)
951cd180 241{
752f10a8 242 FILETIME ftcopy = ft;
6dbb903b 243 FILETIME ftLocal;
752f10a8 244 if ( !::FileTimeToLocalFileTime(&ftcopy, &ftLocal) )
6dbb903b 245 {
9a83f860 246 wxLogLastError(wxT("FileTimeToLocalFileTime"));
6dbb903b 247 }
d56e2b97 248
6dbb903b
VZ
249 SYSTEMTIME st;
250 if ( !::FileTimeToSystemTime(&ftLocal, &st) )
251 {
9a83f860 252 wxLogLastError(wxT("FileTimeToSystemTime"));
6dbb903b 253 }
d56e2b97 254
6dbb903b
VZ
255 dt->Set(st.wDay, wxDateTime::Month(st.wMonth - 1), st.wYear,
256 st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
951cd180
VZ
257}
258
d56e2b97 259static void ConvertWxToFileTime(FILETIME *ft, const wxDateTime& dt)
951cd180 260{
6dbb903b
VZ
261 SYSTEMTIME st;
262 st.wDay = dt.GetDay();
ad816476
WS
263 st.wMonth = (WORD)(dt.GetMonth() + 1);
264 st.wYear = (WORD)dt.GetYear();
6dbb903b
VZ
265 st.wHour = dt.GetHour();
266 st.wMinute = dt.GetMinute();
267 st.wSecond = dt.GetSecond();
268 st.wMilliseconds = dt.GetMillisecond();
269
270 FILETIME ftLocal;
271 if ( !::SystemTimeToFileTime(&st, &ftLocal) )
272 {
9a83f860 273 wxLogLastError(wxT("SystemTimeToFileTime"));
6dbb903b 274 }
d56e2b97 275
6dbb903b
VZ
276 if ( !::LocalFileTimeToFileTime(&ftLocal, ft) )
277 {
9a83f860 278 wxLogLastError(wxT("LocalFileTimeToFileTime"));
6dbb903b 279 }
951cd180
VZ
280}
281
e2b87f38 282#endif // wxUSE_DATETIME && __WIN32__
951cd180 283
67c34f64
VZ
284// return a string with the volume par
285static wxString wxGetVolumeString(const wxString& volume, wxPathFormat format)
286{
287 wxString path;
288
289 if ( !volume.empty() )
290 {
6ce27aa2
VZ
291 format = wxFileName::GetFormat(format);
292
67c34f64
VZ
293 // Special Windows UNC paths hack, part 2: undo what we did in
294 // SplitPath() and make an UNC path if we have a drive which is not a
295 // single letter (hopefully the network shares can't be one letter only
296 // although I didn't find any authoritative docs on this)
297 if ( format == wxPATH_DOS && volume.length() > 1 )
298 {
299 path << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << volume;
300 }
301 else if ( format == wxPATH_DOS || format == wxPATH_VMS )
302 {
303 path << volume << wxFileName::GetVolumeSeparator(format);
304 }
305 // else ignore
306 }
307
308 return path;
309}
310
7b611a3a
VZ
311// return true if the character is a DOS path separator i.e. either a slash or
312// a backslash
313inline bool IsDOSPathSep(wxUniChar ch)
314{
315 return ch == wxFILE_SEP_PATH_DOS || ch == wxFILE_SEP_PATH_UNIX;
316}
317
9e1c7236
VZ
318// return true if the format used is the DOS/Windows one and the string looks
319// like a UNC path
320static bool IsUNCPath(const wxString& path, wxPathFormat format)
321{
322 return format == wxPATH_DOS &&
323 path.length() >= 4 && // "\\a" can't be a UNC path
7b611a3a
VZ
324 IsDOSPathSep(path[0u]) &&
325 IsDOSPathSep(path[1u]) &&
326 !IsDOSPathSep(path[2u]);
9e1c7236
VZ
327}
328
7b611a3a
VZ
329} // anonymous namespace
330
097ead30
VZ
331// ============================================================================
332// implementation
333// ============================================================================
334
335// ----------------------------------------------------------------------------
844f90fb 336// wxFileName construction
097ead30 337// ----------------------------------------------------------------------------
df5ddbca 338
a35b27b1
RR
339void wxFileName::Assign( const wxFileName &filepath )
340{
04c943b1 341 m_volume = filepath.GetVolume();
844f90fb 342 m_dirs = filepath.GetDirs();
04c943b1
VZ
343 m_name = filepath.GetName();
344 m_ext = filepath.GetExt();
a2fa5040 345 m_relative = filepath.m_relative;
dfecbee5 346 m_hasExt = filepath.m_hasExt;
df5ddbca
RR
347}
348
04c943b1
VZ
349void wxFileName::Assign(const wxString& volume,
350 const wxString& path,
351 const wxString& name,
352 const wxString& ext,
dfecbee5 353 bool hasExt,
9e1c7236 354 wxPathFormat format)
a7b51bc8 355{
9e1c7236
VZ
356 // we should ignore paths which look like UNC shares because we already
357 // have the volume here and the UNC notation (\\server\path) is only valid
358 // for paths which don't start with a volume, so prevent SetPath() from
359 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
360 //
361 // note also that this is a rather ugly way to do what we want (passing
362 // some kind of flag telling to ignore UNC paths to SetPath() would be
363 // better) but this is the safest thing to do to avoid breaking backwards
364 // compatibility in 2.8
365 if ( IsUNCPath(path, format) )
366 {
367 // remove one of the 2 leading backslashes to ensure that it's not
368 // recognized as an UNC path by SetPath()
369 wxString pathNonUNC(path, 1, wxString::npos);
370 SetPath(pathNonUNC, format);
371 }
372 else // no UNC complications
373 {
374 SetPath(path, format);
375 }
a7b51bc8
RR
376
377 m_volume = volume;
378 m_ext = ext;
379 m_name = name;
dfecbee5
VZ
380
381 m_hasExt = hasExt;
a7b51bc8
RR
382}
383
f1e77933 384void wxFileName::SetPath( const wxString& pathOrig, wxPathFormat format )
df5ddbca 385{
844f90fb 386 m_dirs.Clear();
90a68369 387
f1e77933 388 if ( pathOrig.empty() )
df5ddbca 389 {
f1e77933
VZ
390 // no path at all
391 m_relative = true;
a2fa5040 392
f1e77933
VZ
393 return;
394 }
90a68369 395
f1e77933 396 format = GetFormat( format );
a2fa5040 397
f1e77933
VZ
398 // 0) deal with possible volume part first
399 wxString volume,
400 path;
401 SplitVolume(pathOrig, &volume, &path, format);
402 if ( !volume.empty() )
403 {
404 m_relative = false;
a2fa5040 405
f1e77933
VZ
406 SetVolume(volume);
407 }
f363e05c 408
f1e77933 409 // 1) Determine if the path is relative or absolute.
0f506ded
VZ
410
411 if ( path.empty() )
412 {
413 // we had only the volume
414 return;
415 }
416
f1e77933 417 wxChar leadingChar = path[0u];
a2fa5040 418
f1e77933
VZ
419 switch (format)
420 {
421 case wxPATH_MAC:
422 m_relative = leadingChar == wxT(':');
423
424 // We then remove a leading ":". The reason is in our
425 // storage form for relative paths:
426 // ":dir:file.txt" actually means "./dir/file.txt" in
427 // DOS notation and should get stored as
428 // (relative) (dir) (file.txt)
429 // "::dir:file.txt" actually means "../dir/file.txt"
430 // stored as (relative) (..) (dir) (file.txt)
431 // This is important only for the Mac as an empty dir
432 // actually means <UP>, whereas under DOS, double
433 // slashes can be ignored: "\\\\" is the same as "\\".
434 if (m_relative)
435 path.erase( 0, 1 );
436 break;
a2fa5040 437
f1e77933
VZ
438 case wxPATH_VMS:
439 // TODO: what is the relative path format here?
440 m_relative = false;
441 break;
90a68369 442
f1e77933 443 default:
9a83f860 444 wxFAIL_MSG( wxT("Unknown path format") );
f1e77933 445 // !! Fall through !!
90a68369 446
f1e77933 447 case wxPATH_UNIX:
be5be16a 448 m_relative = leadingChar != wxT('/');
f1e77933 449 break;
353f41cb 450
f1e77933
VZ
451 case wxPATH_DOS:
452 m_relative = !IsPathSeparator(leadingChar, format);
453 break;
844f90fb 454
df5ddbca 455 }
f1e77933
VZ
456
457 // 2) Break up the path into its members. If the original path
458 // was just "/" or "\\", m_dirs will be empty. We know from
459 // the m_relative field, if this means "nothing" or "root dir".
460
461 wxStringTokenizer tn( path, GetPathSeparators(format) );
462
463 while ( tn.HasMoreTokens() )
a7b51bc8 464 {
f1e77933
VZ
465 wxString token = tn.GetNextToken();
466
467 // Remove empty token under DOS and Unix, interpret them
468 // as .. under Mac.
469 if (token.empty())
470 {
471 if (format == wxPATH_MAC)
472 m_dirs.Add( wxT("..") );
473 // else ignore
474 }
475 else
476 {
477 m_dirs.Add( token );
478 }
a7b51bc8 479 }
844f90fb
VZ
480}
481
482void wxFileName::Assign(const wxString& fullpath,
483 wxPathFormat format)
484{
04c943b1 485 wxString volume, path, name, ext;
dfecbee5
VZ
486 bool hasExt;
487 SplitPath(fullpath, &volume, &path, &name, &ext, &hasExt, format);
844f90fb 488
dfecbee5 489 Assign(volume, path, name, ext, hasExt, format);
844f90fb
VZ
490}
491
81f25632 492void wxFileName::Assign(const wxString& fullpathOrig,
844f90fb
VZ
493 const wxString& fullname,
494 wxPathFormat format)
495{
81f25632
VZ
496 // always recognize fullpath as directory, even if it doesn't end with a
497 // slash
498 wxString fullpath = fullpathOrig;
69858116 499 if ( !fullpath.empty() && !wxEndsWithPathSeparator(fullpath) )
81f25632 500 {
33b97389 501 fullpath += GetPathSeparator(format);
81f25632
VZ
502 }
503
52dbd056 504 wxString volume, path, name, ext;
dfecbee5 505 bool hasExt;
81f25632 506
4b6a582b
VZ
507 // do some consistency checks: the name should be really just the filename
508 // and the path should be really just a path
dfecbee5 509 wxString volDummy, pathDummy, nameDummy, extDummy;
81f25632 510
dfecbee5 511 SplitPath(fullname, &volDummy, &pathDummy, &name, &ext, &hasExt, format);
81f25632 512
dfecbee5 513 wxASSERT_MSG( volDummy.empty() && pathDummy.empty(),
9a83f860 514 wxT("the file name shouldn't contain the path") );
81f25632
VZ
515
516 SplitPath(fullpath, &volume, &path, &nameDummy, &extDummy, format);
517
4c914788
JJ
518#ifndef __VMS
519 // This test makes no sense on an OpenVMS system.
520 wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
9a83f860 521 wxT("the path shouldn't contain file name nor extension") );
4c914788 522#endif
dfecbee5 523 Assign(volume, path, name, ext, hasExt, format);
52dbd056
VZ
524}
525
4c2deb19
VZ
526void wxFileName::Assign(const wxString& pathOrig,
527 const wxString& name,
528 const wxString& ext,
529 wxPathFormat format)
530{
531 wxString volume,
532 path;
533 SplitVolume(pathOrig, &volume, &path, format);
534
535 Assign(volume, path, name, ext, format);
536}
537
52dbd056
VZ
538void wxFileName::AssignDir(const wxString& dir, wxPathFormat format)
539{
b494c48b 540 Assign(dir, wxEmptyString, format);
844f90fb
VZ
541}
542
543void wxFileName::Clear()
544{
545 m_dirs.Clear();
04c943b1
VZ
546
547 m_volume =
844f90fb
VZ
548 m_name =
549 m_ext = wxEmptyString;
fb969475
VZ
550
551 // we don't have any absolute path for now
f363e05c 552 m_relative = true;
dfecbee5
VZ
553
554 // nor any extension
555 m_hasExt = false;
844f90fb
VZ
556}
557
558/* static */
520200fd 559wxFileName wxFileName::FileName(const wxString& file, wxPathFormat format)
844f90fb 560{
520200fd 561 return wxFileName(file, format);
844f90fb
VZ
562}
563
564/* static */
520200fd 565wxFileName wxFileName::DirName(const wxString& dir, wxPathFormat format)
844f90fb
VZ
566{
567 wxFileName fn;
520200fd 568 fn.AssignDir(dir, format);
844f90fb 569 return fn;
df5ddbca
RR
570}
571
844f90fb
VZ
572// ----------------------------------------------------------------------------
573// existence tests
574// ----------------------------------------------------------------------------
575
8e41796c 576bool wxFileName::FileExists() const
df5ddbca 577{
a35b27b1
RR
578 return wxFileName::FileExists( GetFullPath() );
579}
580
5bb59666
VZ
581/* static */
582bool wxFileName::FileExists( const wxString &filePath )
a35b27b1 583{
85b1997c 584#if defined(__WXPALMOS__)
5bb59666
VZ
585 return false;
586#elif defined(__WIN32__) && !defined(__WXMICROWIN__)
587 // we must use GetFileAttributes() instead of the ANSI C functions because
588 // it can cope with network (UNC) paths unlike them
589 DWORD ret = ::GetFileAttributes(filePath.fn_str());
590
591 return (ret != INVALID_FILE_ATTRIBUTES) && !(ret & FILE_ATTRIBUTE_DIRECTORY);
592#else // !__WIN32__
593 #ifndef S_ISREG
594 #define S_ISREG(mode) ((mode) & S_IFREG)
595 #endif
596 wxStructStat st;
597#ifndef wxNEED_WX_UNISTD_H
598 return (wxStat( filePath.fn_str() , &st) == 0 && S_ISREG(st.st_mode))
599#ifdef __OS2__
600 || (errno == EACCES) // if access is denied something with that name
601 // exists and is opened in exclusive mode.
602#endif
603 ;
604#else
605 return wxStat( filePath , &st) == 0 && S_ISREG(st.st_mode);
606#endif
607#endif // __WIN32__/!__WIN32__
df5ddbca
RR
608}
609
8e41796c 610bool wxFileName::DirExists() const
df5ddbca 611{
db759dde 612 return wxFileName::DirExists( GetPath() );
a35b27b1
RR
613}
614
5bb59666
VZ
615/* static */
616bool wxFileName::DirExists( const wxString &dirPath )
a35b27b1 617{
5bb59666
VZ
618 wxString strPath(dirPath);
619
620#if defined(__WINDOWS__) || defined(__OS2__)
621 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
622 // so remove all trailing backslashes from the path - but don't do this for
623 // the paths "d:\" (which are different from "d:") nor for just "\"
624 while ( wxEndsWithPathSeparator(strPath) )
625 {
626 size_t len = strPath.length();
627 if ( len == 1 || (len == 3 && strPath[len - 2] == wxT(':')) )
628 break;
629
630 strPath.Truncate(len - 1);
631 }
632#endif // __WINDOWS__
633
634#ifdef __OS2__
635 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
636 if (strPath.length() == 2 && strPath[1u] == wxT(':'))
637 strPath << wxT('.');
638#endif
639
640#if defined(__WXPALMOS__)
641 return false;
642#elif defined(__WIN32__) && !defined(__WXMICROWIN__)
643 // stat() can't cope with network paths
644 DWORD ret = ::GetFileAttributes(strPath.fn_str());
645
646 return (ret != INVALID_FILE_ATTRIBUTES) && (ret & FILE_ATTRIBUTE_DIRECTORY);
647#elif defined(__OS2__)
648 FILESTATUS3 Info = {{0}};
649 APIRET rc = ::DosQueryPathInfo((PSZ)(WXSTRINGCAST strPath), FIL_STANDARD,
650 (void*) &Info, sizeof(FILESTATUS3));
651
652 return ((rc == NO_ERROR) && (Info.attrFile & FILE_DIRECTORY)) ||
653 (rc == ERROR_SHARING_VIOLATION);
654 // If we got a sharing violation, there must be something with this name.
655#else // !__WIN32__
656
657 wxStructStat st;
658#ifndef __VISAGECPP__
659 return wxStat(strPath.c_str(), &st) == 0 && ((st.st_mode & S_IFMT) == S_IFDIR);
660#else
661 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
662 return wxStat(strPath.c_str(), &st) == 0 && (st.st_mode == S_IFDIR);
663#endif
664
665#endif // __WIN32__/!__WIN32__
df5ddbca
RR
666}
667
844f90fb
VZ
668// ----------------------------------------------------------------------------
669// CWD and HOME stuff
670// ----------------------------------------------------------------------------
671
6f91bc33 672void wxFileName::AssignCwd(const wxString& volume)
df5ddbca 673{
6f91bc33 674 AssignDir(wxFileName::GetCwd(volume));
a35b27b1
RR
675}
676
844f90fb 677/* static */
6f91bc33 678wxString wxFileName::GetCwd(const wxString& volume)
a35b27b1 679{
6f91bc33
VZ
680 // if we have the volume, we must get the current directory on this drive
681 // and to do this we have to chdir to this volume - at least under Windows,
682 // I don't know how to get the current drive on another volume elsewhere
683 // (TODO)
684 wxString cwdOld;
685 if ( !volume.empty() )
686 {
687 cwdOld = wxGetCwd();
688 SetCwd(volume + GetVolumeSeparator());
689 }
690
691 wxString cwd = ::wxGetCwd();
692
693 if ( !volume.empty() )
694 {
695 SetCwd(cwdOld);
696 }
ae4d7004 697
6f91bc33 698 return cwd;
a35b27b1
RR
699}
700
d9e80dce 701bool wxFileName::SetCwd() const
a35b27b1 702{
db759dde 703 return wxFileName::SetCwd( GetPath() );
df5ddbca
RR
704}
705
a35b27b1 706bool wxFileName::SetCwd( const wxString &cwd )
df5ddbca 707{
a35b27b1 708 return ::wxSetWorkingDirectory( cwd );
df5ddbca
RR
709}
710
a35b27b1
RR
711void wxFileName::AssignHomeDir()
712{
844f90fb 713 AssignDir(wxFileName::GetHomeDir());
a35b27b1 714}
844f90fb 715
a35b27b1
RR
716wxString wxFileName::GetHomeDir()
717{
718 return ::wxGetHomeDir();
719}
844f90fb 720
68351053 721
b70a2866
MW
722// ----------------------------------------------------------------------------
723// CreateTempFileName
724// ----------------------------------------------------------------------------
725
726#if wxUSE_FILE || wxUSE_FFILE
727
728
729#if !defined wx_fdopen && defined HAVE_FDOPEN
730 #define wx_fdopen fdopen
731#endif
732
733// NB: GetTempFileName() under Windows creates the file, so using
734// O_EXCL there would fail
735#ifdef __WINDOWS__
736 #define wxOPEN_EXCL 0
737#else
738 #define wxOPEN_EXCL O_EXCL
739#endif
740
741
742#ifdef wxOpenOSFHandle
743#define WX_HAVE_DELETE_ON_CLOSE
744// On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
745//
746static int wxOpenWithDeleteOnClose(const wxString& filename)
df5ddbca 747{
b70a2866
MW
748 DWORD access = GENERIC_READ | GENERIC_WRITE;
749
750 DWORD disposition = OPEN_ALWAYS;
751
752 DWORD attributes = FILE_ATTRIBUTE_TEMPORARY |
753 FILE_FLAG_DELETE_ON_CLOSE;
754
e0a050e3 755 HANDLE h = ::CreateFile(filename.fn_str(), access, 0, NULL,
b70a2866
MW
756 disposition, attributes, NULL);
757
693bfcaf 758 return wxOpenOSFHandle(h, wxO_BINARY);
ade35f11 759}
b70a2866 760#endif // wxOpenOSFHandle
ade35f11 761
b70a2866
MW
762
763// Helper to open the file
764//
765static int wxTempOpen(const wxString& path, bool *deleteOnClose)
766{
767#ifdef WX_HAVE_DELETE_ON_CLOSE
768 if (*deleteOnClose)
769 return wxOpenWithDeleteOnClose(path);
770#endif
771
772 *deleteOnClose = false;
773
774 return wxOpen(path, wxO_BINARY | O_RDWR | O_CREAT | wxOPEN_EXCL, 0600);
775}
776
777
778#if wxUSE_FFILE
779// Helper to open the file and attach it to the wxFFile
780//
781static bool wxTempOpen(wxFFile *file, const wxString& path, bool *deleteOnClose)
ade35f11 782{
b70a2866
MW
783#ifndef wx_fdopen
784 *deleteOnClose = false;
9a83f860 785 return file->Open(path, wxT("w+b"));
b70a2866
MW
786#else // wx_fdopen
787 int fd = wxTempOpen(path, deleteOnClose);
693bfcaf 788 if (fd == -1)
b70a2866
MW
789 return false;
790 file->Attach(wx_fdopen(fd, "w+b"));
791 return file->IsOpened();
792#endif // wx_fdopen
793}
794#endif // wxUSE_FFILE
795
796
797#if !wxUSE_FILE
798 #define WXFILEARGS(x, y) y
799#elif !wxUSE_FFILE
800 #define WXFILEARGS(x, y) x
801#else
802 #define WXFILEARGS(x, y) x, y
803#endif
804
805
806// Implementation of wxFileName::CreateTempFileName().
807//
808static wxString wxCreateTempImpl(
809 const wxString& prefix,
810 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
811 bool *deleteOnClose = NULL)
812{
813#if wxUSE_FILE && wxUSE_FFILE
814 wxASSERT(fileTemp == NULL || ffileTemp == NULL);
815#endif
ade35f11 816 wxString path, dir, name;
b70a2866
MW
817 bool wantDeleteOnClose = false;
818
819 if (deleteOnClose)
820 {
821 // set the result to false initially
822 wantDeleteOnClose = *deleteOnClose;
823 *deleteOnClose = false;
824 }
825 else
826 {
827 // easier if it alwasys points to something
828 deleteOnClose = &wantDeleteOnClose;
829 }
ade35f11
VZ
830
831 // use the directory specified by the prefix
b70a2866 832 wxFileName::SplitPath(prefix, &dir, &name, NULL /* extension */);
ade35f11 833
6091caf0
JS
834 if (dir.empty())
835 {
8d7d6dea 836 dir = wxFileName::GetTempDir();
6091caf0
JS
837 }
838
1c193821 839#if defined(__WXWINCE__)
f05ba7ff 840 path = dir + wxT("\\") + name;
1c193821 841 int i = 1;
b70a2866 842 while (wxFileName::FileExists(path))
1c193821 843 {
f05ba7ff 844 path = dir + wxT("\\") + name ;
1c193821
JS
845 path << i;
846 i ++;
847 }
ade35f11 848
1c193821 849#elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
e0a050e3
VS
850 if ( !::GetTempFileName(dir.fn_str(), name.fn_str(), 0,
851 wxStringBuffer(path, MAX_PATH + 1)) )
ade35f11 852 {
9a83f860 853 wxLogLastError(wxT("GetTempFileName"));
ade35f11
VZ
854
855 path.clear();
856 }
ade35f11 857
5a3912f2 858#else // !Windows
ade35f11
VZ
859 path = dir;
860
861 if ( !wxEndsWithPathSeparator(dir) &&
862 (name.empty() || !wxIsPathSeparator(name[0u])) )
863 {
d9f54bb0 864 path += wxFILE_SEP_PATH;
ade35f11
VZ
865 }
866
867 path += name;
868
7070f55b 869#if defined(HAVE_MKSTEMP)
ade35f11 870 // scratch space for mkstemp()
9a83f860 871 path += wxT("XXXXXX");
ade35f11 872
74cf9763 873 // we need to copy the path to the buffer in which mkstemp() can modify it
86501081 874 wxCharBuffer buf(path.fn_str());
74cf9763
VZ
875
876 // cast is safe because the string length doesn't change
ca11abde 877 int fdTemp = mkstemp( (char*)(const char*) buf );
df22f860 878 if ( fdTemp == -1 )
ade35f11
VZ
879 {
880 // this might be not necessary as mkstemp() on most systems should have
881 // already done it but it doesn't hurt neither...
882 path.clear();
883 }
df22f860
VZ
884 else // mkstemp() succeeded
885 {
ca11abde 886 path = wxConvFile.cMB2WX( (const char*) buf );
a62848fd 887
b70a2866 888 #if wxUSE_FILE
df22f860
VZ
889 // avoid leaking the fd
890 if ( fileTemp )
891 {
892 fileTemp->Attach(fdTemp);
893 }
894 else
b70a2866
MW
895 #endif
896
897 #if wxUSE_FFILE
898 if ( ffileTemp )
899 {
900 #ifdef wx_fdopen
901 ffileTemp->Attach(wx_fdopen(fdTemp, "r+b"));
902 #else
9a83f860 903 ffileTemp->Open(path, wxT("r+b"));
b70a2866
MW
904 close(fdTemp);
905 #endif
906 }
907 else
908 #endif
909
df22f860
VZ
910 {
911 close(fdTemp);
912 }
913 }
ade35f11
VZ
914#else // !HAVE_MKSTEMP
915
916#ifdef HAVE_MKTEMP
917 // same as above
9a83f860 918 path += wxT("XXXXXX");
ade35f11 919
ca11abde 920 wxCharBuffer buf = wxConvFile.cWX2MB( path );
b70a2866 921 if ( !mktemp( (char*)(const char*) buf ) )
ade35f11
VZ
922 {
923 path.clear();
924 }
aed08d79
RR
925 else
926 {
ca11abde 927 path = wxConvFile.cMB2WX( (const char*) buf );
aed08d79 928 }
7070f55b 929#else // !HAVE_MKTEMP (includes __DOS__)
ade35f11 930 // generate the unique file name ourselves
68351053 931 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
ade35f11 932 path << (unsigned int)getpid();
7070f55b 933 #endif
ade35f11
VZ
934
935 wxString pathTry;
936
937 static const size_t numTries = 1000;
938 for ( size_t n = 0; n < numTries; n++ )
939 {
940 // 3 hex digits is enough for numTries == 1000 < 4096
9a83f860 941 pathTry = path + wxString::Format(wxT("%.03x"), (unsigned int) n);
b70a2866 942 if ( !wxFileName::FileExists(pathTry) )
ade35f11
VZ
943 {
944 break;
945 }
946
947 pathTry.clear();
948 }
949
950 path = pathTry;
951#endif // HAVE_MKTEMP/!HAVE_MKTEMP
952
df22f860
VZ
953#endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
954
955#endif // Windows/!Windows
956
957 if ( path.empty() )
958 {
959 wxLogSysError(_("Failed to create a temporary file name"));
960 }
b70a2866 961 else
df22f860 962 {
b70a2866
MW
963 bool ok = true;
964
df22f860 965 // open the file - of course, there is a race condition here, this is
ade35f11 966 // why we always prefer using mkstemp()...
b70a2866
MW
967 #if wxUSE_FILE
968 if ( fileTemp && !fileTemp->IsOpened() )
969 {
970 *deleteOnClose = wantDeleteOnClose;
971 int fd = wxTempOpen(path, deleteOnClose);
972 if (fd != -1)
973 fileTemp->Attach(fd);
974 else
975 ok = false;
976 }
977 #endif
978
979 #if wxUSE_FFILE
980 if ( ffileTemp && !ffileTemp->IsOpened() )
981 {
982 *deleteOnClose = wantDeleteOnClose;
983 ok = wxTempOpen(ffileTemp, path, deleteOnClose);
984 }
985 #endif
986
987 if ( !ok )
ade35f11
VZ
988 {
989 // FIXME: If !ok here should we loop and try again with another
990 // file name? That is the standard recourse if open(O_EXCL)
991 // fails, though of course it should be protected against
992 // possible infinite looping too.
993
994 wxLogError(_("Failed to open temporary file."));
995
996 path.clear();
997 }
998 }
ade35f11
VZ
999
1000 return path;
df5ddbca
RR
1001}
1002
b70a2866
MW
1003
1004static bool wxCreateTempImpl(
1005 const wxString& prefix,
1006 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
1007 wxString *name)
1008{
1009 bool deleteOnClose = true;
1010
1011 *name = wxCreateTempImpl(prefix,
1012 WXFILEARGS(fileTemp, ffileTemp),
1013 &deleteOnClose);
1014
1015 bool ok = !name->empty();
1016
1017 if (deleteOnClose)
1018 name->clear();
1019#ifdef __UNIX__
1020 else if (ok && wxRemoveFile(*name))
1021 name->clear();
1022#endif
1023
1024 return ok;
1025}
1026
1027
1028static void wxAssignTempImpl(
1029 wxFileName *fn,
1030 const wxString& prefix,
1031 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp))
1032{
1033 wxString tempname;
1034 tempname = wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, ffileTemp));
1035
1036 if ( tempname.empty() )
1037 {
1038 // error, failed to get temp file name
1039 fn->Clear();
1040 }
1041 else // ok
1042 {
1043 fn->Assign(tempname);
1044 }
1045}
1046
1047
1048void wxFileName::AssignTempFileName(const wxString& prefix)
1049{
1050 wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, NULL));
1051}
1052
1053/* static */
1054wxString wxFileName::CreateTempFileName(const wxString& prefix)
1055{
1056 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, NULL));
1057}
1058
1059#endif // wxUSE_FILE || wxUSE_FFILE
1060
1061
1062#if wxUSE_FILE
1063
1064wxString wxCreateTempFileName(const wxString& prefix,
1065 wxFile *fileTemp,
1066 bool *deleteOnClose)
1067{
1068 return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), deleteOnClose);
1069}
1070
1071bool wxCreateTempFile(const wxString& prefix,
1072 wxFile *fileTemp,
1073 wxString *name)
1074{
1075 return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), name);
1076}
1077
1078void wxFileName::AssignTempFileName(const wxString& prefix, wxFile *fileTemp)
1079{
1080 wxAssignTempImpl(this, prefix, WXFILEARGS(fileTemp, NULL));
1081}
1082
1083/* static */
1084wxString
1085wxFileName::CreateTempFileName(const wxString& prefix, wxFile *fileTemp)
1086{
1087 return wxCreateTempFileName(prefix, fileTemp);
1088}
1089
68351053
WS
1090#endif // wxUSE_FILE
1091
b70a2866
MW
1092
1093#if wxUSE_FFILE
1094
1095wxString wxCreateTempFileName(const wxString& prefix,
1096 wxFFile *fileTemp,
1097 bool *deleteOnClose)
1098{
1099 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), deleteOnClose);
1100}
1101
1102bool wxCreateTempFile(const wxString& prefix,
1103 wxFFile *fileTemp,
1104 wxString *name)
1105{
1106 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), name);
1107
1108}
1109
1110void wxFileName::AssignTempFileName(const wxString& prefix, wxFFile *fileTemp)
1111{
1112 wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, fileTemp));
1113}
1114
1115/* static */
1116wxString
1117wxFileName::CreateTempFileName(const wxString& prefix, wxFFile *fileTemp)
1118{
1119 return wxCreateTempFileName(prefix, fileTemp);
1120}
1121
1122#endif // wxUSE_FFILE
1123
1124
844f90fb
VZ
1125// ----------------------------------------------------------------------------
1126// directory operations
1127// ----------------------------------------------------------------------------
1128
8758875e
VZ
1129// helper of GetTempDir(): check if the given directory exists and return it if
1130// it does or an empty string otherwise
1131namespace
8d7d6dea 1132{
8d7d6dea 1133
8758875e
VZ
1134wxString CheckIfDirExists(const wxString& dir)
1135{
1136 return wxFileName::DirExists(dir) ? dir : wxString();
1137}
1138
1139} // anonymous namespace
1140
1141wxString wxFileName::GetTempDir()
1142{
1143 // first try getting it from environment: this allows overriding the values
1144 // used by default if the user wants to create temporary files in another
1145 // directory
1146 wxString dir = CheckIfDirExists(wxGetenv("TMPDIR"));
1147 if ( dir.empty() )
8d7d6dea 1148 {
8758875e
VZ
1149 dir = CheckIfDirExists(wxGetenv("TMP"));
1150 if ( dir.empty() )
1151 dir = CheckIfDirExists(wxGetenv("TEMP"));
8d7d6dea 1152 }
8d7d6dea 1153
8758875e 1154 // if no environment variables are set, use the system default
8d7d6dea
JS
1155 if ( dir.empty() )
1156 {
8758875e
VZ
1157#if defined(__WXWINCE__)
1158 dir = CheckIfDirExists(wxT("\\temp"));
1159#elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
8d7d6dea
JS
1160 if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
1161 {
9a83f860 1162 wxLogLastError(wxT("GetTempPath"));
8d7d6dea 1163 }
8758875e
VZ
1164#elif defined(__WXMAC__) && wxOSX_USE_CARBON
1165 dir = wxMacFindFolder(short(kOnSystemDisk), kTemporaryFolderType, kCreateFolder);
1166#endif // systems with native way
8d7d6dea 1167 }
8d7d6dea 1168
8758875e 1169 // fall back to hard coded value
8d7d6dea
JS
1170 if ( dir.empty() )
1171 {
8758875e
VZ
1172#ifdef __UNIX_LIKE__
1173 dir = CheckIfDirExists("/tmp");
1174 if ( dir.empty() )
1175#endif // __UNIX_LIKE__
1176 dir = ".";
8d7d6dea 1177 }
8d7d6dea
JS
1178
1179 return dir;
1180}
1181
89391a4e 1182bool wxFileName::Mkdir( int perm, int flags ) const
a35b27b1 1183{
db759dde 1184 return wxFileName::Mkdir(GetPath(), perm, flags);
a35b27b1
RR
1185}
1186
1527281e 1187bool wxFileName::Mkdir( const wxString& dir, int perm, int flags )
df5ddbca 1188{
1527281e 1189 if ( flags & wxPATH_MKDIR_FULL )
f0ce3409 1190 {
1527281e
VZ
1191 // split the path in components
1192 wxFileName filename;
1193 filename.AssignDir(dir);
f0ce3409 1194
f0ce3409 1195 wxString currPath;
0ea621cc
VZ
1196 if ( filename.HasVolume())
1197 {
1527281e 1198 currPath << wxGetVolumeString(filename.GetVolume(), wxPATH_NATIVE);
0ea621cc 1199 }
f0ce3409 1200
1527281e
VZ
1201 wxArrayString dirs = filename.GetDirs();
1202 size_t count = dirs.GetCount();
1203 for ( size_t i = 0; i < count; i++ )
1204 {
e0d81eac 1205 if ( i > 0 || filename.IsAbsolute() )
f0ce3409 1206 currPath += wxFILE_SEP_PATH;
1527281e 1207 currPath += dirs[i];
f0ce3409
JS
1208
1209 if (!DirExists(currPath))
1527281e 1210 {
f0ce3409 1211 if (!wxMkdir(currPath, perm))
1527281e
VZ
1212 {
1213 // no need to try creating further directories
f363e05c 1214 return false;
1527281e
VZ
1215 }
1216 }
f0ce3409
JS
1217 }
1218
f363e05c 1219 return true;
f0ce3409
JS
1220
1221 }
1527281e
VZ
1222
1223 return ::wxMkdir( dir, perm );
df5ddbca
RR
1224}
1225
89391a4e 1226bool wxFileName::Rmdir(int flags) const
df5ddbca 1227{
110c5094 1228 return wxFileName::Rmdir( GetPath(), flags );
df5ddbca
RR
1229}
1230
110c5094 1231bool wxFileName::Rmdir(const wxString& dir, int flags)
df5ddbca 1232{
110c5094
VZ
1233#ifdef __WXMSW__
1234 if ( flags & wxPATH_RMDIR_RECURSIVE )
1235 {
1236 // SHFileOperation needs double null termination string
1237 // but without separator at the end of the path
1238 wxString path(dir);
1239 if ( path.Last() == wxFILE_SEP_PATH )
1240 path.RemoveLast();
9a83f860 1241 path += wxT('\0');
110c5094
VZ
1242
1243 SHFILEOPSTRUCT fileop;
1244 wxZeroMemory(fileop);
1245 fileop.wFunc = FO_DELETE;
1246 fileop.pFrom = path.fn_str();
1247 fileop.fFlags = FOF_SILENT | FOF_NOCONFIRMATION;
1248 #ifndef __WXWINCE__
1249 // FOF_NOERRORUI is not defined in WinCE
1250 fileop.fFlags |= FOF_NOERRORUI;
1251 #endif
1252
1253 int ret = SHFileOperation(&fileop);
1254 if ( ret != 0 )
1255 {
1256 // SHFileOperation may return non-Win32 error codes, so the error
1257 // message can be incorrect
9a83f860 1258 wxLogApiError(wxT("SHFileOperation"), ret);
110c5094
VZ
1259 return false;
1260 }
1261
1262 return true;
1263 }
1264 else if ( flags & wxPATH_RMDIR_FULL )
1265#else // !__WXMSW__
1266 if ( flags != 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1267#endif // !__WXMSW__
1268 {
1269 wxString path(dir);
1270 if ( path.Last() != wxFILE_SEP_PATH )
1271 path += wxFILE_SEP_PATH;
1272
1273 wxDir d(path);
1274
1275 if ( !d.IsOpened() )
1276 return false;
1277
1278 wxString filename;
1279
1280 // first delete all subdirectories
1281 bool cont = d.GetFirst(&filename, "", wxDIR_DIRS | wxDIR_HIDDEN);
1282 while ( cont )
1283 {
1284 wxFileName::Rmdir(path + filename, flags);
1285 cont = d.GetNext(&filename);
1286 }
1287
1288#ifndef __WXMSW__
1289 if ( flags & wxPATH_RMDIR_RECURSIVE )
1290 {
1291 // delete all files too
1292 cont = d.GetFirst(&filename, "", wxDIR_FILES | wxDIR_HIDDEN);
1293 while ( cont )
1294 {
1295 ::wxRemoveFile(path + filename);
1296 cont = d.GetNext(&filename);
1297 }
1298 }
1299#endif // !__WXMSW__
1300 }
1301
1302 return ::wxRmdir(dir);
df5ddbca
RR
1303}
1304
844f90fb
VZ
1305// ----------------------------------------------------------------------------
1306// path normalization
1307// ----------------------------------------------------------------------------
1308
32a0d013 1309bool wxFileName::Normalize(int flags,
844f90fb
VZ
1310 const wxString& cwd,
1311 wxPathFormat format)
a35b27b1 1312{
05e1201c
VZ
1313 // deal with env vars renaming first as this may seriously change the path
1314 if ( flags & wxPATH_NORM_ENV_VARS )
1315 {
1316 wxString pathOrig = GetFullPath(format);
1317 wxString path = wxExpandEnvVars(pathOrig);
1318 if ( path != pathOrig )
1319 {
1320 Assign(path);
1321 }
1322 }
1323
844f90fb
VZ
1324 // the existing path components
1325 wxArrayString dirs = GetDirs();
1326
1327 // the path to prepend in front to make the path absolute
1328 wxFileName curDir;
1329
1330 format = GetFormat(format);
ae4d7004 1331
bf7f7793 1332 // set up the directory to use for making the path absolute later
a2fa5040 1333 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute(format) )
a35b27b1 1334 {
844f90fb 1335 if ( cwd.empty() )
6f91bc33
VZ
1336 {
1337 curDir.AssignCwd(GetVolume());
1338 }
1339 else // cwd provided
1340 {
844f90fb 1341 curDir.AssignDir(cwd);
6f91bc33 1342 }
a35b27b1 1343 }
ae4d7004 1344
844f90fb 1345 // handle ~ stuff under Unix only
be5be16a 1346 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) && m_relative )
a35b27b1 1347 {
844f90fb
VZ
1348 if ( !dirs.IsEmpty() )
1349 {
1350 wxString dir = dirs[0u];
9a83f860 1351 if ( !dir.empty() && dir[0u] == wxT('~') )
844f90fb 1352 {
bf7f7793 1353 // to make the path absolute use the home directory
844f90fb 1354 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
da2fd5ac 1355 dirs.RemoveAt(0u);
844f90fb
VZ
1356 }
1357 }
a35b27b1 1358 }
844f90fb 1359
52dbd056 1360 // transform relative path into abs one
844f90fb 1361 if ( curDir.IsOk() )
a35b27b1 1362 {
bf7f7793
RR
1363 // this path may be relative because it doesn't have the volume name
1364 // and still have m_relative=true; in this case we shouldn't modify
1365 // our directory components but just set the current volume
1366 if ( !HasVolume() && curDir.HasVolume() )
844f90fb 1367 {
bf7f7793
RR
1368 SetVolume(curDir.GetVolume());
1369
1370 if ( !m_relative )
1371 {
1372 // yes, it was the case - we don't need curDir then
1373 curDir.Clear();
1374 }
844f90fb
VZ
1375 }
1376
bf7f7793
RR
1377 // finally, prepend curDir to the dirs array
1378 wxArrayString dirsNew = curDir.GetDirs();
1379 WX_PREPEND_ARRAY(dirs, dirsNew);
1380
1381 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1382 // return for some reason an absolute path, then curDir maybe not be absolute!
be5be16a 1383 if ( !curDir.m_relative )
bf7f7793
RR
1384 {
1385 // we have prepended an absolute path and thus we are now an absolute
1386 // file name too
1387 m_relative = false;
1388 }
1389 // else if (flags & wxPATH_NORM_ABSOLUTE):
1390 // should we warn the user that we didn't manage to make the path absolute?
a35b27b1 1391 }
844f90fb
VZ
1392
1393 // now deal with ".", ".." and the rest
1394 m_dirs.Empty();
1395 size_t count = dirs.GetCount();
1396 for ( size_t n = 0; n < count; n++ )
a35b27b1 1397 {
844f90fb
VZ
1398 wxString dir = dirs[n];
1399
2bc60417 1400 if ( flags & wxPATH_NORM_DOTS )
844f90fb
VZ
1401 {
1402 if ( dir == wxT(".") )
1403 {
1404 // just ignore
1405 continue;
1406 }
1407
1408 if ( dir == wxT("..") )
1409 {
1410 if ( m_dirs.IsEmpty() )
1411 {
1412 wxLogError(_("The path '%s' contains too many \"..\"!"),
1413 GetFullPath().c_str());
f363e05c 1414 return false;
844f90fb
VZ
1415 }
1416
ae4d7004 1417 m_dirs.RemoveAt(m_dirs.GetCount() - 1);
844f90fb
VZ
1418 continue;
1419 }
1420 }
1421
844f90fb 1422 m_dirs.Add(dir);
a35b27b1 1423 }
a62848fd 1424
6bda7391 1425#if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
21f60945
JS
1426 if ( (flags & wxPATH_NORM_SHORTCUT) )
1427 {
1428 wxString filename;
1429 if (GetShortcutTarget(GetFullPath(format), filename))
1430 {
21f60945
JS
1431 m_relative = false;
1432 Assign(filename);
1433 }
1434 }
1435#endif
844f90fb 1436
9a0c5c01
VZ
1437#if defined(__WIN32__)
1438 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
844f90fb 1439 {
9a0c5c01
VZ
1440 Assign(GetLongPath());
1441 }
1442#endif // Win32
844f90fb 1443
9a0c5c01
VZ
1444 // Change case (this should be kept at the end of the function, to ensure
1445 // that the path doesn't change any more after we normalize its case)
1446 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
1447 {
55268a3a 1448 m_volume.MakeLower();
844f90fb
VZ
1449 m_name.MakeLower();
1450 m_ext.MakeLower();
844f90fb 1451
9a0c5c01
VZ
1452 // directory entries must be made lower case as well
1453 count = m_dirs.GetCount();
1454 for ( size_t i = 0; i < count; i++ )
1455 {
1456 m_dirs[i].MakeLower();
1457 }
9e9b65c1 1458 }
9e9b65c1 1459
f363e05c 1460 return true;
a2fa5040
VZ
1461}
1462
395f3aa8
FM
1463#ifndef __WXWINCE__
1464bool wxFileName::ReplaceEnvVariable(const wxString& envname,
1465 const wxString& replacementFmtString,
1466 wxPathFormat format)
1467{
1468 // look into stringForm for the contents of the given environment variable
1469 wxString val;
1470 if (envname.empty() ||
1471 !wxGetEnv(envname, &val))
1472 return false;
1473 if (val.empty())
1474 return false;
1475
1476 wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
1477 // do not touch the file name and the extension
1478
1479 wxString replacement = wxString::Format(replacementFmtString, envname);
1480 stringForm.Replace(val, replacement);
1481
1482 // Now assign ourselves the modified path:
1483 Assign(stringForm, GetFullName(), format);
1484
1485 return true;
1486}
1487#endif
1488
1489bool wxFileName::ReplaceHomeDir(wxPathFormat format)
1490{
1491 wxString homedir = wxGetHomeDir();
1492 if (homedir.empty())
1493 return false;
1494
1495 wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
1496 // do not touch the file name and the extension
1497
1498 stringForm.Replace(homedir, "~");
1499
1500 // Now assign ourselves the modified path:
1501 Assign(stringForm, GetFullName(), format);
1502
1503 return true;
1504}
1505
21f60945
JS
1506// ----------------------------------------------------------------------------
1507// get the shortcut target
1508// ----------------------------------------------------------------------------
1509
5671b3b6
JS
1510// WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1511// The .lnk file is a plain text file so it should be easy to
1512// make it work. Hint from Google Groups:
1513// "If you open up a lnk file, you'll see a
1514// number, followed by a pound sign (#), followed by more text. The
1515// number is the number of characters that follows the pound sign. The
1516// characters after the pound sign are the command line (which _can_
1517// include arguments) to be executed. Any path (e.g. \windows\program
1518// files\myapp.exe) that includes spaces needs to be enclosed in
1519// quotation marks."
1520
6bda7391 1521#if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
5671b3b6
JS
1522// The following lines are necessary under WinCE
1523// #include "wx/msw/private.h"
1524// #include <ole2.h>
21f60945 1525#include <shlobj.h>
5671b3b6
JS
1526#if defined(__WXWINCE__)
1527#include <shlguid.h>
1528#endif
21f60945 1529
cea0869c
VZ
1530bool wxFileName::GetShortcutTarget(const wxString& shortcutPath,
1531 wxString& targetFilename,
d9e80dce 1532 wxString* arguments) const
21f60945 1533{
21f60945 1534 wxString path, file, ext;
bd365871 1535 wxFileName::SplitPath(shortcutPath, & path, & file, & ext);
a62848fd
WS
1536
1537 HRESULT hres;
1538 IShellLink* psl;
1539 bool success = false;
21f60945
JS
1540
1541 // Assume it's not a shortcut if it doesn't end with lnk
489f6cf7 1542 if (ext.CmpNoCase(wxT("lnk"))!=0)
a62848fd
WS
1543 return false;
1544
1545 // create a ShellLink object
1546 hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1547 IID_IShellLink, (LPVOID*) &psl);
1548
1549 if (SUCCEEDED(hres))
1550 {
1551 IPersistFile* ppf;
1552 hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
1553 if (SUCCEEDED(hres))
1554 {
1555 WCHAR wsz[MAX_PATH];
1556
1557 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
1558 MAX_PATH);
1559
1560 hres = ppf->Load(wsz, 0);
cea0869c
VZ
1561 ppf->Release();
1562
a62848fd
WS
1563 if (SUCCEEDED(hres))
1564 {
21f60945 1565 wxChar buf[2048];
59ba321b
JS
1566 // Wrong prototype in early versions
1567#if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1568 psl->GetPath((CHAR*) buf, 2048, NULL, SLGP_UNCPRIORITY);
1569#else
a62848fd 1570 psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
59ba321b 1571#endif
a62848fd 1572 targetFilename = wxString(buf);
21f60945
JS
1573 success = (shortcutPath != targetFilename);
1574
a62848fd 1575 psl->GetArguments(buf, 2048);
21f60945 1576 wxString args(buf);
b494c48b 1577 if (!args.empty() && arguments)
21f60945
JS
1578 {
1579 *arguments = args;
a62848fd
WS
1580 }
1581 }
1582 }
cea0869c
VZ
1583
1584 psl->Release();
a62848fd 1585 }
a62848fd 1586 return success;
21f60945 1587}
cea0869c
VZ
1588
1589#endif // __WIN32__ && !__WXWINCE__
21f60945
JS
1590
1591
a2fa5040
VZ
1592// ----------------------------------------------------------------------------
1593// absolute/relative paths
1594// ----------------------------------------------------------------------------
1595
1596bool wxFileName::IsAbsolute(wxPathFormat format) const
1597{
be5be16a
VZ
1598 // unix paths beginning with ~ are reported as being absolute
1599 if ( format == wxPATH_UNIX )
1600 {
1601 if ( !m_dirs.IsEmpty() )
1602 {
1603 wxString dir = m_dirs[0u];
1604
9a83f860 1605 if (!dir.empty() && dir[0u] == wxT('~'))
be5be16a
VZ
1606 return true;
1607 }
1608 }
1609
a2fa5040
VZ
1610 // if our path doesn't start with a path separator, it's not an absolute
1611 // path
1612 if ( m_relative )
f363e05c 1613 return false;
a2fa5040
VZ
1614
1615 if ( !GetVolumeSeparator(format).empty() )
1616 {
1617 // this format has volumes and an absolute path must have one, it's not
be5be16a 1618 // enough to have the full path to be an absolute file under Windows
a2fa5040 1619 if ( GetVolume().empty() )
f363e05c 1620 return false;
a2fa5040
VZ
1621 }
1622
f363e05c 1623 return true;
a35b27b1
RR
1624}
1625
f7d886af
VZ
1626bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
1627{
cef9731a 1628 wxFileName fnBase = wxFileName::DirName(pathBase, format);
f7d886af
VZ
1629
1630 // get cwd only once - small time saving
1631 wxString cwd = wxGetCwd();
b5b62eea
JS
1632 Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1633 fnBase.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
f7d886af
VZ
1634
1635 bool withCase = IsCaseSensitive(format);
1636
1637 // we can't do anything if the files live on different volumes
1638 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
1639 {
1640 // nothing done
f363e05c 1641 return false;
f7d886af
VZ
1642 }
1643
1644 // same drive, so we don't need our volume
1645 m_volume.clear();
1646
1647 // remove common directories starting at the top
1648 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
1649 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
1650 {
ae4d7004
VZ
1651 m_dirs.RemoveAt(0);
1652 fnBase.m_dirs.RemoveAt(0);
f7d886af
VZ
1653 }
1654
1655 // add as many ".." as needed
1656 size_t count = fnBase.m_dirs.GetCount();
1657 for ( size_t i = 0; i < count; i++ )
1658 {
1659 m_dirs.Insert(wxT(".."), 0u);
1660 }
90a68369 1661
2db991f4
VZ
1662 if ( format == wxPATH_UNIX || format == wxPATH_DOS )
1663 {
1664 // a directory made relative with respect to itself is '.' under Unix
1665 // and DOS, by definition (but we don't have to insert "./" for the
1666 // files)
1667 if ( m_dirs.IsEmpty() && IsDir() )
1668 {
9a83f860 1669 m_dirs.Add(wxT('.'));
0ea621cc 1670 }
2db991f4
VZ
1671 }
1672
f363e05c 1673 m_relative = true;
f7d886af
VZ
1674
1675 // we were modified
f363e05c 1676 return true;
f7d886af
VZ
1677}
1678
844f90fb
VZ
1679// ----------------------------------------------------------------------------
1680// filename kind tests
1681// ----------------------------------------------------------------------------
1682
2b5f62a0 1683bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const
df5ddbca 1684{
844f90fb
VZ
1685 wxFileName fn1 = *this,
1686 fn2 = filepath;
1687
1688 // get cwd only once - small time saving
1689 wxString cwd = wxGetCwd();
55268a3a
VZ
1690 fn1.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1691 fn2.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
844f90fb
VZ
1692
1693 if ( fn1.GetFullPath() == fn2.GetFullPath() )
f363e05c 1694 return true;
844f90fb
VZ
1695
1696 // TODO: compare inodes for Unix, this works even when filenames are
1697 // different but files are the same (symlinks) (VZ)
1698
f363e05c 1699 return false;
df5ddbca
RR
1700}
1701
844f90fb 1702/* static */
df5ddbca
RR
1703bool wxFileName::IsCaseSensitive( wxPathFormat format )
1704{
04c943b1
VZ
1705 // only Unix filenames are truely case-sensitive
1706 return GetFormat(format) == wxPATH_UNIX;
df5ddbca
RR
1707}
1708
f363e05c
VZ
1709/* static */
1710wxString wxFileName::GetForbiddenChars(wxPathFormat format)
1711{
1712 // Inits to forbidden characters that are common to (almost) all platforms.
1713 wxString strForbiddenChars = wxT("*?");
1714
1c6f2414 1715 // If asserts, wxPathFormat has been changed. In case of a new path format
f363e05c 1716 // addition, the following code might have to be updated.
1c6f2414 1717 wxCOMPILE_TIME_ASSERT(wxPATH_MAX == 5, wxPathFormatChanged);
f363e05c
VZ
1718 switch ( GetFormat(format) )
1719 {
1720 default :
1721 wxFAIL_MSG( wxT("Unknown path format") );
1722 // !! Fall through !!
1723
1724 case wxPATH_UNIX:
1725 break;
1726
1727 case wxPATH_MAC:
1728 // On a Mac even names with * and ? are allowed (Tested with OS
1729 // 9.2.1 and OS X 10.2.5)
1730 strForbiddenChars = wxEmptyString;
1731 break;
1732
1733 case wxPATH_DOS:
1734 strForbiddenChars += wxT("\\/:\"<>|");
1735 break;
1736
1737 case wxPATH_VMS:
1738 break;
1739 }
1740
1741 return strForbiddenChars;
1742}
1743
04c943b1 1744/* static */
bcfa2b31 1745wxString wxFileName::GetVolumeSeparator(wxPathFormat WXUNUSED_IN_WINCE(format))
844f90fb 1746{
bcfa2b31
WS
1747#ifdef __WXWINCE__
1748 return wxEmptyString;
1749#else
04c943b1
VZ
1750 wxString sepVol;
1751
a385b5df
RR
1752 if ( (GetFormat(format) == wxPATH_DOS) ||
1753 (GetFormat(format) == wxPATH_VMS) )
04c943b1 1754 {
04c943b1
VZ
1755 sepVol = wxFILE_SEP_DSK;
1756 }
a385b5df 1757 //else: leave empty
04c943b1
VZ
1758
1759 return sepVol;
bcfa2b31 1760#endif
844f90fb
VZ
1761}
1762
1763/* static */
1764wxString wxFileName::GetPathSeparators(wxPathFormat format)
1765{
1766 wxString seps;
1767 switch ( GetFormat(format) )
df5ddbca 1768 {
844f90fb 1769 case wxPATH_DOS:
04c943b1
VZ
1770 // accept both as native APIs do but put the native one first as
1771 // this is the one we use in GetFullPath()
1772 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
844f90fb
VZ
1773 break;
1774
1775 default:
9a83f860 1776 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
844f90fb
VZ
1777 // fall through
1778
1779 case wxPATH_UNIX:
9e8d8607 1780 seps = wxFILE_SEP_PATH_UNIX;
844f90fb
VZ
1781 break;
1782
1783 case wxPATH_MAC:
9e8d8607 1784 seps = wxFILE_SEP_PATH_MAC;
844f90fb 1785 break;
04c943b1 1786
3c621059
JJ
1787 case wxPATH_VMS:
1788 seps = wxFILE_SEP_PATH_VMS;
1789 break;
df5ddbca
RR
1790 }
1791
844f90fb 1792 return seps;
df5ddbca
RR
1793}
1794
f1e77933
VZ
1795/* static */
1796wxString wxFileName::GetPathTerminators(wxPathFormat format)
1797{
1798 format = GetFormat(format);
1799
1800 // under VMS the end of the path is ']', not the path separator used to
1801 // separate the components
9a83f860 1802 return format == wxPATH_VMS ? wxString(wxT(']')) : GetPathSeparators(format);
f1e77933
VZ
1803}
1804
844f90fb
VZ
1805/* static */
1806bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
df5ddbca 1807{
04c943b1 1808 // wxString::Find() doesn't work as expected with NUL - it will always find
2fb5a4ce 1809 // it, so test for it separately
9a83f860 1810 return ch != wxT('\0') && GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
df5ddbca
RR
1811}
1812
844f90fb
VZ
1813// ----------------------------------------------------------------------------
1814// path components manipulation
1815// ----------------------------------------------------------------------------
1816
5bb9aeb2
VZ
1817/* static */ bool wxFileName::IsValidDirComponent(const wxString& dir)
1818{
1819 if ( dir.empty() )
1820 {
9a83f860 1821 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
5bb9aeb2
VZ
1822
1823 return false;
1824 }
1825
1826 const size_t len = dir.length();
1827 for ( size_t n = 0; n < len; n++ )
1828 {
1829 if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
1830 {
9a83f860 1831 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
5bb9aeb2
VZ
1832
1833 return false;
1834 }
1835 }
1836
1837 return true;
1838}
1839
2458d90b 1840void wxFileName::AppendDir( const wxString& dir )
df5ddbca 1841{
5bb9aeb2
VZ
1842 if ( IsValidDirComponent(dir) )
1843 m_dirs.Add( dir );
df5ddbca
RR
1844}
1845
2458d90b 1846void wxFileName::PrependDir( const wxString& dir )
df5ddbca 1847{
5bb9aeb2 1848 InsertDir(0, dir);
df5ddbca
RR
1849}
1850
2458d90b 1851void wxFileName::InsertDir(size_t before, const wxString& dir)
df5ddbca 1852{
5bb9aeb2 1853 if ( IsValidDirComponent(dir) )
2458d90b 1854 m_dirs.Insert(dir, before);
df5ddbca
RR
1855}
1856
2458d90b 1857void wxFileName::RemoveDir(size_t pos)
df5ddbca 1858{
2458d90b 1859 m_dirs.RemoveAt(pos);
df5ddbca
RR
1860}
1861
844f90fb
VZ
1862// ----------------------------------------------------------------------------
1863// accessors
1864// ----------------------------------------------------------------------------
1865
7124df9b
VZ
1866void wxFileName::SetFullName(const wxString& fullname)
1867{
dfecbee5
VZ
1868 SplitPath(fullname, NULL /* no volume */, NULL /* no path */,
1869 &m_name, &m_ext, &m_hasExt);
7124df9b
VZ
1870}
1871
844f90fb 1872wxString wxFileName::GetFullName() const
a35b27b1 1873{
844f90fb 1874 wxString fullname = m_name;
dfecbee5 1875 if ( m_hasExt )
a35b27b1 1876 {
9e8d8607 1877 fullname << wxFILE_SEP_EXT << m_ext;
a35b27b1 1878 }
a35b27b1 1879
844f90fb 1880 return fullname;
a35b27b1
RR
1881}
1882
33b97389 1883wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
df5ddbca
RR
1884{
1885 format = GetFormat( format );
844f90fb 1886
353f41cb
RR
1887 wxString fullpath;
1888
33b97389
VZ
1889 // return the volume with the path as well if requested
1890 if ( flags & wxPATH_GET_VOLUME )
1891 {
1892 fullpath += wxGetVolumeString(GetVolume(), format);
1893 }
1894
034742fc
VZ
1895 // the leading character
1896 switch ( format )
1897 {
1898 case wxPATH_MAC:
1899 if ( m_relative )
1900 fullpath += wxFILE_SEP_PATH_MAC;
1901 break;
1902
1903 case wxPATH_DOS:
1904 if ( !m_relative )
1905 fullpath += wxFILE_SEP_PATH_DOS;
1906 break;
1907
1908 default:
1909 wxFAIL_MSG( wxT("Unknown path format") );
1910 // fall through
1911
1912 case wxPATH_UNIX:
1913 if ( !m_relative )
1914 {
be5be16a 1915 fullpath += wxFILE_SEP_PATH_UNIX;
034742fc
VZ
1916 }
1917 break;
1918
1919 case wxPATH_VMS:
1920 // no leading character here but use this place to unset
1921 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1922 // as, if I understand correctly, there should never be a dot
1923 // before the closing bracket
1924 flags &= ~wxPATH_GET_SEPARATOR;
1925 }
1926
1927 if ( m_dirs.empty() )
1928 {
1929 // there is nothing more
1930 return fullpath;
1931 }
1932
1933 // then concatenate all the path components using the path separator
1934 if ( format == wxPATH_VMS )
1935 {
1936 fullpath += wxT('[');
1937 }
1938
5bb9aeb2 1939 const size_t dirCount = m_dirs.GetCount();
034742fc 1940 for ( size_t i = 0; i < dirCount; i++ )
353f41cb 1941 {
034742fc 1942 switch (format)
5bb9aeb2
VZ
1943 {
1944 case wxPATH_MAC:
034742fc
VZ
1945 if ( m_dirs[i] == wxT(".") )
1946 {
1947 // skip appending ':', this shouldn't be done in this
1948 // case as "::" is interpreted as ".." under Unix
1949 continue;
1950 }
2361ce82 1951
034742fc 1952 // convert back from ".." to nothing
489f6cf7 1953 if ( !m_dirs[i].IsSameAs(wxT("..")) )
034742fc 1954 fullpath += m_dirs[i];
5bb9aeb2 1955 break;
2361ce82 1956
5bb9aeb2 1957 default:
034742fc
VZ
1958 wxFAIL_MSG( wxT("Unexpected path format") );
1959 // still fall through
2361ce82 1960
034742fc 1961 case wxPATH_DOS:
5bb9aeb2 1962 case wxPATH_UNIX:
034742fc 1963 fullpath += m_dirs[i];
5bb9aeb2 1964 break;
2361ce82 1965
5bb9aeb2 1966 case wxPATH_VMS:
034742fc 1967 // TODO: What to do with ".." under VMS
353f41cb 1968
034742fc 1969 // convert back from ".." to nothing
489f6cf7 1970 if ( !m_dirs[i].IsSameAs(wxT("..")) )
353f41cb 1971 fullpath += m_dirs[i];
034742fc 1972 break;
4175794e
VZ
1973 }
1974
034742fc
VZ
1975 if ( (flags & wxPATH_GET_SEPARATOR) || (i != dirCount - 1) )
1976 fullpath += GetPathSeparator(format);
df5ddbca 1977 }
034742fc
VZ
1978
1979 if ( format == wxPATH_VMS )
5bb9aeb2 1980 {
034742fc 1981 fullpath += wxT(']');
5bb9aeb2 1982 }
844f90fb 1983
353f41cb 1984 return fullpath;
df5ddbca
RR
1985}
1986
1987wxString wxFileName::GetFullPath( wxPathFormat format ) const
1988{
4175794e
VZ
1989 // we already have a function to get the path
1990 wxString fullpath = GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR,
1991 format);
04c943b1 1992
4175794e 1993 // now just add the file name and extension to it
04c943b1
VZ
1994 fullpath += GetFullName();
1995
1996 return fullpath;
df5ddbca
RR
1997}
1998
9e9b65c1
JS
1999// Return the short form of the path (returns identity on non-Windows platforms)
2000wxString wxFileName::GetShortPath() const
2001{
9e9b65c1 2002 wxString path(GetFullPath());
2f3d9587
VZ
2003
2004#if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
e0a050e3 2005 DWORD sz = ::GetShortPathName(path.fn_str(), NULL, 0);
2f3d9587 2006 if ( sz != 0 )
9e9b65c1 2007 {
2f3d9587
VZ
2008 wxString pathOut;
2009 if ( ::GetShortPathName
75ef5722 2010 (
e0a050e3 2011 path.fn_str(),
de564874 2012 wxStringBuffer(pathOut, sz),
75ef5722 2013 sz
2f3d9587
VZ
2014 ) != 0 )
2015 {
2016 return pathOut;
2017 }
9e9b65c1 2018 }
2f3d9587 2019#endif // Windows
5716a1ab
VZ
2020
2021 return path;
9e9b65c1
JS
2022}
2023
2024// Return the long form of the path (returns identity on non-Windows platforms)
2025wxString wxFileName::GetLongPath() const
2026{
52dbd056
VZ
2027 wxString pathOut,
2028 path = GetFullPath();
2029
b517351b 2030#if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
05e7001c 2031
0e207280 2032#if wxUSE_DYNLIB_CLASS
62dcaed6 2033 typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
05e7001c 2034
2f3d9587
VZ
2035 // this is MT-safe as in the worst case we're going to resolve the function
2036 // twice -- but as the result is the same in both threads, it's ok
2037 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
2038 if ( !s_pfnGetLongPathName )
9e9b65c1 2039 {
2f3d9587 2040 static bool s_triedToLoad = false;
2361ce82 2041
2f3d9587 2042 if ( !s_triedToLoad )
05e7001c 2043 {
2f3d9587
VZ
2044 s_triedToLoad = true;
2045
9a83f860 2046 wxDynamicLibrary dllKernel(wxT("kernel32"));
2f3d9587 2047
9a83f860 2048 const wxChar* GetLongPathName = wxT("GetLongPathName")
4377d3ab 2049#if wxUSE_UNICODE
9a83f860 2050 wxT("W");
4377d3ab 2051#else // ANSI
9a83f860 2052 wxT("A");
4377d3ab
WS
2053#endif // Unicode/ANSI
2054
2055 if ( dllKernel.HasSymbol(GetLongPathName) )
05e7001c 2056 {
2f3d9587 2057 s_pfnGetLongPathName = (GET_LONG_PATH_NAME)
4377d3ab 2058 dllKernel.GetSymbol(GetLongPathName);
05e7001c 2059 }
2f3d9587
VZ
2060
2061 // note that kernel32.dll can be unloaded, it stays in memory
2062 // anyhow as all Win32 programs link to it and so it's safe to call
2063 // GetLongPathName() even after unloading it
05e7001c 2064 }
9e9b65c1 2065 }
2361ce82 2066
2f3d9587
VZ
2067 if ( s_pfnGetLongPathName )
2068 {
e0a050e3 2069 DWORD dwSize = (*s_pfnGetLongPathName)(path.fn_str(), NULL, 0);
2f3d9587
VZ
2070 if ( dwSize > 0 )
2071 {
2072 if ( (*s_pfnGetLongPathName)
2073 (
e0a050e3 2074 path.fn_str(),
2f3d9587
VZ
2075 wxStringBuffer(pathOut, dwSize),
2076 dwSize
2077 ) != 0 )
2078 {
2079 return pathOut;
2080 }
2081 }
2082 }
0e207280 2083#endif // wxUSE_DYNLIB_CLASS
05e7001c 2084
2f3d9587
VZ
2085 // The OS didn't support GetLongPathName, or some other error.
2086 // We need to call FindFirstFile on each component in turn.
05e7001c 2087
2f3d9587
VZ
2088 WIN32_FIND_DATA findFileData;
2089 HANDLE hFind;
b5b62eea 2090
2f3d9587
VZ
2091 if ( HasVolume() )
2092 pathOut = GetVolume() +
2093 GetVolumeSeparator(wxPATH_DOS) +
2094 GetPathSeparator(wxPATH_DOS);
2095 else
2096 pathOut = wxEmptyString;
05e7001c 2097
2f3d9587
VZ
2098 wxArrayString dirs = GetDirs();
2099 dirs.Add(GetFullName());
77fe02a8 2100
2f3d9587 2101 wxString tmpPath;
5d978d07 2102
2f3d9587
VZ
2103 size_t count = dirs.GetCount();
2104 for ( size_t i = 0; i < count; i++ )
2105 {
ea6319cb
VZ
2106 const wxString& dir = dirs[i];
2107
2f3d9587
VZ
2108 // We're using pathOut to collect the long-name path, but using a
2109 // temporary for appending the last path component which may be
2110 // short-name
ea6319cb
VZ
2111 tmpPath = pathOut + dir;
2112
2113 // We must not process "." or ".." here as they would be (unexpectedly)
2114 // replaced by the corresponding directory names so just leave them
2115 // alone
2116 //
2117 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2118 if ( tmpPath.empty() || dir == '.' || dir == ".." ||
2119 tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
2f3d9587 2120 {
2f3d9587
VZ
2121 tmpPath += wxFILE_SEP_PATH;
2122 pathOut = tmpPath;
2123 continue;
2124 }
05e7001c 2125
e0a050e3 2126 hFind = ::FindFirstFile(tmpPath.fn_str(), &findFileData);
2f3d9587
VZ
2127 if (hFind == INVALID_HANDLE_VALUE)
2128 {
2129 // Error: most likely reason is that path doesn't exist, so
2130 // append any unprocessed parts and return
2131 for ( i += 1; i < count; i++ )
2132 tmpPath += wxFILE_SEP_PATH + dirs[i];
b5b62eea 2133
2f3d9587
VZ
2134 return tmpPath;
2135 }
05e7001c 2136
2f3d9587
VZ
2137 pathOut += findFileData.cFileName;
2138 if ( (i < (count-1)) )
2139 pathOut += wxFILE_SEP_PATH;
52dbd056 2140
2f3d9587 2141 ::FindClose(hFind);
05e7001c 2142 }
52dbd056
VZ
2143#else // !Win32
2144 pathOut = path;
2145#endif // Win32/!Win32
5716a1ab 2146
05e7001c 2147 return pathOut;
9e9b65c1
JS
2148}
2149
df5ddbca
RR
2150wxPathFormat wxFileName::GetFormat( wxPathFormat format )
2151{
2152 if (format == wxPATH_NATIVE)
2153 {
5a3912f2 2154#if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
df5ddbca 2155 format = wxPATH_DOS;
3c621059 2156#elif defined(__VMS)
04c943b1 2157 format = wxPATH_VMS;
844f90fb 2158#else
df5ddbca
RR
2159 format = wxPATH_UNIX;
2160#endif
2161 }
2162 return format;
2163}
a35b27b1 2164
35c2aa4f
VZ
2165#ifdef wxHAS_FILESYSTEM_VOLUMES
2166
2167/* static */
2168wxString wxFileName::GetVolumeString(char drive, int flags)
2169{
2170 wxASSERT_MSG( !(flags & ~wxPATH_GET_SEPARATOR), "invalid flag specified" );
2171
2172 wxString vol(drive);
2173 vol += wxFILE_SEP_DSK;
2174 if ( flags & wxPATH_GET_SEPARATOR )
2175 vol += wxFILE_SEP_PATH;
2176
2177 return vol;
2178}
2179
2180#endif // wxHAS_FILESYSTEM_VOLUMES
2181
9e8d8607
VZ
2182// ----------------------------------------------------------------------------
2183// path splitting function
2184// ----------------------------------------------------------------------------
2185
6f91bc33 2186/* static */
f1e77933
VZ
2187void
2188wxFileName::SplitVolume(const wxString& fullpathWithVolume,
2189 wxString *pstrVolume,
2190 wxString *pstrPath,
2191 wxPathFormat format)
9e8d8607
VZ
2192{
2193 format = GetFormat(format);
2194
04c943b1
VZ
2195 wxString fullpath = fullpathWithVolume;
2196
04c943b1 2197 // special Windows UNC paths hack: transform \\share\path into share:path
9e1c7236 2198 if ( IsUNCPath(fullpath, format) )
9e8d8607 2199 {
9e1c7236 2200 fullpath.erase(0, 2);
04c943b1 2201
9e1c7236
VZ
2202 size_t posFirstSlash =
2203 fullpath.find_first_of(GetPathTerminators(format));
2204 if ( posFirstSlash != wxString::npos )
2205 {
2206 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
04c943b1 2207
9e1c7236
VZ
2208 // UNC paths are always absolute, right? (FIXME)
2209 fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
3c621059
JJ
2210 }
2211 }
04c943b1 2212
a385b5df
RR
2213 // We separate the volume here
2214 if ( format == wxPATH_DOS || format == wxPATH_VMS )
04c943b1 2215 {
a385b5df 2216 wxString sepVol = GetVolumeSeparator(format);
24eb81cb 2217
0f506ded
VZ
2218 // we have to exclude the case of a colon in the very beginning of the
2219 // string as it can't be a volume separator (nor can this be a valid
2220 // DOS file name at all but we'll leave dealing with this to our caller)
04c943b1 2221 size_t posFirstColon = fullpath.find_first_of(sepVol);
0f506ded 2222 if ( posFirstColon && posFirstColon != wxString::npos )
04c943b1
VZ
2223 {
2224 if ( pstrVolume )
2225 {
2226 *pstrVolume = fullpath.Left(posFirstColon);
2227 }
2228
2229 // remove the volume name and the separator from the full path
2230 fullpath.erase(0, posFirstColon + sepVol.length());
2231 }
2232 }
2233
f1e77933
VZ
2234 if ( pstrPath )
2235 *pstrPath = fullpath;
2236}
2237
2238/* static */
2239void wxFileName::SplitPath(const wxString& fullpathWithVolume,
2240 wxString *pstrVolume,
2241 wxString *pstrPath,
2242 wxString *pstrName,
2243 wxString *pstrExt,
dfecbee5 2244 bool *hasExt,
f1e77933
VZ
2245 wxPathFormat format)
2246{
2247 format = GetFormat(format);
2248
2249 wxString fullpath;
2250 SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
2251
04c943b1
VZ
2252 // find the positions of the last dot and last path separator in the path
2253 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
f1e77933 2254 size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
04c943b1 2255
e5a573a2 2256 // check whether this dot occurs at the very beginning of a path component
04c943b1 2257 if ( (posLastDot != wxString::npos) &&
e5a573a2
VZ
2258 (posLastDot == 0 ||
2259 IsPathSeparator(fullpath[posLastDot - 1]) ||
9a83f860 2260 (format == wxPATH_VMS && fullpath[posLastDot - 1] == wxT(']'))) )
f1e77933
VZ
2261 {
2262 // dot may be (and commonly -- at least under Unix -- is) the first
2263 // character of the filename, don't treat the entire filename as
2264 // extension in this case
2265 posLastDot = wxString::npos;
2266 }
9e8d8607 2267
8e7dda21
VZ
2268 // if we do have a dot and a slash, check that the dot is in the name part
2269 if ( (posLastDot != wxString::npos) &&
2270 (posLastSlash != wxString::npos) &&
2271 (posLastDot < posLastSlash) )
9e8d8607
VZ
2272 {
2273 // the dot is part of the path, not the start of the extension
2274 posLastDot = wxString::npos;
2275 }
2276
2277 // now fill in the variables provided by user
2278 if ( pstrPath )
2279 {
2280 if ( posLastSlash == wxString::npos )
2281 {
2282 // no path at all
2283 pstrPath->Empty();
2284 }
2285 else
2286 {
04c943b1 2287 // take everything up to the path separator but take care to make
353f41cb 2288 // the path equal to something like '/', not empty, for the files
04c943b1
VZ
2289 // immediately under root directory
2290 size_t len = posLastSlash;
91b4bd63
SC
2291
2292 // this rule does not apply to mac since we do not start with colons (sep)
2293 // except for relative paths
2294 if ( !len && format != wxPATH_MAC)
04c943b1
VZ
2295 len++;
2296
2297 *pstrPath = fullpath.Left(len);
2298
2299 // special VMS hack: remove the initial bracket
2300 if ( format == wxPATH_VMS )
2301 {
9a83f860 2302 if ( (*pstrPath)[0u] == wxT('[') )
04c943b1
VZ
2303 pstrPath->erase(0, 1);
2304 }
9e8d8607
VZ
2305 }
2306 }
2307
2308 if ( pstrName )
2309 {
42b1f941
VZ
2310 // take all characters starting from the one after the last slash and
2311 // up to, but excluding, the last dot
9e8d8607 2312 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
8e7dda21
VZ
2313 size_t count;
2314 if ( posLastDot == wxString::npos )
2315 {
2316 // take all until the end
2317 count = wxString::npos;
2318 }
2319 else if ( posLastSlash == wxString::npos )
2320 {
2321 count = posLastDot;
2322 }
2323 else // have both dot and slash
2324 {
2325 count = posLastDot - posLastSlash - 1;
2326 }
9e8d8607
VZ
2327
2328 *pstrName = fullpath.Mid(nStart, count);
2329 }
2330
dfecbee5
VZ
2331 // finally deal with the extension here: we have an added complication that
2332 // extension may be empty (but present) as in "foo." where trailing dot
2333 // indicates the empty extension at the end -- and hence we must remember
2334 // that we have it independently of pstrExt
2335 if ( posLastDot == wxString::npos )
9e8d8607 2336 {
dfecbee5
VZ
2337 // no extension
2338 if ( pstrExt )
2339 pstrExt->clear();
2340 if ( hasExt )
2341 *hasExt = false;
2342 }
2343 else
2344 {
2345 // take everything after the dot
2346 if ( pstrExt )
9e8d8607 2347 *pstrExt = fullpath.Mid(posLastDot + 1);
dfecbee5
VZ
2348 if ( hasExt )
2349 *hasExt = true;
9e8d8607
VZ
2350 }
2351}
951cd180 2352
6f91bc33
VZ
2353/* static */
2354void wxFileName::SplitPath(const wxString& fullpath,
2355 wxString *path,
2356 wxString *name,
2357 wxString *ext,
2358 wxPathFormat format)
2359{
2360 wxString volume;
2361 SplitPath(fullpath, &volume, path, name, ext, format);
2362
67c34f64 2363 if ( path )
6f91bc33 2364 {
67c34f64 2365 path->Prepend(wxGetVolumeString(volume, format));
6f91bc33
VZ
2366 }
2367}
2368
181dd701
VZ
2369/* static */
2370wxString wxFileName::StripExtension(const wxString& fullpath)
2371{
2372 wxFileName fn(fullpath);
2373 fn.SetExt("");
2374 return fn.GetFullPath();
2375}
2376
951cd180
VZ
2377// ----------------------------------------------------------------------------
2378// time functions
2379// ----------------------------------------------------------------------------
2380
e2b87f38
VZ
2381#if wxUSE_DATETIME
2382
6dbb903b
VZ
2383bool wxFileName::SetTimes(const wxDateTime *dtAccess,
2384 const wxDateTime *dtMod,
d9e80dce 2385 const wxDateTime *dtCreate) const
951cd180 2386{
2b5f62a0 2387#if defined(__WIN32__)
6bc176b4
VZ
2388 FILETIME ftAccess, ftCreate, ftWrite;
2389
2390 if ( dtCreate )
2391 ConvertWxToFileTime(&ftCreate, *dtCreate);
2392 if ( dtAccess )
2393 ConvertWxToFileTime(&ftAccess, *dtAccess);
2394 if ( dtMod )
2395 ConvertWxToFileTime(&ftWrite, *dtMod);
2396
2397 wxString path;
2398 int flags;
2b5f62a0
VZ
2399 if ( IsDir() )
2400 {
6bc176b4
VZ
2401 if ( wxGetOsVersion() == wxOS_WINDOWS_9X )
2402 {
2403 wxLogError(_("Setting directory access times is not supported "
2404 "under this OS version"));
2405 return false;
2406 }
2407
2408 path = GetPath();
2409 flags = FILE_FLAG_BACKUP_SEMANTICS;
2b5f62a0
VZ
2410 }
2411 else // file
2412 {
6bc176b4
VZ
2413 path = GetFullPath();
2414 flags = 0;
2415 }
2416
f3c74c8d 2417 wxFileHandle fh(path, wxFileHandle::WriteAttr, flags);
6bc176b4
VZ
2418 if ( fh.IsOk() )
2419 {
2420 if ( ::SetFileTime(fh,
2421 dtCreate ? &ftCreate : NULL,
2422 dtAccess ? &ftAccess : NULL,
2423 dtMod ? &ftWrite : NULL) )
2b5f62a0 2424 {
6bc176b4 2425 return true;
2b5f62a0
VZ
2426 }
2427 }
2428#elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
17a1ebd1
VZ
2429 wxUnusedVar(dtCreate);
2430
246c704f
VZ
2431 if ( !dtAccess && !dtMod )
2432 {
2433 // can't modify the creation time anyhow, don't try
f363e05c 2434 return true;
246c704f
VZ
2435 }
2436
2437 // if dtAccess or dtMod is not specified, use the other one (which must be
2438 // non NULL because of the test above) for both times
951cd180 2439 utimbuf utm;
246c704f
VZ
2440 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
2441 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
401eb3de 2442 if ( utime(GetFullPath().fn_str(), &utm) == 0 )
951cd180 2443 {
f363e05c 2444 return true;
951cd180 2445 }
951cd180 2446#else // other platform
7a893a31
WS
2447 wxUnusedVar(dtAccess);
2448 wxUnusedVar(dtMod);
2449 wxUnusedVar(dtCreate);
951cd180
VZ
2450#endif // platforms
2451
2452 wxLogSysError(_("Failed to modify file times for '%s'"),
2453 GetFullPath().c_str());
2454
f363e05c 2455 return false;
951cd180
VZ
2456}
2457
d9e80dce 2458bool wxFileName::Touch() const
951cd180
VZ
2459{
2460#if defined(__UNIX_LIKE__)
2461 // under Unix touching file is simple: just pass NULL to utime()
401eb3de 2462 if ( utime(GetFullPath().fn_str(), NULL) == 0 )
951cd180 2463 {
f363e05c 2464 return true;
951cd180
VZ
2465 }
2466
2467 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2468
f363e05c 2469 return false;
951cd180
VZ
2470#else // other platform
2471 wxDateTime dtNow = wxDateTime::Now();
2472
6dbb903b 2473 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
951cd180
VZ
2474#endif // platforms
2475}
2476
2477bool wxFileName::GetTimes(wxDateTime *dtAccess,
2478 wxDateTime *dtMod,
6dbb903b 2479 wxDateTime *dtCreate) const
951cd180 2480{
2b5f62a0
VZ
2481#if defined(__WIN32__)
2482 // we must use different methods for the files and directories under
2483 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2484 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2485 // not 9x
2486 bool ok;
2487 FILETIME ftAccess, ftCreate, ftWrite;
9a0c5c01 2488 if ( IsDir() )
2b5f62a0
VZ
2489 {
2490 // implemented in msw/dir.cpp
2491 extern bool wxGetDirectoryTimes(const wxString& dirname,
2492 FILETIME *, FILETIME *, FILETIME *);
2493
2494 // we should pass the path without the trailing separator to
2495 // wxGetDirectoryTimes()
2496 ok = wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME),
2497 &ftAccess, &ftCreate, &ftWrite);
2498 }
2499 else // file
2500 {
f3c74c8d 2501 wxFileHandle fh(GetFullPath(), wxFileHandle::ReadAttr);
2b5f62a0
VZ
2502 if ( fh.IsOk() )
2503 {
2504 ok = ::GetFileTime(fh,
2505 dtCreate ? &ftCreate : NULL,
2506 dtAccess ? &ftAccess : NULL,
2507 dtMod ? &ftWrite : NULL) != 0;
2508 }
2509 else
2510 {
f363e05c 2511 ok = false;
2b5f62a0
VZ
2512 }
2513 }
2514
2515 if ( ok )
2516 {
2517 if ( dtCreate )
2518 ConvertFileTimeToWx(dtCreate, ftCreate);
2519 if ( dtAccess )
2520 ConvertFileTimeToWx(dtAccess, ftAccess);
2521 if ( dtMod )
2522 ConvertFileTimeToWx(dtMod, ftWrite);
2523
f363e05c 2524 return true;
2b5f62a0 2525 }
bf58daba 2526#elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
51cb1a65 2527 // no need to test for IsDir() here
951cd180 2528 wxStructStat stBuf;
92980e90 2529 if ( wxStat( GetFullPath().c_str(), &stBuf) == 0 )
951cd180
VZ
2530 {
2531 if ( dtAccess )
2532 dtAccess->Set(stBuf.st_atime);
2533 if ( dtMod )
2534 dtMod->Set(stBuf.st_mtime);
6dbb903b
VZ
2535 if ( dtCreate )
2536 dtCreate->Set(stBuf.st_ctime);
951cd180 2537
f363e05c 2538 return true;
951cd180 2539 }
951cd180 2540#else // other platform
7a893a31
WS
2541 wxUnusedVar(dtAccess);
2542 wxUnusedVar(dtMod);
2543 wxUnusedVar(dtCreate);
951cd180
VZ
2544#endif // platforms
2545
2546 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2547 GetFullPath().c_str());
2548
f363e05c 2549 return false;
951cd180
VZ
2550}
2551
e2b87f38
VZ
2552#endif // wxUSE_DATETIME
2553
23b8a262
JS
2554
2555// ----------------------------------------------------------------------------
2556// file size functions
2557// ----------------------------------------------------------------------------
2558
bd08f2f7
VZ
2559#if wxUSE_LONGLONG
2560
23b8a262
JS
2561/* static */
2562wxULongLong wxFileName::GetSize(const wxString &filename)
2563{
2564 if (!wxFileExists(filename))
2565 return wxInvalidSize;
2566
cdbce971
WS
2567#if defined(__WXPALMOS__)
2568 // TODO
2569 return wxInvalidSize;
2570#elif defined(__WIN32__)
f3c74c8d 2571 wxFileHandle f(filename, wxFileHandle::ReadAttr);
23b8a262
JS
2572 if (!f.IsOk())
2573 return wxInvalidSize;
2574
2575 DWORD lpFileSizeHigh;
2576 DWORD ret = GetFileSize(f, &lpFileSizeHigh);
5ab9534b 2577 if ( ret == INVALID_FILE_SIZE && ::GetLastError() != NO_ERROR )
23b8a262
JS
2578 return wxInvalidSize;
2579
5ab9534b
VZ
2580 return wxULongLong(lpFileSizeHigh, ret);
2581#else // ! __WIN32__
23b8a262
JS
2582 wxStructStat st;
2583#ifndef wxNEED_WX_UNISTD_H
2584 if (wxStat( filename.fn_str() , &st) != 0)
2585#else
2586 if (wxStat( filename, &st) != 0)
2587#endif
2588 return wxInvalidSize;
2589 return wxULongLong(st.st_size);
2590#endif
2591}
2592
2593/* static */
2594wxString wxFileName::GetHumanReadableSize(const wxULongLong &bs,
2595 const wxString &nullsize,
2596 int precision)
2597{
2598 static const double KILOBYTESIZE = 1024.0;
2599 static const double MEGABYTESIZE = 1024.0*KILOBYTESIZE;
2600 static const double GIGABYTESIZE = 1024.0*MEGABYTESIZE;
2601 static const double TERABYTESIZE = 1024.0*GIGABYTESIZE;
2602
2603 if (bs == 0 || bs == wxInvalidSize)
2604 return nullsize;
2605
2606 double bytesize = bs.ToDouble();
2607 if (bytesize < KILOBYTESIZE)
2608 return wxString::Format(_("%s B"), bs.ToString().c_str());
2609 if (bytesize < MEGABYTESIZE)
2610 return wxString::Format(_("%.*f kB"), precision, bytesize/KILOBYTESIZE);
2611 if (bytesize < GIGABYTESIZE)
2612 return wxString::Format(_("%.*f MB"), precision, bytesize/MEGABYTESIZE);
2613 if (bytesize < TERABYTESIZE)
2614 return wxString::Format(_("%.*f GB"), precision, bytesize/GIGABYTESIZE);
2615
2616 return wxString::Format(_("%.*f TB"), precision, bytesize/TERABYTESIZE);
2617}
2618
2619wxULongLong wxFileName::GetSize() const
2620{
2621 return GetSize(GetFullPath());
2622}
2623
2624wxString wxFileName::GetHumanReadableSize(const wxString &failmsg, int precision) const
2625{
2626 return GetHumanReadableSize(GetSize(), failmsg, precision);
2627}
2628
bd08f2f7 2629#endif // wxUSE_LONGLONG
23b8a262
JS
2630
2631// ----------------------------------------------------------------------------
2632// Mac-specific functions
2633// ----------------------------------------------------------------------------
2634
26eef304 2635#if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
4dfbcdd5 2636
56ce942b
VZ
2637namespace
2638{
2639
0ca4ae93 2640class MacDefaultExtensionRecord
4dfbcdd5 2641{
56ce942b
VZ
2642public:
2643 MacDefaultExtensionRecord()
2644 {
2645 m_type =
2646 m_creator = 0 ;
2647 }
4dfbcdd5 2648
56ce942b 2649 // default copy ctor, assignment operator and dtor are ok
0ca4ae93 2650
56ce942b
VZ
2651 MacDefaultExtensionRecord(const wxString& ext, OSType type, OSType creator)
2652 : m_ext(ext)
2653 {
2654 m_type = type;
2655 m_creator = creator;
2656 }
2657
2658 wxString m_ext;
2659 OSType m_type;
2660 OSType m_creator;
2661};
2662
2663WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray);
2664
2665bool gMacDefaultExtensionsInited = false;
0ca4ae93 2666
4dfbcdd5 2667#include "wx/arrimpl.cpp"
0ca4ae93 2668
56ce942b 2669WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray);
4dfbcdd5 2670
56ce942b 2671MacDefaultExtensionArray gMacDefaultExtensions;
4dfbcdd5 2672
5974c3cf 2673// load the default extensions
56ce942b 2674const MacDefaultExtensionRecord gDefaults[] =
4dfbcdd5 2675{
56ce942b
VZ
2676 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2677 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2678 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2679};
0ea621cc 2680
56ce942b 2681void MacEnsureDefaultExtensionsLoaded()
5974c3cf
SC
2682{
2683 if ( !gMacDefaultExtensionsInited )
4dfbcdd5 2684 {
5974c3cf
SC
2685 // we could load the pc exchange prefs here too
2686 for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
2687 {
2688 gMacDefaultExtensions.Add( gDefaults[i] ) ;
2689 }
56ce942b 2690 gMacDefaultExtensionsInited = true;
0ea621cc 2691 }
4dfbcdd5 2692}
a2b77260 2693
56ce942b
VZ
2694} // anonymous namespace
2695
0ea621cc 2696bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
4dfbcdd5 2697{
a2b77260
SC
2698 FSRef fsRef ;
2699 FSCatalogInfo catInfo;
2700 FileInfo *finfo ;
4dfbcdd5 2701
a2b77260
SC
2702 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2703 {
a62848fd
WS
2704 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2705 {
2706 finfo = (FileInfo*)&catInfo.finderInfo;
2707 finfo->fileType = type ;
2708 finfo->fileCreator = creator ;
2709 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
a2b77260 2710 return true ;
a62848fd 2711 }
a2b77260
SC
2712 }
2713 return false ;
4dfbcdd5
SC
2714}
2715
d9e80dce 2716bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator ) const
4dfbcdd5 2717{
a2b77260
SC
2718 FSRef fsRef ;
2719 FSCatalogInfo catInfo;
2720 FileInfo *finfo ;
4dfbcdd5 2721
a2b77260
SC
2722 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2723 {
a62848fd
WS
2724 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2725 {
2726 finfo = (FileInfo*)&catInfo.finderInfo;
2727 *type = finfo->fileType ;
2728 *creator = finfo->fileCreator ;
a2b77260 2729 return true ;
a62848fd 2730 }
a2b77260
SC
2731 }
2732 return false ;
4dfbcdd5
SC
2733}
2734
2735bool wxFileName::MacSetDefaultTypeAndCreator()
2736{
2737 wxUint32 type , creator ;
2738 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
2739 &creator ) )
2740 {
f63fb56d
GD
2741 return MacSetTypeAndCreator( type , creator ) ;
2742 }
2743 return false;
4dfbcdd5
SC
2744}
2745
0ea621cc 2746bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
4dfbcdd5
SC
2747{
2748 MacEnsureDefaultExtensionsLoaded() ;
2749 wxString extl = ext.Lower() ;
2750 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
2751 {
2752 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
2753 {
2754 *type = gMacDefaultExtensions.Item(i).m_type ;
2755 *creator = gMacDefaultExtensions.Item(i).m_creator ;
2756 return true ;
2757 }
2758 }
2759 return false ;
2760}
2761
2762void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
2763{
56ce942b
VZ
2764 MacEnsureDefaultExtensionsLoaded();
2765 MacDefaultExtensionRecord rec(ext.Lower(), type, creator);
2766 gMacDefaultExtensions.Add( rec );
4dfbcdd5 2767}
56ce942b
VZ
2768
2769#endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON