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