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