]> git.saurik.com Git - wxWidgets.git/blame - src/common/filename.cpp
Change wxVariant GetValue() to GetValue( wxVariant & ).
[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
6091caf0
JS
607 if (dir.empty())
608 {
609 dir = wxGetenv(_T("TMPDIR"));
610 if (dir.empty())
611 {
612 dir = wxGetenv(_T("TMP"));
613 if (dir.empty())
614 {
615 dir = wxGetenv(_T("TEMP"));
616 }
617 }
618 }
619
1c193821
JS
620#if defined(__WXWINCE__)
621 if (dir.empty())
622 {
623 // FIXME. Create \temp dir?
624 dir = wxT("\\");
625 }
f05ba7ff 626 path = dir + wxT("\\") + name;
1c193821 627 int i = 1;
68351053 628 while (FileExists(path))
1c193821 629 {
f05ba7ff 630 path = dir + wxT("\\") + name ;
1c193821
JS
631 path << i;
632 i ++;
633 }
ade35f11 634
1c193821 635#elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
3a5bcc4d 636
ade35f11
VZ
637 if ( dir.empty() )
638 {
639 if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
640 {
641 wxLogLastError(_T("GetTempPath"));
642 }
643
644 if ( dir.empty() )
645 {
646 // GetTempFileName() fails if we pass it an empty string
647 dir = _T('.');
648 }
649 }
a2fa5040
VZ
650 else // we have a dir to create the file in
651 {
652 // ensure we use only the back slashes as GetTempFileName(), unlike all
653 // the other APIs, is picky and doesn't accept the forward ones
654 dir.Replace(_T("/"), _T("\\"));
655 }
ade35f11
VZ
656
657 if ( !::GetTempFileName(dir, name, 0, wxStringBuffer(path, MAX_PATH + 1)) )
658 {
659 wxLogLastError(_T("GetTempFileName"));
660
661 path.clear();
662 }
ade35f11 663
5a3912f2 664#else // !Windows
ade35f11
VZ
665 if ( dir.empty() )
666 {
6091caf0
JS
667 // default
668#if defined(__DOS__) || defined(__OS2__)
669 dir = _T(".");
670#elif defined(__WXMAC__)
671 dir = wxMacFindFolder(short(kOnSystemDisk), kTemporaryFolderType, kCreateFolder);
672#else
673 dir = _T("/tmp");
674#endif
844f90fb 675 }
ade35f11
VZ
676
677 path = dir;
678
679 if ( !wxEndsWithPathSeparator(dir) &&
680 (name.empty() || !wxIsPathSeparator(name[0u])) )
681 {
d9f54bb0 682 path += wxFILE_SEP_PATH;
ade35f11
VZ
683 }
684
685 path += name;
686
7070f55b 687#if defined(HAVE_MKSTEMP)
ade35f11
VZ
688 // scratch space for mkstemp()
689 path += _T("XXXXXX");
690
74cf9763 691 // we need to copy the path to the buffer in which mkstemp() can modify it
2b5f62a0 692 wxCharBuffer buf( wxConvFile.cWX2MB( path ) );
74cf9763
VZ
693
694 // cast is safe because the string length doesn't change
ca11abde 695 int fdTemp = mkstemp( (char*)(const char*) buf );
df22f860 696 if ( fdTemp == -1 )
ade35f11
VZ
697 {
698 // this might be not necessary as mkstemp() on most systems should have
699 // already done it but it doesn't hurt neither...
700 path.clear();
701 }
df22f860
VZ
702 else // mkstemp() succeeded
703 {
ca11abde 704 path = wxConvFile.cMB2WX( (const char*) buf );
a62848fd 705
df22f860
VZ
706 // avoid leaking the fd
707 if ( fileTemp )
708 {
709 fileTemp->Attach(fdTemp);
710 }
711 else
712 {
713 close(fdTemp);
714 }
715 }
ade35f11
VZ
716#else // !HAVE_MKSTEMP
717
718#ifdef HAVE_MKTEMP
719 // same as above
720 path += _T("XXXXXX");
721
ca11abde
RR
722 wxCharBuffer buf = wxConvFile.cWX2MB( path );
723 if ( !mktemp( (const char*) buf ) )
ade35f11
VZ
724 {
725 path.clear();
726 }
aed08d79
RR
727 else
728 {
ca11abde 729 path = wxConvFile.cMB2WX( (const char*) buf );
aed08d79 730 }
7070f55b 731#else // !HAVE_MKTEMP (includes __DOS__)
ade35f11 732 // generate the unique file name ourselves
68351053 733 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
ade35f11 734 path << (unsigned int)getpid();
7070f55b 735 #endif
ade35f11
VZ
736
737 wxString pathTry;
738
739 static const size_t numTries = 1000;
740 for ( size_t n = 0; n < numTries; n++ )
741 {
742 // 3 hex digits is enough for numTries == 1000 < 4096
3e778e3b 743 pathTry = path + wxString::Format(_T("%.03x"), (unsigned int) n);
68351053 744 if ( !FileExists(pathTry) )
ade35f11
VZ
745 {
746 break;
747 }
748
749 pathTry.clear();
750 }
751
752 path = pathTry;
753#endif // HAVE_MKTEMP/!HAVE_MKTEMP
754
df22f860
VZ
755#endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
756
757#endif // Windows/!Windows
758
759 if ( path.empty() )
760 {
761 wxLogSysError(_("Failed to create a temporary file name"));
762 }
763 else if ( fileTemp && !fileTemp->IsOpened() )
764 {
765 // open the file - of course, there is a race condition here, this is
ade35f11 766 // why we always prefer using mkstemp()...
90a68369
VZ
767 //
768 // NB: GetTempFileName() under Windows creates the file, so using
769 // write_excl there would fail
770 if ( !fileTemp->Open(path,
771#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
772 wxFile::write,
773#else
774 wxFile::write_excl,
775#endif
776 wxS_IRUSR | wxS_IWUSR) )
ade35f11
VZ
777 {
778 // FIXME: If !ok here should we loop and try again with another
779 // file name? That is the standard recourse if open(O_EXCL)
780 // fails, though of course it should be protected against
781 // possible infinite looping too.
782
783 wxLogError(_("Failed to open temporary file."));
784
785 path.clear();
786 }
787 }
ade35f11
VZ
788
789 return path;
df5ddbca
RR
790}
791
68351053
WS
792#endif // wxUSE_FILE
793
844f90fb
VZ
794// ----------------------------------------------------------------------------
795// directory operations
796// ----------------------------------------------------------------------------
797
1527281e 798bool wxFileName::Mkdir( int perm, int flags )
a35b27b1 799{
1527281e 800 return wxFileName::Mkdir( GetFullPath(), perm, flags );
a35b27b1
RR
801}
802
1527281e 803bool wxFileName::Mkdir( const wxString& dir, int perm, int flags )
df5ddbca 804{
1527281e 805 if ( flags & wxPATH_MKDIR_FULL )
f0ce3409 806 {
1527281e
VZ
807 // split the path in components
808 wxFileName filename;
809 filename.AssignDir(dir);
f0ce3409 810
f0ce3409 811 wxString currPath;
0ea621cc
VZ
812 if ( filename.HasVolume())
813 {
1527281e 814 currPath << wxGetVolumeString(filename.GetVolume(), wxPATH_NATIVE);
0ea621cc 815 }
f0ce3409 816
1527281e
VZ
817 wxArrayString dirs = filename.GetDirs();
818 size_t count = dirs.GetCount();
819 for ( size_t i = 0; i < count; i++ )
820 {
a62848fd 821 if ( i > 0 ||
6b9eeef2 822#if defined(__WXMAC__) && !defined(__DARWIN__)
a62848fd
WS
823 // relative pathnames are exactely the other way round under mac...
824 !filename.IsAbsolute()
6b9eeef2 825#else
a62848fd 826 filename.IsAbsolute()
6b9eeef2
SC
827#endif
828 )
f0ce3409 829 currPath += wxFILE_SEP_PATH;
1527281e 830 currPath += dirs[i];
f0ce3409
JS
831
832 if (!DirExists(currPath))
1527281e 833 {
f0ce3409 834 if (!wxMkdir(currPath, perm))
1527281e
VZ
835 {
836 // no need to try creating further directories
f363e05c 837 return false;
1527281e
VZ
838 }
839 }
f0ce3409
JS
840 }
841
f363e05c 842 return true;
f0ce3409
JS
843
844 }
1527281e
VZ
845
846 return ::wxMkdir( dir, perm );
df5ddbca
RR
847}
848
a35b27b1 849bool wxFileName::Rmdir()
df5ddbca 850{
a35b27b1 851 return wxFileName::Rmdir( GetFullPath() );
df5ddbca
RR
852}
853
a35b27b1 854bool wxFileName::Rmdir( const wxString &dir )
df5ddbca 855{
a35b27b1 856 return ::wxRmdir( dir );
df5ddbca
RR
857}
858
844f90fb
VZ
859// ----------------------------------------------------------------------------
860// path normalization
861// ----------------------------------------------------------------------------
862
32a0d013 863bool wxFileName::Normalize(int flags,
844f90fb
VZ
864 const wxString& cwd,
865 wxPathFormat format)
a35b27b1 866{
05e1201c
VZ
867 // deal with env vars renaming first as this may seriously change the path
868 if ( flags & wxPATH_NORM_ENV_VARS )
869 {
870 wxString pathOrig = GetFullPath(format);
871 wxString path = wxExpandEnvVars(pathOrig);
872 if ( path != pathOrig )
873 {
874 Assign(path);
875 }
876 }
877
878
844f90fb
VZ
879 // the existing path components
880 wxArrayString dirs = GetDirs();
881
882 // the path to prepend in front to make the path absolute
883 wxFileName curDir;
884
885 format = GetFormat(format);
ae4d7004 886
844f90fb 887 // make the path absolute
a2fa5040 888 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute(format) )
a35b27b1 889 {
844f90fb 890 if ( cwd.empty() )
6f91bc33
VZ
891 {
892 curDir.AssignCwd(GetVolume());
893 }
894 else // cwd provided
895 {
844f90fb 896 curDir.AssignDir(cwd);
6f91bc33 897 }
52dbd056
VZ
898
899 // the path may be not absolute because it doesn't have the volume name
900 // but in this case we shouldn't modify the directory components of it
901 // but just set the current volume
902 if ( !HasVolume() && curDir.HasVolume() )
903 {
904 SetVolume(curDir.GetVolume());
905
a2fa5040 906 if ( !m_relative )
52dbd056
VZ
907 {
908 // yes, it was the case - we don't need curDir then
909 curDir.Clear();
910 }
911 }
a35b27b1 912 }
ae4d7004 913
844f90fb
VZ
914 // handle ~ stuff under Unix only
915 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) )
a35b27b1 916 {
844f90fb
VZ
917 if ( !dirs.IsEmpty() )
918 {
919 wxString dir = dirs[0u];
920 if ( !dir.empty() && dir[0u] == _T('~') )
921 {
922 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
923
da2fd5ac 924 dirs.RemoveAt(0u);
844f90fb
VZ
925 }
926 }
a35b27b1 927 }
844f90fb 928
52dbd056 929 // transform relative path into abs one
844f90fb 930 if ( curDir.IsOk() )
a35b27b1 931 {
844f90fb
VZ
932 wxArrayString dirsNew = curDir.GetDirs();
933 size_t count = dirs.GetCount();
934 for ( size_t n = 0; n < count; n++ )
935 {
936 dirsNew.Add(dirs[n]);
937 }
938
939 dirs = dirsNew;
a35b27b1 940 }
844f90fb
VZ
941
942 // now deal with ".", ".." and the rest
943 m_dirs.Empty();
944 size_t count = dirs.GetCount();
945 for ( size_t n = 0; n < count; n++ )
a35b27b1 946 {
844f90fb
VZ
947 wxString dir = dirs[n];
948
2bc60417 949 if ( flags & wxPATH_NORM_DOTS )
844f90fb
VZ
950 {
951 if ( dir == wxT(".") )
952 {
953 // just ignore
954 continue;
955 }
956
957 if ( dir == wxT("..") )
958 {
959 if ( m_dirs.IsEmpty() )
960 {
961 wxLogError(_("The path '%s' contains too many \"..\"!"),
962 GetFullPath().c_str());
f363e05c 963 return false;
844f90fb
VZ
964 }
965
ae4d7004 966 m_dirs.RemoveAt(m_dirs.GetCount() - 1);
844f90fb
VZ
967 continue;
968 }
969 }
970
844f90fb
VZ
971 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
972 {
973 dir.MakeLower();
974 }
975
976 m_dirs.Add(dir);
a35b27b1 977 }
a62848fd 978
6bda7391 979#if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
21f60945
JS
980 if ( (flags & wxPATH_NORM_SHORTCUT) )
981 {
982 wxString filename;
983 if (GetShortcutTarget(GetFullPath(format), filename))
984 {
985 // Repeat this since we may now have a new path
986 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
987 {
988 filename.MakeLower();
989 }
990 m_relative = false;
991 Assign(filename);
992 }
993 }
994#endif
844f90fb
VZ
995
996 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
997 {
998 // VZ: expand env vars here too?
999
55268a3a 1000 m_volume.MakeLower();
844f90fb
VZ
1001 m_name.MakeLower();
1002 m_ext.MakeLower();
1003 }
1004
e83ecba9
VZ
1005 // we do have the path now
1006 //
1007 // NB: need to do this before (maybe) calling Assign() below
f363e05c 1008 m_relative = false;
e83ecba9 1009
52dbd056
VZ
1010#if defined(__WIN32__)
1011 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
9e9b65c1
JS
1012 {
1013 Assign(GetLongPath());
1014 }
52dbd056 1015#endif // Win32
9e9b65c1 1016
f363e05c 1017 return true;
a2fa5040
VZ
1018}
1019
21f60945
JS
1020// ----------------------------------------------------------------------------
1021// get the shortcut target
1022// ----------------------------------------------------------------------------
1023
5671b3b6
JS
1024// WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1025// The .lnk file is a plain text file so it should be easy to
1026// make it work. Hint from Google Groups:
1027// "If you open up a lnk file, you'll see a
1028// number, followed by a pound sign (#), followed by more text. The
1029// number is the number of characters that follows the pound sign. The
1030// characters after the pound sign are the command line (which _can_
1031// include arguments) to be executed. Any path (e.g. \windows\program
1032// files\myapp.exe) that includes spaces needs to be enclosed in
1033// quotation marks."
1034
6bda7391 1035#if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
5671b3b6
JS
1036// The following lines are necessary under WinCE
1037// #include "wx/msw/private.h"
1038// #include <ole2.h>
21f60945 1039#include <shlobj.h>
5671b3b6
JS
1040#if defined(__WXWINCE__)
1041#include <shlguid.h>
1042#endif
21f60945 1043
21f60945
JS
1044bool wxFileName::GetShortcutTarget(const wxString& shortcutPath, wxString& targetFilename, wxString* arguments)
1045{
21f60945
JS
1046 wxString path, file, ext;
1047 wxSplitPath(shortcutPath, & path, & file, & ext);
a62848fd
WS
1048
1049 HRESULT hres;
1050 IShellLink* psl;
1051 bool success = false;
21f60945
JS
1052
1053 // Assume it's not a shortcut if it doesn't end with lnk
489f6cf7 1054 if (ext.CmpNoCase(wxT("lnk"))!=0)
a62848fd
WS
1055 return false;
1056
1057 // create a ShellLink object
1058 hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1059 IID_IShellLink, (LPVOID*) &psl);
1060
1061 if (SUCCEEDED(hres))
1062 {
1063 IPersistFile* ppf;
1064 hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
1065 if (SUCCEEDED(hres))
1066 {
1067 WCHAR wsz[MAX_PATH];
1068
1069 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
1070 MAX_PATH);
1071
1072 hres = ppf->Load(wsz, 0);
1073 if (SUCCEEDED(hres))
1074 {
21f60945 1075 wxChar buf[2048];
59ba321b
JS
1076 // Wrong prototype in early versions
1077#if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1078 psl->GetPath((CHAR*) buf, 2048, NULL, SLGP_UNCPRIORITY);
1079#else
a62848fd 1080 psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
59ba321b 1081#endif
a62848fd 1082 targetFilename = wxString(buf);
21f60945
JS
1083 success = (shortcutPath != targetFilename);
1084
a62848fd 1085 psl->GetArguments(buf, 2048);
21f60945 1086 wxString args(buf);
b494c48b 1087 if (!args.empty() && arguments)
21f60945
JS
1088 {
1089 *arguments = args;
a62848fd
WS
1090 }
1091 }
1092 }
1093 }
1094 psl->Release();
1095 return success;
21f60945
JS
1096}
1097#endif
1098
1099
a2fa5040
VZ
1100// ----------------------------------------------------------------------------
1101// absolute/relative paths
1102// ----------------------------------------------------------------------------
1103
1104bool wxFileName::IsAbsolute(wxPathFormat format) const
1105{
1106 // if our path doesn't start with a path separator, it's not an absolute
1107 // path
1108 if ( m_relative )
f363e05c 1109 return false;
a2fa5040
VZ
1110
1111 if ( !GetVolumeSeparator(format).empty() )
1112 {
1113 // this format has volumes and an absolute path must have one, it's not
1114 // enough to have the full path to bean absolute file under Windows
1115 if ( GetVolume().empty() )
f363e05c 1116 return false;
a2fa5040
VZ
1117 }
1118
f363e05c 1119 return true;
a35b27b1
RR
1120}
1121
f7d886af
VZ
1122bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
1123{
cef9731a 1124 wxFileName fnBase = wxFileName::DirName(pathBase, format);
f7d886af
VZ
1125
1126 // get cwd only once - small time saving
1127 wxString cwd = wxGetCwd();
b5b62eea
JS
1128 Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1129 fnBase.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
f7d886af
VZ
1130
1131 bool withCase = IsCaseSensitive(format);
1132
1133 // we can't do anything if the files live on different volumes
1134 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
1135 {
1136 // nothing done
f363e05c 1137 return false;
f7d886af
VZ
1138 }
1139
1140 // same drive, so we don't need our volume
1141 m_volume.clear();
1142
1143 // remove common directories starting at the top
1144 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
1145 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
1146 {
ae4d7004
VZ
1147 m_dirs.RemoveAt(0);
1148 fnBase.m_dirs.RemoveAt(0);
f7d886af
VZ
1149 }
1150
1151 // add as many ".." as needed
1152 size_t count = fnBase.m_dirs.GetCount();
1153 for ( size_t i = 0; i < count; i++ )
1154 {
1155 m_dirs.Insert(wxT(".."), 0u);
1156 }
90a68369 1157
2db991f4
VZ
1158 if ( format == wxPATH_UNIX || format == wxPATH_DOS )
1159 {
1160 // a directory made relative with respect to itself is '.' under Unix
1161 // and DOS, by definition (but we don't have to insert "./" for the
1162 // files)
1163 if ( m_dirs.IsEmpty() && IsDir() )
1164 {
1165 m_dirs.Add(_T('.'));
0ea621cc 1166 }
2db991f4
VZ
1167 }
1168
f363e05c 1169 m_relative = true;
f7d886af
VZ
1170
1171 // we were modified
f363e05c 1172 return true;
f7d886af
VZ
1173}
1174
844f90fb
VZ
1175// ----------------------------------------------------------------------------
1176// filename kind tests
1177// ----------------------------------------------------------------------------
1178
2b5f62a0 1179bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const
df5ddbca 1180{
844f90fb
VZ
1181 wxFileName fn1 = *this,
1182 fn2 = filepath;
1183
1184 // get cwd only once - small time saving
1185 wxString cwd = wxGetCwd();
55268a3a
VZ
1186 fn1.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1187 fn2.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
844f90fb
VZ
1188
1189 if ( fn1.GetFullPath() == fn2.GetFullPath() )
f363e05c 1190 return true;
844f90fb
VZ
1191
1192 // TODO: compare inodes for Unix, this works even when filenames are
1193 // different but files are the same (symlinks) (VZ)
1194
f363e05c 1195 return false;
df5ddbca
RR
1196}
1197
844f90fb 1198/* static */
df5ddbca
RR
1199bool wxFileName::IsCaseSensitive( wxPathFormat format )
1200{
04c943b1
VZ
1201 // only Unix filenames are truely case-sensitive
1202 return GetFormat(format) == wxPATH_UNIX;
df5ddbca
RR
1203}
1204
f363e05c
VZ
1205/* static */
1206wxString wxFileName::GetForbiddenChars(wxPathFormat format)
1207{
1208 // Inits to forbidden characters that are common to (almost) all platforms.
1209 wxString strForbiddenChars = wxT("*?");
1210
1c6f2414 1211 // If asserts, wxPathFormat has been changed. In case of a new path format
f363e05c 1212 // addition, the following code might have to be updated.
1c6f2414 1213 wxCOMPILE_TIME_ASSERT(wxPATH_MAX == 5, wxPathFormatChanged);
f363e05c
VZ
1214 switch ( GetFormat(format) )
1215 {
1216 default :
1217 wxFAIL_MSG( wxT("Unknown path format") );
1218 // !! Fall through !!
1219
1220 case wxPATH_UNIX:
1221 break;
1222
1223 case wxPATH_MAC:
1224 // On a Mac even names with * and ? are allowed (Tested with OS
1225 // 9.2.1 and OS X 10.2.5)
1226 strForbiddenChars = wxEmptyString;
1227 break;
1228
1229 case wxPATH_DOS:
1230 strForbiddenChars += wxT("\\/:\"<>|");
1231 break;
1232
1233 case wxPATH_VMS:
1234 break;
1235 }
1236
1237 return strForbiddenChars;
1238}
1239
04c943b1 1240/* static */
bcfa2b31 1241wxString wxFileName::GetVolumeSeparator(wxPathFormat WXUNUSED_IN_WINCE(format))
844f90fb 1242{
bcfa2b31
WS
1243#ifdef __WXWINCE__
1244 return wxEmptyString;
1245#else
04c943b1
VZ
1246 wxString sepVol;
1247
a385b5df
RR
1248 if ( (GetFormat(format) == wxPATH_DOS) ||
1249 (GetFormat(format) == wxPATH_VMS) )
04c943b1 1250 {
04c943b1
VZ
1251 sepVol = wxFILE_SEP_DSK;
1252 }
a385b5df 1253 //else: leave empty
04c943b1
VZ
1254
1255 return sepVol;
bcfa2b31 1256#endif
844f90fb
VZ
1257}
1258
1259/* static */
1260wxString wxFileName::GetPathSeparators(wxPathFormat format)
1261{
1262 wxString seps;
1263 switch ( GetFormat(format) )
df5ddbca 1264 {
844f90fb 1265 case wxPATH_DOS:
04c943b1
VZ
1266 // accept both as native APIs do but put the native one first as
1267 // this is the one we use in GetFullPath()
1268 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
844f90fb
VZ
1269 break;
1270
1271 default:
f363e05c 1272 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
844f90fb
VZ
1273 // fall through
1274
1275 case wxPATH_UNIX:
9e8d8607 1276 seps = wxFILE_SEP_PATH_UNIX;
844f90fb
VZ
1277 break;
1278
1279 case wxPATH_MAC:
9e8d8607 1280 seps = wxFILE_SEP_PATH_MAC;
844f90fb 1281 break;
04c943b1 1282
3c621059
JJ
1283 case wxPATH_VMS:
1284 seps = wxFILE_SEP_PATH_VMS;
1285 break;
df5ddbca
RR
1286 }
1287
844f90fb 1288 return seps;
df5ddbca
RR
1289}
1290
f1e77933
VZ
1291/* static */
1292wxString wxFileName::GetPathTerminators(wxPathFormat format)
1293{
1294 format = GetFormat(format);
1295
1296 // under VMS the end of the path is ']', not the path separator used to
1297 // separate the components
1298 return format == wxPATH_VMS ? wxString(_T(']')) : GetPathSeparators(format);
1299}
1300
844f90fb
VZ
1301/* static */
1302bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
df5ddbca 1303{
04c943b1 1304 // wxString::Find() doesn't work as expected with NUL - it will always find
2fb5a4ce
VZ
1305 // it, so test for it separately
1306 return ch != _T('\0') && GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
df5ddbca
RR
1307}
1308
844f90fb
VZ
1309// ----------------------------------------------------------------------------
1310// path components manipulation
1311// ----------------------------------------------------------------------------
1312
5bb9aeb2
VZ
1313/* static */ bool wxFileName::IsValidDirComponent(const wxString& dir)
1314{
1315 if ( dir.empty() )
1316 {
1317 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1318
1319 return false;
1320 }
1321
1322 const size_t len = dir.length();
1323 for ( size_t n = 0; n < len; n++ )
1324 {
1325 if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
1326 {
1327 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1328
1329 return false;
1330 }
1331 }
1332
1333 return true;
1334}
1335
2458d90b 1336void wxFileName::AppendDir( const wxString& dir )
df5ddbca 1337{
5bb9aeb2
VZ
1338 if ( IsValidDirComponent(dir) )
1339 m_dirs.Add( dir );
df5ddbca
RR
1340}
1341
2458d90b 1342void wxFileName::PrependDir( const wxString& dir )
df5ddbca 1343{
5bb9aeb2 1344 InsertDir(0, dir);
df5ddbca
RR
1345}
1346
2458d90b 1347void wxFileName::InsertDir(size_t before, const wxString& dir)
df5ddbca 1348{
5bb9aeb2 1349 if ( IsValidDirComponent(dir) )
2458d90b 1350 m_dirs.Insert(dir, before);
df5ddbca
RR
1351}
1352
2458d90b 1353void wxFileName::RemoveDir(size_t pos)
df5ddbca 1354{
2458d90b 1355 m_dirs.RemoveAt(pos);
df5ddbca
RR
1356}
1357
844f90fb
VZ
1358// ----------------------------------------------------------------------------
1359// accessors
1360// ----------------------------------------------------------------------------
1361
7124df9b
VZ
1362void wxFileName::SetFullName(const wxString& fullname)
1363{
dfecbee5
VZ
1364 SplitPath(fullname, NULL /* no volume */, NULL /* no path */,
1365 &m_name, &m_ext, &m_hasExt);
7124df9b
VZ
1366}
1367
844f90fb 1368wxString wxFileName::GetFullName() const
a35b27b1 1369{
844f90fb 1370 wxString fullname = m_name;
dfecbee5 1371 if ( m_hasExt )
a35b27b1 1372 {
9e8d8607 1373 fullname << wxFILE_SEP_EXT << m_ext;
a35b27b1 1374 }
a35b27b1 1375
844f90fb 1376 return fullname;
a35b27b1
RR
1377}
1378
33b97389 1379wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
df5ddbca
RR
1380{
1381 format = GetFormat( format );
844f90fb 1382
353f41cb
RR
1383 wxString fullpath;
1384
33b97389
VZ
1385 // return the volume with the path as well if requested
1386 if ( flags & wxPATH_GET_VOLUME )
1387 {
1388 fullpath += wxGetVolumeString(GetVolume(), format);
1389 }
1390
034742fc
VZ
1391 // the leading character
1392 switch ( format )
1393 {
1394 case wxPATH_MAC:
1395 if ( m_relative )
1396 fullpath += wxFILE_SEP_PATH_MAC;
1397 break;
1398
1399 case wxPATH_DOS:
1400 if ( !m_relative )
1401 fullpath += wxFILE_SEP_PATH_DOS;
1402 break;
1403
1404 default:
1405 wxFAIL_MSG( wxT("Unknown path format") );
1406 // fall through
1407
1408 case wxPATH_UNIX:
1409 if ( !m_relative )
1410 {
1411 // normally the absolute file names start with a slash
1412 // with one exception: the ones like "~/foo.bar" don't
1413 // have it
9b3a3820 1414 if ( m_dirs.IsEmpty() || m_dirs[0u] != _T('~') )
034742fc
VZ
1415 {
1416 fullpath += wxFILE_SEP_PATH_UNIX;
1417 }
1418 }
1419 break;
1420
1421 case wxPATH_VMS:
1422 // no leading character here but use this place to unset
1423 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1424 // as, if I understand correctly, there should never be a dot
1425 // before the closing bracket
1426 flags &= ~wxPATH_GET_SEPARATOR;
1427 }
1428
1429 if ( m_dirs.empty() )
1430 {
1431 // there is nothing more
1432 return fullpath;
1433 }
1434
1435 // then concatenate all the path components using the path separator
1436 if ( format == wxPATH_VMS )
1437 {
1438 fullpath += wxT('[');
1439 }
1440
5bb9aeb2 1441 const size_t dirCount = m_dirs.GetCount();
034742fc 1442 for ( size_t i = 0; i < dirCount; i++ )
353f41cb 1443 {
034742fc 1444 switch (format)
5bb9aeb2
VZ
1445 {
1446 case wxPATH_MAC:
034742fc
VZ
1447 if ( m_dirs[i] == wxT(".") )
1448 {
1449 // skip appending ':', this shouldn't be done in this
1450 // case as "::" is interpreted as ".." under Unix
1451 continue;
1452 }
2361ce82 1453
034742fc 1454 // convert back from ".." to nothing
489f6cf7 1455 if ( !m_dirs[i].IsSameAs(wxT("..")) )
034742fc 1456 fullpath += m_dirs[i];
5bb9aeb2 1457 break;
2361ce82 1458
5bb9aeb2 1459 default:
034742fc
VZ
1460 wxFAIL_MSG( wxT("Unexpected path format") );
1461 // still fall through
2361ce82 1462
034742fc 1463 case wxPATH_DOS:
5bb9aeb2 1464 case wxPATH_UNIX:
034742fc 1465 fullpath += m_dirs[i];
5bb9aeb2 1466 break;
2361ce82 1467
5bb9aeb2 1468 case wxPATH_VMS:
034742fc 1469 // TODO: What to do with ".." under VMS
353f41cb 1470
034742fc 1471 // convert back from ".." to nothing
489f6cf7 1472 if ( !m_dirs[i].IsSameAs(wxT("..")) )
353f41cb 1473 fullpath += m_dirs[i];
034742fc 1474 break;
4175794e
VZ
1475 }
1476
034742fc
VZ
1477 if ( (flags & wxPATH_GET_SEPARATOR) || (i != dirCount - 1) )
1478 fullpath += GetPathSeparator(format);
df5ddbca 1479 }
034742fc
VZ
1480
1481 if ( format == wxPATH_VMS )
5bb9aeb2 1482 {
034742fc 1483 fullpath += wxT(']');
5bb9aeb2 1484 }
844f90fb 1485
353f41cb 1486 return fullpath;
df5ddbca
RR
1487}
1488
1489wxString wxFileName::GetFullPath( wxPathFormat format ) const
1490{
4175794e
VZ
1491 // we already have a function to get the path
1492 wxString fullpath = GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR,
1493 format);
04c943b1 1494
4175794e 1495 // now just add the file name and extension to it
04c943b1
VZ
1496 fullpath += GetFullName();
1497
1498 return fullpath;
df5ddbca
RR
1499}
1500
9e9b65c1
JS
1501// Return the short form of the path (returns identity on non-Windows platforms)
1502wxString wxFileName::GetShortPath() const
1503{
9e9b65c1 1504 wxString path(GetFullPath());
2f3d9587
VZ
1505
1506#if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
75ef5722 1507 DWORD sz = ::GetShortPathName(path, NULL, 0);
2f3d9587 1508 if ( sz != 0 )
9e9b65c1 1509 {
2f3d9587
VZ
1510 wxString pathOut;
1511 if ( ::GetShortPathName
75ef5722
JS
1512 (
1513 path,
de564874 1514 wxStringBuffer(pathOut, sz),
75ef5722 1515 sz
2f3d9587
VZ
1516 ) != 0 )
1517 {
1518 return pathOut;
1519 }
9e9b65c1 1520 }
2f3d9587 1521#endif // Windows
5716a1ab
VZ
1522
1523 return path;
9e9b65c1
JS
1524}
1525
1526// Return the long form of the path (returns identity on non-Windows platforms)
1527wxString wxFileName::GetLongPath() const
1528{
52dbd056
VZ
1529 wxString pathOut,
1530 path = GetFullPath();
1531
1532#if defined(__WIN32__) && !defined(__WXMICROWIN__)
05e7001c 1533
35a6691a 1534#if wxUSE_DYNAMIC_LOADER
62dcaed6 1535 typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
05e7001c 1536
2f3d9587
VZ
1537 // this is MT-safe as in the worst case we're going to resolve the function
1538 // twice -- but as the result is the same in both threads, it's ok
1539 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
1540 if ( !s_pfnGetLongPathName )
9e9b65c1 1541 {
2f3d9587 1542 static bool s_triedToLoad = false;
2361ce82 1543
2f3d9587 1544 if ( !s_triedToLoad )
05e7001c 1545 {
2f3d9587
VZ
1546 s_triedToLoad = true;
1547
1548 wxDynamicLibrary dllKernel(_T("kernel32"));
1549
4377d3ab
WS
1550 const wxChar* GetLongPathName = _T("GetLongPathName")
1551#if wxUSE_UNICODE
1552 _T("W");
1553#else // ANSI
1554 _T("A");
1555#endif // Unicode/ANSI
1556
1557 if ( dllKernel.HasSymbol(GetLongPathName) )
05e7001c 1558 {
2f3d9587 1559 s_pfnGetLongPathName = (GET_LONG_PATH_NAME)
4377d3ab 1560 dllKernel.GetSymbol(GetLongPathName);
05e7001c 1561 }
2f3d9587
VZ
1562
1563 // note that kernel32.dll can be unloaded, it stays in memory
1564 // anyhow as all Win32 programs link to it and so it's safe to call
1565 // GetLongPathName() even after unloading it
05e7001c 1566 }
9e9b65c1 1567 }
2361ce82 1568
2f3d9587
VZ
1569 if ( s_pfnGetLongPathName )
1570 {
1571 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
1572 if ( dwSize > 0 )
1573 {
1574 if ( (*s_pfnGetLongPathName)
1575 (
1576 path,
1577 wxStringBuffer(pathOut, dwSize),
1578 dwSize
1579 ) != 0 )
1580 {
1581 return pathOut;
1582 }
1583 }
1584 }
0b9ab0bd 1585#endif // wxUSE_DYNAMIC_LOADER
05e7001c 1586
2f3d9587
VZ
1587 // The OS didn't support GetLongPathName, or some other error.
1588 // We need to call FindFirstFile on each component in turn.
05e7001c 1589
2f3d9587
VZ
1590 WIN32_FIND_DATA findFileData;
1591 HANDLE hFind;
b5b62eea 1592
2f3d9587
VZ
1593 if ( HasVolume() )
1594 pathOut = GetVolume() +
1595 GetVolumeSeparator(wxPATH_DOS) +
1596 GetPathSeparator(wxPATH_DOS);
1597 else
1598 pathOut = wxEmptyString;
05e7001c 1599
2f3d9587
VZ
1600 wxArrayString dirs = GetDirs();
1601 dirs.Add(GetFullName());
77fe02a8 1602
2f3d9587 1603 wxString tmpPath;
5d978d07 1604
2f3d9587
VZ
1605 size_t count = dirs.GetCount();
1606 for ( size_t i = 0; i < count; i++ )
1607 {
1608 // We're using pathOut to collect the long-name path, but using a
1609 // temporary for appending the last path component which may be
1610 // short-name
1611 tmpPath = pathOut + dirs[i];
05e7001c 1612
2f3d9587
VZ
1613 if ( tmpPath.empty() )
1614 continue;
52dbd056 1615
2f3d9587
VZ
1616 // can't see this being necessary? MF
1617 if ( tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
1618 {
1619 // Can't pass a drive and root dir to FindFirstFile,
1620 // so continue to next dir
1621 tmpPath += wxFILE_SEP_PATH;
1622 pathOut = tmpPath;
1623 continue;
1624 }
05e7001c 1625
2f3d9587
VZ
1626 hFind = ::FindFirstFile(tmpPath, &findFileData);
1627 if (hFind == INVALID_HANDLE_VALUE)
1628 {
1629 // Error: most likely reason is that path doesn't exist, so
1630 // append any unprocessed parts and return
1631 for ( i += 1; i < count; i++ )
1632 tmpPath += wxFILE_SEP_PATH + dirs[i];
b5b62eea 1633
2f3d9587
VZ
1634 return tmpPath;
1635 }
05e7001c 1636
2f3d9587
VZ
1637 pathOut += findFileData.cFileName;
1638 if ( (i < (count-1)) )
1639 pathOut += wxFILE_SEP_PATH;
52dbd056 1640
2f3d9587 1641 ::FindClose(hFind);
05e7001c 1642 }
52dbd056
VZ
1643#else // !Win32
1644 pathOut = path;
1645#endif // Win32/!Win32
5716a1ab 1646
05e7001c 1647 return pathOut;
9e9b65c1
JS
1648}
1649
df5ddbca
RR
1650wxPathFormat wxFileName::GetFormat( wxPathFormat format )
1651{
1652 if (format == wxPATH_NATIVE)
1653 {
5a3912f2 1654#if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
df5ddbca 1655 format = wxPATH_DOS;
4d293f8e 1656#elif defined(__WXMAC__) && !defined(__DARWIN__)
04c943b1 1657 format = wxPATH_MAC;
3c621059 1658#elif defined(__VMS)
04c943b1 1659 format = wxPATH_VMS;
844f90fb 1660#else
df5ddbca
RR
1661 format = wxPATH_UNIX;
1662#endif
1663 }
1664 return format;
1665}
a35b27b1 1666
9e8d8607
VZ
1667// ----------------------------------------------------------------------------
1668// path splitting function
1669// ----------------------------------------------------------------------------
1670
6f91bc33 1671/* static */
f1e77933
VZ
1672void
1673wxFileName::SplitVolume(const wxString& fullpathWithVolume,
1674 wxString *pstrVolume,
1675 wxString *pstrPath,
1676 wxPathFormat format)
9e8d8607
VZ
1677{
1678 format = GetFormat(format);
1679
04c943b1
VZ
1680 wxString fullpath = fullpathWithVolume;
1681
04c943b1
VZ
1682 // special Windows UNC paths hack: transform \\share\path into share:path
1683 if ( format == wxPATH_DOS )
9e8d8607 1684 {
04c943b1
VZ
1685 if ( fullpath.length() >= 4 &&
1686 fullpath[0u] == wxFILE_SEP_PATH_DOS &&
1687 fullpath[1u] == wxFILE_SEP_PATH_DOS )
9e8d8607 1688 {
04c943b1
VZ
1689 fullpath.erase(0, 2);
1690
f1e77933
VZ
1691 size_t posFirstSlash =
1692 fullpath.find_first_of(GetPathTerminators(format));
04c943b1
VZ
1693 if ( posFirstSlash != wxString::npos )
1694 {
1695 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
1696
1697 // UNC paths are always absolute, right? (FIXME)
de564874 1698 fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
04c943b1 1699 }
3c621059
JJ
1700 }
1701 }
04c943b1 1702
a385b5df
RR
1703 // We separate the volume here
1704 if ( format == wxPATH_DOS || format == wxPATH_VMS )
04c943b1 1705 {
a385b5df 1706 wxString sepVol = GetVolumeSeparator(format);
24eb81cb 1707
04c943b1
VZ
1708 size_t posFirstColon = fullpath.find_first_of(sepVol);
1709 if ( posFirstColon != wxString::npos )
1710 {
1711 if ( pstrVolume )
1712 {
1713 *pstrVolume = fullpath.Left(posFirstColon);
1714 }
1715
1716 // remove the volume name and the separator from the full path
1717 fullpath.erase(0, posFirstColon + sepVol.length());
1718 }
1719 }
1720
f1e77933
VZ
1721 if ( pstrPath )
1722 *pstrPath = fullpath;
1723}
1724
1725/* static */
1726void wxFileName::SplitPath(const wxString& fullpathWithVolume,
1727 wxString *pstrVolume,
1728 wxString *pstrPath,
1729 wxString *pstrName,
1730 wxString *pstrExt,
dfecbee5 1731 bool *hasExt,
f1e77933
VZ
1732 wxPathFormat format)
1733{
1734 format = GetFormat(format);
1735
1736 wxString fullpath;
1737 SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
1738
04c943b1
VZ
1739 // find the positions of the last dot and last path separator in the path
1740 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
f1e77933 1741 size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
04c943b1 1742
e5a573a2 1743 // check whether this dot occurs at the very beginning of a path component
04c943b1 1744 if ( (posLastDot != wxString::npos) &&
e5a573a2
VZ
1745 (posLastDot == 0 ||
1746 IsPathSeparator(fullpath[posLastDot - 1]) ||
1747 (format == wxPATH_VMS && fullpath[posLastDot - 1] == _T(']'))) )
f1e77933
VZ
1748 {
1749 // dot may be (and commonly -- at least under Unix -- is) the first
1750 // character of the filename, don't treat the entire filename as
1751 // extension in this case
1752 posLastDot = wxString::npos;
1753 }
9e8d8607 1754
8e7dda21
VZ
1755 // if we do have a dot and a slash, check that the dot is in the name part
1756 if ( (posLastDot != wxString::npos) &&
1757 (posLastSlash != wxString::npos) &&
1758 (posLastDot < posLastSlash) )
9e8d8607
VZ
1759 {
1760 // the dot is part of the path, not the start of the extension
1761 posLastDot = wxString::npos;
1762 }
1763
1764 // now fill in the variables provided by user
1765 if ( pstrPath )
1766 {
1767 if ( posLastSlash == wxString::npos )
1768 {
1769 // no path at all
1770 pstrPath->Empty();
1771 }
1772 else
1773 {
04c943b1 1774 // take everything up to the path separator but take care to make
353f41cb 1775 // the path equal to something like '/', not empty, for the files
04c943b1
VZ
1776 // immediately under root directory
1777 size_t len = posLastSlash;
91b4bd63
SC
1778
1779 // this rule does not apply to mac since we do not start with colons (sep)
1780 // except for relative paths
1781 if ( !len && format != wxPATH_MAC)
04c943b1
VZ
1782 len++;
1783
1784 *pstrPath = fullpath.Left(len);
1785
1786 // special VMS hack: remove the initial bracket
1787 if ( format == wxPATH_VMS )
1788 {
1789 if ( (*pstrPath)[0u] == _T('[') )
1790 pstrPath->erase(0, 1);
1791 }
9e8d8607
VZ
1792 }
1793 }
1794
1795 if ( pstrName )
1796 {
42b1f941
VZ
1797 // take all characters starting from the one after the last slash and
1798 // up to, but excluding, the last dot
9e8d8607 1799 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
8e7dda21
VZ
1800 size_t count;
1801 if ( posLastDot == wxString::npos )
1802 {
1803 // take all until the end
1804 count = wxString::npos;
1805 }
1806 else if ( posLastSlash == wxString::npos )
1807 {
1808 count = posLastDot;
1809 }
1810 else // have both dot and slash
1811 {
1812 count = posLastDot - posLastSlash - 1;
1813 }
9e8d8607
VZ
1814
1815 *pstrName = fullpath.Mid(nStart, count);
1816 }
1817
dfecbee5
VZ
1818 // finally deal with the extension here: we have an added complication that
1819 // extension may be empty (but present) as in "foo." where trailing dot
1820 // indicates the empty extension at the end -- and hence we must remember
1821 // that we have it independently of pstrExt
1822 if ( posLastDot == wxString::npos )
9e8d8607 1823 {
dfecbee5
VZ
1824 // no extension
1825 if ( pstrExt )
1826 pstrExt->clear();
1827 if ( hasExt )
1828 *hasExt = false;
1829 }
1830 else
1831 {
1832 // take everything after the dot
1833 if ( pstrExt )
9e8d8607 1834 *pstrExt = fullpath.Mid(posLastDot + 1);
dfecbee5
VZ
1835 if ( hasExt )
1836 *hasExt = true;
9e8d8607
VZ
1837 }
1838}
951cd180 1839
6f91bc33
VZ
1840/* static */
1841void wxFileName::SplitPath(const wxString& fullpath,
1842 wxString *path,
1843 wxString *name,
1844 wxString *ext,
1845 wxPathFormat format)
1846{
1847 wxString volume;
1848 SplitPath(fullpath, &volume, path, name, ext, format);
1849
67c34f64 1850 if ( path )
6f91bc33 1851 {
67c34f64 1852 path->Prepend(wxGetVolumeString(volume, format));
6f91bc33
VZ
1853 }
1854}
1855
951cd180
VZ
1856// ----------------------------------------------------------------------------
1857// time functions
1858// ----------------------------------------------------------------------------
1859
e2b87f38
VZ
1860#if wxUSE_DATETIME
1861
6dbb903b
VZ
1862bool wxFileName::SetTimes(const wxDateTime *dtAccess,
1863 const wxDateTime *dtMod,
1864 const wxDateTime *dtCreate)
951cd180 1865{
2b5f62a0
VZ
1866#if defined(__WIN32__)
1867 if ( IsDir() )
1868 {
1869 // VZ: please let me know how to do this if you can
1870 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
1871 }
1872 else // file
1873 {
1874 wxFileHandle fh(GetFullPath(), wxFileHandle::Write);
1875 if ( fh.IsOk() )
1876 {
1877 FILETIME ftAccess, ftCreate, ftWrite;
1878
1879 if ( dtCreate )
1880 ConvertWxToFileTime(&ftCreate, *dtCreate);
1881 if ( dtAccess )
1882 ConvertWxToFileTime(&ftAccess, *dtAccess);
1883 if ( dtMod )
1884 ConvertWxToFileTime(&ftWrite, *dtMod);
1885
1886 if ( ::SetFileTime(fh,
1887 dtCreate ? &ftCreate : NULL,
1888 dtAccess ? &ftAccess : NULL,
1889 dtMod ? &ftWrite : NULL) )
1890 {
f363e05c 1891 return true;
2b5f62a0
VZ
1892 }
1893 }
1894 }
1895#elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
17a1ebd1
VZ
1896 wxUnusedVar(dtCreate);
1897
246c704f
VZ
1898 if ( !dtAccess && !dtMod )
1899 {
1900 // can't modify the creation time anyhow, don't try
f363e05c 1901 return true;
246c704f
VZ
1902 }
1903
1904 // if dtAccess or dtMod is not specified, use the other one (which must be
1905 // non NULL because of the test above) for both times
951cd180 1906 utimbuf utm;
246c704f
VZ
1907 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
1908 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
401eb3de 1909 if ( utime(GetFullPath().fn_str(), &utm) == 0 )
951cd180 1910 {
f363e05c 1911 return true;
951cd180 1912 }
951cd180 1913#else // other platform
7a893a31
WS
1914 wxUnusedVar(dtAccess);
1915 wxUnusedVar(dtMod);
1916 wxUnusedVar(dtCreate);
951cd180
VZ
1917#endif // platforms
1918
1919 wxLogSysError(_("Failed to modify file times for '%s'"),
1920 GetFullPath().c_str());
1921
f363e05c 1922 return false;
951cd180
VZ
1923}
1924
1925bool wxFileName::Touch()
1926{
1927#if defined(__UNIX_LIKE__)
1928 // under Unix touching file is simple: just pass NULL to utime()
401eb3de 1929 if ( utime(GetFullPath().fn_str(), NULL) == 0 )
951cd180 1930 {
f363e05c 1931 return true;
951cd180
VZ
1932 }
1933
1934 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1935
f363e05c 1936 return false;
951cd180
VZ
1937#else // other platform
1938 wxDateTime dtNow = wxDateTime::Now();
1939
6dbb903b 1940 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
951cd180
VZ
1941#endif // platforms
1942}
1943
1944bool wxFileName::GetTimes(wxDateTime *dtAccess,
1945 wxDateTime *dtMod,
6dbb903b 1946 wxDateTime *dtCreate) const
951cd180 1947{
2b5f62a0
VZ
1948#if defined(__WIN32__)
1949 // we must use different methods for the files and directories under
1950 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
1951 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
1952 // not 9x
1953 bool ok;
1954 FILETIME ftAccess, ftCreate, ftWrite;
1955 if ( IsDir() )
1956 {
1957 // implemented in msw/dir.cpp
1958 extern bool wxGetDirectoryTimes(const wxString& dirname,
1959 FILETIME *, FILETIME *, FILETIME *);
1960
1961 // we should pass the path without the trailing separator to
1962 // wxGetDirectoryTimes()
1963 ok = wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME),
1964 &ftAccess, &ftCreate, &ftWrite);
1965 }
1966 else // file
1967 {
1968 wxFileHandle fh(GetFullPath(), wxFileHandle::Read);
1969 if ( fh.IsOk() )
1970 {
1971 ok = ::GetFileTime(fh,
1972 dtCreate ? &ftCreate : NULL,
1973 dtAccess ? &ftAccess : NULL,
1974 dtMod ? &ftWrite : NULL) != 0;
1975 }
1976 else
1977 {
f363e05c 1978 ok = false;
2b5f62a0
VZ
1979 }
1980 }
1981
1982 if ( ok )
1983 {
1984 if ( dtCreate )
1985 ConvertFileTimeToWx(dtCreate, ftCreate);
1986 if ( dtAccess )
1987 ConvertFileTimeToWx(dtAccess, ftAccess);
1988 if ( dtMod )
1989 ConvertFileTimeToWx(dtMod, ftWrite);
1990
f363e05c 1991 return true;
2b5f62a0 1992 }
bf58daba 1993#elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
951cd180 1994 wxStructStat stBuf;
92980e90 1995 if ( wxStat( GetFullPath().c_str(), &stBuf) == 0 )
951cd180
VZ
1996 {
1997 if ( dtAccess )
1998 dtAccess->Set(stBuf.st_atime);
1999 if ( dtMod )
2000 dtMod->Set(stBuf.st_mtime);
6dbb903b
VZ
2001 if ( dtCreate )
2002 dtCreate->Set(stBuf.st_ctime);
951cd180 2003
f363e05c 2004 return true;
951cd180 2005 }
951cd180 2006#else // other platform
7a893a31
WS
2007 wxUnusedVar(dtAccess);
2008 wxUnusedVar(dtMod);
2009 wxUnusedVar(dtCreate);
951cd180
VZ
2010#endif // platforms
2011
2012 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2013 GetFullPath().c_str());
2014
f363e05c 2015 return false;
951cd180
VZ
2016}
2017
e2b87f38
VZ
2018#endif // wxUSE_DATETIME
2019
4dfbcdd5
SC
2020#ifdef __WXMAC__
2021
2022const short kMacExtensionMaxLength = 16 ;
0ca4ae93 2023class MacDefaultExtensionRecord
4dfbcdd5 2024{
0ca4ae93
SC
2025public :
2026 MacDefaultExtensionRecord()
2027 {
2028 m_ext[0] = 0 ;
1a183bb1 2029 m_type = m_creator = 0 ;
0ca4ae93
SC
2030 }
2031 MacDefaultExtensionRecord( const MacDefaultExtensionRecord& from )
2032 {
44c44c82 2033 wxStrcpy( m_ext , from.m_ext ) ;
0ca4ae93
SC
2034 m_type = from.m_type ;
2035 m_creator = from.m_creator ;
2036 }
44c44c82 2037 MacDefaultExtensionRecord( const wxChar * extension , OSType type , OSType creator )
0ca4ae93 2038 {
44c44c82 2039 wxStrncpy( m_ext , extension , kMacExtensionMaxLength ) ;
0ca4ae93
SC
2040 m_ext[kMacExtensionMaxLength] = 0 ;
2041 m_type = type ;
2042 m_creator = creator ;
2043 }
44c44c82 2044 wxChar m_ext[kMacExtensionMaxLength] ;
4dfbcdd5
SC
2045 OSType m_type ;
2046 OSType m_creator ;
0ca4ae93 2047} ;
4dfbcdd5
SC
2048
2049#include "wx/dynarray.h"
2050WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ;
0ca4ae93
SC
2051
2052bool gMacDefaultExtensionsInited = false ;
2053
4dfbcdd5 2054#include "wx/arrimpl.cpp"
0ca4ae93
SC
2055
2056WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray) ;
4dfbcdd5
SC
2057
2058MacDefaultExtensionArray gMacDefaultExtensions ;
4dfbcdd5 2059
5974c3cf
SC
2060// load the default extensions
2061MacDefaultExtensionRecord gDefaults[] =
4dfbcdd5 2062{
5974c3cf
SC
2063 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2064 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2065 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2066} ;
0ea621cc 2067
5974c3cf
SC
2068static void MacEnsureDefaultExtensionsLoaded()
2069{
2070 if ( !gMacDefaultExtensionsInited )
4dfbcdd5 2071 {
5974c3cf
SC
2072 // we could load the pc exchange prefs here too
2073 for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
2074 {
2075 gMacDefaultExtensions.Add( gDefaults[i] ) ;
2076 }
2077 gMacDefaultExtensionsInited = true ;
0ea621cc 2078 }
4dfbcdd5 2079}
a2b77260 2080
0ea621cc 2081bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
4dfbcdd5 2082{
a2b77260
SC
2083 FSRef fsRef ;
2084 FSCatalogInfo catInfo;
2085 FileInfo *finfo ;
4dfbcdd5 2086
a2b77260
SC
2087 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2088 {
a62848fd
WS
2089 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2090 {
2091 finfo = (FileInfo*)&catInfo.finderInfo;
2092 finfo->fileType = type ;
2093 finfo->fileCreator = creator ;
2094 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
a2b77260 2095 return true ;
a62848fd 2096 }
a2b77260
SC
2097 }
2098 return false ;
4dfbcdd5
SC
2099}
2100
0ea621cc 2101bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
4dfbcdd5 2102{
a2b77260
SC
2103 FSRef fsRef ;
2104 FSCatalogInfo catInfo;
2105 FileInfo *finfo ;
4dfbcdd5 2106
a2b77260
SC
2107 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2108 {
a62848fd
WS
2109 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2110 {
2111 finfo = (FileInfo*)&catInfo.finderInfo;
2112 *type = finfo->fileType ;
2113 *creator = finfo->fileCreator ;
a2b77260 2114 return true ;
a62848fd 2115 }
a2b77260
SC
2116 }
2117 return false ;
4dfbcdd5
SC
2118}
2119
2120bool wxFileName::MacSetDefaultTypeAndCreator()
2121{
2122 wxUint32 type , creator ;
2123 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
2124 &creator ) )
2125 {
f63fb56d
GD
2126 return MacSetTypeAndCreator( type , creator ) ;
2127 }
2128 return false;
4dfbcdd5
SC
2129}
2130
0ea621cc 2131bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
4dfbcdd5
SC
2132{
2133 MacEnsureDefaultExtensionsLoaded() ;
2134 wxString extl = ext.Lower() ;
2135 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
2136 {
2137 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
2138 {
2139 *type = gMacDefaultExtensions.Item(i).m_type ;
2140 *creator = gMacDefaultExtensions.Item(i).m_creator ;
2141 return true ;
2142 }
2143 }
2144 return false ;
2145}
2146
2147void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
2148{
2149 MacEnsureDefaultExtensionsLoaded() ;
2150 MacDefaultExtensionRecord rec ;
2151 rec.m_type = type ;
2152 rec.m_creator = creator ;
44c44c82 2153 wxStrncpy( rec.m_ext , ext.Lower().c_str() , kMacExtensionMaxLength ) ;
4dfbcdd5
SC
2154 gMacDefaultExtensions.Add( rec ) ;
2155}
2156#endif