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