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