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