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