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