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