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