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