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