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