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