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