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