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