]> git.saurik.com Git - wxWidgets.git/blame - src/common/filename.cpp
fixed MSLU check
[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
9// Licence: wxWindows license
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.
50 [ start of directory specyfication
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 63#ifdef __GNUG__
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"
03169422 85//#include "wx/dynlib.h" // see GetLongPath below, code disabled.
df5ddbca 86
9e9b65c1
JS
87// For GetShort/LongPathName
88#ifdef __WIN32__
0b9ab0bd
RL
89#include <windows.h>
90#include "wx/msw/winundef.h"
951cd180
VZ
91#endif
92
76a5e5d2
SC
93#if defined(__WXMAC__)
94 #include "wx/mac/private.h" // includes mac headers
95#endif
96
951cd180
VZ
97// utime() is POSIX so should normally be available on all Unices
98#ifdef __UNIX_LIKE__
0b9ab0bd
RL
99#include <sys/types.h>
100#include <utime.h>
101#include <sys/stat.h>
102#include <unistd.h>
9e9b65c1
JS
103#endif
104
444d61ba
VS
105#ifdef __DJGPP__
106#include <unistd.h>
107#endif
108
01d981ec 109#ifdef __MWERKS__
0b9ab0bd
RL
110#include <stat.h>
111#include <unistd.h>
112#include <unix.h>
01d981ec
RR
113#endif
114
d9f54bb0 115#ifdef __WATCOMC__
0b9ab0bd
RL
116#include <io.h>
117#include <sys/utime.h>
118#include <sys/stat.h>
d9f54bb0
VS
119#endif
120
24eb81cb
DW
121#ifdef __VISAGECPP__
122#ifndef MAX_PATH
123#define MAX_PATH 256
124#endif
125#endif
126
951cd180
VZ
127// ----------------------------------------------------------------------------
128// private classes
129// ----------------------------------------------------------------------------
130
131// small helper class which opens and closes the file - we use it just to get
132// a file handle for the given file name to pass it to some Win32 API function
c67d6888 133#if defined(__WIN32__) && !defined(__WXMICROWIN__)
951cd180
VZ
134
135class wxFileHandle
136{
137public:
138 wxFileHandle(const wxString& filename)
139 {
140 m_hFile = ::CreateFile
141 (
142 filename, // name
143 GENERIC_READ, // access mask
144 0, // no sharing
145 NULL, // no secutity attr
146 OPEN_EXISTING, // creation disposition
147 0, // no flags
148 NULL // no template file
149 );
150
151 if ( m_hFile == INVALID_HANDLE_VALUE )
152 {
153 wxLogSysError(_("Failed to open '%s' for reading"),
154 filename.c_str());
155 }
156 }
157
158 ~wxFileHandle()
159 {
160 if ( m_hFile != INVALID_HANDLE_VALUE )
161 {
162 if ( !::CloseHandle(m_hFile) )
163 {
164 wxLogSysError(_("Failed to close file handle"));
165 }
166 }
167 }
168
169 // return TRUE only if the file could be opened successfully
170 bool IsOk() const { return m_hFile != INVALID_HANDLE_VALUE; }
171
172 // get the handle
173 operator HANDLE() const { return m_hFile; }
174
175private:
176 HANDLE m_hFile;
177};
178
179#endif // __WIN32__
180
181// ----------------------------------------------------------------------------
182// private functions
183// ----------------------------------------------------------------------------
184
c67d6888 185#if defined(__WIN32__) && !defined(__WXMICROWIN__)
951cd180
VZ
186
187// convert between wxDateTime and FILETIME which is a 64-bit value representing
188// the number of 100-nanosecond intervals since January 1, 1601.
189
d56e2b97
VZ
190// the number of milliseconds between the Unix Epoch (January 1, 1970) and the
191// FILETIME reference point (January 1, 1601)
192static const wxLongLong FILETIME_EPOCH_OFFSET = wxLongLong(0xa97, 0x30b66800);
193
194static void ConvertFileTimeToWx(wxDateTime *dt, const FILETIME &ft)
951cd180 195{
d56e2b97
VZ
196 wxLongLong ll(ft.dwHighDateTime, ft.dwLowDateTime);
197
198 // convert 100ns to ms
199 ll /= 10000;
200
201 // move it to our Epoch
202 ll -= FILETIME_EPOCH_OFFSET;
203
204 *dt = wxDateTime(ll);
951cd180
VZ
205}
206
d56e2b97 207static void ConvertWxToFileTime(FILETIME *ft, const wxDateTime& dt)
951cd180 208{
d56e2b97
VZ
209 // do the reverse of ConvertFileTimeToWx()
210 wxLongLong ll = dt.GetValue();
211 ll *= 10000;
212 ll += FILETIME_EPOCH_OFFSET;
213
214 ft->dwHighDateTime = ll.GetHi();
215 ft->dwLowDateTime = ll.GetLo();
951cd180
VZ
216}
217
218#endif // __WIN32__
219
097ead30
VZ
220// ============================================================================
221// implementation
222// ============================================================================
223
224// ----------------------------------------------------------------------------
844f90fb 225// wxFileName construction
097ead30 226// ----------------------------------------------------------------------------
df5ddbca 227
a35b27b1
RR
228void wxFileName::Assign( const wxFileName &filepath )
229{
04c943b1 230 m_volume = filepath.GetVolume();
844f90fb 231 m_dirs = filepath.GetDirs();
04c943b1
VZ
232 m_name = filepath.GetName();
233 m_ext = filepath.GetExt();
353f41cb 234 m_relative = filepath.IsRelative();
df5ddbca
RR
235}
236
04c943b1
VZ
237void wxFileName::Assign(const wxString& volume,
238 const wxString& path,
239 const wxString& name,
240 const wxString& ext,
241 wxPathFormat format )
a7b51bc8
RR
242{
243 SetPath( path, format );
244
245 m_volume = volume;
246 m_ext = ext;
247 m_name = name;
248}
249
250void wxFileName::SetPath( const wxString &path, wxPathFormat format )
df5ddbca 251{
353f41cb
RR
252 wxPathFormat my_format = GetFormat( format );
253 wxString my_path = path;
90a68369 254
844f90fb 255 m_dirs.Clear();
90a68369 256
353f41cb 257 if (!my_path.empty())
df5ddbca 258 {
353f41cb 259 // 1) Determine if the path is relative or absolute.
90a68369 260
353f41cb
RR
261 switch (my_format)
262 {
263 case wxPATH_MAC:
264 m_relative = ( my_path[0u] == wxT(':') );
265 // We then remove a leading ":". The reason is in our
266 // storage form for relative paths:
267 // ":dir:file.txt" actually means "./dir/file.txt" in
90a68369 268 // DOS notation and should get stored as
353f41cb
RR
269 // (relative) (dir) (file.txt)
270 // "::dir:file.txt" actually means "../dir/file.txt"
271 // stored as (relative) (..) (dir) (file.txt)
272 // This is important only for the Mac as an empty dir
273 // actually means <UP>, whereas under DOS, double
274 // slashes can be ignored: "\\\\" is the same as "\\".
275 if (m_relative)
276 my_path.Remove( 0, 1 );
277 break;
278 case wxPATH_VMS:
279 // TODO: what is the relative path format here?
280 m_relative = FALSE;
281 break;
282 case wxPATH_UNIX:
283 m_relative = ( my_path[0u] != wxT('/') );
284 break;
285 case wxPATH_DOS:
286 m_relative = ( (my_path[0u] != wxT('/')) && (my_path[0u] != wxT('\\')) );
287 break;
288 default:
7613582b 289 wxFAIL_MSG( wxT("error") );
353f41cb
RR
290 break;
291 }
90a68369 292
353f41cb
RR
293 // 2) Break up the path into its members. If the original path
294 // was just "/" or "\\", m_dirs will be empty. We know from
295 // the m_relative field, if this means "nothing" or "root dir".
90a68369 296
353f41cb
RR
297 wxStringTokenizer tn( my_path, GetPathSeparators(my_format) );
298
299 while ( tn.HasMoreTokens() )
300 {
301 wxString token = tn.GetNextToken();
844f90fb 302
353f41cb
RR
303 // Remove empty token under DOS and Unix, interpret them
304 // as .. under Mac.
305 if (token.empty())
306 {
307 if (my_format == wxPATH_MAC)
308 m_dirs.Add( wxT("..") );
309 // else ignore
310 }
311 else
312 {
313 m_dirs.Add( token );
314 }
315 }
df5ddbca 316 }
a7b51bc8
RR
317 else
318 {
319 m_relative = TRUE;
320 }
844f90fb
VZ
321}
322
323void wxFileName::Assign(const wxString& fullpath,
324 wxPathFormat format)
325{
04c943b1
VZ
326 wxString volume, path, name, ext;
327 SplitPath(fullpath, &volume, &path, &name, &ext, format);
844f90fb 328
04c943b1 329 Assign(volume, path, name, ext, format);
844f90fb
VZ
330}
331
81f25632 332void wxFileName::Assign(const wxString& fullpathOrig,
844f90fb
VZ
333 const wxString& fullname,
334 wxPathFormat format)
335{
81f25632
VZ
336 // always recognize fullpath as directory, even if it doesn't end with a
337 // slash
338 wxString fullpath = fullpathOrig;
339 if ( !wxEndsWithPathSeparator(fullpath) )
340 {
341 fullpath += GetPathSeparators(format)[0u];
342 }
343
52dbd056 344 wxString volume, path, name, ext;
81f25632
VZ
345
346 // do some consistency checks in debug mode: the name should be really just
353f41cb 347 // the filename and the path should be really just a path
81f25632
VZ
348#ifdef __WXDEBUG__
349 wxString pathDummy, nameDummy, extDummy;
350
351 SplitPath(fullname, &pathDummy, &name, &ext, format);
352
353 wxASSERT_MSG( pathDummy.empty(),
354 _T("the file name shouldn't contain the path") );
355
356 SplitPath(fullpath, &volume, &path, &nameDummy, &extDummy, format);
357
358 wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
359 _T("the path shouldn't contain file name nor extension") );
360
361#else // !__WXDEBUG__
574c939e 362 SplitPath(fullname, NULL /* no path */, &name, &ext, format);
52dbd056 363 SplitPath(fullpath, &volume, &path, NULL, NULL, format);
81f25632 364#endif // __WXDEBUG__/!__WXDEBUG__
844f90fb 365
52dbd056
VZ
366 Assign(volume, path, name, ext, format);
367}
368
369void wxFileName::AssignDir(const wxString& dir, wxPathFormat format)
370{
81f25632 371 Assign(dir, _T(""), format);
844f90fb
VZ
372}
373
374void wxFileName::Clear()
375{
376 m_dirs.Clear();
04c943b1
VZ
377
378 m_volume =
844f90fb
VZ
379 m_name =
380 m_ext = wxEmptyString;
381}
382
383/* static */
384wxFileName wxFileName::FileName(const wxString& file)
385{
386 return wxFileName(file);
387}
388
389/* static */
390wxFileName wxFileName::DirName(const wxString& dir)
391{
392 wxFileName fn;
393 fn.AssignDir(dir);
394 return fn;
df5ddbca
RR
395}
396
844f90fb
VZ
397// ----------------------------------------------------------------------------
398// existence tests
399// ----------------------------------------------------------------------------
400
df5ddbca
RR
401bool wxFileName::FileExists()
402{
a35b27b1
RR
403 return wxFileName::FileExists( GetFullPath() );
404}
405
406bool wxFileName::FileExists( const wxString &file )
407{
408 return ::wxFileExists( file );
df5ddbca
RR
409}
410
411bool wxFileName::DirExists()
412{
a35b27b1
RR
413 return wxFileName::DirExists( GetFullPath() );
414}
415
416bool wxFileName::DirExists( const wxString &dir )
417{
418 return ::wxDirExists( dir );
df5ddbca
RR
419}
420
844f90fb
VZ
421// ----------------------------------------------------------------------------
422// CWD and HOME stuff
423// ----------------------------------------------------------------------------
424
6f91bc33 425void wxFileName::AssignCwd(const wxString& volume)
df5ddbca 426{
6f91bc33 427 AssignDir(wxFileName::GetCwd(volume));
a35b27b1
RR
428}
429
844f90fb 430/* static */
6f91bc33 431wxString wxFileName::GetCwd(const wxString& volume)
a35b27b1 432{
6f91bc33
VZ
433 // if we have the volume, we must get the current directory on this drive
434 // and to do this we have to chdir to this volume - at least under Windows,
435 // I don't know how to get the current drive on another volume elsewhere
436 // (TODO)
437 wxString cwdOld;
438 if ( !volume.empty() )
439 {
440 cwdOld = wxGetCwd();
441 SetCwd(volume + GetVolumeSeparator());
442 }
443
444 wxString cwd = ::wxGetCwd();
445
446 if ( !volume.empty() )
447 {
448 SetCwd(cwdOld);
449 }
ae4d7004 450
6f91bc33 451 return cwd;
a35b27b1
RR
452}
453
454bool wxFileName::SetCwd()
455{
456 return wxFileName::SetCwd( GetFullPath() );
df5ddbca
RR
457}
458
a35b27b1 459bool wxFileName::SetCwd( const wxString &cwd )
df5ddbca 460{
a35b27b1 461 return ::wxSetWorkingDirectory( cwd );
df5ddbca
RR
462}
463
a35b27b1
RR
464void wxFileName::AssignHomeDir()
465{
844f90fb 466 AssignDir(wxFileName::GetHomeDir());
a35b27b1 467}
844f90fb 468
a35b27b1
RR
469wxString wxFileName::GetHomeDir()
470{
471 return ::wxGetHomeDir();
472}
844f90fb 473
df22f860 474void wxFileName::AssignTempFileName(const wxString& prefix, wxFile *fileTemp)
df5ddbca 475{
df22f860 476 wxString tempname = CreateTempFileName(prefix, fileTemp);
ade35f11 477 if ( tempname.empty() )
844f90fb 478 {
ade35f11
VZ
479 // error, failed to get temp file name
480 Clear();
844f90fb 481 }
ade35f11 482 else // ok
844f90fb 483 {
ade35f11
VZ
484 Assign(tempname);
485 }
486}
487
488/* static */
df22f860
VZ
489wxString
490wxFileName::CreateTempFileName(const wxString& prefix, wxFile *fileTemp)
ade35f11
VZ
491{
492 wxString path, dir, name;
493
494 // use the directory specified by the prefix
495 SplitPath(prefix, &dir, &name, NULL /* extension */);
496
497#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
498
499#ifdef __WIN32__
500 if ( dir.empty() )
501 {
502 if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
503 {
504 wxLogLastError(_T("GetTempPath"));
505 }
506
507 if ( dir.empty() )
508 {
509 // GetTempFileName() fails if we pass it an empty string
510 dir = _T('.');
511 }
512 }
513
514 if ( !::GetTempFileName(dir, name, 0, wxStringBuffer(path, MAX_PATH + 1)) )
515 {
516 wxLogLastError(_T("GetTempFileName"));
517
518 path.clear();
519 }
520#else // Win16
521 if ( !::GetTempFileName(NULL, prefix, 0, wxStringBuffer(path, 1025)) )
522 {
523 path.clear();
524 }
525#endif // Win32/16
526
527#elif defined(__WXPM__)
528 // for now just create a file
529 //
530 // future enhancements can be to set some extended attributes for file
531 // systems OS/2 supports that have them (HPFS, FAT32) and security
532 // (HPFS386)
533 static const wxChar *szMktempSuffix = wxT("XXX");
534 path << dir << _T('/') << name << szMktempSuffix;
535
536 // Temporarily remove - MN
537 #ifndef __WATCOMC__
24eb81cb 538 ::DosCreateDir(wxStringBuffer(path, MAX_PATH), NULL);
ade35f11 539 #endif
90a68369 540
7070f55b 541#else // !Windows, !OS/2
ade35f11
VZ
542 if ( dir.empty() )
543 {
3752e0ab 544#if defined(__WXMAC__) && !defined(__DARWIN__)
263a72f3 545 dir = wxMacFindFolder( (short) kOnSystemDisk, kTemporaryFolderType, kCreateFolder ) ;
3752e0ab 546#else // !Mac
ade35f11 547 dir = wxGetenv(_T("TMP"));
3752e0ab 548 if ( dir.empty() )
ade35f11
VZ
549 {
550 dir = wxGetenv(_T("TEMP"));
551 }
552
553 if ( dir.empty() )
554 {
555 // default
d9f54bb0 556 #ifdef __DOS__
903b61cc 557 dir = _T(".");
d9f54bb0 558 #else
903b61cc 559 dir = _T("/tmp");
d9f54bb0 560 #endif
ade35f11 561 }
3752e0ab 562#endif // Mac/!Mac
844f90fb 563 }
ade35f11
VZ
564
565 path = dir;
566
567 if ( !wxEndsWithPathSeparator(dir) &&
568 (name.empty() || !wxIsPathSeparator(name[0u])) )
569 {
d9f54bb0 570 path += wxFILE_SEP_PATH;
ade35f11
VZ
571 }
572
573 path += name;
574
7070f55b 575#if defined(HAVE_MKSTEMP)
ade35f11
VZ
576 // scratch space for mkstemp()
577 path += _T("XXXXXX");
578
579 // can use the cast here because the length doesn't change and the string
580 // is not shared
df22f860
VZ
581 int fdTemp = mkstemp((char *)path.mb_str());
582 if ( fdTemp == -1 )
ade35f11
VZ
583 {
584 // this might be not necessary as mkstemp() on most systems should have
585 // already done it but it doesn't hurt neither...
586 path.clear();
587 }
df22f860
VZ
588 else // mkstemp() succeeded
589 {
590 // avoid leaking the fd
591 if ( fileTemp )
592 {
593 fileTemp->Attach(fdTemp);
594 }
595 else
596 {
597 close(fdTemp);
598 }
599 }
ade35f11
VZ
600#else // !HAVE_MKSTEMP
601
602#ifdef HAVE_MKTEMP
603 // same as above
604 path += _T("XXXXXX");
605
606 if ( !mktemp((char *)path.mb_str()) )
607 {
608 path.clear();
609 }
7070f55b 610#else // !HAVE_MKTEMP (includes __DOS__)
ade35f11 611 // generate the unique file name ourselves
7070f55b 612 #ifndef __DOS__
ade35f11 613 path << (unsigned int)getpid();
7070f55b 614 #endif
ade35f11
VZ
615
616 wxString pathTry;
617
618 static const size_t numTries = 1000;
619 for ( size_t n = 0; n < numTries; n++ )
620 {
621 // 3 hex digits is enough for numTries == 1000 < 4096
622 pathTry = path + wxString::Format(_T("%.03x"), n);
623 if ( !wxFile::Exists(pathTry) )
624 {
625 break;
626 }
627
628 pathTry.clear();
629 }
630
631 path = pathTry;
632#endif // HAVE_MKTEMP/!HAVE_MKTEMP
633
634 if ( !path.empty() )
635 {
df22f860
VZ
636 }
637#endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
638
639#endif // Windows/!Windows
640
641 if ( path.empty() )
642 {
643 wxLogSysError(_("Failed to create a temporary file name"));
644 }
645 else if ( fileTemp && !fileTemp->IsOpened() )
646 {
647 // open the file - of course, there is a race condition here, this is
ade35f11 648 // why we always prefer using mkstemp()...
90a68369
VZ
649 //
650 // NB: GetTempFileName() under Windows creates the file, so using
651 // write_excl there would fail
652 if ( !fileTemp->Open(path,
653#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
654 wxFile::write,
655#else
656 wxFile::write_excl,
657#endif
658 wxS_IRUSR | wxS_IWUSR) )
ade35f11
VZ
659 {
660 // FIXME: If !ok here should we loop and try again with another
661 // file name? That is the standard recourse if open(O_EXCL)
662 // fails, though of course it should be protected against
663 // possible infinite looping too.
664
665 wxLogError(_("Failed to open temporary file."));
666
667 path.clear();
668 }
669 }
ade35f11
VZ
670
671 return path;
df5ddbca
RR
672}
673
844f90fb
VZ
674// ----------------------------------------------------------------------------
675// directory operations
676// ----------------------------------------------------------------------------
677
f0ce3409 678bool wxFileName::Mkdir( int perm, bool full )
a35b27b1 679{
f0ce3409 680 return wxFileName::Mkdir( GetFullPath(), perm, full );
a35b27b1
RR
681}
682
f0ce3409 683bool wxFileName::Mkdir( const wxString &dir, int perm, bool full )
df5ddbca 684{
f0ce3409
JS
685 if (full)
686 {
687 wxFileName filename(dir);
688 wxArrayString dirs = filename.GetDirs();
77fe02a8 689 dirs.Add(filename.GetName());
f0ce3409
JS
690
691 size_t count = dirs.GetCount();
692 size_t i;
693 wxString currPath;
694 int noErrors = 0;
695 for ( i = 0; i < count; i++ )
696 {
697 currPath += dirs[i];
698
699 if (currPath.Last() == wxT(':'))
700 {
701 // Can't create a root directory so continue to next dir
702 currPath += wxFILE_SEP_PATH;
703 continue;
704 }
705
706 if (!DirExists(currPath))
707 if (!wxMkdir(currPath, perm))
708 noErrors ++;
709
710 if ( (i < (count-1)) )
711 currPath += wxFILE_SEP_PATH;
712 }
713
714 return (noErrors == 0);
715
716 }
717 else
718 return ::wxMkdir( dir, perm );
df5ddbca
RR
719}
720
a35b27b1 721bool wxFileName::Rmdir()
df5ddbca 722{
a35b27b1 723 return wxFileName::Rmdir( GetFullPath() );
df5ddbca
RR
724}
725
a35b27b1 726bool wxFileName::Rmdir( const wxString &dir )
df5ddbca 727{
a35b27b1 728 return ::wxRmdir( dir );
df5ddbca
RR
729}
730
844f90fb
VZ
731// ----------------------------------------------------------------------------
732// path normalization
733// ----------------------------------------------------------------------------
734
32a0d013 735bool wxFileName::Normalize(int flags,
844f90fb
VZ
736 const wxString& cwd,
737 wxPathFormat format)
a35b27b1 738{
844f90fb
VZ
739 // the existing path components
740 wxArrayString dirs = GetDirs();
741
742 // the path to prepend in front to make the path absolute
743 wxFileName curDir;
744
745 format = GetFormat(format);
ae4d7004 746
844f90fb 747 // make the path absolute
353f41cb 748 if ( (flags & wxPATH_NORM_ABSOLUTE) && m_relative )
a35b27b1 749 {
844f90fb 750 if ( cwd.empty() )
6f91bc33
VZ
751 {
752 curDir.AssignCwd(GetVolume());
753 }
754 else // cwd provided
755 {
844f90fb 756 curDir.AssignDir(cwd);
6f91bc33 757 }
52dbd056 758
353f41cb 759#if 0
52dbd056
VZ
760 // the path may be not absolute because it doesn't have the volume name
761 // but in this case we shouldn't modify the directory components of it
762 // but just set the current volume
763 if ( !HasVolume() && curDir.HasVolume() )
764 {
765 SetVolume(curDir.GetVolume());
766
767 if ( IsAbsolute() )
768 {
769 // yes, it was the case - we don't need curDir then
770 curDir.Clear();
771 }
772 }
353f41cb 773#endif
5fc67e5c 774 m_relative = FALSE;
a35b27b1 775 }
ae4d7004 776
844f90fb
VZ
777 // handle ~ stuff under Unix only
778 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) )
a35b27b1 779 {
844f90fb
VZ
780 if ( !dirs.IsEmpty() )
781 {
782 wxString dir = dirs[0u];
783 if ( !dir.empty() && dir[0u] == _T('~') )
784 {
785 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
786
da2fd5ac 787 dirs.RemoveAt(0u);
844f90fb
VZ
788 }
789 }
a35b27b1 790 }
844f90fb 791
52dbd056 792 // transform relative path into abs one
844f90fb 793 if ( curDir.IsOk() )
a35b27b1 794 {
844f90fb
VZ
795 wxArrayString dirsNew = curDir.GetDirs();
796 size_t count = dirs.GetCount();
797 for ( size_t n = 0; n < count; n++ )
798 {
799 dirsNew.Add(dirs[n]);
800 }
801
802 dirs = dirsNew;
a35b27b1 803 }
844f90fb
VZ
804
805 // now deal with ".", ".." and the rest
806 m_dirs.Empty();
807 size_t count = dirs.GetCount();
808 for ( size_t n = 0; n < count; n++ )
a35b27b1 809 {
844f90fb
VZ
810 wxString dir = dirs[n];
811
2bc60417 812 if ( flags & wxPATH_NORM_DOTS )
844f90fb
VZ
813 {
814 if ( dir == wxT(".") )
815 {
816 // just ignore
817 continue;
818 }
819
820 if ( dir == wxT("..") )
821 {
822 if ( m_dirs.IsEmpty() )
823 {
824 wxLogError(_("The path '%s' contains too many \"..\"!"),
825 GetFullPath().c_str());
826 return FALSE;
827 }
828
ae4d7004 829 m_dirs.RemoveAt(m_dirs.GetCount() - 1);
844f90fb
VZ
830 continue;
831 }
832 }
833
834 if ( flags & wxPATH_NORM_ENV_VARS )
a35b27b1 835 {
844f90fb 836 dir = wxExpandEnvVars(dir);
a35b27b1 837 }
844f90fb
VZ
838
839 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
840 {
841 dir.MakeLower();
842 }
843
844 m_dirs.Add(dir);
a35b27b1 845 }
844f90fb
VZ
846
847 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
848 {
849 // VZ: expand env vars here too?
850
851 m_name.MakeLower();
852 m_ext.MakeLower();
853 }
854
52dbd056
VZ
855#if defined(__WIN32__)
856 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
9e9b65c1
JS
857 {
858 Assign(GetLongPath());
859 }
52dbd056 860#endif // Win32
9e9b65c1 861
a35b27b1
RR
862 return TRUE;
863}
864
f7d886af
VZ
865bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
866{
867 wxFileName fnBase(pathBase, format);
868
869 // get cwd only once - small time saving
870 wxString cwd = wxGetCwd();
871 Normalize(wxPATH_NORM_ALL, cwd, format);
872 fnBase.Normalize(wxPATH_NORM_ALL, cwd, format);
873
874 bool withCase = IsCaseSensitive(format);
875
876 // we can't do anything if the files live on different volumes
877 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
878 {
879 // nothing done
880 return FALSE;
881 }
882
883 // same drive, so we don't need our volume
884 m_volume.clear();
885
886 // remove common directories starting at the top
887 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
888 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
889 {
ae4d7004
VZ
890 m_dirs.RemoveAt(0);
891 fnBase.m_dirs.RemoveAt(0);
f7d886af
VZ
892 }
893
894 // add as many ".." as needed
895 size_t count = fnBase.m_dirs.GetCount();
896 for ( size_t i = 0; i < count; i++ )
897 {
898 m_dirs.Insert(wxT(".."), 0u);
899 }
90a68369 900
353f41cb 901 m_relative = TRUE;
f7d886af
VZ
902
903 // we were modified
904 return TRUE;
905}
906
844f90fb
VZ
907// ----------------------------------------------------------------------------
908// filename kind tests
909// ----------------------------------------------------------------------------
910
f7d886af 911bool wxFileName::SameAs(const wxFileName &filepath, wxPathFormat format)
df5ddbca 912{
844f90fb
VZ
913 wxFileName fn1 = *this,
914 fn2 = filepath;
915
916 // get cwd only once - small time saving
917 wxString cwd = wxGetCwd();
918 fn1.Normalize(wxPATH_NORM_ALL, cwd, format);
919 fn2.Normalize(wxPATH_NORM_ALL, cwd, format);
920
921 if ( fn1.GetFullPath() == fn2.GetFullPath() )
922 return TRUE;
923
924 // TODO: compare inodes for Unix, this works even when filenames are
925 // different but files are the same (symlinks) (VZ)
926
927 return FALSE;
df5ddbca
RR
928}
929
844f90fb 930/* static */
df5ddbca
RR
931bool wxFileName::IsCaseSensitive( wxPathFormat format )
932{
04c943b1
VZ
933 // only Unix filenames are truely case-sensitive
934 return GetFormat(format) == wxPATH_UNIX;
df5ddbca
RR
935}
936
04c943b1
VZ
937/* static */
938wxString wxFileName::GetVolumeSeparator(wxPathFormat format)
844f90fb 939{
04c943b1
VZ
940 wxString sepVol;
941
a385b5df
RR
942 if ( (GetFormat(format) == wxPATH_DOS) ||
943 (GetFormat(format) == wxPATH_VMS) )
04c943b1 944 {
04c943b1
VZ
945 sepVol = wxFILE_SEP_DSK;
946 }
a385b5df 947 //else: leave empty
04c943b1
VZ
948
949 return sepVol;
844f90fb
VZ
950}
951
952/* static */
953wxString wxFileName::GetPathSeparators(wxPathFormat format)
954{
955 wxString seps;
956 switch ( GetFormat(format) )
df5ddbca 957 {
844f90fb 958 case wxPATH_DOS:
04c943b1
VZ
959 // accept both as native APIs do but put the native one first as
960 // this is the one we use in GetFullPath()
961 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
844f90fb
VZ
962 break;
963
964 default:
965 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
966 // fall through
967
968 case wxPATH_UNIX:
9e8d8607 969 seps = wxFILE_SEP_PATH_UNIX;
844f90fb
VZ
970 break;
971
972 case wxPATH_MAC:
9e8d8607 973 seps = wxFILE_SEP_PATH_MAC;
844f90fb 974 break;
04c943b1 975
3c621059
JJ
976 case wxPATH_VMS:
977 seps = wxFILE_SEP_PATH_VMS;
978 break;
df5ddbca
RR
979 }
980
844f90fb 981 return seps;
df5ddbca
RR
982}
983
844f90fb
VZ
984/* static */
985bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
df5ddbca 986{
04c943b1
VZ
987 // wxString::Find() doesn't work as expected with NUL - it will always find
988 // it, so it is almost surely a bug if this function is called with NUL arg
989 wxASSERT_MSG( ch != _T('\0'), _T("shouldn't be called with NUL") );
990
844f90fb 991 return GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
df5ddbca
RR
992}
993
994bool wxFileName::IsWild( wxPathFormat format )
995{
844f90fb
VZ
996 // FIXME: this is probably false for Mac and this is surely wrong for most
997 // of Unix shells (think about "[...]")
04c943b1 998 (void)format;
844f90fb 999 return m_name.find_first_of(_T("*?")) != wxString::npos;
df5ddbca
RR
1000}
1001
844f90fb
VZ
1002// ----------------------------------------------------------------------------
1003// path components manipulation
1004// ----------------------------------------------------------------------------
1005
df5ddbca
RR
1006void wxFileName::AppendDir( const wxString &dir )
1007{
1008 m_dirs.Add( dir );
1009}
1010
1011void wxFileName::PrependDir( const wxString &dir )
1012{
1013 m_dirs.Insert( dir, 0 );
1014}
1015
1016void wxFileName::InsertDir( int before, const wxString &dir )
1017{
1018 m_dirs.Insert( dir, before );
1019}
1020
1021void wxFileName::RemoveDir( int pos )
1022{
1023 m_dirs.Remove( (size_t)pos );
1024}
1025
844f90fb
VZ
1026// ----------------------------------------------------------------------------
1027// accessors
1028// ----------------------------------------------------------------------------
1029
7124df9b
VZ
1030void wxFileName::SetFullName(const wxString& fullname)
1031{
1032 SplitPath(fullname, NULL /* no path */, &m_name, &m_ext);
1033}
1034
844f90fb 1035wxString wxFileName::GetFullName() const
a35b27b1 1036{
844f90fb
VZ
1037 wxString fullname = m_name;
1038 if ( !m_ext.empty() )
a35b27b1 1039 {
9e8d8607 1040 fullname << wxFILE_SEP_EXT << m_ext;
a35b27b1 1041 }
a35b27b1 1042
844f90fb 1043 return fullname;
a35b27b1
RR
1044}
1045
574c939e 1046wxString wxFileName::GetPath( bool, wxPathFormat format ) const
df5ddbca 1047{
574c939e
KB
1048 // Should add_seperator parameter be used?
1049
df5ddbca 1050 format = GetFormat( format );
844f90fb 1051
353f41cb
RR
1052 wxString fullpath;
1053
1054 // the leading character
1055 if ( format == wxPATH_MAC && m_relative )
1056 {
1057 fullpath += wxFILE_SEP_PATH_MAC;
1058 }
1059 else if ( format == wxPATH_DOS )
1060 {
1061 if (!m_relative)
1062 fullpath += wxFILE_SEP_PATH_DOS;
1063 }
1064 else if ( format == wxPATH_UNIX )
1065 {
1066 if (!m_relative)
1067 fullpath += wxFILE_SEP_PATH_UNIX;
1068 }
90a68369 1069
353f41cb
RR
1070 // then concatenate all the path components using the path separator
1071 size_t dirCount = m_dirs.GetCount();
1072 if ( dirCount )
df5ddbca 1073 {
353f41cb
RR
1074 if ( format == wxPATH_VMS )
1075 {
1076 fullpath += wxT('[');
1077 }
1078
1079
1080 for ( size_t i = 0; i < dirCount; i++ )
1081 {
1082 // TODO: What to do with ".." under VMS
1083
1084 switch (format)
1085 {
1086 case wxPATH_MAC:
1087 {
1088 if (m_dirs[i] == wxT("."))
1089 break;
1090 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1091 fullpath += m_dirs[i];
1092 fullpath += wxT(':');
1093 break;
1094 }
1095 case wxPATH_DOS:
1096 {
1097 fullpath += m_dirs[i];
1098 fullpath += wxT('\\');
1099 break;
1100 }
1101 case wxPATH_UNIX:
1102 {
1103 fullpath += m_dirs[i];
1104 fullpath += wxT('/');
1105 break;
1106 }
1107 case wxPATH_VMS:
1108 {
1109 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1110 fullpath += m_dirs[i];
1111 if (i == dirCount-1)
1112 fullpath += wxT(']');
1113 else
1114 fullpath += wxT('.');
1115 break;
1116 }
1117 default:
1118 {
7613582b 1119 wxFAIL_MSG( wxT("error") );
353f41cb
RR
1120 }
1121 }
1122 }
df5ddbca 1123 }
844f90fb 1124
353f41cb
RR
1125
1126
1127 return fullpath;
df5ddbca
RR
1128}
1129
1130wxString wxFileName::GetFullPath( wxPathFormat format ) const
1131{
04c943b1
VZ
1132 format = GetFormat(format);
1133
1134 wxString fullpath;
1135
1136 // first put the volume
1137 if ( !m_volume.empty() )
dcf0fce4 1138 {
5fc67e5c
RR
1139 {
1140 // Special Windows UNC paths hack, part 2: undo what we did in
1141 // SplitPath() and make an UNC path if we have a drive which is not a
1142 // single letter (hopefully the network shares can't be one letter only
1143 // although I didn't find any authoritative docs on this)
1144 if ( format == wxPATH_DOS && m_volume.length() > 1 )
1145 {
1146 fullpath << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << m_volume;
1147 }
1148 else if ( format == wxPATH_DOS || format == wxPATH_VMS )
1149 {
1150 fullpath << m_volume << GetVolumeSeparator(format);
a385b5df 1151 }
353f41cb 1152 // else ignore
dcf0fce4
RR
1153 }
1154 }
90a68369 1155
353f41cb
RR
1156 // the leading character
1157 if ( format == wxPATH_MAC && m_relative )
1158 {
1159 fullpath += wxFILE_SEP_PATH_MAC;
1160 }
1161 else if ( format == wxPATH_DOS )
1162 {
1163 if (!m_relative)
1164 fullpath += wxFILE_SEP_PATH_DOS;
1165 }
1166 else if ( format == wxPATH_UNIX )
1167 {
1168 if (!m_relative)
1169 fullpath += wxFILE_SEP_PATH_UNIX;
1170 }
90a68369 1171
04c943b1
VZ
1172 // then concatenate all the path components using the path separator
1173 size_t dirCount = m_dirs.GetCount();
1174 if ( dirCount )
3c621059 1175 {
04c943b1 1176 if ( format == wxPATH_VMS )
dcf0fce4 1177 {
353f41cb 1178 fullpath += wxT('[');
04c943b1
VZ
1179 }
1180
353f41cb 1181
04c943b1
VZ
1182 for ( size_t i = 0; i < dirCount; i++ )
1183 {
353f41cb 1184 // TODO: What to do with ".." under VMS
04c943b1 1185
353f41cb
RR
1186 switch (format)
1187 {
1188 case wxPATH_MAC:
1189 {
1190 if (m_dirs[i] == wxT("."))
1191 break;
1192 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1193 fullpath += m_dirs[i];
1194 fullpath += wxT(':');
1195 break;
1196 }
1197 case wxPATH_DOS:
1198 {
1199 fullpath += m_dirs[i];
1200 fullpath += wxT('\\');
1201 break;
1202 }
1203 case wxPATH_UNIX:
1204 {
1205 fullpath += m_dirs[i];
1206 fullpath += wxT('/');
1207 break;
1208 }
1209 case wxPATH_VMS:
1210 {
1211 if (m_dirs[i] != wxT("..")) // convert back from ".." to nothing
1212 fullpath += m_dirs[i];
1213 if (i == dirCount-1)
1214 fullpath += wxT(']');
1215 else
1216 fullpath += wxT('.');
1217 break;
1218 }
1219 default:
1220 {
7613582b 1221 wxFAIL_MSG( wxT("error") );
353f41cb
RR
1222 }
1223 }
dcf0fce4
RR
1224 }
1225 }
04c943b1
VZ
1226
1227 // finally add the file name and extension
1228 fullpath += GetFullName();
1229
1230 return fullpath;
df5ddbca
RR
1231}
1232
9e9b65c1
JS
1233// Return the short form of the path (returns identity on non-Windows platforms)
1234wxString wxFileName::GetShortPath() const
1235{
8cb172b4 1236#if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
9e9b65c1 1237 wxString path(GetFullPath());
75ef5722
JS
1238 wxString pathOut;
1239 DWORD sz = ::GetShortPathName(path, NULL, 0);
1240 bool ok = sz != 0;
1241 if ( ok )
9e9b65c1 1242 {
75ef5722
JS
1243 ok = ::GetShortPathName
1244 (
1245 path,
1246 pathOut.GetWriteBuf(sz),
1247 sz
1248 ) != 0;
1249 pathOut.UngetWriteBuf();
9e9b65c1 1250 }
75ef5722
JS
1251 if (ok)
1252 return pathOut;
5716a1ab
VZ
1253
1254 return path;
9e9b65c1
JS
1255#else
1256 return GetFullPath();
1257#endif
1258}
1259
1260// Return the long form of the path (returns identity on non-Windows platforms)
1261wxString wxFileName::GetLongPath() const
1262{
52dbd056
VZ
1263 wxString pathOut,
1264 path = GetFullPath();
1265
1266#if defined(__WIN32__) && !defined(__WXMICROWIN__)
05e7001c
JS
1267 bool success = FALSE;
1268
5716a1ab 1269 // VZ: this code was disabled, why?
0b9ab0bd 1270#if 0 // wxUSE_DYNAMIC_LOADER
05e7001c
JS
1271 typedef DWORD (*GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
1272
1273 static bool s_triedToLoad = FALSE;
05e7001c
JS
1274
1275 if ( !s_triedToLoad )
9e9b65c1 1276 {
05e7001c 1277 s_triedToLoad = TRUE;
4f89dbc4
RL
1278 wxDynamicLibrary dllKernel(_T("kernel32"));
1279 if ( dllKernel.IsLoaded() )
05e7001c
JS
1280 {
1281 // may succeed or fail depending on the Windows version
04c943b1 1282 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
5d978d07 1283#ifdef _UNICODE
4f89dbc4 1284 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameW"));
5d978d07 1285#else
4f89dbc4 1286 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameA"));
5d978d07 1287#endif
05e7001c 1288
05e7001c
JS
1289 if ( s_pfnGetLongPathName )
1290 {
1291 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
1292 bool ok = dwSize > 0;
1293
1294 if ( ok )
1295 {
1296 DWORD sz = (*s_pfnGetLongPathName)(path, NULL, 0);
1297 ok = sz != 0;
1298 if ( ok )
1299 {
1300 ok = (*s_pfnGetLongPathName)
1301 (
1302 path,
1303 pathOut.GetWriteBuf(sz),
1304 sz
1305 ) != 0;
1306 pathOut.UngetWriteBuf();
1307
1308 success = TRUE;
1309 }
1310 }
1311 }
1312 }
9e9b65c1 1313 }
05e7001c 1314 if (success)
75ef5722 1315 return pathOut;
0b9ab0bd 1316#endif // wxUSE_DYNAMIC_LOADER
05e7001c
JS
1317
1318 if (!success)
1319 {
1320 // The OS didn't support GetLongPathName, or some other error.
1321 // We need to call FindFirstFile on each component in turn.
1322
1323 WIN32_FIND_DATA findFileData;
1324 HANDLE hFind;
1325 pathOut = wxEmptyString;
1326
77fe02a8 1327 wxArrayString dirs = GetDirs();
bcbe86e5 1328 dirs.Add(GetFullName());
77fe02a8 1329
05e7001c 1330 wxString tmpPath;
5d978d07 1331
52dbd056
VZ
1332 size_t count = dirs.GetCount();
1333 for ( size_t i = 0; i < count; i++ )
05e7001c 1334 {
52dbd056
VZ
1335 // We're using pathOut to collect the long-name path, but using a
1336 // temporary for appending the last path component which may be
1337 // short-name
77fe02a8 1338 tmpPath = pathOut + dirs[i];
05e7001c 1339
52dbd056
VZ
1340 if ( tmpPath.empty() )
1341 continue;
1342
1343 if ( tmpPath.Last() == wxT(':') )
5d978d07
JS
1344 {
1345 // Can't pass a drive and root dir to FindFirstFile,
1346 // so continue to next dir
05e7001c 1347 tmpPath += wxFILE_SEP_PATH;
5d978d07
JS
1348 pathOut = tmpPath;
1349 continue;
1350 }
05e7001c
JS
1351
1352 hFind = ::FindFirstFile(tmpPath, &findFileData);
1353 if (hFind == INVALID_HANDLE_VALUE)
1354 {
1355 // Error: return immediately with the original path
1356 return path;
1357 }
05e7001c 1358
52dbd056
VZ
1359 pathOut += findFileData.cFileName;
1360 if ( (i < (count-1)) )
1361 pathOut += wxFILE_SEP_PATH;
1362
1363 ::FindClose(hFind);
05e7001c
JS
1364 }
1365 }
52dbd056
VZ
1366#else // !Win32
1367 pathOut = path;
1368#endif // Win32/!Win32
5716a1ab 1369
05e7001c 1370 return pathOut;
9e9b65c1
JS
1371}
1372
df5ddbca
RR
1373wxPathFormat wxFileName::GetFormat( wxPathFormat format )
1374{
1375 if (format == wxPATH_NATIVE)
1376 {
d9f54bb0 1377#if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
df5ddbca 1378 format = wxPATH_DOS;
4d293f8e 1379#elif defined(__WXMAC__) && !defined(__DARWIN__)
04c943b1 1380 format = wxPATH_MAC;
3c621059 1381#elif defined(__VMS)
04c943b1 1382 format = wxPATH_VMS;
844f90fb 1383#else
df5ddbca
RR
1384 format = wxPATH_UNIX;
1385#endif
1386 }
1387 return format;
1388}
a35b27b1 1389
9e8d8607
VZ
1390// ----------------------------------------------------------------------------
1391// path splitting function
1392// ----------------------------------------------------------------------------
1393
6f91bc33 1394/* static */
04c943b1
VZ
1395void wxFileName::SplitPath(const wxString& fullpathWithVolume,
1396 wxString *pstrVolume,
9e8d8607
VZ
1397 wxString *pstrPath,
1398 wxString *pstrName,
1399 wxString *pstrExt,
1400 wxPathFormat format)
1401{
1402 format = GetFormat(format);
1403
04c943b1
VZ
1404 wxString fullpath = fullpathWithVolume;
1405
1406 // under VMS the end of the path is ']', not the path separator used to
1407 // separate the components
ab3edace 1408 wxString sepPath = format == wxPATH_VMS ? wxString(_T(']'))
04c943b1 1409 : GetPathSeparators(format);
9e8d8607 1410
04c943b1
VZ
1411 // special Windows UNC paths hack: transform \\share\path into share:path
1412 if ( format == wxPATH_DOS )
9e8d8607 1413 {
04c943b1
VZ
1414 if ( fullpath.length() >= 4 &&
1415 fullpath[0u] == wxFILE_SEP_PATH_DOS &&
1416 fullpath[1u] == wxFILE_SEP_PATH_DOS )
9e8d8607 1417 {
04c943b1
VZ
1418 fullpath.erase(0, 2);
1419
1420 size_t posFirstSlash = fullpath.find_first_of(sepPath);
1421 if ( posFirstSlash != wxString::npos )
1422 {
1423 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
1424
1425 // UNC paths are always absolute, right? (FIXME)
1426 fullpath.insert(posFirstSlash + 1, wxFILE_SEP_PATH_DOS);
1427 }
3c621059
JJ
1428 }
1429 }
04c943b1 1430
a385b5df
RR
1431 // We separate the volume here
1432 if ( format == wxPATH_DOS || format == wxPATH_VMS )
04c943b1 1433 {
a385b5df 1434 wxString sepVol = GetVolumeSeparator(format);
24eb81cb 1435
04c943b1
VZ
1436 size_t posFirstColon = fullpath.find_first_of(sepVol);
1437 if ( posFirstColon != wxString::npos )
1438 {
1439 if ( pstrVolume )
1440 {
1441 *pstrVolume = fullpath.Left(posFirstColon);
1442 }
1443
1444 // remove the volume name and the separator from the full path
1445 fullpath.erase(0, posFirstColon + sepVol.length());
1446 }
1447 }
1448
1449 // find the positions of the last dot and last path separator in the path
1450 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
1451 size_t posLastSlash = fullpath.find_last_of(sepPath);
1452
1453 if ( (posLastDot != wxString::npos) &&
1454 ((format == wxPATH_UNIX) || (format == wxPATH_VMS)) )
3c621059
JJ
1455 {
1456 if ( (posLastDot == 0) ||
04c943b1 1457 (fullpath[posLastDot - 1] == sepPath[0u] ) )
3c621059 1458 {
04c943b1
VZ
1459 // under Unix and VMS, dot may be (and commonly is) the first
1460 // character of the filename, don't treat the entire filename as
1461 // extension in this case
9e8d8607
VZ
1462 posLastDot = wxString::npos;
1463 }
1464 }
1465
8e7dda21
VZ
1466 // if we do have a dot and a slash, check that the dot is in the name part
1467 if ( (posLastDot != wxString::npos) &&
1468 (posLastSlash != wxString::npos) &&
1469 (posLastDot < posLastSlash) )
9e8d8607
VZ
1470 {
1471 // the dot is part of the path, not the start of the extension
1472 posLastDot = wxString::npos;
1473 }
1474
1475 // now fill in the variables provided by user
1476 if ( pstrPath )
1477 {
1478 if ( posLastSlash == wxString::npos )
1479 {
1480 // no path at all
1481 pstrPath->Empty();
1482 }
1483 else
1484 {
04c943b1 1485 // take everything up to the path separator but take care to make
353f41cb 1486 // the path equal to something like '/', not empty, for the files
04c943b1
VZ
1487 // immediately under root directory
1488 size_t len = posLastSlash;
91b4bd63
SC
1489
1490 // this rule does not apply to mac since we do not start with colons (sep)
1491 // except for relative paths
1492 if ( !len && format != wxPATH_MAC)
04c943b1
VZ
1493 len++;
1494
1495 *pstrPath = fullpath.Left(len);
1496
1497 // special VMS hack: remove the initial bracket
1498 if ( format == wxPATH_VMS )
1499 {
1500 if ( (*pstrPath)[0u] == _T('[') )
1501 pstrPath->erase(0, 1);
1502 }
9e8d8607
VZ
1503 }
1504 }
1505
1506 if ( pstrName )
1507 {
42b1f941
VZ
1508 // take all characters starting from the one after the last slash and
1509 // up to, but excluding, the last dot
9e8d8607 1510 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
8e7dda21
VZ
1511 size_t count;
1512 if ( posLastDot == wxString::npos )
1513 {
1514 // take all until the end
1515 count = wxString::npos;
1516 }
1517 else if ( posLastSlash == wxString::npos )
1518 {
1519 count = posLastDot;
1520 }
1521 else // have both dot and slash
1522 {
1523 count = posLastDot - posLastSlash - 1;
1524 }
9e8d8607
VZ
1525
1526 *pstrName = fullpath.Mid(nStart, count);
1527 }
1528
1529 if ( pstrExt )
1530 {
1531 if ( posLastDot == wxString::npos )
1532 {
1533 // no extension
1534 pstrExt->Empty();
1535 }
1536 else
1537 {
1538 // take everything after the dot
1539 *pstrExt = fullpath.Mid(posLastDot + 1);
1540 }
1541 }
1542}
951cd180 1543
6f91bc33
VZ
1544/* static */
1545void wxFileName::SplitPath(const wxString& fullpath,
1546 wxString *path,
1547 wxString *name,
1548 wxString *ext,
1549 wxPathFormat format)
1550{
1551 wxString volume;
1552 SplitPath(fullpath, &volume, path, name, ext, format);
1553
1554 if ( path && !volume.empty() )
1555 {
1556 path->Prepend(volume + GetVolumeSeparator(format));
1557 }
1558}
1559
951cd180
VZ
1560// ----------------------------------------------------------------------------
1561// time functions
1562// ----------------------------------------------------------------------------
1563
1564bool wxFileName::SetTimes(const wxDateTime *dtCreate,
1565 const wxDateTime *dtAccess,
1566 const wxDateTime *dtMod)
1567{
d9f54bb0 1568#if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
246c704f
VZ
1569 if ( !dtAccess && !dtMod )
1570 {
1571 // can't modify the creation time anyhow, don't try
1572 return TRUE;
1573 }
1574
1575 // if dtAccess or dtMod is not specified, use the other one (which must be
1576 // non NULL because of the test above) for both times
951cd180 1577 utimbuf utm;
246c704f
VZ
1578 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
1579 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
951cd180
VZ
1580 if ( utime(GetFullPath(), &utm) == 0 )
1581 {
1582 return TRUE;
1583 }
1584#elif defined(__WIN32__)
1585 wxFileHandle fh(GetFullPath());
1586 if ( fh.IsOk() )
1587 {
1588 FILETIME ftAccess, ftCreate, ftWrite;
1589
1590 if ( dtCreate )
1591 ConvertWxToFileTime(&ftCreate, *dtCreate);
1592 if ( dtAccess )
1593 ConvertWxToFileTime(&ftAccess, *dtAccess);
1594 if ( dtMod )
1595 ConvertWxToFileTime(&ftWrite, *dtMod);
1596
1597 if ( ::SetFileTime(fh,
1598 dtCreate ? &ftCreate : NULL,
1599 dtAccess ? &ftAccess : NULL,
1600 dtMod ? &ftWrite : NULL) )
1601 {
1602 return TRUE;
1603 }
1604 }
1605#else // other platform
1606#endif // platforms
1607
1608 wxLogSysError(_("Failed to modify file times for '%s'"),
1609 GetFullPath().c_str());
1610
1611 return FALSE;
1612}
1613
1614bool wxFileName::Touch()
1615{
1616#if defined(__UNIX_LIKE__)
1617 // under Unix touching file is simple: just pass NULL to utime()
1618 if ( utime(GetFullPath(), NULL) == 0 )
1619 {
1620 return TRUE;
1621 }
1622
1623 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1624
1625 return FALSE;
1626#else // other platform
1627 wxDateTime dtNow = wxDateTime::Now();
1628
1629 return SetTimes(NULL /* don't change create time */, &dtNow, &dtNow);
1630#endif // platforms
1631}
1632
1633bool wxFileName::GetTimes(wxDateTime *dtAccess,
1634 wxDateTime *dtMod,
1635 wxDateTime *dtChange) const
1636{
d9f54bb0 1637#if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
951cd180
VZ
1638 wxStructStat stBuf;
1639 if ( wxStat(GetFullPath(), &stBuf) == 0 )
1640 {
1641 if ( dtAccess )
1642 dtAccess->Set(stBuf.st_atime);
1643 if ( dtMod )
1644 dtMod->Set(stBuf.st_mtime);
1645 if ( dtChange )
1646 dtChange->Set(stBuf.st_ctime);
1647
1648 return TRUE;
1649 }
1650#elif defined(__WIN32__)
1651 wxFileHandle fh(GetFullPath());
1652 if ( fh.IsOk() )
1653 {
1654 FILETIME ftAccess, ftCreate, ftWrite;
1655
1656 if ( ::GetFileTime(fh,
1657 dtMod ? &ftCreate : NULL,
1658 dtAccess ? &ftAccess : NULL,
1659 dtChange ? &ftWrite : NULL) )
1660 {
1661 if ( dtMod )
1662 ConvertFileTimeToWx(dtMod, ftCreate);
1663 if ( dtAccess )
1664 ConvertFileTimeToWx(dtAccess, ftAccess);
1665 if ( dtChange )
1666 ConvertFileTimeToWx(dtChange, ftWrite);
1667
1668 return TRUE;
1669 }
1670 }
1671#else // other platform
1672#endif // platforms
1673
1674 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1675 GetFullPath().c_str());
1676
1677 return FALSE;
1678}
1679
4dfbcdd5
SC
1680#ifdef __WXMAC__
1681
1682const short kMacExtensionMaxLength = 16 ;
1683typedef struct
1684{
1685 char m_ext[kMacExtensionMaxLength] ;
1686 OSType m_type ;
1687 OSType m_creator ;
1688} MacDefaultExtensionRecord ;
1689
1690#include "wx/dynarray.h"
1691WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ;
1692#include "wx/arrimpl.cpp"
1693WX_DEFINE_OBJARRAY(MacDefaultExtensionArray) ;
1694
1695MacDefaultExtensionArray gMacDefaultExtensions ;
1696bool gMacDefaultExtensionsInited = false ;
1697
1698static void MacEnsureDefaultExtensionsLoaded()
1699{
1700 if ( !gMacDefaultExtensionsInited )
1701 {
1702 // load the default extensions
1703 MacDefaultExtensionRecord defaults[] =
1704 {
1705 { "txt" , 'TEXT' , 'ttxt' } ,
1706
1707 } ;
1708 // we could load the pc exchange prefs here too
1709
1710 for ( int i = 0 ; i < WXSIZEOF( defaults ) ; ++i )
1711 {
1712 gMacDefaultExtensions.Add( defaults[i] ) ;
1713 }
1714 gMacDefaultExtensionsInited = true ;
1715 }
1716}
1717bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
1718{
1719 FInfo fndrInfo ;
1720 FSSpec spec ;
1721 wxMacFilename2FSSpec(GetFullPath(),&spec) ;
1722 OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
1723 wxCHECK( err == noErr , false ) ;
1724
1725 fndrInfo.fdType = type ;
1726 fndrInfo.fdCreator = creator ;
1727 FSpSetFInfo( &spec , &fndrInfo ) ;
1728 return true ;
1729}
1730
1731bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
1732{
1733 FInfo fndrInfo ;
1734 FSSpec spec ;
1735 wxMacFilename2FSSpec(GetFullPath(),&spec) ;
1736 OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
1737 wxCHECK( err == noErr , false ) ;
1738
1739 *type = fndrInfo.fdType ;
1740 *creator = fndrInfo.fdCreator ;
1741 return true ;
1742}
1743
1744bool wxFileName::MacSetDefaultTypeAndCreator()
1745{
1746 wxUint32 type , creator ;
1747 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
1748 &creator ) )
1749 {
f63fb56d
GD
1750 return MacSetTypeAndCreator( type , creator ) ;
1751 }
1752 return false;
4dfbcdd5
SC
1753}
1754
1755bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
1756{
1757 MacEnsureDefaultExtensionsLoaded() ;
1758 wxString extl = ext.Lower() ;
1759 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
1760 {
1761 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
1762 {
1763 *type = gMacDefaultExtensions.Item(i).m_type ;
1764 *creator = gMacDefaultExtensions.Item(i).m_creator ;
1765 return true ;
1766 }
1767 }
1768 return false ;
1769}
1770
1771void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
1772{
1773 MacEnsureDefaultExtensionsLoaded() ;
1774 MacDefaultExtensionRecord rec ;
1775 rec.m_type = type ;
1776 rec.m_creator = creator ;
1777 strncpy( rec.m_ext , ext.Lower().c_str() , kMacExtensionMaxLength ) ;
1778 gMacDefaultExtensions.Add( rec ) ;
1779}
1780#endif