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