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