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