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