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