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