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