]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
oops, forgot to implement Home button
[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" // see GetLongPath below, code disabled.
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 // VZ: why was this code disabled?
1345 #if 0 // wxUSE_DYNAMIC_LOADER
1346 typedef DWORD (*GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
1347
1348 static bool s_triedToLoad = FALSE;
1349
1350 if ( !s_triedToLoad )
1351 {
1352 s_triedToLoad = TRUE;
1353 wxDynamicLibrary dllKernel(_T("kernel32"));
1354 if ( dllKernel.IsLoaded() )
1355 {
1356 // may succeed or fail depending on the Windows version
1357 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
1358 #ifdef _UNICODE
1359 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameW"));
1360 #else
1361 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) dllKernel.GetSymbol(_T("GetLongPathNameA"));
1362 #endif
1363
1364 if ( s_pfnGetLongPathName )
1365 {
1366 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
1367 bool ok = dwSize > 0;
1368
1369 if ( ok )
1370 {
1371 DWORD sz = (*s_pfnGetLongPathName)(path, NULL, 0);
1372 ok = sz != 0;
1373 if ( ok )
1374 {
1375 ok = (*s_pfnGetLongPathName)
1376 (
1377 path,
1378 pathOut.GetWriteBuf(sz),
1379 sz
1380 ) != 0;
1381 pathOut.UngetWriteBuf();
1382
1383 success = TRUE;
1384 }
1385 }
1386 }
1387 }
1388 }
1389 if (success)
1390 return pathOut;
1391 #endif // wxUSE_DYNAMIC_LOADER
1392
1393 if (!success)
1394 {
1395 // The OS didn't support GetLongPathName, or some other error.
1396 // We need to call FindFirstFile on each component in turn.
1397
1398 WIN32_FIND_DATA findFileData;
1399 HANDLE hFind;
1400 pathOut = wxEmptyString;
1401
1402 wxArrayString dirs = GetDirs();
1403 dirs.Add(GetFullName());
1404
1405 wxString tmpPath;
1406
1407 size_t count = dirs.GetCount();
1408 for ( size_t i = 0; i < count; i++ )
1409 {
1410 // We're using pathOut to collect the long-name path, but using a
1411 // temporary for appending the last path component which may be
1412 // short-name
1413 tmpPath = pathOut + dirs[i];
1414
1415 if ( tmpPath.empty() )
1416 continue;
1417
1418 if ( tmpPath.Last() == wxT(':') )
1419 {
1420 // Can't pass a drive and root dir to FindFirstFile,
1421 // so continue to next dir
1422 tmpPath += wxFILE_SEP_PATH;
1423 pathOut = tmpPath;
1424 continue;
1425 }
1426
1427 hFind = ::FindFirstFile(tmpPath, &findFileData);
1428 if (hFind == INVALID_HANDLE_VALUE)
1429 {
1430 // Error: return immediately with the original path
1431 return path;
1432 }
1433
1434 pathOut += findFileData.cFileName;
1435 if ( (i < (count-1)) )
1436 pathOut += wxFILE_SEP_PATH;
1437
1438 ::FindClose(hFind);
1439 }
1440 }
1441 #else // !Win32
1442 pathOut = path;
1443 #endif // Win32/!Win32
1444
1445 return pathOut;
1446 }
1447
1448 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
1449 {
1450 if (format == wxPATH_NATIVE)
1451 {
1452 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__DOS__)
1453 format = wxPATH_DOS;
1454 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1455 format = wxPATH_MAC;
1456 #elif defined(__VMS)
1457 format = wxPATH_VMS;
1458 #else
1459 format = wxPATH_UNIX;
1460 #endif
1461 }
1462 return format;
1463 }
1464
1465 // ----------------------------------------------------------------------------
1466 // path splitting function
1467 // ----------------------------------------------------------------------------
1468
1469 /* static */
1470 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
1471 wxString *pstrVolume,
1472 wxString *pstrPath,
1473 wxString *pstrName,
1474 wxString *pstrExt,
1475 wxPathFormat format)
1476 {
1477 format = GetFormat(format);
1478
1479 wxString fullpath = fullpathWithVolume;
1480
1481 // under VMS the end of the path is ']', not the path separator used to
1482 // separate the components
1483 wxString sepPath = format == wxPATH_VMS ? wxString(_T(']'))
1484 : GetPathSeparators(format);
1485
1486 // special Windows UNC paths hack: transform \\share\path into share:path
1487 if ( format == wxPATH_DOS )
1488 {
1489 if ( fullpath.length() >= 4 &&
1490 fullpath[0u] == wxFILE_SEP_PATH_DOS &&
1491 fullpath[1u] == wxFILE_SEP_PATH_DOS )
1492 {
1493 fullpath.erase(0, 2);
1494
1495 size_t posFirstSlash = fullpath.find_first_of(sepPath);
1496 if ( posFirstSlash != wxString::npos )
1497 {
1498 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
1499
1500 // UNC paths are always absolute, right? (FIXME)
1501 fullpath.insert(posFirstSlash + 1, wxFILE_SEP_PATH_DOS);
1502 }
1503 }
1504 }
1505
1506 // We separate the volume here
1507 if ( format == wxPATH_DOS || format == wxPATH_VMS )
1508 {
1509 wxString sepVol = GetVolumeSeparator(format);
1510
1511 size_t posFirstColon = fullpath.find_first_of(sepVol);
1512 if ( posFirstColon != wxString::npos )
1513 {
1514 if ( pstrVolume )
1515 {
1516 *pstrVolume = fullpath.Left(posFirstColon);
1517 }
1518
1519 // remove the volume name and the separator from the full path
1520 fullpath.erase(0, posFirstColon + sepVol.length());
1521 }
1522 }
1523
1524 // find the positions of the last dot and last path separator in the path
1525 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
1526 size_t posLastSlash = fullpath.find_last_of(sepPath);
1527
1528 if ( (posLastDot != wxString::npos) &&
1529 ((format == wxPATH_UNIX) || (format == wxPATH_VMS)) )
1530 {
1531 if ( (posLastDot == 0) ||
1532 (fullpath[posLastDot - 1] == sepPath[0u] ) )
1533 {
1534 // under Unix and VMS, dot may be (and commonly is) the first
1535 // character of the filename, don't treat the entire filename as
1536 // extension in this case
1537 posLastDot = wxString::npos;
1538 }
1539 }
1540
1541 // if we do have a dot and a slash, check that the dot is in the name part
1542 if ( (posLastDot != wxString::npos) &&
1543 (posLastSlash != wxString::npos) &&
1544 (posLastDot < posLastSlash) )
1545 {
1546 // the dot is part of the path, not the start of the extension
1547 posLastDot = wxString::npos;
1548 }
1549
1550 // now fill in the variables provided by user
1551 if ( pstrPath )
1552 {
1553 if ( posLastSlash == wxString::npos )
1554 {
1555 // no path at all
1556 pstrPath->Empty();
1557 }
1558 else
1559 {
1560 // take everything up to the path separator but take care to make
1561 // the path equal to something like '/', not empty, for the files
1562 // immediately under root directory
1563 size_t len = posLastSlash;
1564
1565 // this rule does not apply to mac since we do not start with colons (sep)
1566 // except for relative paths
1567 if ( !len && format != wxPATH_MAC)
1568 len++;
1569
1570 *pstrPath = fullpath.Left(len);
1571
1572 // special VMS hack: remove the initial bracket
1573 if ( format == wxPATH_VMS )
1574 {
1575 if ( (*pstrPath)[0u] == _T('[') )
1576 pstrPath->erase(0, 1);
1577 }
1578 }
1579 }
1580
1581 if ( pstrName )
1582 {
1583 // take all characters starting from the one after the last slash and
1584 // up to, but excluding, the last dot
1585 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
1586 size_t count;
1587 if ( posLastDot == wxString::npos )
1588 {
1589 // take all until the end
1590 count = wxString::npos;
1591 }
1592 else if ( posLastSlash == wxString::npos )
1593 {
1594 count = posLastDot;
1595 }
1596 else // have both dot and slash
1597 {
1598 count = posLastDot - posLastSlash - 1;
1599 }
1600
1601 *pstrName = fullpath.Mid(nStart, count);
1602 }
1603
1604 if ( pstrExt )
1605 {
1606 if ( posLastDot == wxString::npos )
1607 {
1608 // no extension
1609 pstrExt->Empty();
1610 }
1611 else
1612 {
1613 // take everything after the dot
1614 *pstrExt = fullpath.Mid(posLastDot + 1);
1615 }
1616 }
1617 }
1618
1619 /* static */
1620 void wxFileName::SplitPath(const wxString& fullpath,
1621 wxString *path,
1622 wxString *name,
1623 wxString *ext,
1624 wxPathFormat format)
1625 {
1626 wxString volume;
1627 SplitPath(fullpath, &volume, path, name, ext, format);
1628
1629 if ( path )
1630 {
1631 path->Prepend(wxGetVolumeString(volume, format));
1632 }
1633 }
1634
1635 // ----------------------------------------------------------------------------
1636 // time functions
1637 // ----------------------------------------------------------------------------
1638
1639 bool wxFileName::SetTimes(const wxDateTime *dtAccess,
1640 const wxDateTime *dtMod,
1641 const wxDateTime *dtCreate)
1642 {
1643 #if defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1644 if ( !dtAccess && !dtMod )
1645 {
1646 // can't modify the creation time anyhow, don't try
1647 return TRUE;
1648 }
1649
1650 // if dtAccess or dtMod is not specified, use the other one (which must be
1651 // non NULL because of the test above) for both times
1652 utimbuf utm;
1653 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
1654 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
1655 if ( utime(GetFullPath(), &utm) == 0 )
1656 {
1657 return TRUE;
1658 }
1659 #elif defined(__WIN32__)
1660 wxFileHandle fh(GetFullPath(), wxFileHandle::Write);
1661 if ( fh.IsOk() )
1662 {
1663 FILETIME ftAccess, ftCreate, ftWrite;
1664
1665 if ( dtCreate )
1666 ConvertWxToFileTime(&ftCreate, *dtCreate);
1667 if ( dtAccess )
1668 ConvertWxToFileTime(&ftAccess, *dtAccess);
1669 if ( dtMod )
1670 ConvertWxToFileTime(&ftWrite, *dtMod);
1671
1672 if ( ::SetFileTime(fh,
1673 dtCreate ? &ftCreate : NULL,
1674 dtAccess ? &ftAccess : NULL,
1675 dtMod ? &ftWrite : NULL) )
1676 {
1677 return TRUE;
1678 }
1679 }
1680 #else // other platform
1681 #endif // platforms
1682
1683 wxLogSysError(_("Failed to modify file times for '%s'"),
1684 GetFullPath().c_str());
1685
1686 return FALSE;
1687 }
1688
1689 bool wxFileName::Touch()
1690 {
1691 #if defined(__UNIX_LIKE__)
1692 // under Unix touching file is simple: just pass NULL to utime()
1693 if ( utime(GetFullPath(), NULL) == 0 )
1694 {
1695 return TRUE;
1696 }
1697
1698 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1699
1700 return FALSE;
1701 #else // other platform
1702 wxDateTime dtNow = wxDateTime::Now();
1703
1704 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
1705 #endif // platforms
1706 }
1707
1708 bool wxFileName::GetTimes(wxDateTime *dtAccess,
1709 wxDateTime *dtMod,
1710 wxDateTime *dtCreate) const
1711 {
1712 #if defined(__UNIX_LIKE__) || defined(__WXMAC__) || (defined(__DOS__) && defined(__WATCOMC__))
1713 wxStructStat stBuf;
1714 if ( wxStat(GetFullPath(), &stBuf) == 0 )
1715 {
1716 if ( dtAccess )
1717 dtAccess->Set(stBuf.st_atime);
1718 if ( dtMod )
1719 dtMod->Set(stBuf.st_mtime);
1720 if ( dtCreate )
1721 dtCreate->Set(stBuf.st_ctime);
1722
1723 return TRUE;
1724 }
1725 #elif defined(__WIN32__)
1726 wxFileHandle fh(GetFullPath(), wxFileHandle::Read);
1727 if ( fh.IsOk() )
1728 {
1729 FILETIME ftAccess, ftCreate, ftWrite;
1730
1731 if ( ::GetFileTime(fh,
1732 dtMod ? &ftCreate : NULL,
1733 dtAccess ? &ftAccess : NULL,
1734 dtCreate ? &ftWrite : NULL) )
1735 {
1736 if ( dtMod )
1737 ConvertFileTimeToWx(dtMod, ftCreate);
1738 if ( dtAccess )
1739 ConvertFileTimeToWx(dtAccess, ftAccess);
1740 if ( dtCreate )
1741 ConvertFileTimeToWx(dtCreate, ftWrite);
1742
1743 return TRUE;
1744 }
1745 }
1746 #else // other platform
1747 #endif // platforms
1748
1749 wxLogSysError(_("Failed to retrieve file times for '%s'"),
1750 GetFullPath().c_str());
1751
1752 return FALSE;
1753 }
1754
1755 #ifdef __WXMAC__
1756
1757 const short kMacExtensionMaxLength = 16 ;
1758 typedef struct
1759 {
1760 char m_ext[kMacExtensionMaxLength] ;
1761 OSType m_type ;
1762 OSType m_creator ;
1763 } MacDefaultExtensionRecord ;
1764
1765 #include "wx/dynarray.h"
1766 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ;
1767 #include "wx/arrimpl.cpp"
1768 WX_DEFINE_OBJARRAY(MacDefaultExtensionArray) ;
1769
1770 MacDefaultExtensionArray gMacDefaultExtensions ;
1771 bool gMacDefaultExtensionsInited = false ;
1772
1773 static void MacEnsureDefaultExtensionsLoaded()
1774 {
1775 if ( !gMacDefaultExtensionsInited )
1776 {
1777 // load the default extensions
1778 MacDefaultExtensionRecord defaults[] =
1779 {
1780 { "txt" , 'TEXT' , 'ttxt' } ,
1781
1782 } ;
1783 // we could load the pc exchange prefs here too
1784
1785 for ( int i = 0 ; i < WXSIZEOF( defaults ) ; ++i )
1786 {
1787 gMacDefaultExtensions.Add( defaults[i] ) ;
1788 }
1789 gMacDefaultExtensionsInited = true ;
1790 }
1791 }
1792 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
1793 {
1794 FInfo fndrInfo ;
1795 FSSpec spec ;
1796 wxMacFilename2FSSpec(GetFullPath(),&spec) ;
1797 OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
1798 wxCHECK( err == noErr , false ) ;
1799
1800 fndrInfo.fdType = type ;
1801 fndrInfo.fdCreator = creator ;
1802 FSpSetFInfo( &spec , &fndrInfo ) ;
1803 return true ;
1804 }
1805
1806 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
1807 {
1808 FInfo fndrInfo ;
1809 FSSpec spec ;
1810 wxMacFilename2FSSpec(GetFullPath(),&spec) ;
1811 OSErr err = FSpGetFInfo( &spec , &fndrInfo ) ;
1812 wxCHECK( err == noErr , false ) ;
1813
1814 *type = fndrInfo.fdType ;
1815 *creator = fndrInfo.fdCreator ;
1816 return true ;
1817 }
1818
1819 bool wxFileName::MacSetDefaultTypeAndCreator()
1820 {
1821 wxUint32 type , creator ;
1822 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
1823 &creator ) )
1824 {
1825 return MacSetTypeAndCreator( type , creator ) ;
1826 }
1827 return false;
1828 }
1829
1830 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
1831 {
1832 MacEnsureDefaultExtensionsLoaded() ;
1833 wxString extl = ext.Lower() ;
1834 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
1835 {
1836 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
1837 {
1838 *type = gMacDefaultExtensions.Item(i).m_type ;
1839 *creator = gMacDefaultExtensions.Item(i).m_creator ;
1840 return true ;
1841 }
1842 }
1843 return false ;
1844 }
1845
1846 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
1847 {
1848 MacEnsureDefaultExtensionsLoaded() ;
1849 MacDefaultExtensionRecord rec ;
1850 rec.m_type = type ;
1851 rec.m_creator = creator ;
1852 strncpy( rec.m_ext , ext.Lower().c_str() , kMacExtensionMaxLength ) ;
1853 gMacDefaultExtensions.Add( rec ) ;
1854 }
1855 #endif