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