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