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