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