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