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