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