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