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