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