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