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