]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
Fix handling of invalid paths with multiple columns in wxFileName.
[wxWidgets.git] / src / common / filename.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/filename.cpp
3 // Purpose: wxFileName - encapsulates a file path
4 // Author: Robert Roebling, Vadim Zeitlin
5 // Modified by:
6 // Created: 28.12.2000
7 // RCS-ID: $Id$
8 // Copyright: (c) 2000 Robert Roebling
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 /*
13 Here are brief descriptions of the filename formats supported by this class:
14
15 wxPATH_UNIX: standard Unix format, used under Darwin as well, absolute file
16 names have the form:
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
21 wxPATH_DOS: DOS/Windows format, absolute file names have the form:
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
27 wxPATH_MAC: Mac OS 8/9 and Mac OS X under CodeWarrior 7 format, absolute file
28 names have the form
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).
35 Since the volume is just part of the file path, it is not
36 treated like a separate entity as it is done under DOS and
37 VMS, it is just treated as another dir.
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 specification
51 . separator between directory and subdirectory
52 ] between directory and file
53 */
54
55 // ============================================================================
56 // declarations
57 // ============================================================================
58
59 // ----------------------------------------------------------------------------
60 // headers
61 // ----------------------------------------------------------------------------
62
63 // For compilers that support precompilation, includes "wx.h".
64 #include "wx/wxprec.h"
65
66 #ifdef __BORLANDC__
67 #pragma hdrstop
68 #endif
69
70 #ifndef WX_PRECOMP
71 #ifdef __WXMSW__
72 #include "wx/msw/wrapwin.h" // For GetShort/LongPathName
73 #endif
74 #include "wx/dynarray.h"
75 #include "wx/intl.h"
76 #include "wx/log.h"
77 #include "wx/utils.h"
78 #include "wx/crt.h"
79 #endif
80
81 #include "wx/filename.h"
82 #include "wx/private/filename.h"
83 #include "wx/tokenzr.h"
84 #include "wx/config.h" // for wxExpandEnvVars
85 #include "wx/dynlib.h"
86 #include "wx/dir.h"
87
88 #if defined(__WIN32__) && defined(__MINGW32__)
89 #include "wx/msw/gccpriv.h"
90 #endif
91
92 #ifdef __WXWINCE__
93 #include "wx/msw/private.h"
94 #endif
95
96 #if defined(__WXMAC__)
97 #include "wx/osx/private.h" // includes mac headers
98 #endif
99
100 // utime() is POSIX so should normally be available on all Unices
101 #ifdef __UNIX_LIKE__
102 #include <sys/types.h>
103 #include <utime.h>
104 #include <sys/stat.h>
105 #include <unistd.h>
106 #endif
107
108 #ifdef __DJGPP__
109 #include <unistd.h>
110 #endif
111
112 #ifdef __MWERKS__
113 #ifdef __MACH__
114 #include <sys/types.h>
115 #include <utime.h>
116 #include <sys/stat.h>
117 #include <unistd.h>
118 #else
119 #include <stat.h>
120 #include <unistd.h>
121 #include <unix.h>
122 #endif
123 #endif
124
125 #ifdef __WATCOMC__
126 #include <io.h>
127 #include <sys/utime.h>
128 #include <sys/stat.h>
129 #endif
130
131 #ifdef __VISAGECPP__
132 #ifndef MAX_PATH
133 #define MAX_PATH 256
134 #endif
135 #endif
136
137 #ifdef __EMX__
138 #include <os2.h>
139 #define MAX_PATH _MAX_PATH
140 #endif
141
142
143 #if wxUSE_LONGLONG
144 extern const wxULongLong wxInvalidSize = (unsigned)-1;
145 #endif // wxUSE_LONGLONG
146
147 namespace
148 {
149
150 // ----------------------------------------------------------------------------
151 // private classes
152 // ----------------------------------------------------------------------------
153
154 // small helper class which opens and closes the file - we use it just to get
155 // a file handle for the given file name to pass it to some Win32 API function
156 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
157
158 class wxFileHandle
159 {
160 public:
161 enum OpenMode
162 {
163 Read,
164 Write
165 };
166
167 wxFileHandle(const wxString& filename, OpenMode mode, int flags = 0)
168 {
169 m_hFile = ::CreateFile
170 (
171 filename.fn_str(), // name
172 mode == Read ? GENERIC_READ // access mask
173 : GENERIC_WRITE,
174 FILE_SHARE_READ | // sharing mode
175 FILE_SHARE_WRITE, // (allow everything)
176 NULL, // no secutity attr
177 OPEN_EXISTING, // creation disposition
178 flags, // flags
179 NULL // no template file
180 );
181
182 if ( m_hFile == INVALID_HANDLE_VALUE )
183 {
184 if ( mode == Read )
185 {
186 wxLogSysError(_("Failed to open '%s' for reading"),
187 filename.c_str());
188 }
189 else
190 {
191 wxLogSysError(_("Failed to open '%s' for writing"),
192 filename.c_str());
193 }
194 }
195 }
196
197 ~wxFileHandle()
198 {
199 if ( m_hFile != INVALID_HANDLE_VALUE )
200 {
201 if ( !::CloseHandle(m_hFile) )
202 {
203 wxLogSysError(_("Failed to close file handle"));
204 }
205 }
206 }
207
208 // return true only if the file could be opened successfully
209 bool IsOk() const { return m_hFile != INVALID_HANDLE_VALUE; }
210
211 // get the handle
212 operator HANDLE() const { return m_hFile; }
213
214 private:
215 HANDLE m_hFile;
216 };
217
218 #endif // __WIN32__
219
220 // ----------------------------------------------------------------------------
221 // private functions
222 // ----------------------------------------------------------------------------
223
224 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
225
226 // convert between wxDateTime and FILETIME which is a 64-bit value representing
227 // the number of 100-nanosecond intervals since January 1, 1601.
228
229 static void ConvertFileTimeToWx(wxDateTime *dt, const FILETIME &ft)
230 {
231 FILETIME ftcopy = ft;
232 FILETIME ftLocal;
233 if ( !::FileTimeToLocalFileTime(&ftcopy, &ftLocal) )
234 {
235 wxLogLastError(wxT("FileTimeToLocalFileTime"));
236 }
237
238 SYSTEMTIME st;
239 if ( !::FileTimeToSystemTime(&ftLocal, &st) )
240 {
241 wxLogLastError(wxT("FileTimeToSystemTime"));
242 }
243
244 dt->Set(st.wDay, wxDateTime::Month(st.wMonth - 1), st.wYear,
245 st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
246 }
247
248 static void ConvertWxToFileTime(FILETIME *ft, const wxDateTime& dt)
249 {
250 SYSTEMTIME st;
251 st.wDay = dt.GetDay();
252 st.wMonth = (WORD)(dt.GetMonth() + 1);
253 st.wYear = (WORD)dt.GetYear();
254 st.wHour = dt.GetHour();
255 st.wMinute = dt.GetMinute();
256 st.wSecond = dt.GetSecond();
257 st.wMilliseconds = dt.GetMillisecond();
258
259 FILETIME ftLocal;
260 if ( !::SystemTimeToFileTime(&st, &ftLocal) )
261 {
262 wxLogLastError(wxT("SystemTimeToFileTime"));
263 }
264
265 if ( !::LocalFileTimeToFileTime(&ftLocal, ft) )
266 {
267 wxLogLastError(wxT("LocalFileTimeToFileTime"));
268 }
269 }
270
271 #endif // wxUSE_DATETIME && __WIN32__
272
273 // return a string with the volume par
274 static wxString wxGetVolumeString(const wxString& volume, wxPathFormat format)
275 {
276 wxString path;
277
278 if ( !volume.empty() )
279 {
280 format = wxFileName::GetFormat(format);
281
282 // Special Windows UNC paths hack, part 2: undo what we did in
283 // SplitPath() and make an UNC path if we have a drive which is not a
284 // single letter (hopefully the network shares can't be one letter only
285 // although I didn't find any authoritative docs on this)
286 if ( format == wxPATH_DOS && volume.length() > 1 )
287 {
288 path << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << volume;
289 }
290 else if ( format == wxPATH_DOS || format == wxPATH_VMS )
291 {
292 path << volume << wxFileName::GetVolumeSeparator(format);
293 }
294 // else ignore
295 }
296
297 return path;
298 }
299
300 // return true if the character is a DOS path separator i.e. either a slash or
301 // a backslash
302 inline bool IsDOSPathSep(wxUniChar ch)
303 {
304 return ch == wxFILE_SEP_PATH_DOS || ch == wxFILE_SEP_PATH_UNIX;
305 }
306
307 // return true if the format used is the DOS/Windows one and the string looks
308 // like a UNC path
309 static bool IsUNCPath(const wxString& path, wxPathFormat format)
310 {
311 return format == wxPATH_DOS &&
312 path.length() >= 4 && // "\\a" can't be a UNC path
313 IsDOSPathSep(path[0u]) &&
314 IsDOSPathSep(path[1u]) &&
315 !IsDOSPathSep(path[2u]);
316 }
317
318 } // anonymous namespace
319
320 // ============================================================================
321 // implementation
322 // ============================================================================
323
324 // ----------------------------------------------------------------------------
325 // wxFileName construction
326 // ----------------------------------------------------------------------------
327
328 void wxFileName::Assign( const wxFileName &filepath )
329 {
330 m_volume = filepath.GetVolume();
331 m_dirs = filepath.GetDirs();
332 m_name = filepath.GetName();
333 m_ext = filepath.GetExt();
334 m_relative = filepath.m_relative;
335 m_hasExt = filepath.m_hasExt;
336 }
337
338 void wxFileName::Assign(const wxString& volume,
339 const wxString& path,
340 const wxString& name,
341 const wxString& ext,
342 bool hasExt,
343 wxPathFormat format)
344 {
345 // we should ignore paths which look like UNC shares because we already
346 // have the volume here and the UNC notation (\\server\path) is only valid
347 // for paths which don't start with a volume, so prevent SetPath() from
348 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
349 //
350 // note also that this is a rather ugly way to do what we want (passing
351 // some kind of flag telling to ignore UNC paths to SetPath() would be
352 // better) but this is the safest thing to do to avoid breaking backwards
353 // compatibility in 2.8
354 if ( IsUNCPath(path, format) )
355 {
356 // remove one of the 2 leading backslashes to ensure that it's not
357 // recognized as an UNC path by SetPath()
358 wxString pathNonUNC(path, 1, wxString::npos);
359 SetPath(pathNonUNC, format);
360 }
361 else // no UNC complications
362 {
363 SetPath(path, format);
364 }
365
366 m_volume = volume;
367 m_ext = ext;
368 m_name = name;
369
370 m_hasExt = hasExt;
371 }
372
373 void wxFileName::SetPath( const wxString& pathOrig, wxPathFormat format )
374 {
375 m_dirs.Clear();
376
377 if ( pathOrig.empty() )
378 {
379 // no path at all
380 m_relative = true;
381
382 return;
383 }
384
385 format = GetFormat( format );
386
387 // 0) deal with possible volume part first
388 wxString volume,
389 path;
390 SplitVolume(pathOrig, &volume, &path, format);
391 if ( !volume.empty() )
392 {
393 m_relative = false;
394
395 SetVolume(volume);
396 }
397
398 // 1) Determine if the path is relative or absolute.
399
400 if ( path.empty() )
401 {
402 // we had only the volume
403 return;
404 }
405
406 wxChar leadingChar = path[0u];
407
408 switch (format)
409 {
410 case wxPATH_MAC:
411 m_relative = leadingChar == wxT(':');
412
413 // We then remove a leading ":". The reason is in our
414 // storage form for relative paths:
415 // ":dir:file.txt" actually means "./dir/file.txt" in
416 // DOS notation and should get stored as
417 // (relative) (dir) (file.txt)
418 // "::dir:file.txt" actually means "../dir/file.txt"
419 // stored as (relative) (..) (dir) (file.txt)
420 // This is important only for the Mac as an empty dir
421 // actually means <UP>, whereas under DOS, double
422 // slashes can be ignored: "\\\\" is the same as "\\".
423 if (m_relative)
424 path.erase( 0, 1 );
425 break;
426
427 case wxPATH_VMS:
428 // TODO: what is the relative path format here?
429 m_relative = false;
430 break;
431
432 default:
433 wxFAIL_MSG( wxT("Unknown path format") );
434 // !! Fall through !!
435
436 case wxPATH_UNIX:
437 m_relative = leadingChar != wxT('/');
438 break;
439
440 case wxPATH_DOS:
441 m_relative = !IsPathSeparator(leadingChar, format);
442 break;
443
444 }
445
446 // 2) Break up the path into its members. If the original path
447 // was just "/" or "\\", m_dirs will be empty. We know from
448 // the m_relative field, if this means "nothing" or "root dir".
449
450 wxStringTokenizer tn( path, GetPathSeparators(format) );
451
452 while ( tn.HasMoreTokens() )
453 {
454 wxString token = tn.GetNextToken();
455
456 // Remove empty token under DOS and Unix, interpret them
457 // as .. under Mac.
458 if (token.empty())
459 {
460 if (format == wxPATH_MAC)
461 m_dirs.Add( wxT("..") );
462 // else ignore
463 }
464 else
465 {
466 m_dirs.Add( token );
467 }
468 }
469 }
470
471 void wxFileName::Assign(const wxString& fullpath,
472 wxPathFormat format)
473 {
474 wxString volume, path, name, ext;
475 bool hasExt;
476 SplitPath(fullpath, &volume, &path, &name, &ext, &hasExt, format);
477
478 Assign(volume, path, name, ext, hasExt, format);
479 }
480
481 void wxFileName::Assign(const wxString& fullpathOrig,
482 const wxString& fullname,
483 wxPathFormat format)
484 {
485 // always recognize fullpath as directory, even if it doesn't end with a
486 // slash
487 wxString fullpath = fullpathOrig;
488 if ( !fullpath.empty() && !wxEndsWithPathSeparator(fullpath) )
489 {
490 fullpath += GetPathSeparator(format);
491 }
492
493 wxString volume, path, name, ext;
494 bool hasExt;
495
496 // do some consistency checks: the name should be really just the filename
497 // and the path should be really just a path
498 wxString volDummy, pathDummy, nameDummy, extDummy;
499
500 SplitPath(fullname, &volDummy, &pathDummy, &name, &ext, &hasExt, format);
501
502 wxASSERT_MSG( volDummy.empty() && pathDummy.empty(),
503 wxT("the file name shouldn't contain the path") );
504
505 SplitPath(fullpath, &volume, &path, &nameDummy, &extDummy, format);
506
507 #ifndef __VMS
508 // This test makes no sense on an OpenVMS system.
509 wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
510 wxT("the path shouldn't contain file name nor extension") );
511 #endif
512 Assign(volume, path, name, ext, hasExt, format);
513 }
514
515 void wxFileName::Assign(const wxString& pathOrig,
516 const wxString& name,
517 const wxString& ext,
518 wxPathFormat format)
519 {
520 wxString volume,
521 path;
522 SplitVolume(pathOrig, &volume, &path, format);
523
524 Assign(volume, path, name, ext, format);
525 }
526
527 void wxFileName::AssignDir(const wxString& dir, wxPathFormat format)
528 {
529 Assign(dir, wxEmptyString, format);
530 }
531
532 void wxFileName::Clear()
533 {
534 m_dirs.Clear();
535
536 m_volume =
537 m_name =
538 m_ext = wxEmptyString;
539
540 // we don't have any absolute path for now
541 m_relative = true;
542
543 // nor any extension
544 m_hasExt = false;
545 }
546
547 /* static */
548 wxFileName wxFileName::FileName(const wxString& file, wxPathFormat format)
549 {
550 return wxFileName(file, format);
551 }
552
553 /* static */
554 wxFileName wxFileName::DirName(const wxString& dir, wxPathFormat format)
555 {
556 wxFileName fn;
557 fn.AssignDir(dir, format);
558 return fn;
559 }
560
561 // ----------------------------------------------------------------------------
562 // existence tests
563 // ----------------------------------------------------------------------------
564
565 bool wxFileName::FileExists() const
566 {
567 return wxFileName::FileExists( GetFullPath() );
568 }
569
570 bool wxFileName::FileExists( const wxString &file )
571 {
572 return ::wxFileExists( file );
573 }
574
575 bool wxFileName::DirExists() const
576 {
577 return wxFileName::DirExists( GetPath() );
578 }
579
580 bool wxFileName::DirExists( const wxString &dir )
581 {
582 return ::wxDirExists( dir );
583 }
584
585 // ----------------------------------------------------------------------------
586 // CWD and HOME stuff
587 // ----------------------------------------------------------------------------
588
589 void wxFileName::AssignCwd(const wxString& volume)
590 {
591 AssignDir(wxFileName::GetCwd(volume));
592 }
593
594 /* static */
595 wxString wxFileName::GetCwd(const wxString& volume)
596 {
597 // if we have the volume, we must get the current directory on this drive
598 // and to do this we have to chdir to this volume - at least under Windows,
599 // I don't know how to get the current drive on another volume elsewhere
600 // (TODO)
601 wxString cwdOld;
602 if ( !volume.empty() )
603 {
604 cwdOld = wxGetCwd();
605 SetCwd(volume + GetVolumeSeparator());
606 }
607
608 wxString cwd = ::wxGetCwd();
609
610 if ( !volume.empty() )
611 {
612 SetCwd(cwdOld);
613 }
614
615 return cwd;
616 }
617
618 bool wxFileName::SetCwd() const
619 {
620 return wxFileName::SetCwd( GetPath() );
621 }
622
623 bool wxFileName::SetCwd( const wxString &cwd )
624 {
625 return ::wxSetWorkingDirectory( cwd );
626 }
627
628 void wxFileName::AssignHomeDir()
629 {
630 AssignDir(wxFileName::GetHomeDir());
631 }
632
633 wxString wxFileName::GetHomeDir()
634 {
635 return ::wxGetHomeDir();
636 }
637
638
639 // ----------------------------------------------------------------------------
640 // CreateTempFileName
641 // ----------------------------------------------------------------------------
642
643 #if wxUSE_FILE || wxUSE_FFILE
644
645
646 #if !defined wx_fdopen && defined HAVE_FDOPEN
647 #define wx_fdopen fdopen
648 #endif
649
650 // NB: GetTempFileName() under Windows creates the file, so using
651 // O_EXCL there would fail
652 #ifdef __WINDOWS__
653 #define wxOPEN_EXCL 0
654 #else
655 #define wxOPEN_EXCL O_EXCL
656 #endif
657
658
659 #ifdef wxOpenOSFHandle
660 #define WX_HAVE_DELETE_ON_CLOSE
661 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
662 //
663 static int wxOpenWithDeleteOnClose(const wxString& filename)
664 {
665 DWORD access = GENERIC_READ | GENERIC_WRITE;
666
667 DWORD disposition = OPEN_ALWAYS;
668
669 DWORD attributes = FILE_ATTRIBUTE_TEMPORARY |
670 FILE_FLAG_DELETE_ON_CLOSE;
671
672 HANDLE h = ::CreateFile(filename.fn_str(), access, 0, NULL,
673 disposition, attributes, NULL);
674
675 return wxOpenOSFHandle(h, wxO_BINARY);
676 }
677 #endif // wxOpenOSFHandle
678
679
680 // Helper to open the file
681 //
682 static int wxTempOpen(const wxString& path, bool *deleteOnClose)
683 {
684 #ifdef WX_HAVE_DELETE_ON_CLOSE
685 if (*deleteOnClose)
686 return wxOpenWithDeleteOnClose(path);
687 #endif
688
689 *deleteOnClose = false;
690
691 return wxOpen(path, wxO_BINARY | O_RDWR | O_CREAT | wxOPEN_EXCL, 0600);
692 }
693
694
695 #if wxUSE_FFILE
696 // Helper to open the file and attach it to the wxFFile
697 //
698 static bool wxTempOpen(wxFFile *file, const wxString& path, bool *deleteOnClose)
699 {
700 #ifndef wx_fdopen
701 *deleteOnClose = false;
702 return file->Open(path, wxT("w+b"));
703 #else // wx_fdopen
704 int fd = wxTempOpen(path, deleteOnClose);
705 if (fd == -1)
706 return false;
707 file->Attach(wx_fdopen(fd, "w+b"));
708 return file->IsOpened();
709 #endif // wx_fdopen
710 }
711 #endif // wxUSE_FFILE
712
713
714 #if !wxUSE_FILE
715 #define WXFILEARGS(x, y) y
716 #elif !wxUSE_FFILE
717 #define WXFILEARGS(x, y) x
718 #else
719 #define WXFILEARGS(x, y) x, y
720 #endif
721
722
723 // Implementation of wxFileName::CreateTempFileName().
724 //
725 static wxString wxCreateTempImpl(
726 const wxString& prefix,
727 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
728 bool *deleteOnClose = NULL)
729 {
730 #if wxUSE_FILE && wxUSE_FFILE
731 wxASSERT(fileTemp == NULL || ffileTemp == NULL);
732 #endif
733 wxString path, dir, name;
734 bool wantDeleteOnClose = false;
735
736 if (deleteOnClose)
737 {
738 // set the result to false initially
739 wantDeleteOnClose = *deleteOnClose;
740 *deleteOnClose = false;
741 }
742 else
743 {
744 // easier if it alwasys points to something
745 deleteOnClose = &wantDeleteOnClose;
746 }
747
748 // use the directory specified by the prefix
749 wxFileName::SplitPath(prefix, &dir, &name, NULL /* extension */);
750
751 if (dir.empty())
752 {
753 dir = wxFileName::GetTempDir();
754 }
755
756 #if defined(__WXWINCE__)
757 path = dir + wxT("\\") + name;
758 int i = 1;
759 while (wxFileName::FileExists(path))
760 {
761 path = dir + wxT("\\") + name ;
762 path << i;
763 i ++;
764 }
765
766 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
767 if ( !::GetTempFileName(dir.fn_str(), name.fn_str(), 0,
768 wxStringBuffer(path, MAX_PATH + 1)) )
769 {
770 wxLogLastError(wxT("GetTempFileName"));
771
772 path.clear();
773 }
774
775 #else // !Windows
776 path = dir;
777
778 if ( !wxEndsWithPathSeparator(dir) &&
779 (name.empty() || !wxIsPathSeparator(name[0u])) )
780 {
781 path += wxFILE_SEP_PATH;
782 }
783
784 path += name;
785
786 #if defined(HAVE_MKSTEMP)
787 // scratch space for mkstemp()
788 path += wxT("XXXXXX");
789
790 // we need to copy the path to the buffer in which mkstemp() can modify it
791 wxCharBuffer buf(path.fn_str());
792
793 // cast is safe because the string length doesn't change
794 int fdTemp = mkstemp( (char*)(const char*) buf );
795 if ( fdTemp == -1 )
796 {
797 // this might be not necessary as mkstemp() on most systems should have
798 // already done it but it doesn't hurt neither...
799 path.clear();
800 }
801 else // mkstemp() succeeded
802 {
803 path = wxConvFile.cMB2WX( (const char*) buf );
804
805 #if wxUSE_FILE
806 // avoid leaking the fd
807 if ( fileTemp )
808 {
809 fileTemp->Attach(fdTemp);
810 }
811 else
812 #endif
813
814 #if wxUSE_FFILE
815 if ( ffileTemp )
816 {
817 #ifdef wx_fdopen
818 ffileTemp->Attach(wx_fdopen(fdTemp, "r+b"));
819 #else
820 ffileTemp->Open(path, wxT("r+b"));
821 close(fdTemp);
822 #endif
823 }
824 else
825 #endif
826
827 {
828 close(fdTemp);
829 }
830 }
831 #else // !HAVE_MKSTEMP
832
833 #ifdef HAVE_MKTEMP
834 // same as above
835 path += wxT("XXXXXX");
836
837 wxCharBuffer buf = wxConvFile.cWX2MB( path );
838 if ( !mktemp( (char*)(const char*) buf ) )
839 {
840 path.clear();
841 }
842 else
843 {
844 path = wxConvFile.cMB2WX( (const char*) buf );
845 }
846 #else // !HAVE_MKTEMP (includes __DOS__)
847 // generate the unique file name ourselves
848 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
849 path << (unsigned int)getpid();
850 #endif
851
852 wxString pathTry;
853
854 static const size_t numTries = 1000;
855 for ( size_t n = 0; n < numTries; n++ )
856 {
857 // 3 hex digits is enough for numTries == 1000 < 4096
858 pathTry = path + wxString::Format(wxT("%.03x"), (unsigned int) n);
859 if ( !wxFileName::FileExists(pathTry) )
860 {
861 break;
862 }
863
864 pathTry.clear();
865 }
866
867 path = pathTry;
868 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
869
870 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
871
872 #endif // Windows/!Windows
873
874 if ( path.empty() )
875 {
876 wxLogSysError(_("Failed to create a temporary file name"));
877 }
878 else
879 {
880 bool ok = true;
881
882 // open the file - of course, there is a race condition here, this is
883 // why we always prefer using mkstemp()...
884 #if wxUSE_FILE
885 if ( fileTemp && !fileTemp->IsOpened() )
886 {
887 *deleteOnClose = wantDeleteOnClose;
888 int fd = wxTempOpen(path, deleteOnClose);
889 if (fd != -1)
890 fileTemp->Attach(fd);
891 else
892 ok = false;
893 }
894 #endif
895
896 #if wxUSE_FFILE
897 if ( ffileTemp && !ffileTemp->IsOpened() )
898 {
899 *deleteOnClose = wantDeleteOnClose;
900 ok = wxTempOpen(ffileTemp, path, deleteOnClose);
901 }
902 #endif
903
904 if ( !ok )
905 {
906 // FIXME: If !ok here should we loop and try again with another
907 // file name? That is the standard recourse if open(O_EXCL)
908 // fails, though of course it should be protected against
909 // possible infinite looping too.
910
911 wxLogError(_("Failed to open temporary file."));
912
913 path.clear();
914 }
915 }
916
917 return path;
918 }
919
920
921 static bool wxCreateTempImpl(
922 const wxString& prefix,
923 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
924 wxString *name)
925 {
926 bool deleteOnClose = true;
927
928 *name = wxCreateTempImpl(prefix,
929 WXFILEARGS(fileTemp, ffileTemp),
930 &deleteOnClose);
931
932 bool ok = !name->empty();
933
934 if (deleteOnClose)
935 name->clear();
936 #ifdef __UNIX__
937 else if (ok && wxRemoveFile(*name))
938 name->clear();
939 #endif
940
941 return ok;
942 }
943
944
945 static void wxAssignTempImpl(
946 wxFileName *fn,
947 const wxString& prefix,
948 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp))
949 {
950 wxString tempname;
951 tempname = wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, ffileTemp));
952
953 if ( tempname.empty() )
954 {
955 // error, failed to get temp file name
956 fn->Clear();
957 }
958 else // ok
959 {
960 fn->Assign(tempname);
961 }
962 }
963
964
965 void wxFileName::AssignTempFileName(const wxString& prefix)
966 {
967 wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, NULL));
968 }
969
970 /* static */
971 wxString wxFileName::CreateTempFileName(const wxString& prefix)
972 {
973 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, NULL));
974 }
975
976 #endif // wxUSE_FILE || wxUSE_FFILE
977
978
979 #if wxUSE_FILE
980
981 wxString wxCreateTempFileName(const wxString& prefix,
982 wxFile *fileTemp,
983 bool *deleteOnClose)
984 {
985 return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), deleteOnClose);
986 }
987
988 bool wxCreateTempFile(const wxString& prefix,
989 wxFile *fileTemp,
990 wxString *name)
991 {
992 return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), name);
993 }
994
995 void wxFileName::AssignTempFileName(const wxString& prefix, wxFile *fileTemp)
996 {
997 wxAssignTempImpl(this, prefix, WXFILEARGS(fileTemp, NULL));
998 }
999
1000 /* static */
1001 wxString
1002 wxFileName::CreateTempFileName(const wxString& prefix, wxFile *fileTemp)
1003 {
1004 return wxCreateTempFileName(prefix, fileTemp);
1005 }
1006
1007 #endif // wxUSE_FILE
1008
1009
1010 #if wxUSE_FFILE
1011
1012 wxString wxCreateTempFileName(const wxString& prefix,
1013 wxFFile *fileTemp,
1014 bool *deleteOnClose)
1015 {
1016 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), deleteOnClose);
1017 }
1018
1019 bool wxCreateTempFile(const wxString& prefix,
1020 wxFFile *fileTemp,
1021 wxString *name)
1022 {
1023 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), name);
1024
1025 }
1026
1027 void wxFileName::AssignTempFileName(const wxString& prefix, wxFFile *fileTemp)
1028 {
1029 wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, fileTemp));
1030 }
1031
1032 /* static */
1033 wxString
1034 wxFileName::CreateTempFileName(const wxString& prefix, wxFFile *fileTemp)
1035 {
1036 return wxCreateTempFileName(prefix, fileTemp);
1037 }
1038
1039 #endif // wxUSE_FFILE
1040
1041
1042 // ----------------------------------------------------------------------------
1043 // directory operations
1044 // ----------------------------------------------------------------------------
1045
1046 // helper of GetTempDir(): check if the given directory exists and return it if
1047 // it does or an empty string otherwise
1048 namespace
1049 {
1050
1051 wxString CheckIfDirExists(const wxString& dir)
1052 {
1053 return wxFileName::DirExists(dir) ? dir : wxString();
1054 }
1055
1056 } // anonymous namespace
1057
1058 wxString wxFileName::GetTempDir()
1059 {
1060 // first try getting it from environment: this allows overriding the values
1061 // used by default if the user wants to create temporary files in another
1062 // directory
1063 wxString dir = CheckIfDirExists(wxGetenv("TMPDIR"));
1064 if ( dir.empty() )
1065 {
1066 dir = CheckIfDirExists(wxGetenv("TMP"));
1067 if ( dir.empty() )
1068 dir = CheckIfDirExists(wxGetenv("TEMP"));
1069 }
1070
1071 // if no environment variables are set, use the system default
1072 if ( dir.empty() )
1073 {
1074 #if defined(__WXWINCE__)
1075 dir = CheckIfDirExists(wxT("\\temp"));
1076 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1077 if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
1078 {
1079 wxLogLastError(wxT("GetTempPath"));
1080 }
1081 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1082 dir = wxMacFindFolder(short(kOnSystemDisk), kTemporaryFolderType, kCreateFolder);
1083 #endif // systems with native way
1084 }
1085
1086 // fall back to hard coded value
1087 if ( dir.empty() )
1088 {
1089 #ifdef __UNIX_LIKE__
1090 dir = CheckIfDirExists("/tmp");
1091 if ( dir.empty() )
1092 #endif // __UNIX_LIKE__
1093 dir = ".";
1094 }
1095
1096 return dir;
1097 }
1098
1099 bool wxFileName::Mkdir( int perm, int flags ) const
1100 {
1101 return wxFileName::Mkdir(GetPath(), perm, flags);
1102 }
1103
1104 bool wxFileName::Mkdir( const wxString& dir, int perm, int flags )
1105 {
1106 if ( flags & wxPATH_MKDIR_FULL )
1107 {
1108 // split the path in components
1109 wxFileName filename;
1110 filename.AssignDir(dir);
1111
1112 wxString currPath;
1113 if ( filename.HasVolume())
1114 {
1115 currPath << wxGetVolumeString(filename.GetVolume(), wxPATH_NATIVE);
1116 }
1117
1118 wxArrayString dirs = filename.GetDirs();
1119 size_t count = dirs.GetCount();
1120 for ( size_t i = 0; i < count; i++ )
1121 {
1122 if ( i > 0 || filename.IsAbsolute() )
1123 currPath += wxFILE_SEP_PATH;
1124 currPath += dirs[i];
1125
1126 if (!DirExists(currPath))
1127 {
1128 if (!wxMkdir(currPath, perm))
1129 {
1130 // no need to try creating further directories
1131 return false;
1132 }
1133 }
1134 }
1135
1136 return true;
1137
1138 }
1139
1140 return ::wxMkdir( dir, perm );
1141 }
1142
1143 bool wxFileName::Rmdir(int flags) const
1144 {
1145 return wxFileName::Rmdir( GetPath(), flags );
1146 }
1147
1148 bool wxFileName::Rmdir(const wxString& dir, int flags)
1149 {
1150 #ifdef __WXMSW__
1151 if ( flags & wxPATH_RMDIR_RECURSIVE )
1152 {
1153 // SHFileOperation needs double null termination string
1154 // but without separator at the end of the path
1155 wxString path(dir);
1156 if ( path.Last() == wxFILE_SEP_PATH )
1157 path.RemoveLast();
1158 path += wxT('\0');
1159
1160 SHFILEOPSTRUCT fileop;
1161 wxZeroMemory(fileop);
1162 fileop.wFunc = FO_DELETE;
1163 fileop.pFrom = path.fn_str();
1164 fileop.fFlags = FOF_SILENT | FOF_NOCONFIRMATION;
1165 #ifndef __WXWINCE__
1166 // FOF_NOERRORUI is not defined in WinCE
1167 fileop.fFlags |= FOF_NOERRORUI;
1168 #endif
1169
1170 int ret = SHFileOperation(&fileop);
1171 if ( ret != 0 )
1172 {
1173 // SHFileOperation may return non-Win32 error codes, so the error
1174 // message can be incorrect
1175 wxLogApiError(wxT("SHFileOperation"), ret);
1176 return false;
1177 }
1178
1179 return true;
1180 }
1181 else if ( flags & wxPATH_RMDIR_FULL )
1182 #else // !__WXMSW__
1183 if ( flags != 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1184 #endif // !__WXMSW__
1185 {
1186 wxString path(dir);
1187 if ( path.Last() != wxFILE_SEP_PATH )
1188 path += wxFILE_SEP_PATH;
1189
1190 wxDir d(path);
1191
1192 if ( !d.IsOpened() )
1193 return false;
1194
1195 wxString filename;
1196
1197 // first delete all subdirectories
1198 bool cont = d.GetFirst(&filename, "", wxDIR_DIRS | wxDIR_HIDDEN);
1199 while ( cont )
1200 {
1201 wxFileName::Rmdir(path + filename, flags);
1202 cont = d.GetNext(&filename);
1203 }
1204
1205 #ifndef __WXMSW__
1206 if ( flags & wxPATH_RMDIR_RECURSIVE )
1207 {
1208 // delete all files too
1209 cont = d.GetFirst(&filename, "", wxDIR_FILES | wxDIR_HIDDEN);
1210 while ( cont )
1211 {
1212 ::wxRemoveFile(path + filename);
1213 cont = d.GetNext(&filename);
1214 }
1215 }
1216 #endif // !__WXMSW__
1217 }
1218
1219 return ::wxRmdir(dir);
1220 }
1221
1222 // ----------------------------------------------------------------------------
1223 // path normalization
1224 // ----------------------------------------------------------------------------
1225
1226 bool wxFileName::Normalize(int flags,
1227 const wxString& cwd,
1228 wxPathFormat format)
1229 {
1230 // deal with env vars renaming first as this may seriously change the path
1231 if ( flags & wxPATH_NORM_ENV_VARS )
1232 {
1233 wxString pathOrig = GetFullPath(format);
1234 wxString path = wxExpandEnvVars(pathOrig);
1235 if ( path != pathOrig )
1236 {
1237 Assign(path);
1238 }
1239 }
1240
1241 // the existing path components
1242 wxArrayString dirs = GetDirs();
1243
1244 // the path to prepend in front to make the path absolute
1245 wxFileName curDir;
1246
1247 format = GetFormat(format);
1248
1249 // set up the directory to use for making the path absolute later
1250 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute(format) )
1251 {
1252 if ( cwd.empty() )
1253 {
1254 curDir.AssignCwd(GetVolume());
1255 }
1256 else // cwd provided
1257 {
1258 curDir.AssignDir(cwd);
1259 }
1260 }
1261
1262 // handle ~ stuff under Unix only
1263 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) && m_relative )
1264 {
1265 if ( !dirs.IsEmpty() )
1266 {
1267 wxString dir = dirs[0u];
1268 if ( !dir.empty() && dir[0u] == wxT('~') )
1269 {
1270 // to make the path absolute use the home directory
1271 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
1272 dirs.RemoveAt(0u);
1273 }
1274 }
1275 }
1276
1277 // transform relative path into abs one
1278 if ( curDir.IsOk() )
1279 {
1280 // this path may be relative because it doesn't have the volume name
1281 // and still have m_relative=true; in this case we shouldn't modify
1282 // our directory components but just set the current volume
1283 if ( !HasVolume() && curDir.HasVolume() )
1284 {
1285 SetVolume(curDir.GetVolume());
1286
1287 if ( !m_relative )
1288 {
1289 // yes, it was the case - we don't need curDir then
1290 curDir.Clear();
1291 }
1292 }
1293
1294 // finally, prepend curDir to the dirs array
1295 wxArrayString dirsNew = curDir.GetDirs();
1296 WX_PREPEND_ARRAY(dirs, dirsNew);
1297
1298 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1299 // return for some reason an absolute path, then curDir maybe not be absolute!
1300 if ( !curDir.m_relative )
1301 {
1302 // we have prepended an absolute path and thus we are now an absolute
1303 // file name too
1304 m_relative = false;
1305 }
1306 // else if (flags & wxPATH_NORM_ABSOLUTE):
1307 // should we warn the user that we didn't manage to make the path absolute?
1308 }
1309
1310 // now deal with ".", ".." and the rest
1311 m_dirs.Empty();
1312 size_t count = dirs.GetCount();
1313 for ( size_t n = 0; n < count; n++ )
1314 {
1315 wxString dir = dirs[n];
1316
1317 if ( flags & wxPATH_NORM_DOTS )
1318 {
1319 if ( dir == wxT(".") )
1320 {
1321 // just ignore
1322 continue;
1323 }
1324
1325 if ( dir == wxT("..") )
1326 {
1327 if ( m_dirs.IsEmpty() )
1328 {
1329 wxLogError(_("The path '%s' contains too many \"..\"!"),
1330 GetFullPath().c_str());
1331 return false;
1332 }
1333
1334 m_dirs.RemoveAt(m_dirs.GetCount() - 1);
1335 continue;
1336 }
1337 }
1338
1339 m_dirs.Add(dir);
1340 }
1341
1342 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1343 if ( (flags & wxPATH_NORM_SHORTCUT) )
1344 {
1345 wxString filename;
1346 if (GetShortcutTarget(GetFullPath(format), filename))
1347 {
1348 m_relative = false;
1349 Assign(filename);
1350 }
1351 }
1352 #endif
1353
1354 #if defined(__WIN32__)
1355 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
1356 {
1357 Assign(GetLongPath());
1358 }
1359 #endif // Win32
1360
1361 // Change case (this should be kept at the end of the function, to ensure
1362 // that the path doesn't change any more after we normalize its case)
1363 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
1364 {
1365 m_volume.MakeLower();
1366 m_name.MakeLower();
1367 m_ext.MakeLower();
1368
1369 // directory entries must be made lower case as well
1370 count = m_dirs.GetCount();
1371 for ( size_t i = 0; i < count; i++ )
1372 {
1373 m_dirs[i].MakeLower();
1374 }
1375 }
1376
1377 return true;
1378 }
1379
1380 #ifndef __WXWINCE__
1381 bool wxFileName::ReplaceEnvVariable(const wxString& envname,
1382 const wxString& replacementFmtString,
1383 wxPathFormat format)
1384 {
1385 // look into stringForm for the contents of the given environment variable
1386 wxString val;
1387 if (envname.empty() ||
1388 !wxGetEnv(envname, &val))
1389 return false;
1390 if (val.empty())
1391 return false;
1392
1393 wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
1394 // do not touch the file name and the extension
1395
1396 wxString replacement = wxString::Format(replacementFmtString, envname);
1397 stringForm.Replace(val, replacement);
1398
1399 // Now assign ourselves the modified path:
1400 Assign(stringForm, GetFullName(), format);
1401
1402 return true;
1403 }
1404 #endif
1405
1406 bool wxFileName::ReplaceHomeDir(wxPathFormat format)
1407 {
1408 wxString homedir = wxGetHomeDir();
1409 if (homedir.empty())
1410 return false;
1411
1412 wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
1413 // do not touch the file name and the extension
1414
1415 stringForm.Replace(homedir, "~");
1416
1417 // Now assign ourselves the modified path:
1418 Assign(stringForm, GetFullName(), format);
1419
1420 return true;
1421 }
1422
1423 // ----------------------------------------------------------------------------
1424 // get the shortcut target
1425 // ----------------------------------------------------------------------------
1426
1427 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1428 // The .lnk file is a plain text file so it should be easy to
1429 // make it work. Hint from Google Groups:
1430 // "If you open up a lnk file, you'll see a
1431 // number, followed by a pound sign (#), followed by more text. The
1432 // number is the number of characters that follows the pound sign. The
1433 // characters after the pound sign are the command line (which _can_
1434 // include arguments) to be executed. Any path (e.g. \windows\program
1435 // files\myapp.exe) that includes spaces needs to be enclosed in
1436 // quotation marks."
1437
1438 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1439 // The following lines are necessary under WinCE
1440 // #include "wx/msw/private.h"
1441 // #include <ole2.h>
1442 #include <shlobj.h>
1443 #if defined(__WXWINCE__)
1444 #include <shlguid.h>
1445 #endif
1446
1447 bool wxFileName::GetShortcutTarget(const wxString& shortcutPath,
1448 wxString& targetFilename,
1449 wxString* arguments) const
1450 {
1451 wxString path, file, ext;
1452 wxFileName::SplitPath(shortcutPath, & path, & file, & ext);
1453
1454 HRESULT hres;
1455 IShellLink* psl;
1456 bool success = false;
1457
1458 // Assume it's not a shortcut if it doesn't end with lnk
1459 if (ext.CmpNoCase(wxT("lnk"))!=0)
1460 return false;
1461
1462 // create a ShellLink object
1463 hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1464 IID_IShellLink, (LPVOID*) &psl);
1465
1466 if (SUCCEEDED(hres))
1467 {
1468 IPersistFile* ppf;
1469 hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
1470 if (SUCCEEDED(hres))
1471 {
1472 WCHAR wsz[MAX_PATH];
1473
1474 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
1475 MAX_PATH);
1476
1477 hres = ppf->Load(wsz, 0);
1478 ppf->Release();
1479
1480 if (SUCCEEDED(hres))
1481 {
1482 wxChar buf[2048];
1483 // Wrong prototype in early versions
1484 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1485 psl->GetPath((CHAR*) buf, 2048, NULL, SLGP_UNCPRIORITY);
1486 #else
1487 psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
1488 #endif
1489 targetFilename = wxString(buf);
1490 success = (shortcutPath != targetFilename);
1491
1492 psl->GetArguments(buf, 2048);
1493 wxString args(buf);
1494 if (!args.empty() && arguments)
1495 {
1496 *arguments = args;
1497 }
1498 }
1499 }
1500
1501 psl->Release();
1502 }
1503 return success;
1504 }
1505
1506 #endif // __WIN32__ && !__WXWINCE__
1507
1508
1509 // ----------------------------------------------------------------------------
1510 // absolute/relative paths
1511 // ----------------------------------------------------------------------------
1512
1513 bool wxFileName::IsAbsolute(wxPathFormat format) const
1514 {
1515 // unix paths beginning with ~ are reported as being absolute
1516 if ( format == wxPATH_UNIX )
1517 {
1518 if ( !m_dirs.IsEmpty() )
1519 {
1520 wxString dir = m_dirs[0u];
1521
1522 if (!dir.empty() && dir[0u] == wxT('~'))
1523 return true;
1524 }
1525 }
1526
1527 // if our path doesn't start with a path separator, it's not an absolute
1528 // path
1529 if ( m_relative )
1530 return false;
1531
1532 if ( !GetVolumeSeparator(format).empty() )
1533 {
1534 // this format has volumes and an absolute path must have one, it's not
1535 // enough to have the full path to be an absolute file under Windows
1536 if ( GetVolume().empty() )
1537 return false;
1538 }
1539
1540 return true;
1541 }
1542
1543 bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
1544 {
1545 wxFileName fnBase = wxFileName::DirName(pathBase, format);
1546
1547 // get cwd only once - small time saving
1548 wxString cwd = wxGetCwd();
1549 Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1550 fnBase.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1551
1552 bool withCase = IsCaseSensitive(format);
1553
1554 // we can't do anything if the files live on different volumes
1555 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
1556 {
1557 // nothing done
1558 return false;
1559 }
1560
1561 // same drive, so we don't need our volume
1562 m_volume.clear();
1563
1564 // remove common directories starting at the top
1565 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
1566 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
1567 {
1568 m_dirs.RemoveAt(0);
1569 fnBase.m_dirs.RemoveAt(0);
1570 }
1571
1572 // add as many ".." as needed
1573 size_t count = fnBase.m_dirs.GetCount();
1574 for ( size_t i = 0; i < count; i++ )
1575 {
1576 m_dirs.Insert(wxT(".."), 0u);
1577 }
1578
1579 if ( format == wxPATH_UNIX || format == wxPATH_DOS )
1580 {
1581 // a directory made relative with respect to itself is '.' under Unix
1582 // and DOS, by definition (but we don't have to insert "./" for the
1583 // files)
1584 if ( m_dirs.IsEmpty() && IsDir() )
1585 {
1586 m_dirs.Add(wxT('.'));
1587 }
1588 }
1589
1590 m_relative = true;
1591
1592 // we were modified
1593 return true;
1594 }
1595
1596 // ----------------------------------------------------------------------------
1597 // filename kind tests
1598 // ----------------------------------------------------------------------------
1599
1600 bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const
1601 {
1602 wxFileName fn1 = *this,
1603 fn2 = filepath;
1604
1605 // get cwd only once - small time saving
1606 wxString cwd = wxGetCwd();
1607 fn1.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1608 fn2.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1609
1610 if ( fn1.GetFullPath() == fn2.GetFullPath() )
1611 return true;
1612
1613 // TODO: compare inodes for Unix, this works even when filenames are
1614 // different but files are the same (symlinks) (VZ)
1615
1616 return false;
1617 }
1618
1619 /* static */
1620 bool wxFileName::IsCaseSensitive( wxPathFormat format )
1621 {
1622 // only Unix filenames are truely case-sensitive
1623 return GetFormat(format) == wxPATH_UNIX;
1624 }
1625
1626 /* static */
1627 wxString wxFileName::GetForbiddenChars(wxPathFormat format)
1628 {
1629 // Inits to forbidden characters that are common to (almost) all platforms.
1630 wxString strForbiddenChars = wxT("*?");
1631
1632 // If asserts, wxPathFormat has been changed. In case of a new path format
1633 // addition, the following code might have to be updated.
1634 wxCOMPILE_TIME_ASSERT(wxPATH_MAX == 5, wxPathFormatChanged);
1635 switch ( GetFormat(format) )
1636 {
1637 default :
1638 wxFAIL_MSG( wxT("Unknown path format") );
1639 // !! Fall through !!
1640
1641 case wxPATH_UNIX:
1642 break;
1643
1644 case wxPATH_MAC:
1645 // On a Mac even names with * and ? are allowed (Tested with OS
1646 // 9.2.1 and OS X 10.2.5)
1647 strForbiddenChars = wxEmptyString;
1648 break;
1649
1650 case wxPATH_DOS:
1651 strForbiddenChars += wxT("\\/:\"<>|");
1652 break;
1653
1654 case wxPATH_VMS:
1655 break;
1656 }
1657
1658 return strForbiddenChars;
1659 }
1660
1661 /* static */
1662 wxString wxFileName::GetVolumeSeparator(wxPathFormat WXUNUSED_IN_WINCE(format))
1663 {
1664 #ifdef __WXWINCE__
1665 return wxEmptyString;
1666 #else
1667 wxString sepVol;
1668
1669 if ( (GetFormat(format) == wxPATH_DOS) ||
1670 (GetFormat(format) == wxPATH_VMS) )
1671 {
1672 sepVol = wxFILE_SEP_DSK;
1673 }
1674 //else: leave empty
1675
1676 return sepVol;
1677 #endif
1678 }
1679
1680 /* static */
1681 wxString wxFileName::GetPathSeparators(wxPathFormat format)
1682 {
1683 wxString seps;
1684 switch ( GetFormat(format) )
1685 {
1686 case wxPATH_DOS:
1687 // accept both as native APIs do but put the native one first as
1688 // this is the one we use in GetFullPath()
1689 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
1690 break;
1691
1692 default:
1693 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1694 // fall through
1695
1696 case wxPATH_UNIX:
1697 seps = wxFILE_SEP_PATH_UNIX;
1698 break;
1699
1700 case wxPATH_MAC:
1701 seps = wxFILE_SEP_PATH_MAC;
1702 break;
1703
1704 case wxPATH_VMS:
1705 seps = wxFILE_SEP_PATH_VMS;
1706 break;
1707 }
1708
1709 return seps;
1710 }
1711
1712 /* static */
1713 wxString wxFileName::GetPathTerminators(wxPathFormat format)
1714 {
1715 format = GetFormat(format);
1716
1717 // under VMS the end of the path is ']', not the path separator used to
1718 // separate the components
1719 return format == wxPATH_VMS ? wxString(wxT(']')) : GetPathSeparators(format);
1720 }
1721
1722 /* static */
1723 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
1724 {
1725 // wxString::Find() doesn't work as expected with NUL - it will always find
1726 // it, so test for it separately
1727 return ch != wxT('\0') && GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
1728 }
1729
1730 // ----------------------------------------------------------------------------
1731 // path components manipulation
1732 // ----------------------------------------------------------------------------
1733
1734 /* static */ bool wxFileName::IsValidDirComponent(const wxString& dir)
1735 {
1736 if ( dir.empty() )
1737 {
1738 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1739
1740 return false;
1741 }
1742
1743 const size_t len = dir.length();
1744 for ( size_t n = 0; n < len; n++ )
1745 {
1746 if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
1747 {
1748 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1749
1750 return false;
1751 }
1752 }
1753
1754 return true;
1755 }
1756
1757 void wxFileName::AppendDir( const wxString& dir )
1758 {
1759 if ( IsValidDirComponent(dir) )
1760 m_dirs.Add( dir );
1761 }
1762
1763 void wxFileName::PrependDir( const wxString& dir )
1764 {
1765 InsertDir(0, dir);
1766 }
1767
1768 void wxFileName::InsertDir(size_t before, const wxString& dir)
1769 {
1770 if ( IsValidDirComponent(dir) )
1771 m_dirs.Insert(dir, before);
1772 }
1773
1774 void wxFileName::RemoveDir(size_t pos)
1775 {
1776 m_dirs.RemoveAt(pos);
1777 }
1778
1779 // ----------------------------------------------------------------------------
1780 // accessors
1781 // ----------------------------------------------------------------------------
1782
1783 void wxFileName::SetFullName(const wxString& fullname)
1784 {
1785 SplitPath(fullname, NULL /* no volume */, NULL /* no path */,
1786 &m_name, &m_ext, &m_hasExt);
1787 }
1788
1789 wxString wxFileName::GetFullName() const
1790 {
1791 wxString fullname = m_name;
1792 if ( m_hasExt )
1793 {
1794 fullname << wxFILE_SEP_EXT << m_ext;
1795 }
1796
1797 return fullname;
1798 }
1799
1800 wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
1801 {
1802 format = GetFormat( format );
1803
1804 wxString fullpath;
1805
1806 // return the volume with the path as well if requested
1807 if ( flags & wxPATH_GET_VOLUME )
1808 {
1809 fullpath += wxGetVolumeString(GetVolume(), format);
1810 }
1811
1812 // the leading character
1813 switch ( format )
1814 {
1815 case wxPATH_MAC:
1816 if ( m_relative )
1817 fullpath += wxFILE_SEP_PATH_MAC;
1818 break;
1819
1820 case wxPATH_DOS:
1821 if ( !m_relative )
1822 fullpath += wxFILE_SEP_PATH_DOS;
1823 break;
1824
1825 default:
1826 wxFAIL_MSG( wxT("Unknown path format") );
1827 // fall through
1828
1829 case wxPATH_UNIX:
1830 if ( !m_relative )
1831 {
1832 fullpath += wxFILE_SEP_PATH_UNIX;
1833 }
1834 break;
1835
1836 case wxPATH_VMS:
1837 // no leading character here but use this place to unset
1838 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1839 // as, if I understand correctly, there should never be a dot
1840 // before the closing bracket
1841 flags &= ~wxPATH_GET_SEPARATOR;
1842 }
1843
1844 if ( m_dirs.empty() )
1845 {
1846 // there is nothing more
1847 return fullpath;
1848 }
1849
1850 // then concatenate all the path components using the path separator
1851 if ( format == wxPATH_VMS )
1852 {
1853 fullpath += wxT('[');
1854 }
1855
1856 const size_t dirCount = m_dirs.GetCount();
1857 for ( size_t i = 0; i < dirCount; i++ )
1858 {
1859 switch (format)
1860 {
1861 case wxPATH_MAC:
1862 if ( m_dirs[i] == wxT(".") )
1863 {
1864 // skip appending ':', this shouldn't be done in this
1865 // case as "::" is interpreted as ".." under Unix
1866 continue;
1867 }
1868
1869 // convert back from ".." to nothing
1870 if ( !m_dirs[i].IsSameAs(wxT("..")) )
1871 fullpath += m_dirs[i];
1872 break;
1873
1874 default:
1875 wxFAIL_MSG( wxT("Unexpected path format") );
1876 // still fall through
1877
1878 case wxPATH_DOS:
1879 case wxPATH_UNIX:
1880 fullpath += m_dirs[i];
1881 break;
1882
1883 case wxPATH_VMS:
1884 // TODO: What to do with ".." under VMS
1885
1886 // convert back from ".." to nothing
1887 if ( !m_dirs[i].IsSameAs(wxT("..")) )
1888 fullpath += m_dirs[i];
1889 break;
1890 }
1891
1892 if ( (flags & wxPATH_GET_SEPARATOR) || (i != dirCount - 1) )
1893 fullpath += GetPathSeparator(format);
1894 }
1895
1896 if ( format == wxPATH_VMS )
1897 {
1898 fullpath += wxT(']');
1899 }
1900
1901 return fullpath;
1902 }
1903
1904 wxString wxFileName::GetFullPath( wxPathFormat format ) const
1905 {
1906 // we already have a function to get the path
1907 wxString fullpath = GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR,
1908 format);
1909
1910 // now just add the file name and extension to it
1911 fullpath += GetFullName();
1912
1913 return fullpath;
1914 }
1915
1916 // Return the short form of the path (returns identity on non-Windows platforms)
1917 wxString wxFileName::GetShortPath() const
1918 {
1919 wxString path(GetFullPath());
1920
1921 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1922 DWORD sz = ::GetShortPathName(path.fn_str(), NULL, 0);
1923 if ( sz != 0 )
1924 {
1925 wxString pathOut;
1926 if ( ::GetShortPathName
1927 (
1928 path.fn_str(),
1929 wxStringBuffer(pathOut, sz),
1930 sz
1931 ) != 0 )
1932 {
1933 return pathOut;
1934 }
1935 }
1936 #endif // Windows
1937
1938 return path;
1939 }
1940
1941 // Return the long form of the path (returns identity on non-Windows platforms)
1942 wxString wxFileName::GetLongPath() const
1943 {
1944 wxString pathOut,
1945 path = GetFullPath();
1946
1947 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
1948
1949 #if wxUSE_DYNLIB_CLASS
1950 typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
1951
1952 // this is MT-safe as in the worst case we're going to resolve the function
1953 // twice -- but as the result is the same in both threads, it's ok
1954 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
1955 if ( !s_pfnGetLongPathName )
1956 {
1957 static bool s_triedToLoad = false;
1958
1959 if ( !s_triedToLoad )
1960 {
1961 s_triedToLoad = true;
1962
1963 wxDynamicLibrary dllKernel(wxT("kernel32"));
1964
1965 const wxChar* GetLongPathName = wxT("GetLongPathName")
1966 #if wxUSE_UNICODE
1967 wxT("W");
1968 #else // ANSI
1969 wxT("A");
1970 #endif // Unicode/ANSI
1971
1972 if ( dllKernel.HasSymbol(GetLongPathName) )
1973 {
1974 s_pfnGetLongPathName = (GET_LONG_PATH_NAME)
1975 dllKernel.GetSymbol(GetLongPathName);
1976 }
1977
1978 // note that kernel32.dll can be unloaded, it stays in memory
1979 // anyhow as all Win32 programs link to it and so it's safe to call
1980 // GetLongPathName() even after unloading it
1981 }
1982 }
1983
1984 if ( s_pfnGetLongPathName )
1985 {
1986 DWORD dwSize = (*s_pfnGetLongPathName)(path.fn_str(), NULL, 0);
1987 if ( dwSize > 0 )
1988 {
1989 if ( (*s_pfnGetLongPathName)
1990 (
1991 path.fn_str(),
1992 wxStringBuffer(pathOut, dwSize),
1993 dwSize
1994 ) != 0 )
1995 {
1996 return pathOut;
1997 }
1998 }
1999 }
2000 #endif // wxUSE_DYNLIB_CLASS
2001
2002 // The OS didn't support GetLongPathName, or some other error.
2003 // We need to call FindFirstFile on each component in turn.
2004
2005 WIN32_FIND_DATA findFileData;
2006 HANDLE hFind;
2007
2008 if ( HasVolume() )
2009 pathOut = GetVolume() +
2010 GetVolumeSeparator(wxPATH_DOS) +
2011 GetPathSeparator(wxPATH_DOS);
2012 else
2013 pathOut = wxEmptyString;
2014
2015 wxArrayString dirs = GetDirs();
2016 dirs.Add(GetFullName());
2017
2018 wxString tmpPath;
2019
2020 size_t count = dirs.GetCount();
2021 for ( size_t i = 0; i < count; i++ )
2022 {
2023 const wxString& dir = dirs[i];
2024
2025 // We're using pathOut to collect the long-name path, but using a
2026 // temporary for appending the last path component which may be
2027 // short-name
2028 tmpPath = pathOut + dir;
2029
2030 // We must not process "." or ".." here as they would be (unexpectedly)
2031 // replaced by the corresponding directory names so just leave them
2032 // alone
2033 //
2034 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2035 if ( tmpPath.empty() || dir == '.' || dir == ".." ||
2036 tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
2037 {
2038 tmpPath += wxFILE_SEP_PATH;
2039 pathOut = tmpPath;
2040 continue;
2041 }
2042
2043 hFind = ::FindFirstFile(tmpPath.fn_str(), &findFileData);
2044 if (hFind == INVALID_HANDLE_VALUE)
2045 {
2046 // Error: most likely reason is that path doesn't exist, so
2047 // append any unprocessed parts and return
2048 for ( i += 1; i < count; i++ )
2049 tmpPath += wxFILE_SEP_PATH + dirs[i];
2050
2051 return tmpPath;
2052 }
2053
2054 pathOut += findFileData.cFileName;
2055 if ( (i < (count-1)) )
2056 pathOut += wxFILE_SEP_PATH;
2057
2058 ::FindClose(hFind);
2059 }
2060 #else // !Win32
2061 pathOut = path;
2062 #endif // Win32/!Win32
2063
2064 return pathOut;
2065 }
2066
2067 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
2068 {
2069 if (format == wxPATH_NATIVE)
2070 {
2071 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2072 format = wxPATH_DOS;
2073 #elif defined(__VMS)
2074 format = wxPATH_VMS;
2075 #else
2076 format = wxPATH_UNIX;
2077 #endif
2078 }
2079 return format;
2080 }
2081
2082 #ifdef wxHAS_FILESYSTEM_VOLUMES
2083
2084 /* static */
2085 wxString wxFileName::GetVolumeString(char drive, int flags)
2086 {
2087 wxASSERT_MSG( !(flags & ~wxPATH_GET_SEPARATOR), "invalid flag specified" );
2088
2089 wxString vol(drive);
2090 vol += wxFILE_SEP_DSK;
2091 if ( flags & wxPATH_GET_SEPARATOR )
2092 vol += wxFILE_SEP_PATH;
2093
2094 return vol;
2095 }
2096
2097 #endif // wxHAS_FILESYSTEM_VOLUMES
2098
2099 // ----------------------------------------------------------------------------
2100 // path splitting function
2101 // ----------------------------------------------------------------------------
2102
2103 /* static */
2104 void
2105 wxFileName::SplitVolume(const wxString& fullpathWithVolume,
2106 wxString *pstrVolume,
2107 wxString *pstrPath,
2108 wxPathFormat format)
2109 {
2110 format = GetFormat(format);
2111
2112 wxString fullpath = fullpathWithVolume;
2113
2114 // special Windows UNC paths hack: transform \\share\path into share:path
2115 if ( IsUNCPath(fullpath, format) )
2116 {
2117 fullpath.erase(0, 2);
2118
2119 size_t posFirstSlash =
2120 fullpath.find_first_of(GetPathTerminators(format));
2121 if ( posFirstSlash != wxString::npos )
2122 {
2123 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
2124
2125 // UNC paths are always absolute, right? (FIXME)
2126 fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
2127 }
2128 }
2129
2130 // We separate the volume here
2131 if ( format == wxPATH_DOS || format == wxPATH_VMS )
2132 {
2133 wxString sepVol = GetVolumeSeparator(format);
2134
2135 // we have to exclude the case of a colon in the very beginning of the
2136 // string as it can't be a volume separator (nor can this be a valid
2137 // DOS file name at all but we'll leave dealing with this to our caller)
2138 size_t posFirstColon = fullpath.find_first_of(sepVol);
2139 if ( posFirstColon && posFirstColon != wxString::npos )
2140 {
2141 if ( pstrVolume )
2142 {
2143 *pstrVolume = fullpath.Left(posFirstColon);
2144 }
2145
2146 // remove the volume name and the separator from the full path
2147 fullpath.erase(0, posFirstColon + sepVol.length());
2148 }
2149 }
2150
2151 if ( pstrPath )
2152 *pstrPath = fullpath;
2153 }
2154
2155 /* static */
2156 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
2157 wxString *pstrVolume,
2158 wxString *pstrPath,
2159 wxString *pstrName,
2160 wxString *pstrExt,
2161 bool *hasExt,
2162 wxPathFormat format)
2163 {
2164 format = GetFormat(format);
2165
2166 wxString fullpath;
2167 SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
2168
2169 // find the positions of the last dot and last path separator in the path
2170 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
2171 size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
2172
2173 // check whether this dot occurs at the very beginning of a path component
2174 if ( (posLastDot != wxString::npos) &&
2175 (posLastDot == 0 ||
2176 IsPathSeparator(fullpath[posLastDot - 1]) ||
2177 (format == wxPATH_VMS && fullpath[posLastDot - 1] == wxT(']'))) )
2178 {
2179 // dot may be (and commonly -- at least under Unix -- is) the first
2180 // character of the filename, don't treat the entire filename as
2181 // extension in this case
2182 posLastDot = wxString::npos;
2183 }
2184
2185 // if we do have a dot and a slash, check that the dot is in the name part
2186 if ( (posLastDot != wxString::npos) &&
2187 (posLastSlash != wxString::npos) &&
2188 (posLastDot < posLastSlash) )
2189 {
2190 // the dot is part of the path, not the start of the extension
2191 posLastDot = wxString::npos;
2192 }
2193
2194 // now fill in the variables provided by user
2195 if ( pstrPath )
2196 {
2197 if ( posLastSlash == wxString::npos )
2198 {
2199 // no path at all
2200 pstrPath->Empty();
2201 }
2202 else
2203 {
2204 // take everything up to the path separator but take care to make
2205 // the path equal to something like '/', not empty, for the files
2206 // immediately under root directory
2207 size_t len = posLastSlash;
2208
2209 // this rule does not apply to mac since we do not start with colons (sep)
2210 // except for relative paths
2211 if ( !len && format != wxPATH_MAC)
2212 len++;
2213
2214 *pstrPath = fullpath.Left(len);
2215
2216 // special VMS hack: remove the initial bracket
2217 if ( format == wxPATH_VMS )
2218 {
2219 if ( (*pstrPath)[0u] == wxT('[') )
2220 pstrPath->erase(0, 1);
2221 }
2222 }
2223 }
2224
2225 if ( pstrName )
2226 {
2227 // take all characters starting from the one after the last slash and
2228 // up to, but excluding, the last dot
2229 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
2230 size_t count;
2231 if ( posLastDot == wxString::npos )
2232 {
2233 // take all until the end
2234 count = wxString::npos;
2235 }
2236 else if ( posLastSlash == wxString::npos )
2237 {
2238 count = posLastDot;
2239 }
2240 else // have both dot and slash
2241 {
2242 count = posLastDot - posLastSlash - 1;
2243 }
2244
2245 *pstrName = fullpath.Mid(nStart, count);
2246 }
2247
2248 // finally deal with the extension here: we have an added complication that
2249 // extension may be empty (but present) as in "foo." where trailing dot
2250 // indicates the empty extension at the end -- and hence we must remember
2251 // that we have it independently of pstrExt
2252 if ( posLastDot == wxString::npos )
2253 {
2254 // no extension
2255 if ( pstrExt )
2256 pstrExt->clear();
2257 if ( hasExt )
2258 *hasExt = false;
2259 }
2260 else
2261 {
2262 // take everything after the dot
2263 if ( pstrExt )
2264 *pstrExt = fullpath.Mid(posLastDot + 1);
2265 if ( hasExt )
2266 *hasExt = true;
2267 }
2268 }
2269
2270 /* static */
2271 void wxFileName::SplitPath(const wxString& fullpath,
2272 wxString *path,
2273 wxString *name,
2274 wxString *ext,
2275 wxPathFormat format)
2276 {
2277 wxString volume;
2278 SplitPath(fullpath, &volume, path, name, ext, format);
2279
2280 if ( path )
2281 {
2282 path->Prepend(wxGetVolumeString(volume, format));
2283 }
2284 }
2285
2286 /* static */
2287 wxString wxFileName::StripExtension(const wxString& fullpath)
2288 {
2289 wxFileName fn(fullpath);
2290 fn.SetExt("");
2291 return fn.GetFullPath();
2292 }
2293
2294 // ----------------------------------------------------------------------------
2295 // time functions
2296 // ----------------------------------------------------------------------------
2297
2298 #if wxUSE_DATETIME
2299
2300 bool wxFileName::SetTimes(const wxDateTime *dtAccess,
2301 const wxDateTime *dtMod,
2302 const wxDateTime *dtCreate) const
2303 {
2304 #if defined(__WIN32__)
2305 FILETIME ftAccess, ftCreate, ftWrite;
2306
2307 if ( dtCreate )
2308 ConvertWxToFileTime(&ftCreate, *dtCreate);
2309 if ( dtAccess )
2310 ConvertWxToFileTime(&ftAccess, *dtAccess);
2311 if ( dtMod )
2312 ConvertWxToFileTime(&ftWrite, *dtMod);
2313
2314 wxString path;
2315 int flags;
2316 if ( IsDir() )
2317 {
2318 if ( wxGetOsVersion() == wxOS_WINDOWS_9X )
2319 {
2320 wxLogError(_("Setting directory access times is not supported "
2321 "under this OS version"));
2322 return false;
2323 }
2324
2325 path = GetPath();
2326 flags = FILE_FLAG_BACKUP_SEMANTICS;
2327 }
2328 else // file
2329 {
2330 path = GetFullPath();
2331 flags = 0;
2332 }
2333
2334 wxFileHandle fh(path, wxFileHandle::Write, flags);
2335 if ( fh.IsOk() )
2336 {
2337 if ( ::SetFileTime(fh,
2338 dtCreate ? &ftCreate : NULL,
2339 dtAccess ? &ftAccess : NULL,
2340 dtMod ? &ftWrite : NULL) )
2341 {
2342 return true;
2343 }
2344 }
2345 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2346 wxUnusedVar(dtCreate);
2347
2348 if ( !dtAccess && !dtMod )
2349 {
2350 // can't modify the creation time anyhow, don't try
2351 return true;
2352 }
2353
2354 // if dtAccess or dtMod is not specified, use the other one (which must be
2355 // non NULL because of the test above) for both times
2356 utimbuf utm;
2357 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
2358 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
2359 if ( utime(GetFullPath().fn_str(), &utm) == 0 )
2360 {
2361 return true;
2362 }
2363 #else // other platform
2364 wxUnusedVar(dtAccess);
2365 wxUnusedVar(dtMod);
2366 wxUnusedVar(dtCreate);
2367 #endif // platforms
2368
2369 wxLogSysError(_("Failed to modify file times for '%s'"),
2370 GetFullPath().c_str());
2371
2372 return false;
2373 }
2374
2375 bool wxFileName::Touch() const
2376 {
2377 #if defined(__UNIX_LIKE__)
2378 // under Unix touching file is simple: just pass NULL to utime()
2379 if ( utime(GetFullPath().fn_str(), NULL) == 0 )
2380 {
2381 return true;
2382 }
2383
2384 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2385
2386 return false;
2387 #else // other platform
2388 wxDateTime dtNow = wxDateTime::Now();
2389
2390 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
2391 #endif // platforms
2392 }
2393
2394 bool wxFileName::GetTimes(wxDateTime *dtAccess,
2395 wxDateTime *dtMod,
2396 wxDateTime *dtCreate) const
2397 {
2398 #if defined(__WIN32__)
2399 // we must use different methods for the files and directories under
2400 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2401 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2402 // not 9x
2403 bool ok;
2404 FILETIME ftAccess, ftCreate, ftWrite;
2405 if ( IsDir() )
2406 {
2407 // implemented in msw/dir.cpp
2408 extern bool wxGetDirectoryTimes(const wxString& dirname,
2409 FILETIME *, FILETIME *, FILETIME *);
2410
2411 // we should pass the path without the trailing separator to
2412 // wxGetDirectoryTimes()
2413 ok = wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME),
2414 &ftAccess, &ftCreate, &ftWrite);
2415 }
2416 else // file
2417 {
2418 wxFileHandle fh(GetFullPath(), wxFileHandle::Read);
2419 if ( fh.IsOk() )
2420 {
2421 ok = ::GetFileTime(fh,
2422 dtCreate ? &ftCreate : NULL,
2423 dtAccess ? &ftAccess : NULL,
2424 dtMod ? &ftWrite : NULL) != 0;
2425 }
2426 else
2427 {
2428 ok = false;
2429 }
2430 }
2431
2432 if ( ok )
2433 {
2434 if ( dtCreate )
2435 ConvertFileTimeToWx(dtCreate, ftCreate);
2436 if ( dtAccess )
2437 ConvertFileTimeToWx(dtAccess, ftAccess);
2438 if ( dtMod )
2439 ConvertFileTimeToWx(dtMod, ftWrite);
2440
2441 return true;
2442 }
2443 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2444 // no need to test for IsDir() here
2445 wxStructStat stBuf;
2446 if ( wxStat( GetFullPath().c_str(), &stBuf) == 0 )
2447 {
2448 if ( dtAccess )
2449 dtAccess->Set(stBuf.st_atime);
2450 if ( dtMod )
2451 dtMod->Set(stBuf.st_mtime);
2452 if ( dtCreate )
2453 dtCreate->Set(stBuf.st_ctime);
2454
2455 return true;
2456 }
2457 #else // other platform
2458 wxUnusedVar(dtAccess);
2459 wxUnusedVar(dtMod);
2460 wxUnusedVar(dtCreate);
2461 #endif // platforms
2462
2463 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2464 GetFullPath().c_str());
2465
2466 return false;
2467 }
2468
2469 #endif // wxUSE_DATETIME
2470
2471
2472 // ----------------------------------------------------------------------------
2473 // file size functions
2474 // ----------------------------------------------------------------------------
2475
2476 #if wxUSE_LONGLONG
2477
2478 /* static */
2479 wxULongLong wxFileName::GetSize(const wxString &filename)
2480 {
2481 if (!wxFileExists(filename))
2482 return wxInvalidSize;
2483
2484 #if defined(__WXPALMOS__)
2485 // TODO
2486 return wxInvalidSize;
2487 #elif defined(__WIN32__)
2488 wxFileHandle f(filename, wxFileHandle::Read);
2489 if (!f.IsOk())
2490 return wxInvalidSize;
2491
2492 DWORD lpFileSizeHigh;
2493 DWORD ret = GetFileSize(f, &lpFileSizeHigh);
2494 if ( ret == INVALID_FILE_SIZE && ::GetLastError() != NO_ERROR )
2495 return wxInvalidSize;
2496
2497 return wxULongLong(lpFileSizeHigh, ret);
2498 #else // ! __WIN32__
2499 wxStructStat st;
2500 #ifndef wxNEED_WX_UNISTD_H
2501 if (wxStat( filename.fn_str() , &st) != 0)
2502 #else
2503 if (wxStat( filename, &st) != 0)
2504 #endif
2505 return wxInvalidSize;
2506 return wxULongLong(st.st_size);
2507 #endif
2508 }
2509
2510 /* static */
2511 wxString wxFileName::GetHumanReadableSize(const wxULongLong &bs,
2512 const wxString &nullsize,
2513 int precision)
2514 {
2515 static const double KILOBYTESIZE = 1024.0;
2516 static const double MEGABYTESIZE = 1024.0*KILOBYTESIZE;
2517 static const double GIGABYTESIZE = 1024.0*MEGABYTESIZE;
2518 static const double TERABYTESIZE = 1024.0*GIGABYTESIZE;
2519
2520 if (bs == 0 || bs == wxInvalidSize)
2521 return nullsize;
2522
2523 double bytesize = bs.ToDouble();
2524 if (bytesize < KILOBYTESIZE)
2525 return wxString::Format(_("%s B"), bs.ToString().c_str());
2526 if (bytesize < MEGABYTESIZE)
2527 return wxString::Format(_("%.*f kB"), precision, bytesize/KILOBYTESIZE);
2528 if (bytesize < GIGABYTESIZE)
2529 return wxString::Format(_("%.*f MB"), precision, bytesize/MEGABYTESIZE);
2530 if (bytesize < TERABYTESIZE)
2531 return wxString::Format(_("%.*f GB"), precision, bytesize/GIGABYTESIZE);
2532
2533 return wxString::Format(_("%.*f TB"), precision, bytesize/TERABYTESIZE);
2534 }
2535
2536 wxULongLong wxFileName::GetSize() const
2537 {
2538 return GetSize(GetFullPath());
2539 }
2540
2541 wxString wxFileName::GetHumanReadableSize(const wxString &failmsg, int precision) const
2542 {
2543 return GetHumanReadableSize(GetSize(), failmsg, precision);
2544 }
2545
2546 #endif // wxUSE_LONGLONG
2547
2548 // ----------------------------------------------------------------------------
2549 // Mac-specific functions
2550 // ----------------------------------------------------------------------------
2551
2552 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2553
2554 namespace
2555 {
2556
2557 class MacDefaultExtensionRecord
2558 {
2559 public:
2560 MacDefaultExtensionRecord()
2561 {
2562 m_type =
2563 m_creator = 0 ;
2564 }
2565
2566 // default copy ctor, assignment operator and dtor are ok
2567
2568 MacDefaultExtensionRecord(const wxString& ext, OSType type, OSType creator)
2569 : m_ext(ext)
2570 {
2571 m_type = type;
2572 m_creator = creator;
2573 }
2574
2575 wxString m_ext;
2576 OSType m_type;
2577 OSType m_creator;
2578 };
2579
2580 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray);
2581
2582 bool gMacDefaultExtensionsInited = false;
2583
2584 #include "wx/arrimpl.cpp"
2585
2586 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray);
2587
2588 MacDefaultExtensionArray gMacDefaultExtensions;
2589
2590 // load the default extensions
2591 const MacDefaultExtensionRecord gDefaults[] =
2592 {
2593 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2594 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2595 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2596 };
2597
2598 void MacEnsureDefaultExtensionsLoaded()
2599 {
2600 if ( !gMacDefaultExtensionsInited )
2601 {
2602 // we could load the pc exchange prefs here too
2603 for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
2604 {
2605 gMacDefaultExtensions.Add( gDefaults[i] ) ;
2606 }
2607 gMacDefaultExtensionsInited = true;
2608 }
2609 }
2610
2611 } // anonymous namespace
2612
2613 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
2614 {
2615 FSRef fsRef ;
2616 FSCatalogInfo catInfo;
2617 FileInfo *finfo ;
2618
2619 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2620 {
2621 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2622 {
2623 finfo = (FileInfo*)&catInfo.finderInfo;
2624 finfo->fileType = type ;
2625 finfo->fileCreator = creator ;
2626 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
2627 return true ;
2628 }
2629 }
2630 return false ;
2631 }
2632
2633 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator ) const
2634 {
2635 FSRef fsRef ;
2636 FSCatalogInfo catInfo;
2637 FileInfo *finfo ;
2638
2639 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2640 {
2641 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2642 {
2643 finfo = (FileInfo*)&catInfo.finderInfo;
2644 *type = finfo->fileType ;
2645 *creator = finfo->fileCreator ;
2646 return true ;
2647 }
2648 }
2649 return false ;
2650 }
2651
2652 bool wxFileName::MacSetDefaultTypeAndCreator()
2653 {
2654 wxUint32 type , creator ;
2655 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
2656 &creator ) )
2657 {
2658 return MacSetTypeAndCreator( type , creator ) ;
2659 }
2660 return false;
2661 }
2662
2663 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
2664 {
2665 MacEnsureDefaultExtensionsLoaded() ;
2666 wxString extl = ext.Lower() ;
2667 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
2668 {
2669 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
2670 {
2671 *type = gMacDefaultExtensions.Item(i).m_type ;
2672 *creator = gMacDefaultExtensions.Item(i).m_creator ;
2673 return true ;
2674 }
2675 }
2676 return false ;
2677 }
2678
2679 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
2680 {
2681 MacEnsureDefaultExtensionsLoaded();
2682 MacDefaultExtensionRecord rec(ext.Lower(), type, creator);
2683 gMacDefaultExtensions.Add( rec );
2684 }
2685
2686 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON