]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
implement wxFileModificationTime() in terms of wxFileName::GetTimes() (replaces broke...
[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 specification
51 . separator between directory and subdirectory
52 ] between directory and file
53 */
54
55 // ============================================================================
56 // declarations
57 // ============================================================================
58
59 // ----------------------------------------------------------------------------
60 // headers
61 // ----------------------------------------------------------------------------
62
63 // For compilers that support precompilation, includes "wx.h".
64 #include "wx/wxprec.h"
65
66 #ifdef __BORLANDC__
67 #pragma hdrstop
68 #endif
69
70 #ifndef WX_PRECOMP
71 #include "wx/intl.h"
72 #include "wx/log.h"
73 #include "wx/file.h"
74 #endif
75
76 #include "wx/filename.h"
77 #include "wx/tokenzr.h"
78 #include "wx/config.h" // for wxExpandEnvVars
79 #include "wx/utils.h"
80 #include "wx/file.h"
81 #include "wx/dynlib.h"
82
83 // For GetShort/LongPathName
84 #ifdef __WIN32__
85 #include "wx/msw/wrapwin.h"
86 #if defined(__MINGW32__)
87 #include "wx/msw/gccpriv.h"
88 #endif
89 #endif
90
91 #ifdef __WXWINCE__
92 #include "wx/msw/private.h"
93 #endif
94
95 #if defined(__WXMAC__)
96 #include "wx/mac/private.h" // includes mac headers
97 #endif
98
99 // utime() is POSIX so should normally be available on all Unices
100 #ifdef __UNIX_LIKE__
101 #include <sys/types.h>
102 #include <utime.h>
103 #include <sys/stat.h>
104 #include <unistd.h>
105 #endif
106
107 #ifdef __DJGPP__
108 #include <unistd.h>
109 #endif
110
111 #ifdef __MWERKS__
112 #ifdef __MACH__
113 #include <sys/types.h>
114 #include <utime.h>
115 #include <sys/stat.h>
116 #include <unistd.h>
117 #else
118 #include <stat.h>
119 #include <unistd.h>
120 #include <unix.h>
121 #endif
122 #endif
123
124 #ifdef __WATCOMC__
125 #include <io.h>
126 #include <sys/utime.h>
127 #include <sys/stat.h>
128 #endif
129
130 #ifdef __VISAGECPP__
131 #ifndef MAX_PATH
132 #define MAX_PATH 256
133 #endif
134 #endif
135
136 #ifdef __EMX__
137 #include <os2.h>
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 FILE_SHARE_READ | // sharing mode
166 FILE_SHARE_WRITE, // (allow everything)
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 = (WORD)(dt.GetMonth() + 1);
237 st.wYear = (WORD)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 m_hasExt = filepath.m_hasExt;
300 }
301
302 void wxFileName::Assign(const wxString& volume,
303 const wxString& path,
304 const wxString& name,
305 const wxString& ext,
306 bool hasExt,
307 wxPathFormat format )
308 {
309 SetPath( path, format );
310
311 m_volume = volume;
312 m_ext = ext;
313 m_name = name;
314
315 m_hasExt = hasExt;
316 }
317
318 void wxFileName::SetPath( const wxString& pathOrig, wxPathFormat format )
319 {
320 m_dirs.Clear();
321
322 if ( pathOrig.empty() )
323 {
324 // no path at all
325 m_relative = true;
326
327 return;
328 }
329
330 format = GetFormat( format );
331
332 // 0) deal with possible volume part first
333 wxString volume,
334 path;
335 SplitVolume(pathOrig, &volume, &path, format);
336 if ( !volume.empty() )
337 {
338 m_relative = false;
339
340 SetVolume(volume);
341 }
342
343 // 1) Determine if the path is relative or absolute.
344 wxChar leadingChar = path[0u];
345
346 switch (format)
347 {
348 case wxPATH_MAC:
349 m_relative = leadingChar == wxT(':');
350
351 // We then remove a leading ":". The reason is in our
352 // storage form for relative paths:
353 // ":dir:file.txt" actually means "./dir/file.txt" in
354 // DOS notation and should get stored as
355 // (relative) (dir) (file.txt)
356 // "::dir:file.txt" actually means "../dir/file.txt"
357 // stored as (relative) (..) (dir) (file.txt)
358 // This is important only for the Mac as an empty dir
359 // actually means <UP>, whereas under DOS, double
360 // slashes can be ignored: "\\\\" is the same as "\\".
361 if (m_relative)
362 path.erase( 0, 1 );
363 break;
364
365 case wxPATH_VMS:
366 // TODO: what is the relative path format here?
367 m_relative = false;
368 break;
369
370 default:
371 wxFAIL_MSG( _T("Unknown path format") );
372 // !! Fall through !!
373
374 case wxPATH_UNIX:
375 // the paths of the form "~" or "~username" are absolute
376 m_relative = leadingChar != wxT('/') && leadingChar != _T('~');
377 break;
378
379 case wxPATH_DOS:
380 m_relative = !IsPathSeparator(leadingChar, format);
381 break;
382
383 }
384
385 // 2) Break up the path into its members. If the original path
386 // was just "/" or "\\", m_dirs will be empty. We know from
387 // the m_relative field, if this means "nothing" or "root dir".
388
389 wxStringTokenizer tn( path, GetPathSeparators(format) );
390
391 while ( tn.HasMoreTokens() )
392 {
393 wxString token = tn.GetNextToken();
394
395 // Remove empty token under DOS and Unix, interpret them
396 // as .. under Mac.
397 if (token.empty())
398 {
399 if (format == wxPATH_MAC)
400 m_dirs.Add( wxT("..") );
401 // else ignore
402 }
403 else
404 {
405 m_dirs.Add( token );
406 }
407 }
408 }
409
410 void wxFileName::Assign(const wxString& fullpath,
411 wxPathFormat format)
412 {
413 wxString volume, path, name, ext;
414 bool hasExt;
415 SplitPath(fullpath, &volume, &path, &name, &ext, &hasExt, format);
416
417 Assign(volume, path, name, ext, hasExt, format);
418 }
419
420 void wxFileName::Assign(const wxString& fullpathOrig,
421 const wxString& fullname,
422 wxPathFormat format)
423 {
424 // always recognize fullpath as directory, even if it doesn't end with a
425 // slash
426 wxString fullpath = fullpathOrig;
427 if ( !wxEndsWithPathSeparator(fullpath) )
428 {
429 fullpath += GetPathSeparator(format);
430 }
431
432 wxString volume, path, name, ext;
433 bool hasExt;
434
435 // do some consistency checks in debug mode: the name should be really just
436 // the filename and the path should be really just a path
437 #ifdef __WXDEBUG__
438 wxString volDummy, pathDummy, nameDummy, extDummy;
439
440 SplitPath(fullname, &volDummy, &pathDummy, &name, &ext, &hasExt, format);
441
442 wxASSERT_MSG( volDummy.empty() && pathDummy.empty(),
443 _T("the file name shouldn't contain the path") );
444
445 SplitPath(fullpath, &volume, &path, &nameDummy, &extDummy, format);
446
447 wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
448 _T("the path shouldn't contain file name nor extension") );
449
450 #else // !__WXDEBUG__
451 SplitPath(fullname, NULL /* no volume */, NULL /* no path */,
452 &name, &ext, &hasExt, format);
453 SplitPath(fullpath, &volume, &path, NULL, NULL, format);
454 #endif // __WXDEBUG__/!__WXDEBUG__
455
456 Assign(volume, path, name, ext, hasExt, format);
457 }
458
459 void wxFileName::Assign(const wxString& pathOrig,
460 const wxString& name,
461 const wxString& ext,
462 wxPathFormat format)
463 {
464 wxString volume,
465 path;
466 SplitVolume(pathOrig, &volume, &path, format);
467
468 Assign(volume, path, name, ext, format);
469 }
470
471 void wxFileName::AssignDir(const wxString& dir, wxPathFormat format)
472 {
473 Assign(dir, wxEmptyString, format);
474 }
475
476 void wxFileName::Clear()
477 {
478 m_dirs.Clear();
479
480 m_volume =
481 m_name =
482 m_ext = wxEmptyString;
483
484 // we don't have any absolute path for now
485 m_relative = true;
486
487 // nor any extension
488 m_hasExt = false;
489 }
490
491 /* static */
492 wxFileName wxFileName::FileName(const wxString& file, wxPathFormat format)
493 {
494 return wxFileName(file, format);
495 }
496
497 /* static */
498 wxFileName wxFileName::DirName(const wxString& dir, wxPathFormat format)
499 {
500 wxFileName fn;
501 fn.AssignDir(dir, format);
502 return fn;
503 }
504
505 // ----------------------------------------------------------------------------
506 // existence tests
507 // ----------------------------------------------------------------------------
508
509 bool wxFileName::FileExists() const
510 {
511 return wxFileName::FileExists( GetFullPath() );
512 }
513
514 bool wxFileName::FileExists( const wxString &file )
515 {
516 return ::wxFileExists( file );
517 }
518
519 bool wxFileName::DirExists() const
520 {
521 return wxFileName::DirExists( GetFullPath() );
522 }
523
524 bool wxFileName::DirExists( const wxString &dir )
525 {
526 return ::wxDirExists( dir );
527 }
528
529 // ----------------------------------------------------------------------------
530 // CWD and HOME stuff
531 // ----------------------------------------------------------------------------
532
533 void wxFileName::AssignCwd(const wxString& volume)
534 {
535 AssignDir(wxFileName::GetCwd(volume));
536 }
537
538 /* static */
539 wxString wxFileName::GetCwd(const wxString& volume)
540 {
541 // if we have the volume, we must get the current directory on this drive
542 // and to do this we have to chdir to this volume - at least under Windows,
543 // I don't know how to get the current drive on another volume elsewhere
544 // (TODO)
545 wxString cwdOld;
546 if ( !volume.empty() )
547 {
548 cwdOld = wxGetCwd();
549 SetCwd(volume + GetVolumeSeparator());
550 }
551
552 wxString cwd = ::wxGetCwd();
553
554 if ( !volume.empty() )
555 {
556 SetCwd(cwdOld);
557 }
558
559 return cwd;
560 }
561
562 bool wxFileName::SetCwd()
563 {
564 return wxFileName::SetCwd( GetFullPath() );
565 }
566
567 bool wxFileName::SetCwd( const wxString &cwd )
568 {
569 return ::wxSetWorkingDirectory( cwd );
570 }
571
572 void wxFileName::AssignHomeDir()
573 {
574 AssignDir(wxFileName::GetHomeDir());
575 }
576
577 wxString wxFileName::GetHomeDir()
578 {
579 return ::wxGetHomeDir();
580 }
581
582 #if wxUSE_FILE
583
584 void wxFileName::AssignTempFileName(const wxString& prefix, wxFile *fileTemp)
585 {
586 wxString tempname = CreateTempFileName(prefix, fileTemp);
587 if ( tempname.empty() )
588 {
589 // error, failed to get temp file name
590 Clear();
591 }
592 else // ok
593 {
594 Assign(tempname);
595 }
596 }
597
598 /* static */
599 wxString
600 wxFileName::CreateTempFileName(const wxString& prefix, wxFile *fileTemp)
601 {
602 wxString path, dir, name;
603
604 // use the directory specified by the prefix
605 SplitPath(prefix, &dir, &name, NULL /* extension */);
606
607 if (dir.empty())
608 {
609 dir = wxGetenv(_T("TMPDIR"));
610 if (dir.empty())
611 {
612 dir = wxGetenv(_T("TMP"));
613 if (dir.empty())
614 {
615 dir = wxGetenv(_T("TEMP"));
616 }
617 }
618 }
619
620 #if defined(__WXWINCE__)
621 if (dir.empty())
622 {
623 // FIXME. Create \temp dir?
624 if (DirExists(wxT("\\temp")))
625 dir = wxT("\\temp");
626 }
627 path = dir + wxT("\\") + name;
628 int i = 1;
629 while (FileExists(path))
630 {
631 path = dir + wxT("\\") + name ;
632 path << i;
633 i ++;
634 }
635
636 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
637
638 if ( dir.empty() )
639 {
640 if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
641 {
642 wxLogLastError(_T("GetTempPath"));
643 }
644
645 if ( dir.empty() )
646 {
647 // GetTempFileName() fails if we pass it an empty string
648 dir = _T('.');
649 }
650 }
651 else // we have a dir to create the file in
652 {
653 // ensure we use only the back slashes as GetTempFileName(), unlike all
654 // the other APIs, is picky and doesn't accept the forward ones
655 dir.Replace(_T("/"), _T("\\"));
656 }
657
658 if ( !::GetTempFileName(dir, name, 0, wxStringBuffer(path, MAX_PATH + 1)) )
659 {
660 wxLogLastError(_T("GetTempFileName"));
661
662 path.clear();
663 }
664
665 #else // !Windows
666 if ( dir.empty() )
667 {
668 // default
669 #if defined(__DOS__) || defined(__OS2__)
670 dir = _T(".");
671 #elif defined(__WXMAC__)
672 dir = wxMacFindFolder(short(kOnSystemDisk), kTemporaryFolderType, kCreateFolder);
673 #else
674 dir = _T("/tmp");
675 #endif
676 }
677
678 path = dir;
679
680 if ( !wxEndsWithPathSeparator(dir) &&
681 (name.empty() || !wxIsPathSeparator(name[0u])) )
682 {
683 path += wxFILE_SEP_PATH;
684 }
685
686 path += name;
687
688 #if defined(HAVE_MKSTEMP)
689 // scratch space for mkstemp()
690 path += _T("XXXXXX");
691
692 // we need to copy the path to the buffer in which mkstemp() can modify it
693 wxCharBuffer buf( wxConvFile.cWX2MB( path ) );
694
695 // cast is safe because the string length doesn't change
696 int fdTemp = mkstemp( (char*)(const char*) buf );
697 if ( fdTemp == -1 )
698 {
699 // this might be not necessary as mkstemp() on most systems should have
700 // already done it but it doesn't hurt neither...
701 path.clear();
702 }
703 else // mkstemp() succeeded
704 {
705 path = wxConvFile.cMB2WX( (const char*) buf );
706
707 // avoid leaking the fd
708 if ( fileTemp )
709 {
710 fileTemp->Attach(fdTemp);
711 }
712 else
713 {
714 close(fdTemp);
715 }
716 }
717 #else // !HAVE_MKSTEMP
718
719 #ifdef HAVE_MKTEMP
720 // same as above
721 path += _T("XXXXXX");
722
723 wxCharBuffer buf = wxConvFile.cWX2MB( path );
724 if ( !mktemp( (const char*) buf ) )
725 {
726 path.clear();
727 }
728 else
729 {
730 path = wxConvFile.cMB2WX( (const char*) buf );
731 }
732 #else // !HAVE_MKTEMP (includes __DOS__)
733 // generate the unique file name ourselves
734 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
735 path << (unsigned int)getpid();
736 #endif
737
738 wxString pathTry;
739
740 static const size_t numTries = 1000;
741 for ( size_t n = 0; n < numTries; n++ )
742 {
743 // 3 hex digits is enough for numTries == 1000 < 4096
744 pathTry = path + wxString::Format(_T("%.03x"), (unsigned int) n);
745 if ( !FileExists(pathTry) )
746 {
747 break;
748 }
749
750 pathTry.clear();
751 }
752
753 path = pathTry;
754 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
755
756 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
757
758 #endif // Windows/!Windows
759
760 if ( path.empty() )
761 {
762 wxLogSysError(_("Failed to create a temporary file name"));
763 }
764 else if ( fileTemp && !fileTemp->IsOpened() )
765 {
766 // open the file - of course, there is a race condition here, this is
767 // why we always prefer using mkstemp()...
768 //
769 // NB: GetTempFileName() under Windows creates the file, so using
770 // write_excl there would fail
771 if ( !fileTemp->Open(path,
772 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
773 wxFile::write,
774 #else
775 wxFile::write_excl,
776 #endif
777 wxS_IRUSR | wxS_IWUSR) )
778 {
779 // FIXME: If !ok here should we loop and try again with another
780 // file name? That is the standard recourse if open(O_EXCL)
781 // fails, though of course it should be protected against
782 // possible infinite looping too.
783
784 wxLogError(_("Failed to open temporary file."));
785
786 path.clear();
787 }
788 }
789
790 return path;
791 }
792
793 #endif // wxUSE_FILE
794
795 // ----------------------------------------------------------------------------
796 // directory operations
797 // ----------------------------------------------------------------------------
798
799 bool wxFileName::Mkdir( int perm, int flags )
800 {
801 return wxFileName::Mkdir( GetFullPath(), perm, flags );
802 }
803
804 bool wxFileName::Mkdir( const wxString& dir, int perm, int flags )
805 {
806 if ( flags & wxPATH_MKDIR_FULL )
807 {
808 // split the path in components
809 wxFileName filename;
810 filename.AssignDir(dir);
811
812 wxString currPath;
813 if ( filename.HasVolume())
814 {
815 currPath << wxGetVolumeString(filename.GetVolume(), wxPATH_NATIVE);
816 }
817
818 wxArrayString dirs = filename.GetDirs();
819 size_t count = dirs.GetCount();
820 for ( size_t i = 0; i < count; i++ )
821 {
822 if ( i > 0 ||
823 #if defined(__WXMAC__) && !defined(__DARWIN__)
824 // relative pathnames are exactely the other way round under mac...
825 !filename.IsAbsolute()
826 #else
827 filename.IsAbsolute()
828 #endif
829 )
830 currPath += wxFILE_SEP_PATH;
831 currPath += dirs[i];
832
833 if (!DirExists(currPath))
834 {
835 if (!wxMkdir(currPath, perm))
836 {
837 // no need to try creating further directories
838 return false;
839 }
840 }
841 }
842
843 return true;
844
845 }
846
847 return ::wxMkdir( dir, perm );
848 }
849
850 bool wxFileName::Rmdir()
851 {
852 return wxFileName::Rmdir( GetFullPath() );
853 }
854
855 bool wxFileName::Rmdir( const wxString &dir )
856 {
857 return ::wxRmdir( dir );
858 }
859
860 // ----------------------------------------------------------------------------
861 // path normalization
862 // ----------------------------------------------------------------------------
863
864 bool wxFileName::Normalize(int flags,
865 const wxString& cwd,
866 wxPathFormat format)
867 {
868 // deal with env vars renaming first as this may seriously change the path
869 if ( flags & wxPATH_NORM_ENV_VARS )
870 {
871 wxString pathOrig = GetFullPath(format);
872 wxString path = wxExpandEnvVars(pathOrig);
873 if ( path != pathOrig )
874 {
875 Assign(path);
876 }
877 }
878
879
880 // the existing path components
881 wxArrayString dirs = GetDirs();
882
883 // the path to prepend in front to make the path absolute
884 wxFileName curDir;
885
886 format = GetFormat(format);
887
888 // make the path absolute
889 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute(format) )
890 {
891 if ( cwd.empty() )
892 {
893 curDir.AssignCwd(GetVolume());
894 }
895 else // cwd provided
896 {
897 curDir.AssignDir(cwd);
898 }
899
900 // the path may be not absolute because it doesn't have the volume name
901 // but in this case we shouldn't modify the directory components of it
902 // but just set the current volume
903 if ( !HasVolume() && curDir.HasVolume() )
904 {
905 SetVolume(curDir.GetVolume());
906
907 if ( !m_relative )
908 {
909 // yes, it was the case - we don't need curDir then
910 curDir.Clear();
911 }
912 }
913 }
914
915 // handle ~ stuff under Unix only
916 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) )
917 {
918 if ( !dirs.IsEmpty() )
919 {
920 wxString dir = dirs[0u];
921 if ( !dir.empty() && dir[0u] == _T('~') )
922 {
923 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
924
925 dirs.RemoveAt(0u);
926 }
927 }
928 }
929
930 // transform relative path into abs one
931 if ( curDir.IsOk() )
932 {
933 wxArrayString dirsNew = curDir.GetDirs();
934 size_t count = dirs.GetCount();
935 for ( size_t n = 0; n < count; n++ )
936 {
937 dirsNew.Add(dirs[n]);
938 }
939
940 dirs = dirsNew;
941 }
942
943 // now deal with ".", ".." and the rest
944 m_dirs.Empty();
945 size_t count = dirs.GetCount();
946 for ( size_t n = 0; n < count; n++ )
947 {
948 wxString dir = dirs[n];
949
950 if ( flags & wxPATH_NORM_DOTS )
951 {
952 if ( dir == wxT(".") )
953 {
954 // just ignore
955 continue;
956 }
957
958 if ( dir == wxT("..") )
959 {
960 if ( m_dirs.IsEmpty() )
961 {
962 wxLogError(_("The path '%s' contains too many \"..\"!"),
963 GetFullPath().c_str());
964 return false;
965 }
966
967 m_dirs.RemoveAt(m_dirs.GetCount() - 1);
968 continue;
969 }
970 }
971
972 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
973 {
974 dir.MakeLower();
975 }
976
977 m_dirs.Add(dir);
978 }
979
980 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
981 if ( (flags & wxPATH_NORM_SHORTCUT) )
982 {
983 wxString filename;
984 if (GetShortcutTarget(GetFullPath(format), filename))
985 {
986 // Repeat this since we may now have a new path
987 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
988 {
989 filename.MakeLower();
990 }
991 m_relative = false;
992 Assign(filename);
993 }
994 }
995 #endif
996
997 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
998 {
999 // VZ: expand env vars here too?
1000
1001 m_volume.MakeLower();
1002 m_name.MakeLower();
1003 m_ext.MakeLower();
1004 }
1005
1006 // we do have the path now
1007 //
1008 // NB: need to do this before (maybe) calling Assign() below
1009 m_relative = false;
1010
1011 #if defined(__WIN32__)
1012 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
1013 {
1014 Assign(GetLongPath());
1015 }
1016 #endif // Win32
1017
1018 return true;
1019 }
1020
1021 // ----------------------------------------------------------------------------
1022 // get the shortcut target
1023 // ----------------------------------------------------------------------------
1024
1025 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1026 // The .lnk file is a plain text file so it should be easy to
1027 // make it work. Hint from Google Groups:
1028 // "If you open up a lnk file, you'll see a
1029 // number, followed by a pound sign (#), followed by more text. The
1030 // number is the number of characters that follows the pound sign. The
1031 // characters after the pound sign are the command line (which _can_
1032 // include arguments) to be executed. Any path (e.g. \windows\program
1033 // files\myapp.exe) that includes spaces needs to be enclosed in
1034 // quotation marks."
1035
1036 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1037 // The following lines are necessary under WinCE
1038 // #include "wx/msw/private.h"
1039 // #include <ole2.h>
1040 #include <shlobj.h>
1041 #if defined(__WXWINCE__)
1042 #include <shlguid.h>
1043 #endif
1044
1045 bool wxFileName::GetShortcutTarget(const wxString& shortcutPath, wxString& targetFilename, wxString* arguments)
1046 {
1047 wxString path, file, ext;
1048 wxSplitPath(shortcutPath, & path, & file, & ext);
1049
1050 HRESULT hres;
1051 IShellLink* psl;
1052 bool success = false;
1053
1054 // Assume it's not a shortcut if it doesn't end with lnk
1055 if (ext.CmpNoCase(wxT("lnk"))!=0)
1056 return false;
1057
1058 // create a ShellLink object
1059 hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1060 IID_IShellLink, (LPVOID*) &psl);
1061
1062 if (SUCCEEDED(hres))
1063 {
1064 IPersistFile* ppf;
1065 hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
1066 if (SUCCEEDED(hres))
1067 {
1068 WCHAR wsz[MAX_PATH];
1069
1070 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
1071 MAX_PATH);
1072
1073 hres = ppf->Load(wsz, 0);
1074 if (SUCCEEDED(hres))
1075 {
1076 wxChar buf[2048];
1077 // Wrong prototype in early versions
1078 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1079 psl->GetPath((CHAR*) buf, 2048, NULL, SLGP_UNCPRIORITY);
1080 #else
1081 psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
1082 #endif
1083 targetFilename = wxString(buf);
1084 success = (shortcutPath != targetFilename);
1085
1086 psl->GetArguments(buf, 2048);
1087 wxString args(buf);
1088 if (!args.empty() && arguments)
1089 {
1090 *arguments = args;
1091 }
1092 }
1093 }
1094 }
1095 psl->Release();
1096 return success;
1097 }
1098 #endif
1099
1100
1101 // ----------------------------------------------------------------------------
1102 // absolute/relative paths
1103 // ----------------------------------------------------------------------------
1104
1105 bool wxFileName::IsAbsolute(wxPathFormat format) const
1106 {
1107 // if our path doesn't start with a path separator, it's not an absolute
1108 // path
1109 if ( m_relative )
1110 return false;
1111
1112 if ( !GetVolumeSeparator(format).empty() )
1113 {
1114 // this format has volumes and an absolute path must have one, it's not
1115 // enough to have the full path to bean absolute file under Windows
1116 if ( GetVolume().empty() )
1117 return false;
1118 }
1119
1120 return true;
1121 }
1122
1123 bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
1124 {
1125 wxFileName fnBase = wxFileName::DirName(pathBase, format);
1126
1127 // get cwd only once - small time saving
1128 wxString cwd = wxGetCwd();
1129 Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1130 fnBase.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1131
1132 bool withCase = IsCaseSensitive(format);
1133
1134 // we can't do anything if the files live on different volumes
1135 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
1136 {
1137 // nothing done
1138 return false;
1139 }
1140
1141 // same drive, so we don't need our volume
1142 m_volume.clear();
1143
1144 // remove common directories starting at the top
1145 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
1146 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
1147 {
1148 m_dirs.RemoveAt(0);
1149 fnBase.m_dirs.RemoveAt(0);
1150 }
1151
1152 // add as many ".." as needed
1153 size_t count = fnBase.m_dirs.GetCount();
1154 for ( size_t i = 0; i < count; i++ )
1155 {
1156 m_dirs.Insert(wxT(".."), 0u);
1157 }
1158
1159 if ( format == wxPATH_UNIX || format == wxPATH_DOS )
1160 {
1161 // a directory made relative with respect to itself is '.' under Unix
1162 // and DOS, by definition (but we don't have to insert "./" for the
1163 // files)
1164 if ( m_dirs.IsEmpty() && IsDir() )
1165 {
1166 m_dirs.Add(_T('.'));
1167 }
1168 }
1169
1170 m_relative = true;
1171
1172 // we were modified
1173 return true;
1174 }
1175
1176 // ----------------------------------------------------------------------------
1177 // filename kind tests
1178 // ----------------------------------------------------------------------------
1179
1180 bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const
1181 {
1182 wxFileName fn1 = *this,
1183 fn2 = filepath;
1184
1185 // get cwd only once - small time saving
1186 wxString cwd = wxGetCwd();
1187 fn1.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1188 fn2.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1189
1190 if ( fn1.GetFullPath() == fn2.GetFullPath() )
1191 return true;
1192
1193 // TODO: compare inodes for Unix, this works even when filenames are
1194 // different but files are the same (symlinks) (VZ)
1195
1196 return false;
1197 }
1198
1199 /* static */
1200 bool wxFileName::IsCaseSensitive( wxPathFormat format )
1201 {
1202 // only Unix filenames are truely case-sensitive
1203 return GetFormat(format) == wxPATH_UNIX;
1204 }
1205
1206 /* static */
1207 wxString wxFileName::GetForbiddenChars(wxPathFormat format)
1208 {
1209 // Inits to forbidden characters that are common to (almost) all platforms.
1210 wxString strForbiddenChars = wxT("*?");
1211
1212 // If asserts, wxPathFormat has been changed. In case of a new path format
1213 // addition, the following code might have to be updated.
1214 wxCOMPILE_TIME_ASSERT(wxPATH_MAX == 5, wxPathFormatChanged);
1215 switch ( GetFormat(format) )
1216 {
1217 default :
1218 wxFAIL_MSG( wxT("Unknown path format") );
1219 // !! Fall through !!
1220
1221 case wxPATH_UNIX:
1222 break;
1223
1224 case wxPATH_MAC:
1225 // On a Mac even names with * and ? are allowed (Tested with OS
1226 // 9.2.1 and OS X 10.2.5)
1227 strForbiddenChars = wxEmptyString;
1228 break;
1229
1230 case wxPATH_DOS:
1231 strForbiddenChars += wxT("\\/:\"<>|");
1232 break;
1233
1234 case wxPATH_VMS:
1235 break;
1236 }
1237
1238 return strForbiddenChars;
1239 }
1240
1241 /* static */
1242 wxString wxFileName::GetVolumeSeparator(wxPathFormat WXUNUSED_IN_WINCE(format))
1243 {
1244 #ifdef __WXWINCE__
1245 return wxEmptyString;
1246 #else
1247 wxString sepVol;
1248
1249 if ( (GetFormat(format) == wxPATH_DOS) ||
1250 (GetFormat(format) == wxPATH_VMS) )
1251 {
1252 sepVol = wxFILE_SEP_DSK;
1253 }
1254 //else: leave empty
1255
1256 return sepVol;
1257 #endif
1258 }
1259
1260 /* static */
1261 wxString wxFileName::GetPathSeparators(wxPathFormat format)
1262 {
1263 wxString seps;
1264 switch ( GetFormat(format) )
1265 {
1266 case wxPATH_DOS:
1267 // accept both as native APIs do but put the native one first as
1268 // this is the one we use in GetFullPath()
1269 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
1270 break;
1271
1272 default:
1273 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1274 // fall through
1275
1276 case wxPATH_UNIX:
1277 seps = wxFILE_SEP_PATH_UNIX;
1278 break;
1279
1280 case wxPATH_MAC:
1281 seps = wxFILE_SEP_PATH_MAC;
1282 break;
1283
1284 case wxPATH_VMS:
1285 seps = wxFILE_SEP_PATH_VMS;
1286 break;
1287 }
1288
1289 return seps;
1290 }
1291
1292 /* static */
1293 wxString wxFileName::GetPathTerminators(wxPathFormat format)
1294 {
1295 format = GetFormat(format);
1296
1297 // under VMS the end of the path is ']', not the path separator used to
1298 // separate the components
1299 return format == wxPATH_VMS ? wxString(_T(']')) : GetPathSeparators(format);
1300 }
1301
1302 /* static */
1303 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
1304 {
1305 // wxString::Find() doesn't work as expected with NUL - it will always find
1306 // it, so test for it separately
1307 return ch != _T('\0') && GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
1308 }
1309
1310 // ----------------------------------------------------------------------------
1311 // path components manipulation
1312 // ----------------------------------------------------------------------------
1313
1314 /* static */ bool wxFileName::IsValidDirComponent(const wxString& dir)
1315 {
1316 if ( dir.empty() )
1317 {
1318 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1319
1320 return false;
1321 }
1322
1323 const size_t len = dir.length();
1324 for ( size_t n = 0; n < len; n++ )
1325 {
1326 if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
1327 {
1328 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1329
1330 return false;
1331 }
1332 }
1333
1334 return true;
1335 }
1336
1337 void wxFileName::AppendDir( const wxString& dir )
1338 {
1339 if ( IsValidDirComponent(dir) )
1340 m_dirs.Add( dir );
1341 }
1342
1343 void wxFileName::PrependDir( const wxString& dir )
1344 {
1345 InsertDir(0, dir);
1346 }
1347
1348 void wxFileName::InsertDir(size_t before, const wxString& dir)
1349 {
1350 if ( IsValidDirComponent(dir) )
1351 m_dirs.Insert(dir, before);
1352 }
1353
1354 void wxFileName::RemoveDir(size_t pos)
1355 {
1356 m_dirs.RemoveAt(pos);
1357 }
1358
1359 // ----------------------------------------------------------------------------
1360 // accessors
1361 // ----------------------------------------------------------------------------
1362
1363 void wxFileName::SetFullName(const wxString& fullname)
1364 {
1365 SplitPath(fullname, NULL /* no volume */, NULL /* no path */,
1366 &m_name, &m_ext, &m_hasExt);
1367 }
1368
1369 wxString wxFileName::GetFullName() const
1370 {
1371 wxString fullname = m_name;
1372 if ( m_hasExt )
1373 {
1374 fullname << wxFILE_SEP_EXT << m_ext;
1375 }
1376
1377 return fullname;
1378 }
1379
1380 wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
1381 {
1382 format = GetFormat( format );
1383
1384 wxString fullpath;
1385
1386 // return the volume with the path as well if requested
1387 if ( flags & wxPATH_GET_VOLUME )
1388 {
1389 fullpath += wxGetVolumeString(GetVolume(), format);
1390 }
1391
1392 // the leading character
1393 switch ( format )
1394 {
1395 case wxPATH_MAC:
1396 if ( m_relative )
1397 fullpath += wxFILE_SEP_PATH_MAC;
1398 break;
1399
1400 case wxPATH_DOS:
1401 if ( !m_relative )
1402 fullpath += wxFILE_SEP_PATH_DOS;
1403 break;
1404
1405 default:
1406 wxFAIL_MSG( wxT("Unknown path format") );
1407 // fall through
1408
1409 case wxPATH_UNIX:
1410 if ( !m_relative )
1411 {
1412 // normally the absolute file names start with a slash
1413 // with one exception: the ones like "~/foo.bar" don't
1414 // have it
1415 if ( m_dirs.IsEmpty() || m_dirs[0u] != _T('~') )
1416 {
1417 fullpath += wxFILE_SEP_PATH_UNIX;
1418 }
1419 }
1420 break;
1421
1422 case wxPATH_VMS:
1423 // no leading character here but use this place to unset
1424 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1425 // as, if I understand correctly, there should never be a dot
1426 // before the closing bracket
1427 flags &= ~wxPATH_GET_SEPARATOR;
1428 }
1429
1430 if ( m_dirs.empty() )
1431 {
1432 // there is nothing more
1433 return fullpath;
1434 }
1435
1436 // then concatenate all the path components using the path separator
1437 if ( format == wxPATH_VMS )
1438 {
1439 fullpath += wxT('[');
1440 }
1441
1442 const size_t dirCount = m_dirs.GetCount();
1443 for ( size_t i = 0; i < dirCount; i++ )
1444 {
1445 switch (format)
1446 {
1447 case wxPATH_MAC:
1448 if ( m_dirs[i] == wxT(".") )
1449 {
1450 // skip appending ':', this shouldn't be done in this
1451 // case as "::" is interpreted as ".." under Unix
1452 continue;
1453 }
1454
1455 // convert back from ".." to nothing
1456 if ( !m_dirs[i].IsSameAs(wxT("..")) )
1457 fullpath += m_dirs[i];
1458 break;
1459
1460 default:
1461 wxFAIL_MSG( wxT("Unexpected path format") );
1462 // still fall through
1463
1464 case wxPATH_DOS:
1465 case wxPATH_UNIX:
1466 fullpath += m_dirs[i];
1467 break;
1468
1469 case wxPATH_VMS:
1470 // TODO: What to do with ".." under VMS
1471
1472 // convert back from ".." to nothing
1473 if ( !m_dirs[i].IsSameAs(wxT("..")) )
1474 fullpath += m_dirs[i];
1475 break;
1476 }
1477
1478 if ( (flags & wxPATH_GET_SEPARATOR) || (i != dirCount - 1) )
1479 fullpath += GetPathSeparator(format);
1480 }
1481
1482 if ( format == wxPATH_VMS )
1483 {
1484 fullpath += wxT(']');
1485 }
1486
1487 return fullpath;
1488 }
1489
1490 wxString wxFileName::GetFullPath( wxPathFormat format ) const
1491 {
1492 // we already have a function to get the path
1493 wxString fullpath = GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR,
1494 format);
1495
1496 // now just add the file name and extension to it
1497 fullpath += GetFullName();
1498
1499 return fullpath;
1500 }
1501
1502 // Return the short form of the path (returns identity on non-Windows platforms)
1503 wxString wxFileName::GetShortPath() const
1504 {
1505 wxString path(GetFullPath());
1506
1507 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1508 DWORD sz = ::GetShortPathName(path, NULL, 0);
1509 if ( sz != 0 )
1510 {
1511 wxString pathOut;
1512 if ( ::GetShortPathName
1513 (
1514 path,
1515 wxStringBuffer(pathOut, sz),
1516 sz
1517 ) != 0 )
1518 {
1519 return pathOut;
1520 }
1521 }
1522 #endif // Windows
1523
1524 return path;
1525 }
1526
1527 // Return the long form of the path (returns identity on non-Windows platforms)
1528 wxString wxFileName::GetLongPath() const
1529 {
1530 wxString pathOut,
1531 path = GetFullPath();
1532
1533 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1534
1535 #if wxUSE_DYNAMIC_LOADER
1536 typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
1537
1538 // this is MT-safe as in the worst case we're going to resolve the function
1539 // twice -- but as the result is the same in both threads, it's ok
1540 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
1541 if ( !s_pfnGetLongPathName )
1542 {
1543 static bool s_triedToLoad = false;
1544
1545 if ( !s_triedToLoad )
1546 {
1547 s_triedToLoad = true;
1548
1549 wxDynamicLibrary dllKernel(_T("kernel32"));
1550
1551 const wxChar* GetLongPathName = _T("GetLongPathName")
1552 #if wxUSE_UNICODE
1553 _T("W");
1554 #else // ANSI
1555 _T("A");
1556 #endif // Unicode/ANSI
1557
1558 if ( dllKernel.HasSymbol(GetLongPathName) )
1559 {
1560 s_pfnGetLongPathName = (GET_LONG_PATH_NAME)
1561 dllKernel.GetSymbol(GetLongPathName);
1562 }
1563
1564 // note that kernel32.dll can be unloaded, it stays in memory
1565 // anyhow as all Win32 programs link to it and so it's safe to call
1566 // GetLongPathName() even after unloading it
1567 }
1568 }
1569
1570 if ( s_pfnGetLongPathName )
1571 {
1572 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
1573 if ( dwSize > 0 )
1574 {
1575 if ( (*s_pfnGetLongPathName)
1576 (
1577 path,
1578 wxStringBuffer(pathOut, dwSize),
1579 dwSize
1580 ) != 0 )
1581 {
1582 return pathOut;
1583 }
1584 }
1585 }
1586 #endif // wxUSE_DYNAMIC_LOADER
1587
1588 // The OS didn't support GetLongPathName, or some other error.
1589 // We need to call FindFirstFile on each component in turn.
1590
1591 WIN32_FIND_DATA findFileData;
1592 HANDLE hFind;
1593
1594 if ( HasVolume() )
1595 pathOut = GetVolume() +
1596 GetVolumeSeparator(wxPATH_DOS) +
1597 GetPathSeparator(wxPATH_DOS);
1598 else
1599 pathOut = wxEmptyString;
1600
1601 wxArrayString dirs = GetDirs();
1602 dirs.Add(GetFullName());
1603
1604 wxString tmpPath;
1605
1606 size_t count = dirs.GetCount();
1607 for ( size_t i = 0; i < count; i++ )
1608 {
1609 // We're using pathOut to collect the long-name path, but using a
1610 // temporary for appending the last path component which may be
1611 // short-name
1612 tmpPath = pathOut + dirs[i];
1613
1614 if ( tmpPath.empty() )
1615 continue;
1616
1617 // can't see this being necessary? MF
1618 if ( tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
1619 {
1620 // Can't pass a drive and root dir to FindFirstFile,
1621 // so continue to next dir
1622 tmpPath += wxFILE_SEP_PATH;
1623 pathOut = tmpPath;
1624 continue;
1625 }
1626
1627 hFind = ::FindFirstFile(tmpPath, &findFileData);
1628 if (hFind == INVALID_HANDLE_VALUE)
1629 {
1630 // Error: most likely reason is that path doesn't exist, so
1631 // append any unprocessed parts and return
1632 for ( i += 1; i < count; i++ )
1633 tmpPath += wxFILE_SEP_PATH + dirs[i];
1634
1635 return tmpPath;
1636 }
1637
1638 pathOut += findFileData.cFileName;
1639 if ( (i < (count-1)) )
1640 pathOut += wxFILE_SEP_PATH;
1641
1642 ::FindClose(hFind);
1643 }
1644 #else // !Win32
1645 pathOut = path;
1646 #endif // Win32/!Win32
1647
1648 return pathOut;
1649 }
1650
1651 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
1652 {
1653 if (format == wxPATH_NATIVE)
1654 {
1655 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1656 format = wxPATH_DOS;
1657 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1658 format = wxPATH_MAC;
1659 #elif defined(__VMS)
1660 format = wxPATH_VMS;
1661 #else
1662 format = wxPATH_UNIX;
1663 #endif
1664 }
1665 return format;
1666 }
1667
1668 // ----------------------------------------------------------------------------
1669 // path splitting function
1670 // ----------------------------------------------------------------------------
1671
1672 /* static */
1673 void
1674 wxFileName::SplitVolume(const wxString& fullpathWithVolume,
1675 wxString *pstrVolume,
1676 wxString *pstrPath,
1677 wxPathFormat format)
1678 {
1679 format = GetFormat(format);
1680
1681 wxString fullpath = fullpathWithVolume;
1682
1683 // special Windows UNC paths hack: transform \\share\path into share:path
1684 if ( format == wxPATH_DOS )
1685 {
1686 if ( fullpath.length() >= 4 &&
1687 fullpath[0u] == wxFILE_SEP_PATH_DOS &&
1688 fullpath[1u] == wxFILE_SEP_PATH_DOS )
1689 {
1690 fullpath.erase(0, 2);
1691
1692 size_t posFirstSlash =
1693 fullpath.find_first_of(GetPathTerminators(format));
1694 if ( posFirstSlash != wxString::npos )
1695 {
1696 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
1697
1698 // UNC paths are always absolute, right? (FIXME)
1699 fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
1700 }
1701 }
1702 }
1703
1704 // We separate the volume here
1705 if ( format == wxPATH_DOS || format == wxPATH_VMS )
1706 {
1707 wxString sepVol = GetVolumeSeparator(format);
1708
1709 size_t posFirstColon = fullpath.find_first_of(sepVol);
1710 if ( posFirstColon != wxString::npos )
1711 {
1712 if ( pstrVolume )
1713 {
1714 *pstrVolume = fullpath.Left(posFirstColon);
1715 }
1716
1717 // remove the volume name and the separator from the full path
1718 fullpath.erase(0, posFirstColon + sepVol.length());
1719 }
1720 }
1721
1722 if ( pstrPath )
1723 *pstrPath = fullpath;
1724 }
1725
1726 /* static */
1727 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
1728 wxString *pstrVolume,
1729 wxString *pstrPath,
1730 wxString *pstrName,
1731 wxString *pstrExt,
1732 bool *hasExt,
1733 wxPathFormat format)
1734 {
1735 format = GetFormat(format);
1736
1737 wxString fullpath;
1738 SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
1739
1740 // find the positions of the last dot and last path separator in the path
1741 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
1742 size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
1743
1744 // check whether this dot occurs at the very beginning of a path component
1745 if ( (posLastDot != wxString::npos) &&
1746 (posLastDot == 0 ||
1747 IsPathSeparator(fullpath[posLastDot - 1]) ||
1748 (format == wxPATH_VMS && fullpath[posLastDot - 1] == _T(']'))) )
1749 {
1750 // dot may be (and commonly -- at least under Unix -- is) the first
1751 // character of the filename, don't treat the entire filename as
1752 // extension in this case
1753 posLastDot = wxString::npos;
1754 }
1755
1756 // if we do have a dot and a slash, check that the dot is in the name part
1757 if ( (posLastDot != wxString::npos) &&
1758 (posLastSlash != wxString::npos) &&
1759 (posLastDot < posLastSlash) )
1760 {
1761 // the dot is part of the path, not the start of the extension
1762 posLastDot = wxString::npos;
1763 }
1764
1765 // now fill in the variables provided by user
1766 if ( pstrPath )
1767 {
1768 if ( posLastSlash == wxString::npos )
1769 {
1770 // no path at all
1771 pstrPath->Empty();
1772 }
1773 else
1774 {
1775 // take everything up to the path separator but take care to make
1776 // the path equal to something like '/', not empty, for the files
1777 // immediately under root directory
1778 size_t len = posLastSlash;
1779
1780 // this rule does not apply to mac since we do not start with colons (sep)
1781 // except for relative paths
1782 if ( !len && format != wxPATH_MAC)
1783 len++;
1784
1785 *pstrPath = fullpath.Left(len);
1786
1787 // special VMS hack: remove the initial bracket
1788 if ( format == wxPATH_VMS )
1789 {
1790 if ( (*pstrPath)[0u] == _T('[') )
1791 pstrPath->erase(0, 1);
1792 }
1793 }
1794 }
1795
1796 if ( pstrName )
1797 {
1798 // take all characters starting from the one after the last slash and
1799 // up to, but excluding, the last dot
1800 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
1801 size_t count;
1802 if ( posLastDot == wxString::npos )
1803 {
1804 // take all until the end
1805 count = wxString::npos;
1806 }
1807 else if ( posLastSlash == wxString::npos )
1808 {
1809 count = posLastDot;
1810 }
1811 else // have both dot and slash
1812 {
1813 count = posLastDot - posLastSlash - 1;
1814 }
1815
1816 *pstrName = fullpath.Mid(nStart, count);
1817 }
1818
1819 // finally deal with the extension here: we have an added complication that
1820 // extension may be empty (but present) as in "foo." where trailing dot
1821 // indicates the empty extension at the end -- and hence we must remember
1822 // that we have it independently of pstrExt
1823 if ( posLastDot == wxString::npos )
1824 {
1825 // no extension
1826 if ( pstrExt )
1827 pstrExt->clear();
1828 if ( hasExt )
1829 *hasExt = false;
1830 }
1831 else
1832 {
1833 // take everything after the dot
1834 if ( pstrExt )
1835 *pstrExt = fullpath.Mid(posLastDot + 1);
1836 if ( hasExt )
1837 *hasExt = true;
1838 }
1839 }
1840
1841 /* static */
1842 void wxFileName::SplitPath(const wxString& fullpath,
1843 wxString *path,
1844 wxString *name,
1845 wxString *ext,
1846 wxPathFormat format)
1847 {
1848 wxString volume;
1849 SplitPath(fullpath, &volume, path, name, ext, format);
1850
1851 if ( path )
1852 {
1853 path->Prepend(wxGetVolumeString(volume, format));
1854 }
1855 }
1856
1857 // ----------------------------------------------------------------------------
1858 // time functions
1859 // ----------------------------------------------------------------------------
1860
1861 #if wxUSE_DATETIME
1862
1863 bool wxFileName::SetTimes(const wxDateTime *dtAccess,
1864 const wxDateTime *dtMod,
1865 const wxDateTime *dtCreate)
1866 {
1867 #if defined(__WIN32__)
1868 if ( IsDir() )
1869 {
1870 // VZ: please let me know how to do this if you can
1871 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
1872 }
1873 else // file
1874 {
1875 wxFileHandle fh(GetFullPath(), wxFileHandle::Write);
1876 if ( fh.IsOk() )
1877 {
1878 FILETIME ftAccess, ftCreate, ftWrite;
1879
1880 if ( dtCreate )
1881 ConvertWxToFileTime(&ftCreate, *dtCreate);
1882 if ( dtAccess )
1883 ConvertWxToFileTime(&ftAccess, *dtAccess);
1884 if ( dtMod )
1885 ConvertWxToFileTime(&ftWrite, *dtMod);
1886
1887 if ( ::SetFileTime(fh,
1888 dtCreate ? &ftCreate : NULL,
1889 dtAccess ? &ftAccess : NULL,
1890 dtMod ? &ftWrite : NULL) )
1891 {
1892 return true;
1893 }
1894 }
1895 }
1896 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1897 wxUnusedVar(dtCreate);
1898
1899 if ( !dtAccess && !dtMod )
1900 {
1901 // can't modify the creation time anyhow, don't try
1902 return true;
1903 }
1904
1905 // if dtAccess or dtMod is not specified, use the other one (which must be
1906 // non NULL because of the test above) for both times
1907 utimbuf utm;
1908 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
1909 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
1910 if ( utime(GetFullPath().fn_str(), &utm) == 0 )
1911 {
1912 return true;
1913 }
1914 #else // other platform
1915 wxUnusedVar(dtAccess);
1916 wxUnusedVar(dtMod);
1917 wxUnusedVar(dtCreate);
1918 #endif // platforms
1919
1920 wxLogSysError(_("Failed to modify file times for '%s'"),
1921 GetFullPath().c_str());
1922
1923 return false;
1924 }
1925
1926 bool wxFileName::Touch()
1927 {
1928 #if defined(__UNIX_LIKE__)
1929 // under Unix touching file is simple: just pass NULL to utime()
1930 if ( utime(GetFullPath().fn_str(), NULL) == 0 )
1931 {
1932 return true;
1933 }
1934
1935 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1936
1937 return false;
1938 #else // other platform
1939 wxDateTime dtNow = wxDateTime::Now();
1940
1941 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
1942 #endif // platforms
1943 }
1944
1945 bool wxFileName::GetTimes(wxDateTime *dtAccess,
1946 wxDateTime *dtMod,
1947 wxDateTime *dtCreate) const
1948 {
1949 #if defined(__WIN32__)
1950 // we must use different methods for the files and directories under
1951 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
1952 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
1953 // not 9x
1954 bool ok;
1955 FILETIME ftAccess, ftCreate, ftWrite;
1956 if ( IsDir() )
1957 {
1958 // implemented in msw/dir.cpp
1959 extern bool wxGetDirectoryTimes(const wxString& dirname,
1960 FILETIME *, FILETIME *, FILETIME *);
1961
1962 // we should pass the path without the trailing separator to
1963 // wxGetDirectoryTimes()
1964 ok = wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME),
1965 &ftAccess, &ftCreate, &ftWrite);
1966 }
1967 else // file
1968 {
1969 wxFileHandle fh(GetFullPath(), wxFileHandle::Read);
1970 if ( fh.IsOk() )
1971 {
1972 ok = ::GetFileTime(fh,
1973 dtCreate ? &ftCreate : NULL,
1974 dtAccess ? &ftAccess : NULL,
1975 dtMod ? &ftWrite : NULL) != 0;
1976 }
1977 else
1978 {
1979 ok = false;
1980 }
1981 }
1982
1983 if ( ok )
1984 {
1985 if ( dtCreate )
1986 ConvertFileTimeToWx(dtCreate, ftCreate);
1987 if ( dtAccess )
1988 ConvertFileTimeToWx(dtAccess, ftAccess);
1989 if ( dtMod )
1990 ConvertFileTimeToWx(dtMod, ftWrite);
1991
1992 return true;
1993 }
1994 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
1995 wxStructStat stBuf;
1996 if ( wxStat( GetFullPath().c_str(), &stBuf) == 0 )
1997 {
1998 if ( dtAccess )
1999 dtAccess->Set(stBuf.st_atime);
2000 if ( dtMod )
2001 dtMod->Set(stBuf.st_mtime);
2002 if ( dtCreate )
2003 dtCreate->Set(stBuf.st_ctime);
2004
2005 return true;
2006 }
2007 #else // other platform
2008 wxUnusedVar(dtAccess);
2009 wxUnusedVar(dtMod);
2010 wxUnusedVar(dtCreate);
2011 #endif // platforms
2012
2013 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2014 GetFullPath().c_str());
2015
2016 return false;
2017 }
2018
2019 #endif // wxUSE_DATETIME
2020
2021 #ifdef __WXMAC__
2022
2023 const short kMacExtensionMaxLength = 16 ;
2024 class MacDefaultExtensionRecord
2025 {
2026 public :
2027 MacDefaultExtensionRecord()
2028 {
2029 m_ext[0] = 0 ;
2030 m_type = m_creator = 0 ;
2031 }
2032 MacDefaultExtensionRecord( const MacDefaultExtensionRecord& from )
2033 {
2034 wxStrcpy( m_ext , from.m_ext ) ;
2035 m_type = from.m_type ;
2036 m_creator = from.m_creator ;
2037 }
2038 MacDefaultExtensionRecord( const wxChar * extension , OSType type , OSType creator )
2039 {
2040 wxStrncpy( m_ext , extension , kMacExtensionMaxLength ) ;
2041 m_ext[kMacExtensionMaxLength] = 0 ;
2042 m_type = type ;
2043 m_creator = creator ;
2044 }
2045 wxChar m_ext[kMacExtensionMaxLength] ;
2046 OSType m_type ;
2047 OSType m_creator ;
2048 } ;
2049
2050 #include "wx/dynarray.h"
2051 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ;
2052
2053 bool gMacDefaultExtensionsInited = false ;
2054
2055 #include "wx/arrimpl.cpp"
2056
2057 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray) ;
2058
2059 MacDefaultExtensionArray gMacDefaultExtensions ;
2060
2061 // load the default extensions
2062 MacDefaultExtensionRecord gDefaults[] =
2063 {
2064 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2065 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2066 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2067 } ;
2068
2069 static void MacEnsureDefaultExtensionsLoaded()
2070 {
2071 if ( !gMacDefaultExtensionsInited )
2072 {
2073 // we could load the pc exchange prefs here too
2074 for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
2075 {
2076 gMacDefaultExtensions.Add( gDefaults[i] ) ;
2077 }
2078 gMacDefaultExtensionsInited = true ;
2079 }
2080 }
2081
2082 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
2083 {
2084 FSRef fsRef ;
2085 FSCatalogInfo catInfo;
2086 FileInfo *finfo ;
2087
2088 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2089 {
2090 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2091 {
2092 finfo = (FileInfo*)&catInfo.finderInfo;
2093 finfo->fileType = type ;
2094 finfo->fileCreator = creator ;
2095 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
2096 return true ;
2097 }
2098 }
2099 return false ;
2100 }
2101
2102 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
2103 {
2104 FSRef fsRef ;
2105 FSCatalogInfo catInfo;
2106 FileInfo *finfo ;
2107
2108 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2109 {
2110 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2111 {
2112 finfo = (FileInfo*)&catInfo.finderInfo;
2113 *type = finfo->fileType ;
2114 *creator = finfo->fileCreator ;
2115 return true ;
2116 }
2117 }
2118 return false ;
2119 }
2120
2121 bool wxFileName::MacSetDefaultTypeAndCreator()
2122 {
2123 wxUint32 type , creator ;
2124 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
2125 &creator ) )
2126 {
2127 return MacSetTypeAndCreator( type , creator ) ;
2128 }
2129 return false;
2130 }
2131
2132 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
2133 {
2134 MacEnsureDefaultExtensionsLoaded() ;
2135 wxString extl = ext.Lower() ;
2136 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
2137 {
2138 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
2139 {
2140 *type = gMacDefaultExtensions.Item(i).m_type ;
2141 *creator = gMacDefaultExtensions.Item(i).m_creator ;
2142 return true ;
2143 }
2144 }
2145 return false ;
2146 }
2147
2148 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
2149 {
2150 MacEnsureDefaultExtensionsLoaded() ;
2151 MacDefaultExtensionRecord rec ;
2152 rec.m_type = type ;
2153 rec.m_creator = creator ;
2154 wxStrncpy( rec.m_ext , ext.Lower().c_str() , kMacExtensionMaxLength ) ;
2155 gMacDefaultExtensions.Add( rec ) ;
2156 }
2157 #endif