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