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