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