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