Applied patch [ 1531615 ] size support for wxFileName
[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, wxString& targetFilename, wxString* arguments)
1051 {
1052 wxString path, file, ext;
1053 wxSplitPath(shortcutPath, & path, & file, & ext);
1054
1055 HRESULT hres;
1056 IShellLink* psl;
1057 bool success = false;
1058
1059 // Assume it's not a shortcut if it doesn't end with lnk
1060 if (ext.CmpNoCase(wxT("lnk"))!=0)
1061 return false;
1062
1063 // create a ShellLink object
1064 hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1065 IID_IShellLink, (LPVOID*) &psl);
1066
1067 if (SUCCEEDED(hres))
1068 {
1069 IPersistFile* ppf;
1070 hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
1071 if (SUCCEEDED(hres))
1072 {
1073 WCHAR wsz[MAX_PATH];
1074
1075 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
1076 MAX_PATH);
1077
1078 hres = ppf->Load(wsz, 0);
1079 if (SUCCEEDED(hres))
1080 {
1081 wxChar buf[2048];
1082 // Wrong prototype in early versions
1083 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1084 psl->GetPath((CHAR*) buf, 2048, NULL, SLGP_UNCPRIORITY);
1085 #else
1086 psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
1087 #endif
1088 targetFilename = wxString(buf);
1089 success = (shortcutPath != targetFilename);
1090
1091 psl->GetArguments(buf, 2048);
1092 wxString args(buf);
1093 if (!args.empty() && arguments)
1094 {
1095 *arguments = args;
1096 }
1097 }
1098 }
1099 }
1100 psl->Release();
1101 return success;
1102 }
1103 #endif
1104
1105
1106 // ----------------------------------------------------------------------------
1107 // absolute/relative paths
1108 // ----------------------------------------------------------------------------
1109
1110 bool wxFileName::IsAbsolute(wxPathFormat format) const
1111 {
1112 // if our path doesn't start with a path separator, it's not an absolute
1113 // path
1114 if ( m_relative )
1115 return false;
1116
1117 if ( !GetVolumeSeparator(format).empty() )
1118 {
1119 // this format has volumes and an absolute path must have one, it's not
1120 // enough to have the full path to bean absolute file under Windows
1121 if ( GetVolume().empty() )
1122 return false;
1123 }
1124
1125 return true;
1126 }
1127
1128 bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
1129 {
1130 wxFileName fnBase = wxFileName::DirName(pathBase, format);
1131
1132 // get cwd only once - small time saving
1133 wxString cwd = wxGetCwd();
1134 Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1135 fnBase.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1136
1137 bool withCase = IsCaseSensitive(format);
1138
1139 // we can't do anything if the files live on different volumes
1140 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
1141 {
1142 // nothing done
1143 return false;
1144 }
1145
1146 // same drive, so we don't need our volume
1147 m_volume.clear();
1148
1149 // remove common directories starting at the top
1150 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
1151 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
1152 {
1153 m_dirs.RemoveAt(0);
1154 fnBase.m_dirs.RemoveAt(0);
1155 }
1156
1157 // add as many ".." as needed
1158 size_t count = fnBase.m_dirs.GetCount();
1159 for ( size_t i = 0; i < count; i++ )
1160 {
1161 m_dirs.Insert(wxT(".."), 0u);
1162 }
1163
1164 if ( format == wxPATH_UNIX || format == wxPATH_DOS )
1165 {
1166 // a directory made relative with respect to itself is '.' under Unix
1167 // and DOS, by definition (but we don't have to insert "./" for the
1168 // files)
1169 if ( m_dirs.IsEmpty() && IsDir() )
1170 {
1171 m_dirs.Add(_T('.'));
1172 }
1173 }
1174
1175 m_relative = true;
1176
1177 // we were modified
1178 return true;
1179 }
1180
1181 // ----------------------------------------------------------------------------
1182 // filename kind tests
1183 // ----------------------------------------------------------------------------
1184
1185 bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const
1186 {
1187 wxFileName fn1 = *this,
1188 fn2 = filepath;
1189
1190 // get cwd only once - small time saving
1191 wxString cwd = wxGetCwd();
1192 fn1.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1193 fn2.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1194
1195 if ( fn1.GetFullPath() == fn2.GetFullPath() )
1196 return true;
1197
1198 // TODO: compare inodes for Unix, this works even when filenames are
1199 // different but files are the same (symlinks) (VZ)
1200
1201 return false;
1202 }
1203
1204 /* static */
1205 bool wxFileName::IsCaseSensitive( wxPathFormat format )
1206 {
1207 // only Unix filenames are truely case-sensitive
1208 return GetFormat(format) == wxPATH_UNIX;
1209 }
1210
1211 /* static */
1212 wxString wxFileName::GetForbiddenChars(wxPathFormat format)
1213 {
1214 // Inits to forbidden characters that are common to (almost) all platforms.
1215 wxString strForbiddenChars = wxT("*?");
1216
1217 // If asserts, wxPathFormat has been changed. In case of a new path format
1218 // addition, the following code might have to be updated.
1219 wxCOMPILE_TIME_ASSERT(wxPATH_MAX == 5, wxPathFormatChanged);
1220 switch ( GetFormat(format) )
1221 {
1222 default :
1223 wxFAIL_MSG( wxT("Unknown path format") );
1224 // !! Fall through !!
1225
1226 case wxPATH_UNIX:
1227 break;
1228
1229 case wxPATH_MAC:
1230 // On a Mac even names with * and ? are allowed (Tested with OS
1231 // 9.2.1 and OS X 10.2.5)
1232 strForbiddenChars = wxEmptyString;
1233 break;
1234
1235 case wxPATH_DOS:
1236 strForbiddenChars += wxT("\\/:\"<>|");
1237 break;
1238
1239 case wxPATH_VMS:
1240 break;
1241 }
1242
1243 return strForbiddenChars;
1244 }
1245
1246 /* static */
1247 wxString wxFileName::GetVolumeSeparator(wxPathFormat WXUNUSED_IN_WINCE(format))
1248 {
1249 #ifdef __WXWINCE__
1250 return wxEmptyString;
1251 #else
1252 wxString sepVol;
1253
1254 if ( (GetFormat(format) == wxPATH_DOS) ||
1255 (GetFormat(format) == wxPATH_VMS) )
1256 {
1257 sepVol = wxFILE_SEP_DSK;
1258 }
1259 //else: leave empty
1260
1261 return sepVol;
1262 #endif
1263 }
1264
1265 /* static */
1266 wxString wxFileName::GetPathSeparators(wxPathFormat format)
1267 {
1268 wxString seps;
1269 switch ( GetFormat(format) )
1270 {
1271 case wxPATH_DOS:
1272 // accept both as native APIs do but put the native one first as
1273 // this is the one we use in GetFullPath()
1274 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
1275 break;
1276
1277 default:
1278 wxFAIL_MSG( _T("Unknown wxPATH_XXX style") );
1279 // fall through
1280
1281 case wxPATH_UNIX:
1282 seps = wxFILE_SEP_PATH_UNIX;
1283 break;
1284
1285 case wxPATH_MAC:
1286 seps = wxFILE_SEP_PATH_MAC;
1287 break;
1288
1289 case wxPATH_VMS:
1290 seps = wxFILE_SEP_PATH_VMS;
1291 break;
1292 }
1293
1294 return seps;
1295 }
1296
1297 /* static */
1298 wxString wxFileName::GetPathTerminators(wxPathFormat format)
1299 {
1300 format = GetFormat(format);
1301
1302 // under VMS the end of the path is ']', not the path separator used to
1303 // separate the components
1304 return format == wxPATH_VMS ? wxString(_T(']')) : GetPathSeparators(format);
1305 }
1306
1307 /* static */
1308 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
1309 {
1310 // wxString::Find() doesn't work as expected with NUL - it will always find
1311 // it, so test for it separately
1312 return ch != _T('\0') && GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
1313 }
1314
1315 // ----------------------------------------------------------------------------
1316 // path components manipulation
1317 // ----------------------------------------------------------------------------
1318
1319 /* static */ bool wxFileName::IsValidDirComponent(const wxString& dir)
1320 {
1321 if ( dir.empty() )
1322 {
1323 wxFAIL_MSG( _T("empty directory passed to wxFileName::InsertDir()") );
1324
1325 return false;
1326 }
1327
1328 const size_t len = dir.length();
1329 for ( size_t n = 0; n < len; n++ )
1330 {
1331 if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
1332 {
1333 wxFAIL_MSG( _T("invalid directory component in wxFileName") );
1334
1335 return false;
1336 }
1337 }
1338
1339 return true;
1340 }
1341
1342 void wxFileName::AppendDir( const wxString& dir )
1343 {
1344 if ( IsValidDirComponent(dir) )
1345 m_dirs.Add( dir );
1346 }
1347
1348 void wxFileName::PrependDir( const wxString& dir )
1349 {
1350 InsertDir(0, dir);
1351 }
1352
1353 void wxFileName::InsertDir(size_t before, const wxString& dir)
1354 {
1355 if ( IsValidDirComponent(dir) )
1356 m_dirs.Insert(dir, before);
1357 }
1358
1359 void wxFileName::RemoveDir(size_t pos)
1360 {
1361 m_dirs.RemoveAt(pos);
1362 }
1363
1364 // ----------------------------------------------------------------------------
1365 // accessors
1366 // ----------------------------------------------------------------------------
1367
1368 void wxFileName::SetFullName(const wxString& fullname)
1369 {
1370 SplitPath(fullname, NULL /* no volume */, NULL /* no path */,
1371 &m_name, &m_ext, &m_hasExt);
1372 }
1373
1374 wxString wxFileName::GetFullName() const
1375 {
1376 wxString fullname = m_name;
1377 if ( m_hasExt )
1378 {
1379 fullname << wxFILE_SEP_EXT << m_ext;
1380 }
1381
1382 return fullname;
1383 }
1384
1385 wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
1386 {
1387 format = GetFormat( format );
1388
1389 wxString fullpath;
1390
1391 // return the volume with the path as well if requested
1392 if ( flags & wxPATH_GET_VOLUME )
1393 {
1394 fullpath += wxGetVolumeString(GetVolume(), format);
1395 }
1396
1397 // the leading character
1398 switch ( format )
1399 {
1400 case wxPATH_MAC:
1401 if ( m_relative )
1402 fullpath += wxFILE_SEP_PATH_MAC;
1403 break;
1404
1405 case wxPATH_DOS:
1406 if ( !m_relative )
1407 fullpath += wxFILE_SEP_PATH_DOS;
1408 break;
1409
1410 default:
1411 wxFAIL_MSG( wxT("Unknown path format") );
1412 // fall through
1413
1414 case wxPATH_UNIX:
1415 if ( !m_relative )
1416 {
1417 // normally the absolute file names start with a slash
1418 // with one exception: the ones like "~/foo.bar" don't
1419 // have it
1420 if ( m_dirs.IsEmpty() || m_dirs[0u] != _T('~') )
1421 {
1422 fullpath += wxFILE_SEP_PATH_UNIX;
1423 }
1424 }
1425 break;
1426
1427 case wxPATH_VMS:
1428 // no leading character here but use this place to unset
1429 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1430 // as, if I understand correctly, there should never be a dot
1431 // before the closing bracket
1432 flags &= ~wxPATH_GET_SEPARATOR;
1433 }
1434
1435 if ( m_dirs.empty() )
1436 {
1437 // there is nothing more
1438 return fullpath;
1439 }
1440
1441 // then concatenate all the path components using the path separator
1442 if ( format == wxPATH_VMS )
1443 {
1444 fullpath += wxT('[');
1445 }
1446
1447 const size_t dirCount = m_dirs.GetCount();
1448 for ( size_t i = 0; i < dirCount; i++ )
1449 {
1450 switch (format)
1451 {
1452 case wxPATH_MAC:
1453 if ( m_dirs[i] == wxT(".") )
1454 {
1455 // skip appending ':', this shouldn't be done in this
1456 // case as "::" is interpreted as ".." under Unix
1457 continue;
1458 }
1459
1460 // convert back from ".." to nothing
1461 if ( !m_dirs[i].IsSameAs(wxT("..")) )
1462 fullpath += m_dirs[i];
1463 break;
1464
1465 default:
1466 wxFAIL_MSG( wxT("Unexpected path format") );
1467 // still fall through
1468
1469 case wxPATH_DOS:
1470 case wxPATH_UNIX:
1471 fullpath += m_dirs[i];
1472 break;
1473
1474 case wxPATH_VMS:
1475 // TODO: What to do with ".." under VMS
1476
1477 // convert back from ".." to nothing
1478 if ( !m_dirs[i].IsSameAs(wxT("..")) )
1479 fullpath += m_dirs[i];
1480 break;
1481 }
1482
1483 if ( (flags & wxPATH_GET_SEPARATOR) || (i != dirCount - 1) )
1484 fullpath += GetPathSeparator(format);
1485 }
1486
1487 if ( format == wxPATH_VMS )
1488 {
1489 fullpath += wxT(']');
1490 }
1491
1492 return fullpath;
1493 }
1494
1495 wxString wxFileName::GetFullPath( wxPathFormat format ) const
1496 {
1497 // we already have a function to get the path
1498 wxString fullpath = GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR,
1499 format);
1500
1501 // now just add the file name and extension to it
1502 fullpath += GetFullName();
1503
1504 return fullpath;
1505 }
1506
1507 // Return the short form of the path (returns identity on non-Windows platforms)
1508 wxString wxFileName::GetShortPath() const
1509 {
1510 wxString path(GetFullPath());
1511
1512 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1513 DWORD sz = ::GetShortPathName(path, NULL, 0);
1514 if ( sz != 0 )
1515 {
1516 wxString pathOut;
1517 if ( ::GetShortPathName
1518 (
1519 path,
1520 wxStringBuffer(pathOut, sz),
1521 sz
1522 ) != 0 )
1523 {
1524 return pathOut;
1525 }
1526 }
1527 #endif // Windows
1528
1529 return path;
1530 }
1531
1532 // Return the long form of the path (returns identity on non-Windows platforms)
1533 wxString wxFileName::GetLongPath() const
1534 {
1535 wxString pathOut,
1536 path = GetFullPath();
1537
1538 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1539
1540 #if wxUSE_DYNAMIC_LOADER
1541 typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
1542
1543 // this is MT-safe as in the worst case we're going to resolve the function
1544 // twice -- but as the result is the same in both threads, it's ok
1545 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
1546 if ( !s_pfnGetLongPathName )
1547 {
1548 static bool s_triedToLoad = false;
1549
1550 if ( !s_triedToLoad )
1551 {
1552 s_triedToLoad = true;
1553
1554 wxDynamicLibrary dllKernel(_T("kernel32"));
1555
1556 const wxChar* GetLongPathName = _T("GetLongPathName")
1557 #if wxUSE_UNICODE
1558 _T("W");
1559 #else // ANSI
1560 _T("A");
1561 #endif // Unicode/ANSI
1562
1563 if ( dllKernel.HasSymbol(GetLongPathName) )
1564 {
1565 s_pfnGetLongPathName = (GET_LONG_PATH_NAME)
1566 dllKernel.GetSymbol(GetLongPathName);
1567 }
1568
1569 // note that kernel32.dll can be unloaded, it stays in memory
1570 // anyhow as all Win32 programs link to it and so it's safe to call
1571 // GetLongPathName() even after unloading it
1572 }
1573 }
1574
1575 if ( s_pfnGetLongPathName )
1576 {
1577 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
1578 if ( dwSize > 0 )
1579 {
1580 if ( (*s_pfnGetLongPathName)
1581 (
1582 path,
1583 wxStringBuffer(pathOut, dwSize),
1584 dwSize
1585 ) != 0 )
1586 {
1587 return pathOut;
1588 }
1589 }
1590 }
1591 #endif // wxUSE_DYNAMIC_LOADER
1592
1593 // The OS didn't support GetLongPathName, or some other error.
1594 // We need to call FindFirstFile on each component in turn.
1595
1596 WIN32_FIND_DATA findFileData;
1597 HANDLE hFind;
1598
1599 if ( HasVolume() )
1600 pathOut = GetVolume() +
1601 GetVolumeSeparator(wxPATH_DOS) +
1602 GetPathSeparator(wxPATH_DOS);
1603 else
1604 pathOut = wxEmptyString;
1605
1606 wxArrayString dirs = GetDirs();
1607 dirs.Add(GetFullName());
1608
1609 wxString tmpPath;
1610
1611 size_t count = dirs.GetCount();
1612 for ( size_t i = 0; i < count; i++ )
1613 {
1614 // We're using pathOut to collect the long-name path, but using a
1615 // temporary for appending the last path component which may be
1616 // short-name
1617 tmpPath = pathOut + dirs[i];
1618
1619 if ( tmpPath.empty() )
1620 continue;
1621
1622 // can't see this being necessary? MF
1623 if ( tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
1624 {
1625 // Can't pass a drive and root dir to FindFirstFile,
1626 // so continue to next dir
1627 tmpPath += wxFILE_SEP_PATH;
1628 pathOut = tmpPath;
1629 continue;
1630 }
1631
1632 hFind = ::FindFirstFile(tmpPath, &findFileData);
1633 if (hFind == INVALID_HANDLE_VALUE)
1634 {
1635 // Error: most likely reason is that path doesn't exist, so
1636 // append any unprocessed parts and return
1637 for ( i += 1; i < count; i++ )
1638 tmpPath += wxFILE_SEP_PATH + dirs[i];
1639
1640 return tmpPath;
1641 }
1642
1643 pathOut += findFileData.cFileName;
1644 if ( (i < (count-1)) )
1645 pathOut += wxFILE_SEP_PATH;
1646
1647 ::FindClose(hFind);
1648 }
1649 #else // !Win32
1650 pathOut = path;
1651 #endif // Win32/!Win32
1652
1653 return pathOut;
1654 }
1655
1656 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
1657 {
1658 if (format == wxPATH_NATIVE)
1659 {
1660 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
1661 format = wxPATH_DOS;
1662 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1663 format = wxPATH_MAC;
1664 #elif defined(__VMS)
1665 format = wxPATH_VMS;
1666 #else
1667 format = wxPATH_UNIX;
1668 #endif
1669 }
1670 return format;
1671 }
1672
1673 // ----------------------------------------------------------------------------
1674 // path splitting function
1675 // ----------------------------------------------------------------------------
1676
1677 /* static */
1678 void
1679 wxFileName::SplitVolume(const wxString& fullpathWithVolume,
1680 wxString *pstrVolume,
1681 wxString *pstrPath,
1682 wxPathFormat format)
1683 {
1684 format = GetFormat(format);
1685
1686 wxString fullpath = fullpathWithVolume;
1687
1688 // special Windows UNC paths hack: transform \\share\path into share:path
1689 if ( format == wxPATH_DOS )
1690 {
1691 if ( fullpath.length() >= 4 &&
1692 fullpath[0u] == wxFILE_SEP_PATH_DOS &&
1693 fullpath[1u] == wxFILE_SEP_PATH_DOS )
1694 {
1695 fullpath.erase(0, 2);
1696
1697 size_t posFirstSlash =
1698 fullpath.find_first_of(GetPathTerminators(format));
1699 if ( posFirstSlash != wxString::npos )
1700 {
1701 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
1702
1703 // UNC paths are always absolute, right? (FIXME)
1704 fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
1705 }
1706 }
1707 }
1708
1709 // We separate the volume here
1710 if ( format == wxPATH_DOS || format == wxPATH_VMS )
1711 {
1712 wxString sepVol = GetVolumeSeparator(format);
1713
1714 size_t posFirstColon = fullpath.find_first_of(sepVol);
1715 if ( posFirstColon != wxString::npos )
1716 {
1717 if ( pstrVolume )
1718 {
1719 *pstrVolume = fullpath.Left(posFirstColon);
1720 }
1721
1722 // remove the volume name and the separator from the full path
1723 fullpath.erase(0, posFirstColon + sepVol.length());
1724 }
1725 }
1726
1727 if ( pstrPath )
1728 *pstrPath = fullpath;
1729 }
1730
1731 /* static */
1732 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
1733 wxString *pstrVolume,
1734 wxString *pstrPath,
1735 wxString *pstrName,
1736 wxString *pstrExt,
1737 bool *hasExt,
1738 wxPathFormat format)
1739 {
1740 format = GetFormat(format);
1741
1742 wxString fullpath;
1743 SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
1744
1745 // find the positions of the last dot and last path separator in the path
1746 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
1747 size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
1748
1749 // check whether this dot occurs at the very beginning of a path component
1750 if ( (posLastDot != wxString::npos) &&
1751 (posLastDot == 0 ||
1752 IsPathSeparator(fullpath[posLastDot - 1]) ||
1753 (format == wxPATH_VMS && fullpath[posLastDot - 1] == _T(']'))) )
1754 {
1755 // dot may be (and commonly -- at least under Unix -- is) the first
1756 // character of the filename, don't treat the entire filename as
1757 // extension in this case
1758 posLastDot = wxString::npos;
1759 }
1760
1761 // if we do have a dot and a slash, check that the dot is in the name part
1762 if ( (posLastDot != wxString::npos) &&
1763 (posLastSlash != wxString::npos) &&
1764 (posLastDot < posLastSlash) )
1765 {
1766 // the dot is part of the path, not the start of the extension
1767 posLastDot = wxString::npos;
1768 }
1769
1770 // now fill in the variables provided by user
1771 if ( pstrPath )
1772 {
1773 if ( posLastSlash == wxString::npos )
1774 {
1775 // no path at all
1776 pstrPath->Empty();
1777 }
1778 else
1779 {
1780 // take everything up to the path separator but take care to make
1781 // the path equal to something like '/', not empty, for the files
1782 // immediately under root directory
1783 size_t len = posLastSlash;
1784
1785 // this rule does not apply to mac since we do not start with colons (sep)
1786 // except for relative paths
1787 if ( !len && format != wxPATH_MAC)
1788 len++;
1789
1790 *pstrPath = fullpath.Left(len);
1791
1792 // special VMS hack: remove the initial bracket
1793 if ( format == wxPATH_VMS )
1794 {
1795 if ( (*pstrPath)[0u] == _T('[') )
1796 pstrPath->erase(0, 1);
1797 }
1798 }
1799 }
1800
1801 if ( pstrName )
1802 {
1803 // take all characters starting from the one after the last slash and
1804 // up to, but excluding, the last dot
1805 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
1806 size_t count;
1807 if ( posLastDot == wxString::npos )
1808 {
1809 // take all until the end
1810 count = wxString::npos;
1811 }
1812 else if ( posLastSlash == wxString::npos )
1813 {
1814 count = posLastDot;
1815 }
1816 else // have both dot and slash
1817 {
1818 count = posLastDot - posLastSlash - 1;
1819 }
1820
1821 *pstrName = fullpath.Mid(nStart, count);
1822 }
1823
1824 // finally deal with the extension here: we have an added complication that
1825 // extension may be empty (but present) as in "foo." where trailing dot
1826 // indicates the empty extension at the end -- and hence we must remember
1827 // that we have it independently of pstrExt
1828 if ( posLastDot == wxString::npos )
1829 {
1830 // no extension
1831 if ( pstrExt )
1832 pstrExt->clear();
1833 if ( hasExt )
1834 *hasExt = false;
1835 }
1836 else
1837 {
1838 // take everything after the dot
1839 if ( pstrExt )
1840 *pstrExt = fullpath.Mid(posLastDot + 1);
1841 if ( hasExt )
1842 *hasExt = true;
1843 }
1844 }
1845
1846 /* static */
1847 void wxFileName::SplitPath(const wxString& fullpath,
1848 wxString *path,
1849 wxString *name,
1850 wxString *ext,
1851 wxPathFormat format)
1852 {
1853 wxString volume;
1854 SplitPath(fullpath, &volume, path, name, ext, format);
1855
1856 if ( path )
1857 {
1858 path->Prepend(wxGetVolumeString(volume, format));
1859 }
1860 }
1861
1862 // ----------------------------------------------------------------------------
1863 // time functions
1864 // ----------------------------------------------------------------------------
1865
1866 #if wxUSE_DATETIME
1867
1868 bool wxFileName::SetTimes(const wxDateTime *dtAccess,
1869 const wxDateTime *dtMod,
1870 const wxDateTime *dtCreate)
1871 {
1872 #if defined(__WIN32__)
1873 if ( IsDir() )
1874 {
1875 // VZ: please let me know how to do this if you can
1876 wxFAIL_MSG( _T("SetTimes() not implemented for the directories") );
1877 }
1878 else // file
1879 {
1880 wxFileHandle fh(GetFullPath(), wxFileHandle::Write);
1881 if ( fh.IsOk() )
1882 {
1883 FILETIME ftAccess, ftCreate, ftWrite;
1884
1885 if ( dtCreate )
1886 ConvertWxToFileTime(&ftCreate, *dtCreate);
1887 if ( dtAccess )
1888 ConvertWxToFileTime(&ftAccess, *dtAccess);
1889 if ( dtMod )
1890 ConvertWxToFileTime(&ftWrite, *dtMod);
1891
1892 if ( ::SetFileTime(fh,
1893 dtCreate ? &ftCreate : NULL,
1894 dtAccess ? &ftAccess : NULL,
1895 dtMod ? &ftWrite : NULL) )
1896 {
1897 return true;
1898 }
1899 }
1900 }
1901 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
1902 wxUnusedVar(dtCreate);
1903
1904 if ( !dtAccess && !dtMod )
1905 {
1906 // can't modify the creation time anyhow, don't try
1907 return true;
1908 }
1909
1910 // if dtAccess or dtMod is not specified, use the other one (which must be
1911 // non NULL because of the test above) for both times
1912 utimbuf utm;
1913 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
1914 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
1915 if ( utime(GetFullPath().fn_str(), &utm) == 0 )
1916 {
1917 return true;
1918 }
1919 #else // other platform
1920 wxUnusedVar(dtAccess);
1921 wxUnusedVar(dtMod);
1922 wxUnusedVar(dtCreate);
1923 #endif // platforms
1924
1925 wxLogSysError(_("Failed to modify file times for '%s'"),
1926 GetFullPath().c_str());
1927
1928 return false;
1929 }
1930
1931 bool wxFileName::Touch()
1932 {
1933 #if defined(__UNIX_LIKE__)
1934 // under Unix touching file is simple: just pass NULL to utime()
1935 if ( utime(GetFullPath().fn_str(), NULL) == 0 )
1936 {
1937 return true;
1938 }
1939
1940 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
1941
1942 return false;
1943 #else // other platform
1944 wxDateTime dtNow = wxDateTime::Now();
1945
1946 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
1947 #endif // platforms
1948 }
1949
1950 bool wxFileName::GetTimes(wxDateTime *dtAccess,
1951 wxDateTime *dtMod,
1952 wxDateTime *dtCreate) const
1953 {
1954 #if defined(__WIN32__)
1955 // we must use different methods for the files and directories under
1956 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
1957 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
1958 // not 9x
1959 bool ok;
1960 FILETIME ftAccess, ftCreate, ftWrite;
1961 if ( IsDir() )
1962 {
1963 // implemented in msw/dir.cpp
1964 extern bool wxGetDirectoryTimes(const wxString& dirname,
1965 FILETIME *, FILETIME *, FILETIME *);
1966
1967 // we should pass the path without the trailing separator to
1968 // wxGetDirectoryTimes()
1969 ok = wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME),
1970 &ftAccess, &ftCreate, &ftWrite);
1971 }
1972 else // file
1973 {
1974 wxFileHandle fh(GetFullPath(), wxFileHandle::Read);
1975 if ( fh.IsOk() )
1976 {
1977 ok = ::GetFileTime(fh,
1978 dtCreate ? &ftCreate : NULL,
1979 dtAccess ? &ftAccess : NULL,
1980 dtMod ? &ftWrite : NULL) != 0;
1981 }
1982 else
1983 {
1984 ok = false;
1985 }
1986 }
1987
1988 if ( ok )
1989 {
1990 if ( dtCreate )
1991 ConvertFileTimeToWx(dtCreate, ftCreate);
1992 if ( dtAccess )
1993 ConvertFileTimeToWx(dtAccess, ftAccess);
1994 if ( dtMod )
1995 ConvertFileTimeToWx(dtMod, ftWrite);
1996
1997 return true;
1998 }
1999 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2000 wxStructStat stBuf;
2001 if ( wxStat( GetFullPath().c_str(), &stBuf) == 0 )
2002 {
2003 if ( dtAccess )
2004 dtAccess->Set(stBuf.st_atime);
2005 if ( dtMod )
2006 dtMod->Set(stBuf.st_mtime);
2007 if ( dtCreate )
2008 dtCreate->Set(stBuf.st_ctime);
2009
2010 return true;
2011 }
2012 #else // other platform
2013 wxUnusedVar(dtAccess);
2014 wxUnusedVar(dtMod);
2015 wxUnusedVar(dtCreate);
2016 #endif // platforms
2017
2018 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2019 GetFullPath().c_str());
2020
2021 return false;
2022 }
2023
2024 #endif // wxUSE_DATETIME
2025
2026
2027 // ----------------------------------------------------------------------------
2028 // file size functions
2029 // ----------------------------------------------------------------------------
2030
2031 /* static */
2032 wxULongLong wxFileName::GetSize(const wxString &filename)
2033 {
2034 if (!wxFileExists(filename))
2035 return wxInvalidSize;
2036
2037 #ifdef __WIN32__
2038 wxFileHandle f(filename, wxFileHandle::Read);
2039 if (!f.IsOk())
2040 return wxInvalidSize;
2041
2042 DWORD lpFileSizeHigh;
2043 DWORD ret = GetFileSize(f, &lpFileSizeHigh);
2044 if (ret == INVALID_FILE_SIZE)
2045 return wxInvalidSize;
2046
2047 // compose the low-order and high-order byte sizes
2048 return wxULongLong(ret | (lpFileSizeHigh << sizeof(WORD)*2));
2049
2050 #else // ! __WIN32__
2051
2052 wxStructStat st;
2053 #ifndef wxNEED_WX_UNISTD_H
2054 if (wxStat( filename.fn_str() , &st) != 0)
2055 #else
2056 if (wxStat( filename, &st) != 0)
2057 #endif
2058 return wxInvalidSize;
2059 return wxULongLong(st.st_size);
2060 #endif
2061 }
2062
2063 /* static */
2064 wxString wxFileName::GetHumanReadableSize(const wxULongLong &bs,
2065 const wxString &nullsize,
2066 int precision)
2067 {
2068 static const double KILOBYTESIZE = 1024.0;
2069 static const double MEGABYTESIZE = 1024.0*KILOBYTESIZE;
2070 static const double GIGABYTESIZE = 1024.0*MEGABYTESIZE;
2071 static const double TERABYTESIZE = 1024.0*GIGABYTESIZE;
2072
2073 if (bs == 0 || bs == wxInvalidSize)
2074 return nullsize;
2075
2076 double bytesize = bs.ToDouble();
2077 if (bytesize < KILOBYTESIZE)
2078 return wxString::Format(_("%s B"), bs.ToString().c_str());
2079 if (bytesize < MEGABYTESIZE)
2080 return wxString::Format(_("%.*f kB"), precision, bytesize/KILOBYTESIZE);
2081 if (bytesize < GIGABYTESIZE)
2082 return wxString::Format(_("%.*f MB"), precision, bytesize/MEGABYTESIZE);
2083 if (bytesize < TERABYTESIZE)
2084 return wxString::Format(_("%.*f GB"), precision, bytesize/GIGABYTESIZE);
2085
2086 return wxString::Format(_("%.*f TB"), precision, bytesize/TERABYTESIZE);
2087 }
2088
2089 wxULongLong wxFileName::GetSize() const
2090 {
2091 return GetSize(GetFullPath());
2092 }
2093
2094 wxString wxFileName::GetHumanReadableSize(const wxString &failmsg, int precision) const
2095 {
2096 return GetHumanReadableSize(GetSize(), failmsg, precision);
2097 }
2098
2099
2100 // ----------------------------------------------------------------------------
2101 // Mac-specific functions
2102 // ----------------------------------------------------------------------------
2103
2104 #ifdef __WXMAC__
2105
2106 const short kMacExtensionMaxLength = 16 ;
2107 class MacDefaultExtensionRecord
2108 {
2109 public :
2110 MacDefaultExtensionRecord()
2111 {
2112 m_ext[0] = 0 ;
2113 m_type = m_creator = 0 ;
2114 }
2115 MacDefaultExtensionRecord( const MacDefaultExtensionRecord& from )
2116 {
2117 wxStrcpy( m_ext , from.m_ext ) ;
2118 m_type = from.m_type ;
2119 m_creator = from.m_creator ;
2120 }
2121 MacDefaultExtensionRecord( const wxChar * extension , OSType type , OSType creator )
2122 {
2123 wxStrncpy( m_ext , extension , kMacExtensionMaxLength ) ;
2124 m_ext[kMacExtensionMaxLength] = 0 ;
2125 m_type = type ;
2126 m_creator = creator ;
2127 }
2128 wxChar m_ext[kMacExtensionMaxLength] ;
2129 OSType m_type ;
2130 OSType m_creator ;
2131 } ;
2132
2133 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray) ;
2134
2135 bool gMacDefaultExtensionsInited = false ;
2136
2137 #include "wx/arrimpl.cpp"
2138
2139 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray) ;
2140
2141 MacDefaultExtensionArray gMacDefaultExtensions ;
2142
2143 // load the default extensions
2144 MacDefaultExtensionRecord gDefaults[] =
2145 {
2146 MacDefaultExtensionRecord( wxT("txt") , 'TEXT' , 'ttxt' ) ,
2147 MacDefaultExtensionRecord( wxT("tif") , 'TIFF' , '****' ) ,
2148 MacDefaultExtensionRecord( wxT("jpg") , 'JPEG' , '****' ) ,
2149 } ;
2150
2151 static void MacEnsureDefaultExtensionsLoaded()
2152 {
2153 if ( !gMacDefaultExtensionsInited )
2154 {
2155 // we could load the pc exchange prefs here too
2156 for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
2157 {
2158 gMacDefaultExtensions.Add( gDefaults[i] ) ;
2159 }
2160 gMacDefaultExtensionsInited = true ;
2161 }
2162 }
2163
2164 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
2165 {
2166 FSRef fsRef ;
2167 FSCatalogInfo catInfo;
2168 FileInfo *finfo ;
2169
2170 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2171 {
2172 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2173 {
2174 finfo = (FileInfo*)&catInfo.finderInfo;
2175 finfo->fileType = type ;
2176 finfo->fileCreator = creator ;
2177 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
2178 return true ;
2179 }
2180 }
2181 return false ;
2182 }
2183
2184 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
2185 {
2186 FSRef fsRef ;
2187 FSCatalogInfo catInfo;
2188 FileInfo *finfo ;
2189
2190 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2191 {
2192 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2193 {
2194 finfo = (FileInfo*)&catInfo.finderInfo;
2195 *type = finfo->fileType ;
2196 *creator = finfo->fileCreator ;
2197 return true ;
2198 }
2199 }
2200 return false ;
2201 }
2202
2203 bool wxFileName::MacSetDefaultTypeAndCreator()
2204 {
2205 wxUint32 type , creator ;
2206 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
2207 &creator ) )
2208 {
2209 return MacSetTypeAndCreator( type , creator ) ;
2210 }
2211 return false;
2212 }
2213
2214 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
2215 {
2216 MacEnsureDefaultExtensionsLoaded() ;
2217 wxString extl = ext.Lower() ;
2218 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
2219 {
2220 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
2221 {
2222 *type = gMacDefaultExtensions.Item(i).m_type ;
2223 *creator = gMacDefaultExtensions.Item(i).m_creator ;
2224 return true ;
2225 }
2226 }
2227 return false ;
2228 }
2229
2230 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
2231 {
2232 MacEnsureDefaultExtensionsLoaded() ;
2233 MacDefaultExtensionRecord rec ;
2234 rec.m_type = type ;
2235 rec.m_creator = creator ;
2236 wxStrncpy( rec.m_ext , ext.Lower().c_str() , kMacExtensionMaxLength ) ;
2237 gMacDefaultExtensions.Add( rec ) ;
2238 }
2239 #endif