]> git.saurik.com Git - wxWidgets.git/blob - src/common/filename.cpp
Implement wx{File,Dir}Exists() in terms of wxFileName methods.
[wxWidgets.git] / src / common / filename.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/filename.cpp
3 // Purpose: wxFileName - encapsulates a file path
4 // Author: Robert Roebling, Vadim Zeitlin
5 // Modified by:
6 // Created: 28.12.2000
7 // RCS-ID: $Id$
8 // Copyright: (c) 2000 Robert Roebling
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 /*
13 Here are brief descriptions of the filename formats supported by this class:
14
15 wxPATH_UNIX: standard Unix format, used under Darwin as well, absolute file
16 names have the form:
17 /dir1/dir2/.../dirN/filename, "." and ".." stand for the
18 current and parent directory respectively, "~" is parsed as the
19 user HOME and "~username" as the HOME of that user
20
21 wxPATH_DOS: DOS/Windows format, absolute file names have the form:
22 drive:\dir1\dir2\...\dirN\filename.ext where drive is a single
23 letter. "." and ".." as for Unix but no "~".
24
25 There are also UNC names of the form \\share\fullpath
26
27 wxPATH_MAC: Mac OS 8/9 and Mac OS X under CodeWarrior 7 format, absolute file
28 names have the form
29 volume:dir1:...:dirN:filename
30 and the relative file names are either
31 :dir1:...:dirN:filename
32 or just
33 filename
34 (although :filename works as well).
35 Since the volume is just part of the file path, it is not
36 treated like a separate entity as it is done under DOS and
37 VMS, it is just treated as another dir.
38
39 wxPATH_VMS: VMS native format, absolute file names have the form
40 <device>:[dir1.dir2.dir3]file.txt
41 or
42 <device>:[000000.dir1.dir2.dir3]file.txt
43
44 the <device> is the physical device (i.e. disk). 000000 is the
45 root directory on the device which can be omitted.
46
47 Note that VMS uses different separators unlike Unix:
48 : always after the device. If the path does not contain : than
49 the default (the device of the current directory) is assumed.
50 [ start of directory specification
51 . separator between directory and subdirectory
52 ] between directory and file
53 */
54
55 // ============================================================================
56 // declarations
57 // ============================================================================
58
59 // ----------------------------------------------------------------------------
60 // headers
61 // ----------------------------------------------------------------------------
62
63 // For compilers that support precompilation, includes "wx.h".
64 #include "wx/wxprec.h"
65
66 #ifdef __BORLANDC__
67 #pragma hdrstop
68 #endif
69
70 #ifndef WX_PRECOMP
71 #ifdef __WXMSW__
72 #include "wx/msw/wrapwin.h" // For GetShort/LongPathName
73 #endif
74 #include "wx/dynarray.h"
75 #include "wx/intl.h"
76 #include "wx/log.h"
77 #include "wx/utils.h"
78 #include "wx/crt.h"
79 #endif
80
81 #include "wx/filename.h"
82 #include "wx/private/filename.h"
83 #include "wx/tokenzr.h"
84 #include "wx/config.h" // for wxExpandEnvVars
85 #include "wx/dynlib.h"
86 #include "wx/dir.h"
87
88 #if defined(__WIN32__) && defined(__MINGW32__)
89 #include "wx/msw/gccpriv.h"
90 #endif
91
92 #ifdef __WXWINCE__
93 #include "wx/msw/private.h"
94 #endif
95
96 #if defined(__WXMAC__)
97 #include "wx/osx/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 #if wxUSE_LONGLONG
144 extern const wxULongLong wxInvalidSize = (unsigned)-1;
145 #endif // wxUSE_LONGLONG
146
147 namespace
148 {
149
150 // ----------------------------------------------------------------------------
151 // private classes
152 // ----------------------------------------------------------------------------
153
154 // small helper class which opens and closes the file - we use it just to get
155 // a file handle for the given file name to pass it to some Win32 API function
156 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
157
158 class wxFileHandle
159 {
160 public:
161 enum OpenMode
162 {
163 ReadAttr,
164 WriteAttr
165 };
166
167 wxFileHandle(const wxString& filename, OpenMode mode, int flags = 0)
168 {
169 // be careful and use FILE_{READ,WRITE}_ATTRIBUTES here instead of the
170 // usual GENERIC_{READ,WRITE} as we don't want the file access time to
171 // be changed when we open it because this class is used for setting
172 // access time (see #10567)
173 m_hFile = ::CreateFile
174 (
175 filename.fn_str(), // name
176 mode == ReadAttr ? FILE_READ_ATTRIBUTES // access mask
177 : FILE_WRITE_ATTRIBUTES,
178 FILE_SHARE_READ | // sharing mode
179 FILE_SHARE_WRITE, // (allow everything)
180 NULL, // no secutity attr
181 OPEN_EXISTING, // creation disposition
182 flags, // flags
183 NULL // no template file
184 );
185
186 if ( m_hFile == INVALID_HANDLE_VALUE )
187 {
188 if ( mode == ReadAttr )
189 {
190 wxLogSysError(_("Failed to open '%s' for reading"),
191 filename.c_str());
192 }
193 else
194 {
195 wxLogSysError(_("Failed to open '%s' for writing"),
196 filename.c_str());
197 }
198 }
199 }
200
201 ~wxFileHandle()
202 {
203 if ( m_hFile != INVALID_HANDLE_VALUE )
204 {
205 if ( !::CloseHandle(m_hFile) )
206 {
207 wxLogSysError(_("Failed to close file handle"));
208 }
209 }
210 }
211
212 // return true only if the file could be opened successfully
213 bool IsOk() const { return m_hFile != INVALID_HANDLE_VALUE; }
214
215 // get the handle
216 operator HANDLE() const { return m_hFile; }
217
218 private:
219 HANDLE m_hFile;
220 };
221
222 #endif // __WIN32__
223
224 // ----------------------------------------------------------------------------
225 // private functions
226 // ----------------------------------------------------------------------------
227
228 #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
229
230 // convert between wxDateTime and FILETIME which is a 64-bit value representing
231 // the number of 100-nanosecond intervals since January 1, 1601.
232
233 static void ConvertFileTimeToWx(wxDateTime *dt, const FILETIME &ft)
234 {
235 FILETIME ftcopy = ft;
236 FILETIME ftLocal;
237 if ( !::FileTimeToLocalFileTime(&ftcopy, &ftLocal) )
238 {
239 wxLogLastError(wxT("FileTimeToLocalFileTime"));
240 }
241
242 SYSTEMTIME st;
243 if ( !::FileTimeToSystemTime(&ftLocal, &st) )
244 {
245 wxLogLastError(wxT("FileTimeToSystemTime"));
246 }
247
248 dt->Set(st.wDay, wxDateTime::Month(st.wMonth - 1), st.wYear,
249 st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
250 }
251
252 static void ConvertWxToFileTime(FILETIME *ft, const wxDateTime& dt)
253 {
254 SYSTEMTIME st;
255 st.wDay = dt.GetDay();
256 st.wMonth = (WORD)(dt.GetMonth() + 1);
257 st.wYear = (WORD)dt.GetYear();
258 st.wHour = dt.GetHour();
259 st.wMinute = dt.GetMinute();
260 st.wSecond = dt.GetSecond();
261 st.wMilliseconds = dt.GetMillisecond();
262
263 FILETIME ftLocal;
264 if ( !::SystemTimeToFileTime(&st, &ftLocal) )
265 {
266 wxLogLastError(wxT("SystemTimeToFileTime"));
267 }
268
269 if ( !::LocalFileTimeToFileTime(&ftLocal, ft) )
270 {
271 wxLogLastError(wxT("LocalFileTimeToFileTime"));
272 }
273 }
274
275 #endif // wxUSE_DATETIME && __WIN32__
276
277 // return a string with the volume par
278 static wxString wxGetVolumeString(const wxString& volume, wxPathFormat format)
279 {
280 wxString path;
281
282 if ( !volume.empty() )
283 {
284 format = wxFileName::GetFormat(format);
285
286 // Special Windows UNC paths hack, part 2: undo what we did in
287 // SplitPath() and make an UNC path if we have a drive which is not a
288 // single letter (hopefully the network shares can't be one letter only
289 // although I didn't find any authoritative docs on this)
290 if ( format == wxPATH_DOS && volume.length() > 1 )
291 {
292 path << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_DOS << volume;
293 }
294 else if ( format == wxPATH_DOS || format == wxPATH_VMS )
295 {
296 path << volume << wxFileName::GetVolumeSeparator(format);
297 }
298 // else ignore
299 }
300
301 return path;
302 }
303
304 // return true if the character is a DOS path separator i.e. either a slash or
305 // a backslash
306 inline bool IsDOSPathSep(wxUniChar ch)
307 {
308 return ch == wxFILE_SEP_PATH_DOS || ch == wxFILE_SEP_PATH_UNIX;
309 }
310
311 // return true if the format used is the DOS/Windows one and the string looks
312 // like a UNC path
313 static bool IsUNCPath(const wxString& path, wxPathFormat format)
314 {
315 return format == wxPATH_DOS &&
316 path.length() >= 4 && // "\\a" can't be a UNC path
317 IsDOSPathSep(path[0u]) &&
318 IsDOSPathSep(path[1u]) &&
319 !IsDOSPathSep(path[2u]);
320 }
321
322 } // anonymous namespace
323
324 // ============================================================================
325 // implementation
326 // ============================================================================
327
328 // ----------------------------------------------------------------------------
329 // wxFileName construction
330 // ----------------------------------------------------------------------------
331
332 void wxFileName::Assign( const wxFileName &filepath )
333 {
334 m_volume = filepath.GetVolume();
335 m_dirs = filepath.GetDirs();
336 m_name = filepath.GetName();
337 m_ext = filepath.GetExt();
338 m_relative = filepath.m_relative;
339 m_hasExt = filepath.m_hasExt;
340 }
341
342 void wxFileName::Assign(const wxString& volume,
343 const wxString& path,
344 const wxString& name,
345 const wxString& ext,
346 bool hasExt,
347 wxPathFormat format)
348 {
349 // we should ignore paths which look like UNC shares because we already
350 // have the volume here and the UNC notation (\\server\path) is only valid
351 // for paths which don't start with a volume, so prevent SetPath() from
352 // recognizing "\\foo\bar" in "c:\\foo\bar" as an UNC path
353 //
354 // note also that this is a rather ugly way to do what we want (passing
355 // some kind of flag telling to ignore UNC paths to SetPath() would be
356 // better) but this is the safest thing to do to avoid breaking backwards
357 // compatibility in 2.8
358 if ( IsUNCPath(path, format) )
359 {
360 // remove one of the 2 leading backslashes to ensure that it's not
361 // recognized as an UNC path by SetPath()
362 wxString pathNonUNC(path, 1, wxString::npos);
363 SetPath(pathNonUNC, format);
364 }
365 else // no UNC complications
366 {
367 SetPath(path, format);
368 }
369
370 m_volume = volume;
371 m_ext = ext;
372 m_name = name;
373
374 m_hasExt = hasExt;
375 }
376
377 void wxFileName::SetPath( const wxString& pathOrig, wxPathFormat format )
378 {
379 m_dirs.Clear();
380
381 if ( pathOrig.empty() )
382 {
383 // no path at all
384 m_relative = true;
385
386 return;
387 }
388
389 format = GetFormat( format );
390
391 // 0) deal with possible volume part first
392 wxString volume,
393 path;
394 SplitVolume(pathOrig, &volume, &path, format);
395 if ( !volume.empty() )
396 {
397 m_relative = false;
398
399 SetVolume(volume);
400 }
401
402 // 1) Determine if the path is relative or absolute.
403
404 if ( path.empty() )
405 {
406 // we had only the volume
407 return;
408 }
409
410 wxChar leadingChar = path[0u];
411
412 switch (format)
413 {
414 case wxPATH_MAC:
415 m_relative = leadingChar == wxT(':');
416
417 // We then remove a leading ":". The reason is in our
418 // storage form for relative paths:
419 // ":dir:file.txt" actually means "./dir/file.txt" in
420 // DOS notation and should get stored as
421 // (relative) (dir) (file.txt)
422 // "::dir:file.txt" actually means "../dir/file.txt"
423 // stored as (relative) (..) (dir) (file.txt)
424 // This is important only for the Mac as an empty dir
425 // actually means <UP>, whereas under DOS, double
426 // slashes can be ignored: "\\\\" is the same as "\\".
427 if (m_relative)
428 path.erase( 0, 1 );
429 break;
430
431 case wxPATH_VMS:
432 // TODO: what is the relative path format here?
433 m_relative = false;
434 break;
435
436 default:
437 wxFAIL_MSG( wxT("Unknown path format") );
438 // !! Fall through !!
439
440 case wxPATH_UNIX:
441 m_relative = leadingChar != wxT('/');
442 break;
443
444 case wxPATH_DOS:
445 m_relative = !IsPathSeparator(leadingChar, format);
446 break;
447
448 }
449
450 // 2) Break up the path into its members. If the original path
451 // was just "/" or "\\", m_dirs will be empty. We know from
452 // the m_relative field, if this means "nothing" or "root dir".
453
454 wxStringTokenizer tn( path, GetPathSeparators(format) );
455
456 while ( tn.HasMoreTokens() )
457 {
458 wxString token = tn.GetNextToken();
459
460 // Remove empty token under DOS and Unix, interpret them
461 // as .. under Mac.
462 if (token.empty())
463 {
464 if (format == wxPATH_MAC)
465 m_dirs.Add( wxT("..") );
466 // else ignore
467 }
468 else
469 {
470 m_dirs.Add( token );
471 }
472 }
473 }
474
475 void wxFileName::Assign(const wxString& fullpath,
476 wxPathFormat format)
477 {
478 wxString volume, path, name, ext;
479 bool hasExt;
480 SplitPath(fullpath, &volume, &path, &name, &ext, &hasExt, format);
481
482 Assign(volume, path, name, ext, hasExt, format);
483 }
484
485 void wxFileName::Assign(const wxString& fullpathOrig,
486 const wxString& fullname,
487 wxPathFormat format)
488 {
489 // always recognize fullpath as directory, even if it doesn't end with a
490 // slash
491 wxString fullpath = fullpathOrig;
492 if ( !fullpath.empty() && !wxEndsWithPathSeparator(fullpath) )
493 {
494 fullpath += GetPathSeparator(format);
495 }
496
497 wxString volume, path, name, ext;
498 bool hasExt;
499
500 // do some consistency checks: the name should be really just the filename
501 // and the path should be really just a path
502 wxString volDummy, pathDummy, nameDummy, extDummy;
503
504 SplitPath(fullname, &volDummy, &pathDummy, &name, &ext, &hasExt, format);
505
506 wxASSERT_MSG( volDummy.empty() && pathDummy.empty(),
507 wxT("the file name shouldn't contain the path") );
508
509 SplitPath(fullpath, &volume, &path, &nameDummy, &extDummy, format);
510
511 #ifndef __VMS
512 // This test makes no sense on an OpenVMS system.
513 wxASSERT_MSG( nameDummy.empty() && extDummy.empty(),
514 wxT("the path shouldn't contain file name nor extension") );
515 #endif
516 Assign(volume, path, name, ext, hasExt, format);
517 }
518
519 void wxFileName::Assign(const wxString& pathOrig,
520 const wxString& name,
521 const wxString& ext,
522 wxPathFormat format)
523 {
524 wxString volume,
525 path;
526 SplitVolume(pathOrig, &volume, &path, format);
527
528 Assign(volume, path, name, ext, format);
529 }
530
531 void wxFileName::AssignDir(const wxString& dir, wxPathFormat format)
532 {
533 Assign(dir, wxEmptyString, format);
534 }
535
536 void wxFileName::Clear()
537 {
538 m_dirs.Clear();
539
540 m_volume =
541 m_name =
542 m_ext = wxEmptyString;
543
544 // we don't have any absolute path for now
545 m_relative = true;
546
547 // nor any extension
548 m_hasExt = false;
549 }
550
551 /* static */
552 wxFileName wxFileName::FileName(const wxString& file, wxPathFormat format)
553 {
554 return wxFileName(file, format);
555 }
556
557 /* static */
558 wxFileName wxFileName::DirName(const wxString& dir, wxPathFormat format)
559 {
560 wxFileName fn;
561 fn.AssignDir(dir, format);
562 return fn;
563 }
564
565 // ----------------------------------------------------------------------------
566 // existence tests
567 // ----------------------------------------------------------------------------
568
569 bool wxFileName::FileExists() const
570 {
571 return wxFileName::FileExists( GetFullPath() );
572 }
573
574 /* static */
575 bool wxFileName::FileExists( const wxString &filePath )
576 {
577 #if defined(__WXPALMOS__)
578 return false;
579 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
580 // we must use GetFileAttributes() instead of the ANSI C functions because
581 // it can cope with network (UNC) paths unlike them
582 DWORD ret = ::GetFileAttributes(filePath.fn_str());
583
584 return (ret != INVALID_FILE_ATTRIBUTES) && !(ret & FILE_ATTRIBUTE_DIRECTORY);
585 #else // !__WIN32__
586 #ifndef S_ISREG
587 #define S_ISREG(mode) ((mode) & S_IFREG)
588 #endif
589 wxStructStat st;
590 #ifndef wxNEED_WX_UNISTD_H
591 return (wxStat( filePath.fn_str() , &st) == 0 && S_ISREG(st.st_mode))
592 #ifdef __OS2__
593 || (errno == EACCES) // if access is denied something with that name
594 // exists and is opened in exclusive mode.
595 #endif
596 ;
597 #else
598 return wxStat( filePath , &st) == 0 && S_ISREG(st.st_mode);
599 #endif
600 #endif // __WIN32__/!__WIN32__
601 }
602
603 bool wxFileName::DirExists() const
604 {
605 return wxFileName::DirExists( GetPath() );
606 }
607
608 /* static */
609 bool wxFileName::DirExists( const wxString &dirPath )
610 {
611 wxString strPath(dirPath);
612
613 #if defined(__WINDOWS__) || defined(__OS2__)
614 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
615 // so remove all trailing backslashes from the path - but don't do this for
616 // the paths "d:\" (which are different from "d:") nor for just "\"
617 while ( wxEndsWithPathSeparator(strPath) )
618 {
619 size_t len = strPath.length();
620 if ( len == 1 || (len == 3 && strPath[len - 2] == wxT(':')) )
621 break;
622
623 strPath.Truncate(len - 1);
624 }
625 #endif // __WINDOWS__
626
627 #ifdef __OS2__
628 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
629 if (strPath.length() == 2 && strPath[1u] == wxT(':'))
630 strPath << wxT('.');
631 #endif
632
633 #if defined(__WXPALMOS__)
634 return false;
635 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
636 // stat() can't cope with network paths
637 DWORD ret = ::GetFileAttributes(strPath.fn_str());
638
639 return (ret != INVALID_FILE_ATTRIBUTES) && (ret & FILE_ATTRIBUTE_DIRECTORY);
640 #elif defined(__OS2__)
641 FILESTATUS3 Info = {{0}};
642 APIRET rc = ::DosQueryPathInfo((PSZ)(WXSTRINGCAST strPath), FIL_STANDARD,
643 (void*) &Info, sizeof(FILESTATUS3));
644
645 return ((rc == NO_ERROR) && (Info.attrFile & FILE_DIRECTORY)) ||
646 (rc == ERROR_SHARING_VIOLATION);
647 // If we got a sharing violation, there must be something with this name.
648 #else // !__WIN32__
649
650 wxStructStat st;
651 #ifndef __VISAGECPP__
652 return wxStat(strPath.c_str(), &st) == 0 && ((st.st_mode & S_IFMT) == S_IFDIR);
653 #else
654 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
655 return wxStat(strPath.c_str(), &st) == 0 && (st.st_mode == S_IFDIR);
656 #endif
657
658 #endif // __WIN32__/!__WIN32__
659 }
660
661 // ----------------------------------------------------------------------------
662 // CWD and HOME stuff
663 // ----------------------------------------------------------------------------
664
665 void wxFileName::AssignCwd(const wxString& volume)
666 {
667 AssignDir(wxFileName::GetCwd(volume));
668 }
669
670 /* static */
671 wxString wxFileName::GetCwd(const wxString& volume)
672 {
673 // if we have the volume, we must get the current directory on this drive
674 // and to do this we have to chdir to this volume - at least under Windows,
675 // I don't know how to get the current drive on another volume elsewhere
676 // (TODO)
677 wxString cwdOld;
678 if ( !volume.empty() )
679 {
680 cwdOld = wxGetCwd();
681 SetCwd(volume + GetVolumeSeparator());
682 }
683
684 wxString cwd = ::wxGetCwd();
685
686 if ( !volume.empty() )
687 {
688 SetCwd(cwdOld);
689 }
690
691 return cwd;
692 }
693
694 bool wxFileName::SetCwd() const
695 {
696 return wxFileName::SetCwd( GetPath() );
697 }
698
699 bool wxFileName::SetCwd( const wxString &cwd )
700 {
701 return ::wxSetWorkingDirectory( cwd );
702 }
703
704 void wxFileName::AssignHomeDir()
705 {
706 AssignDir(wxFileName::GetHomeDir());
707 }
708
709 wxString wxFileName::GetHomeDir()
710 {
711 return ::wxGetHomeDir();
712 }
713
714
715 // ----------------------------------------------------------------------------
716 // CreateTempFileName
717 // ----------------------------------------------------------------------------
718
719 #if wxUSE_FILE || wxUSE_FFILE
720
721
722 #if !defined wx_fdopen && defined HAVE_FDOPEN
723 #define wx_fdopen fdopen
724 #endif
725
726 // NB: GetTempFileName() under Windows creates the file, so using
727 // O_EXCL there would fail
728 #ifdef __WINDOWS__
729 #define wxOPEN_EXCL 0
730 #else
731 #define wxOPEN_EXCL O_EXCL
732 #endif
733
734
735 #ifdef wxOpenOSFHandle
736 #define WX_HAVE_DELETE_ON_CLOSE
737 // On Windows create a file with the FILE_FLAGS_DELETE_ON_CLOSE flags.
738 //
739 static int wxOpenWithDeleteOnClose(const wxString& filename)
740 {
741 DWORD access = GENERIC_READ | GENERIC_WRITE;
742
743 DWORD disposition = OPEN_ALWAYS;
744
745 DWORD attributes = FILE_ATTRIBUTE_TEMPORARY |
746 FILE_FLAG_DELETE_ON_CLOSE;
747
748 HANDLE h = ::CreateFile(filename.fn_str(), access, 0, NULL,
749 disposition, attributes, NULL);
750
751 return wxOpenOSFHandle(h, wxO_BINARY);
752 }
753 #endif // wxOpenOSFHandle
754
755
756 // Helper to open the file
757 //
758 static int wxTempOpen(const wxString& path, bool *deleteOnClose)
759 {
760 #ifdef WX_HAVE_DELETE_ON_CLOSE
761 if (*deleteOnClose)
762 return wxOpenWithDeleteOnClose(path);
763 #endif
764
765 *deleteOnClose = false;
766
767 return wxOpen(path, wxO_BINARY | O_RDWR | O_CREAT | wxOPEN_EXCL, 0600);
768 }
769
770
771 #if wxUSE_FFILE
772 // Helper to open the file and attach it to the wxFFile
773 //
774 static bool wxTempOpen(wxFFile *file, const wxString& path, bool *deleteOnClose)
775 {
776 #ifndef wx_fdopen
777 *deleteOnClose = false;
778 return file->Open(path, wxT("w+b"));
779 #else // wx_fdopen
780 int fd = wxTempOpen(path, deleteOnClose);
781 if (fd == -1)
782 return false;
783 file->Attach(wx_fdopen(fd, "w+b"));
784 return file->IsOpened();
785 #endif // wx_fdopen
786 }
787 #endif // wxUSE_FFILE
788
789
790 #if !wxUSE_FILE
791 #define WXFILEARGS(x, y) y
792 #elif !wxUSE_FFILE
793 #define WXFILEARGS(x, y) x
794 #else
795 #define WXFILEARGS(x, y) x, y
796 #endif
797
798
799 // Implementation of wxFileName::CreateTempFileName().
800 //
801 static wxString wxCreateTempImpl(
802 const wxString& prefix,
803 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
804 bool *deleteOnClose = NULL)
805 {
806 #if wxUSE_FILE && wxUSE_FFILE
807 wxASSERT(fileTemp == NULL || ffileTemp == NULL);
808 #endif
809 wxString path, dir, name;
810 bool wantDeleteOnClose = false;
811
812 if (deleteOnClose)
813 {
814 // set the result to false initially
815 wantDeleteOnClose = *deleteOnClose;
816 *deleteOnClose = false;
817 }
818 else
819 {
820 // easier if it alwasys points to something
821 deleteOnClose = &wantDeleteOnClose;
822 }
823
824 // use the directory specified by the prefix
825 wxFileName::SplitPath(prefix, &dir, &name, NULL /* extension */);
826
827 if (dir.empty())
828 {
829 dir = wxFileName::GetTempDir();
830 }
831
832 #if defined(__WXWINCE__)
833 path = dir + wxT("\\") + name;
834 int i = 1;
835 while (wxFileName::FileExists(path))
836 {
837 path = dir + wxT("\\") + name ;
838 path << i;
839 i ++;
840 }
841
842 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
843 if ( !::GetTempFileName(dir.fn_str(), name.fn_str(), 0,
844 wxStringBuffer(path, MAX_PATH + 1)) )
845 {
846 wxLogLastError(wxT("GetTempFileName"));
847
848 path.clear();
849 }
850
851 #else // !Windows
852 path = dir;
853
854 if ( !wxEndsWithPathSeparator(dir) &&
855 (name.empty() || !wxIsPathSeparator(name[0u])) )
856 {
857 path += wxFILE_SEP_PATH;
858 }
859
860 path += name;
861
862 #if defined(HAVE_MKSTEMP)
863 // scratch space for mkstemp()
864 path += wxT("XXXXXX");
865
866 // we need to copy the path to the buffer in which mkstemp() can modify it
867 wxCharBuffer buf(path.fn_str());
868
869 // cast is safe because the string length doesn't change
870 int fdTemp = mkstemp( (char*)(const char*) buf );
871 if ( fdTemp == -1 )
872 {
873 // this might be not necessary as mkstemp() on most systems should have
874 // already done it but it doesn't hurt neither...
875 path.clear();
876 }
877 else // mkstemp() succeeded
878 {
879 path = wxConvFile.cMB2WX( (const char*) buf );
880
881 #if wxUSE_FILE
882 // avoid leaking the fd
883 if ( fileTemp )
884 {
885 fileTemp->Attach(fdTemp);
886 }
887 else
888 #endif
889
890 #if wxUSE_FFILE
891 if ( ffileTemp )
892 {
893 #ifdef wx_fdopen
894 ffileTemp->Attach(wx_fdopen(fdTemp, "r+b"));
895 #else
896 ffileTemp->Open(path, wxT("r+b"));
897 close(fdTemp);
898 #endif
899 }
900 else
901 #endif
902
903 {
904 close(fdTemp);
905 }
906 }
907 #else // !HAVE_MKSTEMP
908
909 #ifdef HAVE_MKTEMP
910 // same as above
911 path += wxT("XXXXXX");
912
913 wxCharBuffer buf = wxConvFile.cWX2MB( path );
914 if ( !mktemp( (char*)(const char*) buf ) )
915 {
916 path.clear();
917 }
918 else
919 {
920 path = wxConvFile.cMB2WX( (const char*) buf );
921 }
922 #else // !HAVE_MKTEMP (includes __DOS__)
923 // generate the unique file name ourselves
924 #if !defined(__DOS__) && !defined(__PALMOS__) && (!defined(__MWERKS__) || defined(__DARWIN__) )
925 path << (unsigned int)getpid();
926 #endif
927
928 wxString pathTry;
929
930 static const size_t numTries = 1000;
931 for ( size_t n = 0; n < numTries; n++ )
932 {
933 // 3 hex digits is enough for numTries == 1000 < 4096
934 pathTry = path + wxString::Format(wxT("%.03x"), (unsigned int) n);
935 if ( !wxFileName::FileExists(pathTry) )
936 {
937 break;
938 }
939
940 pathTry.clear();
941 }
942
943 path = pathTry;
944 #endif // HAVE_MKTEMP/!HAVE_MKTEMP
945
946 #endif // HAVE_MKSTEMP/!HAVE_MKSTEMP
947
948 #endif // Windows/!Windows
949
950 if ( path.empty() )
951 {
952 wxLogSysError(_("Failed to create a temporary file name"));
953 }
954 else
955 {
956 bool ok = true;
957
958 // open the file - of course, there is a race condition here, this is
959 // why we always prefer using mkstemp()...
960 #if wxUSE_FILE
961 if ( fileTemp && !fileTemp->IsOpened() )
962 {
963 *deleteOnClose = wantDeleteOnClose;
964 int fd = wxTempOpen(path, deleteOnClose);
965 if (fd != -1)
966 fileTemp->Attach(fd);
967 else
968 ok = false;
969 }
970 #endif
971
972 #if wxUSE_FFILE
973 if ( ffileTemp && !ffileTemp->IsOpened() )
974 {
975 *deleteOnClose = wantDeleteOnClose;
976 ok = wxTempOpen(ffileTemp, path, deleteOnClose);
977 }
978 #endif
979
980 if ( !ok )
981 {
982 // FIXME: If !ok here should we loop and try again with another
983 // file name? That is the standard recourse if open(O_EXCL)
984 // fails, though of course it should be protected against
985 // possible infinite looping too.
986
987 wxLogError(_("Failed to open temporary file."));
988
989 path.clear();
990 }
991 }
992
993 return path;
994 }
995
996
997 static bool wxCreateTempImpl(
998 const wxString& prefix,
999 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp),
1000 wxString *name)
1001 {
1002 bool deleteOnClose = true;
1003
1004 *name = wxCreateTempImpl(prefix,
1005 WXFILEARGS(fileTemp, ffileTemp),
1006 &deleteOnClose);
1007
1008 bool ok = !name->empty();
1009
1010 if (deleteOnClose)
1011 name->clear();
1012 #ifdef __UNIX__
1013 else if (ok && wxRemoveFile(*name))
1014 name->clear();
1015 #endif
1016
1017 return ok;
1018 }
1019
1020
1021 static void wxAssignTempImpl(
1022 wxFileName *fn,
1023 const wxString& prefix,
1024 WXFILEARGS(wxFile *fileTemp, wxFFile *ffileTemp))
1025 {
1026 wxString tempname;
1027 tempname = wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, ffileTemp));
1028
1029 if ( tempname.empty() )
1030 {
1031 // error, failed to get temp file name
1032 fn->Clear();
1033 }
1034 else // ok
1035 {
1036 fn->Assign(tempname);
1037 }
1038 }
1039
1040
1041 void wxFileName::AssignTempFileName(const wxString& prefix)
1042 {
1043 wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, NULL));
1044 }
1045
1046 /* static */
1047 wxString wxFileName::CreateTempFileName(const wxString& prefix)
1048 {
1049 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, NULL));
1050 }
1051
1052 #endif // wxUSE_FILE || wxUSE_FFILE
1053
1054
1055 #if wxUSE_FILE
1056
1057 wxString wxCreateTempFileName(const wxString& prefix,
1058 wxFile *fileTemp,
1059 bool *deleteOnClose)
1060 {
1061 return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), deleteOnClose);
1062 }
1063
1064 bool wxCreateTempFile(const wxString& prefix,
1065 wxFile *fileTemp,
1066 wxString *name)
1067 {
1068 return wxCreateTempImpl(prefix, WXFILEARGS(fileTemp, NULL), name);
1069 }
1070
1071 void wxFileName::AssignTempFileName(const wxString& prefix, wxFile *fileTemp)
1072 {
1073 wxAssignTempImpl(this, prefix, WXFILEARGS(fileTemp, NULL));
1074 }
1075
1076 /* static */
1077 wxString
1078 wxFileName::CreateTempFileName(const wxString& prefix, wxFile *fileTemp)
1079 {
1080 return wxCreateTempFileName(prefix, fileTemp);
1081 }
1082
1083 #endif // wxUSE_FILE
1084
1085
1086 #if wxUSE_FFILE
1087
1088 wxString wxCreateTempFileName(const wxString& prefix,
1089 wxFFile *fileTemp,
1090 bool *deleteOnClose)
1091 {
1092 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), deleteOnClose);
1093 }
1094
1095 bool wxCreateTempFile(const wxString& prefix,
1096 wxFFile *fileTemp,
1097 wxString *name)
1098 {
1099 return wxCreateTempImpl(prefix, WXFILEARGS(NULL, fileTemp), name);
1100
1101 }
1102
1103 void wxFileName::AssignTempFileName(const wxString& prefix, wxFFile *fileTemp)
1104 {
1105 wxAssignTempImpl(this, prefix, WXFILEARGS(NULL, fileTemp));
1106 }
1107
1108 /* static */
1109 wxString
1110 wxFileName::CreateTempFileName(const wxString& prefix, wxFFile *fileTemp)
1111 {
1112 return wxCreateTempFileName(prefix, fileTemp);
1113 }
1114
1115 #endif // wxUSE_FFILE
1116
1117
1118 // ----------------------------------------------------------------------------
1119 // directory operations
1120 // ----------------------------------------------------------------------------
1121
1122 // helper of GetTempDir(): check if the given directory exists and return it if
1123 // it does or an empty string otherwise
1124 namespace
1125 {
1126
1127 wxString CheckIfDirExists(const wxString& dir)
1128 {
1129 return wxFileName::DirExists(dir) ? dir : wxString();
1130 }
1131
1132 } // anonymous namespace
1133
1134 wxString wxFileName::GetTempDir()
1135 {
1136 // first try getting it from environment: this allows overriding the values
1137 // used by default if the user wants to create temporary files in another
1138 // directory
1139 wxString dir = CheckIfDirExists(wxGetenv("TMPDIR"));
1140 if ( dir.empty() )
1141 {
1142 dir = CheckIfDirExists(wxGetenv("TMP"));
1143 if ( dir.empty() )
1144 dir = CheckIfDirExists(wxGetenv("TEMP"));
1145 }
1146
1147 // if no environment variables are set, use the system default
1148 if ( dir.empty() )
1149 {
1150 #if defined(__WXWINCE__)
1151 dir = CheckIfDirExists(wxT("\\temp"));
1152 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1153 if ( !::GetTempPath(MAX_PATH, wxStringBuffer(dir, MAX_PATH + 1)) )
1154 {
1155 wxLogLastError(wxT("GetTempPath"));
1156 }
1157 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1158 dir = wxMacFindFolder(short(kOnSystemDisk), kTemporaryFolderType, kCreateFolder);
1159 #endif // systems with native way
1160 }
1161
1162 // fall back to hard coded value
1163 if ( dir.empty() )
1164 {
1165 #ifdef __UNIX_LIKE__
1166 dir = CheckIfDirExists("/tmp");
1167 if ( dir.empty() )
1168 #endif // __UNIX_LIKE__
1169 dir = ".";
1170 }
1171
1172 return dir;
1173 }
1174
1175 bool wxFileName::Mkdir( int perm, int flags ) const
1176 {
1177 return wxFileName::Mkdir(GetPath(), perm, flags);
1178 }
1179
1180 bool wxFileName::Mkdir( const wxString& dir, int perm, int flags )
1181 {
1182 if ( flags & wxPATH_MKDIR_FULL )
1183 {
1184 // split the path in components
1185 wxFileName filename;
1186 filename.AssignDir(dir);
1187
1188 wxString currPath;
1189 if ( filename.HasVolume())
1190 {
1191 currPath << wxGetVolumeString(filename.GetVolume(), wxPATH_NATIVE);
1192 }
1193
1194 wxArrayString dirs = filename.GetDirs();
1195 size_t count = dirs.GetCount();
1196 for ( size_t i = 0; i < count; i++ )
1197 {
1198 if ( i > 0 || filename.IsAbsolute() )
1199 currPath += wxFILE_SEP_PATH;
1200 currPath += dirs[i];
1201
1202 if (!DirExists(currPath))
1203 {
1204 if (!wxMkdir(currPath, perm))
1205 {
1206 // no need to try creating further directories
1207 return false;
1208 }
1209 }
1210 }
1211
1212 return true;
1213
1214 }
1215
1216 return ::wxMkdir( dir, perm );
1217 }
1218
1219 bool wxFileName::Rmdir(int flags) const
1220 {
1221 return wxFileName::Rmdir( GetPath(), flags );
1222 }
1223
1224 bool wxFileName::Rmdir(const wxString& dir, int flags)
1225 {
1226 #ifdef __WXMSW__
1227 if ( flags & wxPATH_RMDIR_RECURSIVE )
1228 {
1229 // SHFileOperation needs double null termination string
1230 // but without separator at the end of the path
1231 wxString path(dir);
1232 if ( path.Last() == wxFILE_SEP_PATH )
1233 path.RemoveLast();
1234 path += wxT('\0');
1235
1236 SHFILEOPSTRUCT fileop;
1237 wxZeroMemory(fileop);
1238 fileop.wFunc = FO_DELETE;
1239 fileop.pFrom = path.fn_str();
1240 fileop.fFlags = FOF_SILENT | FOF_NOCONFIRMATION;
1241 #ifndef __WXWINCE__
1242 // FOF_NOERRORUI is not defined in WinCE
1243 fileop.fFlags |= FOF_NOERRORUI;
1244 #endif
1245
1246 int ret = SHFileOperation(&fileop);
1247 if ( ret != 0 )
1248 {
1249 // SHFileOperation may return non-Win32 error codes, so the error
1250 // message can be incorrect
1251 wxLogApiError(wxT("SHFileOperation"), ret);
1252 return false;
1253 }
1254
1255 return true;
1256 }
1257 else if ( flags & wxPATH_RMDIR_FULL )
1258 #else // !__WXMSW__
1259 if ( flags != 0 ) // wxPATH_RMDIR_FULL or wxPATH_RMDIR_RECURSIVE
1260 #endif // !__WXMSW__
1261 {
1262 wxString path(dir);
1263 if ( path.Last() != wxFILE_SEP_PATH )
1264 path += wxFILE_SEP_PATH;
1265
1266 wxDir d(path);
1267
1268 if ( !d.IsOpened() )
1269 return false;
1270
1271 wxString filename;
1272
1273 // first delete all subdirectories
1274 bool cont = d.GetFirst(&filename, "", wxDIR_DIRS | wxDIR_HIDDEN);
1275 while ( cont )
1276 {
1277 wxFileName::Rmdir(path + filename, flags);
1278 cont = d.GetNext(&filename);
1279 }
1280
1281 #ifndef __WXMSW__
1282 if ( flags & wxPATH_RMDIR_RECURSIVE )
1283 {
1284 // delete all files too
1285 cont = d.GetFirst(&filename, "", wxDIR_FILES | wxDIR_HIDDEN);
1286 while ( cont )
1287 {
1288 ::wxRemoveFile(path + filename);
1289 cont = d.GetNext(&filename);
1290 }
1291 }
1292 #endif // !__WXMSW__
1293 }
1294
1295 return ::wxRmdir(dir);
1296 }
1297
1298 // ----------------------------------------------------------------------------
1299 // path normalization
1300 // ----------------------------------------------------------------------------
1301
1302 bool wxFileName::Normalize(int flags,
1303 const wxString& cwd,
1304 wxPathFormat format)
1305 {
1306 // deal with env vars renaming first as this may seriously change the path
1307 if ( flags & wxPATH_NORM_ENV_VARS )
1308 {
1309 wxString pathOrig = GetFullPath(format);
1310 wxString path = wxExpandEnvVars(pathOrig);
1311 if ( path != pathOrig )
1312 {
1313 Assign(path);
1314 }
1315 }
1316
1317 // the existing path components
1318 wxArrayString dirs = GetDirs();
1319
1320 // the path to prepend in front to make the path absolute
1321 wxFileName curDir;
1322
1323 format = GetFormat(format);
1324
1325 // set up the directory to use for making the path absolute later
1326 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute(format) )
1327 {
1328 if ( cwd.empty() )
1329 {
1330 curDir.AssignCwd(GetVolume());
1331 }
1332 else // cwd provided
1333 {
1334 curDir.AssignDir(cwd);
1335 }
1336 }
1337
1338 // handle ~ stuff under Unix only
1339 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) && m_relative )
1340 {
1341 if ( !dirs.IsEmpty() )
1342 {
1343 wxString dir = dirs[0u];
1344 if ( !dir.empty() && dir[0u] == wxT('~') )
1345 {
1346 // to make the path absolute use the home directory
1347 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
1348 dirs.RemoveAt(0u);
1349 }
1350 }
1351 }
1352
1353 // transform relative path into abs one
1354 if ( curDir.IsOk() )
1355 {
1356 // this path may be relative because it doesn't have the volume name
1357 // and still have m_relative=true; in this case we shouldn't modify
1358 // our directory components but just set the current volume
1359 if ( !HasVolume() && curDir.HasVolume() )
1360 {
1361 SetVolume(curDir.GetVolume());
1362
1363 if ( !m_relative )
1364 {
1365 // yes, it was the case - we don't need curDir then
1366 curDir.Clear();
1367 }
1368 }
1369
1370 // finally, prepend curDir to the dirs array
1371 wxArrayString dirsNew = curDir.GetDirs();
1372 WX_PREPEND_ARRAY(dirs, dirsNew);
1373
1374 // if we used e.g. tilde expansion previously and wxGetUserHome didn't
1375 // return for some reason an absolute path, then curDir maybe not be absolute!
1376 if ( !curDir.m_relative )
1377 {
1378 // we have prepended an absolute path and thus we are now an absolute
1379 // file name too
1380 m_relative = false;
1381 }
1382 // else if (flags & wxPATH_NORM_ABSOLUTE):
1383 // should we warn the user that we didn't manage to make the path absolute?
1384 }
1385
1386 // now deal with ".", ".." and the rest
1387 m_dirs.Empty();
1388 size_t count = dirs.GetCount();
1389 for ( size_t n = 0; n < count; n++ )
1390 {
1391 wxString dir = dirs[n];
1392
1393 if ( flags & wxPATH_NORM_DOTS )
1394 {
1395 if ( dir == wxT(".") )
1396 {
1397 // just ignore
1398 continue;
1399 }
1400
1401 if ( dir == wxT("..") )
1402 {
1403 if ( m_dirs.IsEmpty() )
1404 {
1405 wxLogError(_("The path '%s' contains too many \"..\"!"),
1406 GetFullPath().c_str());
1407 return false;
1408 }
1409
1410 m_dirs.RemoveAt(m_dirs.GetCount() - 1);
1411 continue;
1412 }
1413 }
1414
1415 m_dirs.Add(dir);
1416 }
1417
1418 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1419 if ( (flags & wxPATH_NORM_SHORTCUT) )
1420 {
1421 wxString filename;
1422 if (GetShortcutTarget(GetFullPath(format), filename))
1423 {
1424 m_relative = false;
1425 Assign(filename);
1426 }
1427 }
1428 #endif
1429
1430 #if defined(__WIN32__)
1431 if ( (flags & wxPATH_NORM_LONG) && (format == wxPATH_DOS) )
1432 {
1433 Assign(GetLongPath());
1434 }
1435 #endif // Win32
1436
1437 // Change case (this should be kept at the end of the function, to ensure
1438 // that the path doesn't change any more after we normalize its case)
1439 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
1440 {
1441 m_volume.MakeLower();
1442 m_name.MakeLower();
1443 m_ext.MakeLower();
1444
1445 // directory entries must be made lower case as well
1446 count = m_dirs.GetCount();
1447 for ( size_t i = 0; i < count; i++ )
1448 {
1449 m_dirs[i].MakeLower();
1450 }
1451 }
1452
1453 return true;
1454 }
1455
1456 #ifndef __WXWINCE__
1457 bool wxFileName::ReplaceEnvVariable(const wxString& envname,
1458 const wxString& replacementFmtString,
1459 wxPathFormat format)
1460 {
1461 // look into stringForm for the contents of the given environment variable
1462 wxString val;
1463 if (envname.empty() ||
1464 !wxGetEnv(envname, &val))
1465 return false;
1466 if (val.empty())
1467 return false;
1468
1469 wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
1470 // do not touch the file name and the extension
1471
1472 wxString replacement = wxString::Format(replacementFmtString, envname);
1473 stringForm.Replace(val, replacement);
1474
1475 // Now assign ourselves the modified path:
1476 Assign(stringForm, GetFullName(), format);
1477
1478 return true;
1479 }
1480 #endif
1481
1482 bool wxFileName::ReplaceHomeDir(wxPathFormat format)
1483 {
1484 wxString homedir = wxGetHomeDir();
1485 if (homedir.empty())
1486 return false;
1487
1488 wxString stringForm = GetPath(wxPATH_GET_VOLUME, format);
1489 // do not touch the file name and the extension
1490
1491 stringForm.Replace(homedir, "~");
1492
1493 // Now assign ourselves the modified path:
1494 Assign(stringForm, GetFullName(), format);
1495
1496 return true;
1497 }
1498
1499 // ----------------------------------------------------------------------------
1500 // get the shortcut target
1501 // ----------------------------------------------------------------------------
1502
1503 // WinCE (3) doesn't have CLSID_ShellLink, IID_IShellLink definitions.
1504 // The .lnk file is a plain text file so it should be easy to
1505 // make it work. Hint from Google Groups:
1506 // "If you open up a lnk file, you'll see a
1507 // number, followed by a pound sign (#), followed by more text. The
1508 // number is the number of characters that follows the pound sign. The
1509 // characters after the pound sign are the command line (which _can_
1510 // include arguments) to be executed. Any path (e.g. \windows\program
1511 // files\myapp.exe) that includes spaces needs to be enclosed in
1512 // quotation marks."
1513
1514 #if defined(__WIN32__) && !defined(__WXWINCE__) && wxUSE_OLE
1515 // The following lines are necessary under WinCE
1516 // #include "wx/msw/private.h"
1517 // #include <ole2.h>
1518 #include <shlobj.h>
1519 #if defined(__WXWINCE__)
1520 #include <shlguid.h>
1521 #endif
1522
1523 bool wxFileName::GetShortcutTarget(const wxString& shortcutPath,
1524 wxString& targetFilename,
1525 wxString* arguments) const
1526 {
1527 wxString path, file, ext;
1528 wxFileName::SplitPath(shortcutPath, & path, & file, & ext);
1529
1530 HRESULT hres;
1531 IShellLink* psl;
1532 bool success = false;
1533
1534 // Assume it's not a shortcut if it doesn't end with lnk
1535 if (ext.CmpNoCase(wxT("lnk"))!=0)
1536 return false;
1537
1538 // create a ShellLink object
1539 hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1540 IID_IShellLink, (LPVOID*) &psl);
1541
1542 if (SUCCEEDED(hres))
1543 {
1544 IPersistFile* ppf;
1545 hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
1546 if (SUCCEEDED(hres))
1547 {
1548 WCHAR wsz[MAX_PATH];
1549
1550 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, shortcutPath.mb_str(), -1, wsz,
1551 MAX_PATH);
1552
1553 hres = ppf->Load(wsz, 0);
1554 ppf->Release();
1555
1556 if (SUCCEEDED(hres))
1557 {
1558 wxChar buf[2048];
1559 // Wrong prototype in early versions
1560 #if defined(__MINGW32__) && !wxCHECK_W32API_VERSION(2, 2)
1561 psl->GetPath((CHAR*) buf, 2048, NULL, SLGP_UNCPRIORITY);
1562 #else
1563 psl->GetPath(buf, 2048, NULL, SLGP_UNCPRIORITY);
1564 #endif
1565 targetFilename = wxString(buf);
1566 success = (shortcutPath != targetFilename);
1567
1568 psl->GetArguments(buf, 2048);
1569 wxString args(buf);
1570 if (!args.empty() && arguments)
1571 {
1572 *arguments = args;
1573 }
1574 }
1575 }
1576
1577 psl->Release();
1578 }
1579 return success;
1580 }
1581
1582 #endif // __WIN32__ && !__WXWINCE__
1583
1584
1585 // ----------------------------------------------------------------------------
1586 // absolute/relative paths
1587 // ----------------------------------------------------------------------------
1588
1589 bool wxFileName::IsAbsolute(wxPathFormat format) const
1590 {
1591 // unix paths beginning with ~ are reported as being absolute
1592 if ( format == wxPATH_UNIX )
1593 {
1594 if ( !m_dirs.IsEmpty() )
1595 {
1596 wxString dir = m_dirs[0u];
1597
1598 if (!dir.empty() && dir[0u] == wxT('~'))
1599 return true;
1600 }
1601 }
1602
1603 // if our path doesn't start with a path separator, it's not an absolute
1604 // path
1605 if ( m_relative )
1606 return false;
1607
1608 if ( !GetVolumeSeparator(format).empty() )
1609 {
1610 // this format has volumes and an absolute path must have one, it's not
1611 // enough to have the full path to be an absolute file under Windows
1612 if ( GetVolume().empty() )
1613 return false;
1614 }
1615
1616 return true;
1617 }
1618
1619 bool wxFileName::MakeRelativeTo(const wxString& pathBase, wxPathFormat format)
1620 {
1621 wxFileName fnBase = wxFileName::DirName(pathBase, format);
1622
1623 // get cwd only once - small time saving
1624 wxString cwd = wxGetCwd();
1625 Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1626 fnBase.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, cwd, format);
1627
1628 bool withCase = IsCaseSensitive(format);
1629
1630 // we can't do anything if the files live on different volumes
1631 if ( !GetVolume().IsSameAs(fnBase.GetVolume(), withCase) )
1632 {
1633 // nothing done
1634 return false;
1635 }
1636
1637 // same drive, so we don't need our volume
1638 m_volume.clear();
1639
1640 // remove common directories starting at the top
1641 while ( !m_dirs.IsEmpty() && !fnBase.m_dirs.IsEmpty() &&
1642 m_dirs[0u].IsSameAs(fnBase.m_dirs[0u], withCase) )
1643 {
1644 m_dirs.RemoveAt(0);
1645 fnBase.m_dirs.RemoveAt(0);
1646 }
1647
1648 // add as many ".." as needed
1649 size_t count = fnBase.m_dirs.GetCount();
1650 for ( size_t i = 0; i < count; i++ )
1651 {
1652 m_dirs.Insert(wxT(".."), 0u);
1653 }
1654
1655 if ( format == wxPATH_UNIX || format == wxPATH_DOS )
1656 {
1657 // a directory made relative with respect to itself is '.' under Unix
1658 // and DOS, by definition (but we don't have to insert "./" for the
1659 // files)
1660 if ( m_dirs.IsEmpty() && IsDir() )
1661 {
1662 m_dirs.Add(wxT('.'));
1663 }
1664 }
1665
1666 m_relative = true;
1667
1668 // we were modified
1669 return true;
1670 }
1671
1672 // ----------------------------------------------------------------------------
1673 // filename kind tests
1674 // ----------------------------------------------------------------------------
1675
1676 bool wxFileName::SameAs(const wxFileName& filepath, wxPathFormat format) const
1677 {
1678 wxFileName fn1 = *this,
1679 fn2 = filepath;
1680
1681 // get cwd only once - small time saving
1682 wxString cwd = wxGetCwd();
1683 fn1.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1684 fn2.Normalize(wxPATH_NORM_ALL | wxPATH_NORM_CASE, cwd, format);
1685
1686 if ( fn1.GetFullPath() == fn2.GetFullPath() )
1687 return true;
1688
1689 // TODO: compare inodes for Unix, this works even when filenames are
1690 // different but files are the same (symlinks) (VZ)
1691
1692 return false;
1693 }
1694
1695 /* static */
1696 bool wxFileName::IsCaseSensitive( wxPathFormat format )
1697 {
1698 // only Unix filenames are truely case-sensitive
1699 return GetFormat(format) == wxPATH_UNIX;
1700 }
1701
1702 /* static */
1703 wxString wxFileName::GetForbiddenChars(wxPathFormat format)
1704 {
1705 // Inits to forbidden characters that are common to (almost) all platforms.
1706 wxString strForbiddenChars = wxT("*?");
1707
1708 // If asserts, wxPathFormat has been changed. In case of a new path format
1709 // addition, the following code might have to be updated.
1710 wxCOMPILE_TIME_ASSERT(wxPATH_MAX == 5, wxPathFormatChanged);
1711 switch ( GetFormat(format) )
1712 {
1713 default :
1714 wxFAIL_MSG( wxT("Unknown path format") );
1715 // !! Fall through !!
1716
1717 case wxPATH_UNIX:
1718 break;
1719
1720 case wxPATH_MAC:
1721 // On a Mac even names with * and ? are allowed (Tested with OS
1722 // 9.2.1 and OS X 10.2.5)
1723 strForbiddenChars = wxEmptyString;
1724 break;
1725
1726 case wxPATH_DOS:
1727 strForbiddenChars += wxT("\\/:\"<>|");
1728 break;
1729
1730 case wxPATH_VMS:
1731 break;
1732 }
1733
1734 return strForbiddenChars;
1735 }
1736
1737 /* static */
1738 wxString wxFileName::GetVolumeSeparator(wxPathFormat WXUNUSED_IN_WINCE(format))
1739 {
1740 #ifdef __WXWINCE__
1741 return wxEmptyString;
1742 #else
1743 wxString sepVol;
1744
1745 if ( (GetFormat(format) == wxPATH_DOS) ||
1746 (GetFormat(format) == wxPATH_VMS) )
1747 {
1748 sepVol = wxFILE_SEP_DSK;
1749 }
1750 //else: leave empty
1751
1752 return sepVol;
1753 #endif
1754 }
1755
1756 /* static */
1757 wxString wxFileName::GetPathSeparators(wxPathFormat format)
1758 {
1759 wxString seps;
1760 switch ( GetFormat(format) )
1761 {
1762 case wxPATH_DOS:
1763 // accept both as native APIs do but put the native one first as
1764 // this is the one we use in GetFullPath()
1765 seps << wxFILE_SEP_PATH_DOS << wxFILE_SEP_PATH_UNIX;
1766 break;
1767
1768 default:
1769 wxFAIL_MSG( wxT("Unknown wxPATH_XXX style") );
1770 // fall through
1771
1772 case wxPATH_UNIX:
1773 seps = wxFILE_SEP_PATH_UNIX;
1774 break;
1775
1776 case wxPATH_MAC:
1777 seps = wxFILE_SEP_PATH_MAC;
1778 break;
1779
1780 case wxPATH_VMS:
1781 seps = wxFILE_SEP_PATH_VMS;
1782 break;
1783 }
1784
1785 return seps;
1786 }
1787
1788 /* static */
1789 wxString wxFileName::GetPathTerminators(wxPathFormat format)
1790 {
1791 format = GetFormat(format);
1792
1793 // under VMS the end of the path is ']', not the path separator used to
1794 // separate the components
1795 return format == wxPATH_VMS ? wxString(wxT(']')) : GetPathSeparators(format);
1796 }
1797
1798 /* static */
1799 bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
1800 {
1801 // wxString::Find() doesn't work as expected with NUL - it will always find
1802 // it, so test for it separately
1803 return ch != wxT('\0') && GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
1804 }
1805
1806 // ----------------------------------------------------------------------------
1807 // path components manipulation
1808 // ----------------------------------------------------------------------------
1809
1810 /* static */ bool wxFileName::IsValidDirComponent(const wxString& dir)
1811 {
1812 if ( dir.empty() )
1813 {
1814 wxFAIL_MSG( wxT("empty directory passed to wxFileName::InsertDir()") );
1815
1816 return false;
1817 }
1818
1819 const size_t len = dir.length();
1820 for ( size_t n = 0; n < len; n++ )
1821 {
1822 if ( dir[n] == GetVolumeSeparator() || IsPathSeparator(dir[n]) )
1823 {
1824 wxFAIL_MSG( wxT("invalid directory component in wxFileName") );
1825
1826 return false;
1827 }
1828 }
1829
1830 return true;
1831 }
1832
1833 void wxFileName::AppendDir( const wxString& dir )
1834 {
1835 if ( IsValidDirComponent(dir) )
1836 m_dirs.Add( dir );
1837 }
1838
1839 void wxFileName::PrependDir( const wxString& dir )
1840 {
1841 InsertDir(0, dir);
1842 }
1843
1844 void wxFileName::InsertDir(size_t before, const wxString& dir)
1845 {
1846 if ( IsValidDirComponent(dir) )
1847 m_dirs.Insert(dir, before);
1848 }
1849
1850 void wxFileName::RemoveDir(size_t pos)
1851 {
1852 m_dirs.RemoveAt(pos);
1853 }
1854
1855 // ----------------------------------------------------------------------------
1856 // accessors
1857 // ----------------------------------------------------------------------------
1858
1859 void wxFileName::SetFullName(const wxString& fullname)
1860 {
1861 SplitPath(fullname, NULL /* no volume */, NULL /* no path */,
1862 &m_name, &m_ext, &m_hasExt);
1863 }
1864
1865 wxString wxFileName::GetFullName() const
1866 {
1867 wxString fullname = m_name;
1868 if ( m_hasExt )
1869 {
1870 fullname << wxFILE_SEP_EXT << m_ext;
1871 }
1872
1873 return fullname;
1874 }
1875
1876 wxString wxFileName::GetPath( int flags, wxPathFormat format ) const
1877 {
1878 format = GetFormat( format );
1879
1880 wxString fullpath;
1881
1882 // return the volume with the path as well if requested
1883 if ( flags & wxPATH_GET_VOLUME )
1884 {
1885 fullpath += wxGetVolumeString(GetVolume(), format);
1886 }
1887
1888 // the leading character
1889 switch ( format )
1890 {
1891 case wxPATH_MAC:
1892 if ( m_relative )
1893 fullpath += wxFILE_SEP_PATH_MAC;
1894 break;
1895
1896 case wxPATH_DOS:
1897 if ( !m_relative )
1898 fullpath += wxFILE_SEP_PATH_DOS;
1899 break;
1900
1901 default:
1902 wxFAIL_MSG( wxT("Unknown path format") );
1903 // fall through
1904
1905 case wxPATH_UNIX:
1906 if ( !m_relative )
1907 {
1908 fullpath += wxFILE_SEP_PATH_UNIX;
1909 }
1910 break;
1911
1912 case wxPATH_VMS:
1913 // no leading character here but use this place to unset
1914 // wxPATH_GET_SEPARATOR flag: under VMS it doesn't make sense
1915 // as, if I understand correctly, there should never be a dot
1916 // before the closing bracket
1917 flags &= ~wxPATH_GET_SEPARATOR;
1918 }
1919
1920 if ( m_dirs.empty() )
1921 {
1922 // there is nothing more
1923 return fullpath;
1924 }
1925
1926 // then concatenate all the path components using the path separator
1927 if ( format == wxPATH_VMS )
1928 {
1929 fullpath += wxT('[');
1930 }
1931
1932 const size_t dirCount = m_dirs.GetCount();
1933 for ( size_t i = 0; i < dirCount; i++ )
1934 {
1935 switch (format)
1936 {
1937 case wxPATH_MAC:
1938 if ( m_dirs[i] == wxT(".") )
1939 {
1940 // skip appending ':', this shouldn't be done in this
1941 // case as "::" is interpreted as ".." under Unix
1942 continue;
1943 }
1944
1945 // convert back from ".." to nothing
1946 if ( !m_dirs[i].IsSameAs(wxT("..")) )
1947 fullpath += m_dirs[i];
1948 break;
1949
1950 default:
1951 wxFAIL_MSG( wxT("Unexpected path format") );
1952 // still fall through
1953
1954 case wxPATH_DOS:
1955 case wxPATH_UNIX:
1956 fullpath += m_dirs[i];
1957 break;
1958
1959 case wxPATH_VMS:
1960 // TODO: What to do with ".." under VMS
1961
1962 // convert back from ".." to nothing
1963 if ( !m_dirs[i].IsSameAs(wxT("..")) )
1964 fullpath += m_dirs[i];
1965 break;
1966 }
1967
1968 if ( (flags & wxPATH_GET_SEPARATOR) || (i != dirCount - 1) )
1969 fullpath += GetPathSeparator(format);
1970 }
1971
1972 if ( format == wxPATH_VMS )
1973 {
1974 fullpath += wxT(']');
1975 }
1976
1977 return fullpath;
1978 }
1979
1980 wxString wxFileName::GetFullPath( wxPathFormat format ) const
1981 {
1982 // we already have a function to get the path
1983 wxString fullpath = GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR,
1984 format);
1985
1986 // now just add the file name and extension to it
1987 fullpath += GetFullName();
1988
1989 return fullpath;
1990 }
1991
1992 // Return the short form of the path (returns identity on non-Windows platforms)
1993 wxString wxFileName::GetShortPath() const
1994 {
1995 wxString path(GetFullPath());
1996
1997 #if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
1998 DWORD sz = ::GetShortPathName(path.fn_str(), NULL, 0);
1999 if ( sz != 0 )
2000 {
2001 wxString pathOut;
2002 if ( ::GetShortPathName
2003 (
2004 path.fn_str(),
2005 wxStringBuffer(pathOut, sz),
2006 sz
2007 ) != 0 )
2008 {
2009 return pathOut;
2010 }
2011 }
2012 #endif // Windows
2013
2014 return path;
2015 }
2016
2017 // Return the long form of the path (returns identity on non-Windows platforms)
2018 wxString wxFileName::GetLongPath() const
2019 {
2020 wxString pathOut,
2021 path = GetFullPath();
2022
2023 #if defined(__WIN32__) && !defined(__WXWINCE__) && !defined(__WXMICROWIN__)
2024
2025 #if wxUSE_DYNLIB_CLASS
2026 typedef DWORD (WINAPI *GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
2027
2028 // this is MT-safe as in the worst case we're going to resolve the function
2029 // twice -- but as the result is the same in both threads, it's ok
2030 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
2031 if ( !s_pfnGetLongPathName )
2032 {
2033 static bool s_triedToLoad = false;
2034
2035 if ( !s_triedToLoad )
2036 {
2037 s_triedToLoad = true;
2038
2039 wxDynamicLibrary dllKernel(wxT("kernel32"));
2040
2041 const wxChar* GetLongPathName = wxT("GetLongPathName")
2042 #if wxUSE_UNICODE
2043 wxT("W");
2044 #else // ANSI
2045 wxT("A");
2046 #endif // Unicode/ANSI
2047
2048 if ( dllKernel.HasSymbol(GetLongPathName) )
2049 {
2050 s_pfnGetLongPathName = (GET_LONG_PATH_NAME)
2051 dllKernel.GetSymbol(GetLongPathName);
2052 }
2053
2054 // note that kernel32.dll can be unloaded, it stays in memory
2055 // anyhow as all Win32 programs link to it and so it's safe to call
2056 // GetLongPathName() even after unloading it
2057 }
2058 }
2059
2060 if ( s_pfnGetLongPathName )
2061 {
2062 DWORD dwSize = (*s_pfnGetLongPathName)(path.fn_str(), NULL, 0);
2063 if ( dwSize > 0 )
2064 {
2065 if ( (*s_pfnGetLongPathName)
2066 (
2067 path.fn_str(),
2068 wxStringBuffer(pathOut, dwSize),
2069 dwSize
2070 ) != 0 )
2071 {
2072 return pathOut;
2073 }
2074 }
2075 }
2076 #endif // wxUSE_DYNLIB_CLASS
2077
2078 // The OS didn't support GetLongPathName, or some other error.
2079 // We need to call FindFirstFile on each component in turn.
2080
2081 WIN32_FIND_DATA findFileData;
2082 HANDLE hFind;
2083
2084 if ( HasVolume() )
2085 pathOut = GetVolume() +
2086 GetVolumeSeparator(wxPATH_DOS) +
2087 GetPathSeparator(wxPATH_DOS);
2088 else
2089 pathOut = wxEmptyString;
2090
2091 wxArrayString dirs = GetDirs();
2092 dirs.Add(GetFullName());
2093
2094 wxString tmpPath;
2095
2096 size_t count = dirs.GetCount();
2097 for ( size_t i = 0; i < count; i++ )
2098 {
2099 const wxString& dir = dirs[i];
2100
2101 // We're using pathOut to collect the long-name path, but using a
2102 // temporary for appending the last path component which may be
2103 // short-name
2104 tmpPath = pathOut + dir;
2105
2106 // We must not process "." or ".." here as they would be (unexpectedly)
2107 // replaced by the corresponding directory names so just leave them
2108 // alone
2109 //
2110 // And we can't pass a drive and root dir to FindFirstFile (VZ: why?)
2111 if ( tmpPath.empty() || dir == '.' || dir == ".." ||
2112 tmpPath.Last() == GetVolumeSeparator(wxPATH_DOS) )
2113 {
2114 tmpPath += wxFILE_SEP_PATH;
2115 pathOut = tmpPath;
2116 continue;
2117 }
2118
2119 hFind = ::FindFirstFile(tmpPath.fn_str(), &findFileData);
2120 if (hFind == INVALID_HANDLE_VALUE)
2121 {
2122 // Error: most likely reason is that path doesn't exist, so
2123 // append any unprocessed parts and return
2124 for ( i += 1; i < count; i++ )
2125 tmpPath += wxFILE_SEP_PATH + dirs[i];
2126
2127 return tmpPath;
2128 }
2129
2130 pathOut += findFileData.cFileName;
2131 if ( (i < (count-1)) )
2132 pathOut += wxFILE_SEP_PATH;
2133
2134 ::FindClose(hFind);
2135 }
2136 #else // !Win32
2137 pathOut = path;
2138 #endif // Win32/!Win32
2139
2140 return pathOut;
2141 }
2142
2143 wxPathFormat wxFileName::GetFormat( wxPathFormat format )
2144 {
2145 if (format == wxPATH_NATIVE)
2146 {
2147 #if defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__)
2148 format = wxPATH_DOS;
2149 #elif defined(__VMS)
2150 format = wxPATH_VMS;
2151 #else
2152 format = wxPATH_UNIX;
2153 #endif
2154 }
2155 return format;
2156 }
2157
2158 #ifdef wxHAS_FILESYSTEM_VOLUMES
2159
2160 /* static */
2161 wxString wxFileName::GetVolumeString(char drive, int flags)
2162 {
2163 wxASSERT_MSG( !(flags & ~wxPATH_GET_SEPARATOR), "invalid flag specified" );
2164
2165 wxString vol(drive);
2166 vol += wxFILE_SEP_DSK;
2167 if ( flags & wxPATH_GET_SEPARATOR )
2168 vol += wxFILE_SEP_PATH;
2169
2170 return vol;
2171 }
2172
2173 #endif // wxHAS_FILESYSTEM_VOLUMES
2174
2175 // ----------------------------------------------------------------------------
2176 // path splitting function
2177 // ----------------------------------------------------------------------------
2178
2179 /* static */
2180 void
2181 wxFileName::SplitVolume(const wxString& fullpathWithVolume,
2182 wxString *pstrVolume,
2183 wxString *pstrPath,
2184 wxPathFormat format)
2185 {
2186 format = GetFormat(format);
2187
2188 wxString fullpath = fullpathWithVolume;
2189
2190 // special Windows UNC paths hack: transform \\share\path into share:path
2191 if ( IsUNCPath(fullpath, format) )
2192 {
2193 fullpath.erase(0, 2);
2194
2195 size_t posFirstSlash =
2196 fullpath.find_first_of(GetPathTerminators(format));
2197 if ( posFirstSlash != wxString::npos )
2198 {
2199 fullpath[posFirstSlash] = wxFILE_SEP_DSK;
2200
2201 // UNC paths are always absolute, right? (FIXME)
2202 fullpath.insert(posFirstSlash + 1, 1, wxFILE_SEP_PATH_DOS);
2203 }
2204 }
2205
2206 // We separate the volume here
2207 if ( format == wxPATH_DOS || format == wxPATH_VMS )
2208 {
2209 wxString sepVol = GetVolumeSeparator(format);
2210
2211 // we have to exclude the case of a colon in the very beginning of the
2212 // string as it can't be a volume separator (nor can this be a valid
2213 // DOS file name at all but we'll leave dealing with this to our caller)
2214 size_t posFirstColon = fullpath.find_first_of(sepVol);
2215 if ( posFirstColon && posFirstColon != wxString::npos )
2216 {
2217 if ( pstrVolume )
2218 {
2219 *pstrVolume = fullpath.Left(posFirstColon);
2220 }
2221
2222 // remove the volume name and the separator from the full path
2223 fullpath.erase(0, posFirstColon + sepVol.length());
2224 }
2225 }
2226
2227 if ( pstrPath )
2228 *pstrPath = fullpath;
2229 }
2230
2231 /* static */
2232 void wxFileName::SplitPath(const wxString& fullpathWithVolume,
2233 wxString *pstrVolume,
2234 wxString *pstrPath,
2235 wxString *pstrName,
2236 wxString *pstrExt,
2237 bool *hasExt,
2238 wxPathFormat format)
2239 {
2240 format = GetFormat(format);
2241
2242 wxString fullpath;
2243 SplitVolume(fullpathWithVolume, pstrVolume, &fullpath, format);
2244
2245 // find the positions of the last dot and last path separator in the path
2246 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
2247 size_t posLastSlash = fullpath.find_last_of(GetPathTerminators(format));
2248
2249 // check whether this dot occurs at the very beginning of a path component
2250 if ( (posLastDot != wxString::npos) &&
2251 (posLastDot == 0 ||
2252 IsPathSeparator(fullpath[posLastDot - 1]) ||
2253 (format == wxPATH_VMS && fullpath[posLastDot - 1] == wxT(']'))) )
2254 {
2255 // dot may be (and commonly -- at least under Unix -- is) the first
2256 // character of the filename, don't treat the entire filename as
2257 // extension in this case
2258 posLastDot = wxString::npos;
2259 }
2260
2261 // if we do have a dot and a slash, check that the dot is in the name part
2262 if ( (posLastDot != wxString::npos) &&
2263 (posLastSlash != wxString::npos) &&
2264 (posLastDot < posLastSlash) )
2265 {
2266 // the dot is part of the path, not the start of the extension
2267 posLastDot = wxString::npos;
2268 }
2269
2270 // now fill in the variables provided by user
2271 if ( pstrPath )
2272 {
2273 if ( posLastSlash == wxString::npos )
2274 {
2275 // no path at all
2276 pstrPath->Empty();
2277 }
2278 else
2279 {
2280 // take everything up to the path separator but take care to make
2281 // the path equal to something like '/', not empty, for the files
2282 // immediately under root directory
2283 size_t len = posLastSlash;
2284
2285 // this rule does not apply to mac since we do not start with colons (sep)
2286 // except for relative paths
2287 if ( !len && format != wxPATH_MAC)
2288 len++;
2289
2290 *pstrPath = fullpath.Left(len);
2291
2292 // special VMS hack: remove the initial bracket
2293 if ( format == wxPATH_VMS )
2294 {
2295 if ( (*pstrPath)[0u] == wxT('[') )
2296 pstrPath->erase(0, 1);
2297 }
2298 }
2299 }
2300
2301 if ( pstrName )
2302 {
2303 // take all characters starting from the one after the last slash and
2304 // up to, but excluding, the last dot
2305 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
2306 size_t count;
2307 if ( posLastDot == wxString::npos )
2308 {
2309 // take all until the end
2310 count = wxString::npos;
2311 }
2312 else if ( posLastSlash == wxString::npos )
2313 {
2314 count = posLastDot;
2315 }
2316 else // have both dot and slash
2317 {
2318 count = posLastDot - posLastSlash - 1;
2319 }
2320
2321 *pstrName = fullpath.Mid(nStart, count);
2322 }
2323
2324 // finally deal with the extension here: we have an added complication that
2325 // extension may be empty (but present) as in "foo." where trailing dot
2326 // indicates the empty extension at the end -- and hence we must remember
2327 // that we have it independently of pstrExt
2328 if ( posLastDot == wxString::npos )
2329 {
2330 // no extension
2331 if ( pstrExt )
2332 pstrExt->clear();
2333 if ( hasExt )
2334 *hasExt = false;
2335 }
2336 else
2337 {
2338 // take everything after the dot
2339 if ( pstrExt )
2340 *pstrExt = fullpath.Mid(posLastDot + 1);
2341 if ( hasExt )
2342 *hasExt = true;
2343 }
2344 }
2345
2346 /* static */
2347 void wxFileName::SplitPath(const wxString& fullpath,
2348 wxString *path,
2349 wxString *name,
2350 wxString *ext,
2351 wxPathFormat format)
2352 {
2353 wxString volume;
2354 SplitPath(fullpath, &volume, path, name, ext, format);
2355
2356 if ( path )
2357 {
2358 path->Prepend(wxGetVolumeString(volume, format));
2359 }
2360 }
2361
2362 /* static */
2363 wxString wxFileName::StripExtension(const wxString& fullpath)
2364 {
2365 wxFileName fn(fullpath);
2366 fn.SetExt("");
2367 return fn.GetFullPath();
2368 }
2369
2370 // ----------------------------------------------------------------------------
2371 // time functions
2372 // ----------------------------------------------------------------------------
2373
2374 #if wxUSE_DATETIME
2375
2376 bool wxFileName::SetTimes(const wxDateTime *dtAccess,
2377 const wxDateTime *dtMod,
2378 const wxDateTime *dtCreate) const
2379 {
2380 #if defined(__WIN32__)
2381 FILETIME ftAccess, ftCreate, ftWrite;
2382
2383 if ( dtCreate )
2384 ConvertWxToFileTime(&ftCreate, *dtCreate);
2385 if ( dtAccess )
2386 ConvertWxToFileTime(&ftAccess, *dtAccess);
2387 if ( dtMod )
2388 ConvertWxToFileTime(&ftWrite, *dtMod);
2389
2390 wxString path;
2391 int flags;
2392 if ( IsDir() )
2393 {
2394 if ( wxGetOsVersion() == wxOS_WINDOWS_9X )
2395 {
2396 wxLogError(_("Setting directory access times is not supported "
2397 "under this OS version"));
2398 return false;
2399 }
2400
2401 path = GetPath();
2402 flags = FILE_FLAG_BACKUP_SEMANTICS;
2403 }
2404 else // file
2405 {
2406 path = GetFullPath();
2407 flags = 0;
2408 }
2409
2410 wxFileHandle fh(path, wxFileHandle::WriteAttr, flags);
2411 if ( fh.IsOk() )
2412 {
2413 if ( ::SetFileTime(fh,
2414 dtCreate ? &ftCreate : NULL,
2415 dtAccess ? &ftAccess : NULL,
2416 dtMod ? &ftWrite : NULL) )
2417 {
2418 return true;
2419 }
2420 }
2421 #elif defined(__UNIX_LIKE__) || (defined(__DOS__) && defined(__WATCOMC__))
2422 wxUnusedVar(dtCreate);
2423
2424 if ( !dtAccess && !dtMod )
2425 {
2426 // can't modify the creation time anyhow, don't try
2427 return true;
2428 }
2429
2430 // if dtAccess or dtMod is not specified, use the other one (which must be
2431 // non NULL because of the test above) for both times
2432 utimbuf utm;
2433 utm.actime = dtAccess ? dtAccess->GetTicks() : dtMod->GetTicks();
2434 utm.modtime = dtMod ? dtMod->GetTicks() : dtAccess->GetTicks();
2435 if ( utime(GetFullPath().fn_str(), &utm) == 0 )
2436 {
2437 return true;
2438 }
2439 #else // other platform
2440 wxUnusedVar(dtAccess);
2441 wxUnusedVar(dtMod);
2442 wxUnusedVar(dtCreate);
2443 #endif // platforms
2444
2445 wxLogSysError(_("Failed to modify file times for '%s'"),
2446 GetFullPath().c_str());
2447
2448 return false;
2449 }
2450
2451 bool wxFileName::Touch() const
2452 {
2453 #if defined(__UNIX_LIKE__)
2454 // under Unix touching file is simple: just pass NULL to utime()
2455 if ( utime(GetFullPath().fn_str(), NULL) == 0 )
2456 {
2457 return true;
2458 }
2459
2460 wxLogSysError(_("Failed to touch the file '%s'"), GetFullPath().c_str());
2461
2462 return false;
2463 #else // other platform
2464 wxDateTime dtNow = wxDateTime::Now();
2465
2466 return SetTimes(&dtNow, &dtNow, NULL /* don't change create time */);
2467 #endif // platforms
2468 }
2469
2470 bool wxFileName::GetTimes(wxDateTime *dtAccess,
2471 wxDateTime *dtMod,
2472 wxDateTime *dtCreate) const
2473 {
2474 #if defined(__WIN32__)
2475 // we must use different methods for the files and directories under
2476 // Windows as CreateFile(GENERIC_READ) doesn't work for the directories and
2477 // CreateFile(FILE_FLAG_BACKUP_SEMANTICS) works -- but only under NT and
2478 // not 9x
2479 bool ok;
2480 FILETIME ftAccess, ftCreate, ftWrite;
2481 if ( IsDir() )
2482 {
2483 // implemented in msw/dir.cpp
2484 extern bool wxGetDirectoryTimes(const wxString& dirname,
2485 FILETIME *, FILETIME *, FILETIME *);
2486
2487 // we should pass the path without the trailing separator to
2488 // wxGetDirectoryTimes()
2489 ok = wxGetDirectoryTimes(GetPath(wxPATH_GET_VOLUME),
2490 &ftAccess, &ftCreate, &ftWrite);
2491 }
2492 else // file
2493 {
2494 wxFileHandle fh(GetFullPath(), wxFileHandle::ReadAttr);
2495 if ( fh.IsOk() )
2496 {
2497 ok = ::GetFileTime(fh,
2498 dtCreate ? &ftCreate : NULL,
2499 dtAccess ? &ftAccess : NULL,
2500 dtMod ? &ftWrite : NULL) != 0;
2501 }
2502 else
2503 {
2504 ok = false;
2505 }
2506 }
2507
2508 if ( ok )
2509 {
2510 if ( dtCreate )
2511 ConvertFileTimeToWx(dtCreate, ftCreate);
2512 if ( dtAccess )
2513 ConvertFileTimeToWx(dtAccess, ftAccess);
2514 if ( dtMod )
2515 ConvertFileTimeToWx(dtMod, ftWrite);
2516
2517 return true;
2518 }
2519 #elif defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__OS2__) || (defined(__DOS__) && defined(__WATCOMC__))
2520 // no need to test for IsDir() here
2521 wxStructStat stBuf;
2522 if ( wxStat( GetFullPath().c_str(), &stBuf) == 0 )
2523 {
2524 if ( dtAccess )
2525 dtAccess->Set(stBuf.st_atime);
2526 if ( dtMod )
2527 dtMod->Set(stBuf.st_mtime);
2528 if ( dtCreate )
2529 dtCreate->Set(stBuf.st_ctime);
2530
2531 return true;
2532 }
2533 #else // other platform
2534 wxUnusedVar(dtAccess);
2535 wxUnusedVar(dtMod);
2536 wxUnusedVar(dtCreate);
2537 #endif // platforms
2538
2539 wxLogSysError(_("Failed to retrieve file times for '%s'"),
2540 GetFullPath().c_str());
2541
2542 return false;
2543 }
2544
2545 #endif // wxUSE_DATETIME
2546
2547
2548 // ----------------------------------------------------------------------------
2549 // file size functions
2550 // ----------------------------------------------------------------------------
2551
2552 #if wxUSE_LONGLONG
2553
2554 /* static */
2555 wxULongLong wxFileName::GetSize(const wxString &filename)
2556 {
2557 if (!wxFileExists(filename))
2558 return wxInvalidSize;
2559
2560 #if defined(__WXPALMOS__)
2561 // TODO
2562 return wxInvalidSize;
2563 #elif defined(__WIN32__)
2564 wxFileHandle f(filename, wxFileHandle::ReadAttr);
2565 if (!f.IsOk())
2566 return wxInvalidSize;
2567
2568 DWORD lpFileSizeHigh;
2569 DWORD ret = GetFileSize(f, &lpFileSizeHigh);
2570 if ( ret == INVALID_FILE_SIZE && ::GetLastError() != NO_ERROR )
2571 return wxInvalidSize;
2572
2573 return wxULongLong(lpFileSizeHigh, ret);
2574 #else // ! __WIN32__
2575 wxStructStat st;
2576 #ifndef wxNEED_WX_UNISTD_H
2577 if (wxStat( filename.fn_str() , &st) != 0)
2578 #else
2579 if (wxStat( filename, &st) != 0)
2580 #endif
2581 return wxInvalidSize;
2582 return wxULongLong(st.st_size);
2583 #endif
2584 }
2585
2586 /* static */
2587 wxString wxFileName::GetHumanReadableSize(const wxULongLong &bs,
2588 const wxString &nullsize,
2589 int precision)
2590 {
2591 static const double KILOBYTESIZE = 1024.0;
2592 static const double MEGABYTESIZE = 1024.0*KILOBYTESIZE;
2593 static const double GIGABYTESIZE = 1024.0*MEGABYTESIZE;
2594 static const double TERABYTESIZE = 1024.0*GIGABYTESIZE;
2595
2596 if (bs == 0 || bs == wxInvalidSize)
2597 return nullsize;
2598
2599 double bytesize = bs.ToDouble();
2600 if (bytesize < KILOBYTESIZE)
2601 return wxString::Format(_("%s B"), bs.ToString().c_str());
2602 if (bytesize < MEGABYTESIZE)
2603 return wxString::Format(_("%.*f kB"), precision, bytesize/KILOBYTESIZE);
2604 if (bytesize < GIGABYTESIZE)
2605 return wxString::Format(_("%.*f MB"), precision, bytesize/MEGABYTESIZE);
2606 if (bytesize < TERABYTESIZE)
2607 return wxString::Format(_("%.*f GB"), precision, bytesize/GIGABYTESIZE);
2608
2609 return wxString::Format(_("%.*f TB"), precision, bytesize/TERABYTESIZE);
2610 }
2611
2612 wxULongLong wxFileName::GetSize() const
2613 {
2614 return GetSize(GetFullPath());
2615 }
2616
2617 wxString wxFileName::GetHumanReadableSize(const wxString &failmsg, int precision) const
2618 {
2619 return GetHumanReadableSize(GetSize(), failmsg, precision);
2620 }
2621
2622 #endif // wxUSE_LONGLONG
2623
2624 // ----------------------------------------------------------------------------
2625 // Mac-specific functions
2626 // ----------------------------------------------------------------------------
2627
2628 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
2629
2630 namespace
2631 {
2632
2633 class MacDefaultExtensionRecord
2634 {
2635 public:
2636 MacDefaultExtensionRecord()
2637 {
2638 m_type =
2639 m_creator = 0 ;
2640 }
2641
2642 // default copy ctor, assignment operator and dtor are ok
2643
2644 MacDefaultExtensionRecord(const wxString& ext, OSType type, OSType creator)
2645 : m_ext(ext)
2646 {
2647 m_type = type;
2648 m_creator = creator;
2649 }
2650
2651 wxString m_ext;
2652 OSType m_type;
2653 OSType m_creator;
2654 };
2655
2656 WX_DECLARE_OBJARRAY(MacDefaultExtensionRecord, MacDefaultExtensionArray);
2657
2658 bool gMacDefaultExtensionsInited = false;
2659
2660 #include "wx/arrimpl.cpp"
2661
2662 WX_DEFINE_EXPORTED_OBJARRAY(MacDefaultExtensionArray);
2663
2664 MacDefaultExtensionArray gMacDefaultExtensions;
2665
2666 // load the default extensions
2667 const MacDefaultExtensionRecord gDefaults[] =
2668 {
2669 MacDefaultExtensionRecord( "txt", 'TEXT', 'ttxt' ),
2670 MacDefaultExtensionRecord( "tif", 'TIFF', '****' ),
2671 MacDefaultExtensionRecord( "jpg", 'JPEG', '****' ),
2672 };
2673
2674 void MacEnsureDefaultExtensionsLoaded()
2675 {
2676 if ( !gMacDefaultExtensionsInited )
2677 {
2678 // we could load the pc exchange prefs here too
2679 for ( size_t i = 0 ; i < WXSIZEOF( gDefaults ) ; ++i )
2680 {
2681 gMacDefaultExtensions.Add( gDefaults[i] ) ;
2682 }
2683 gMacDefaultExtensionsInited = true;
2684 }
2685 }
2686
2687 } // anonymous namespace
2688
2689 bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
2690 {
2691 FSRef fsRef ;
2692 FSCatalogInfo catInfo;
2693 FileInfo *finfo ;
2694
2695 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2696 {
2697 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2698 {
2699 finfo = (FileInfo*)&catInfo.finderInfo;
2700 finfo->fileType = type ;
2701 finfo->fileCreator = creator ;
2702 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
2703 return true ;
2704 }
2705 }
2706 return false ;
2707 }
2708
2709 bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator ) const
2710 {
2711 FSRef fsRef ;
2712 FSCatalogInfo catInfo;
2713 FileInfo *finfo ;
2714
2715 if ( wxMacPathToFSRef( GetFullPath() , &fsRef ) == noErr )
2716 {
2717 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
2718 {
2719 finfo = (FileInfo*)&catInfo.finderInfo;
2720 *type = finfo->fileType ;
2721 *creator = finfo->fileCreator ;
2722 return true ;
2723 }
2724 }
2725 return false ;
2726 }
2727
2728 bool wxFileName::MacSetDefaultTypeAndCreator()
2729 {
2730 wxUint32 type , creator ;
2731 if ( wxFileName::MacFindDefaultTypeAndCreator(GetExt() , &type ,
2732 &creator ) )
2733 {
2734 return MacSetTypeAndCreator( type , creator ) ;
2735 }
2736 return false;
2737 }
2738
2739 bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
2740 {
2741 MacEnsureDefaultExtensionsLoaded() ;
2742 wxString extl = ext.Lower() ;
2743 for( int i = gMacDefaultExtensions.Count() - 1 ; i >= 0 ; --i )
2744 {
2745 if ( gMacDefaultExtensions.Item(i).m_ext == extl )
2746 {
2747 *type = gMacDefaultExtensions.Item(i).m_type ;
2748 *creator = gMacDefaultExtensions.Item(i).m_creator ;
2749 return true ;
2750 }
2751 }
2752 return false ;
2753 }
2754
2755 void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )
2756 {
2757 MacEnsureDefaultExtensionsLoaded();
2758 MacDefaultExtensionRecord rec(ext.Lower(), type, creator);
2759 gMacDefaultExtensions.Add( rec );
2760 }
2761
2762 #endif // defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON