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