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