]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/filename.cpp
better learn the operators...
[wxWidgets.git] / src / common / filename.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: src/common/filename.cpp
3// Purpose: wxFileName - encapsulates a file path
4// Author: Robert Roebling, Vadim Zeitlin
5// Modified by:
6// Created: 28.12.2000
7// RCS-ID: $Id$
8// Copyright: (c) 2000 Robert Roebling
9// Licence: wxWindows license
10/////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
20#ifdef __GNUG__
21 #pragma implementation "filename.h"
22#endif
23
24// For compilers that support precompilation, includes "wx.h".
25#include "wx/wxprec.h"
26
27#ifdef __BORLANDC__
28 #pragma hdrstop
29#endif
30
31#ifndef WX_PRECOMP
32 #include "wx/intl.h"
33 #include "wx/log.h"
34#endif
35
36#include "wx/filename.h"
37#include "wx/tokenzr.h"
38#include "wx/config.h" // for wxExpandEnvVars
39#include "wx/utils.h"
40
41#if wxUSE_DYNLIB_CLASS
42#include "wx/dynlib.h"
43#endif
44
45// For GetShort/LongPathName
46#ifdef __WIN32__
47#include <windows.h>
48#include "wx/msw/winundef.h"
49#endif
50
51// ============================================================================
52// implementation
53// ============================================================================
54
55// ----------------------------------------------------------------------------
56// wxFileName construction
57// ----------------------------------------------------------------------------
58
59void wxFileName::Assign( const wxFileName &filepath )
60{
61 m_ext = filepath.GetExt();
62 m_name = filepath.GetName();
63 m_dirs = filepath.GetDirs();
64}
65
66void wxFileName::Assign( const wxString& path,
67 const wxString& name,
68 const wxString& ext,
69 wxPathFormat format )
70{
71 wxStringTokenizer tn(path, GetPathSeparators(format),
72 wxTOKEN_RET_EMPTY_ALL);
73 bool first = TRUE;
74 m_dirs.Clear();
75 while ( tn.HasMoreTokens() )
76 {
77 wxString token = tn.GetNextToken();
78
79 // If the path starts with a slash, we need the first
80 // dir entry to be an empty for later reassembly.
81 if (first || !token.IsEmpty())
82 m_dirs.Add( token );
83
84 first = FALSE;
85 }
86
87 m_ext = ext;
88 m_name = name;
89}
90
91void wxFileName::Assign(const wxString& fullpath,
92 wxPathFormat format)
93{
94 wxString path, name, ext;
95 SplitPath(fullpath, &path, &name, &ext, format);
96
97 Assign(path, name, ext, format);
98}
99
100void wxFileName::Assign(const wxString& path,
101 const wxString& fullname,
102 wxPathFormat format)
103{
104 wxString name, ext;
105 SplitPath(fullname, NULL /* no path */, &name, &ext, format);
106
107 Assign(path, name, ext, format);
108}
109
110void wxFileName::Clear()
111{
112 m_dirs.Clear();
113 m_name =
114 m_ext = wxEmptyString;
115}
116
117/* static */
118wxFileName wxFileName::FileName(const wxString& file)
119{
120 return wxFileName(file);
121}
122
123/* static */
124wxFileName wxFileName::DirName(const wxString& dir)
125{
126 wxFileName fn;
127 fn.AssignDir(dir);
128 return fn;
129}
130
131// ----------------------------------------------------------------------------
132// existence tests
133// ----------------------------------------------------------------------------
134
135bool wxFileName::FileExists()
136{
137 return wxFileName::FileExists( GetFullPath() );
138}
139
140bool wxFileName::FileExists( const wxString &file )
141{
142 return ::wxFileExists( file );
143}
144
145bool wxFileName::DirExists()
146{
147 return wxFileName::DirExists( GetFullPath() );
148}
149
150bool wxFileName::DirExists( const wxString &dir )
151{
152 return ::wxDirExists( dir );
153}
154
155wxDateTime wxFileName::GetModificationTime()
156{
157 wxDateTime ret( wxFileModificationTime( GetFullPath() ) );
158
159 return ret;
160}
161
162// ----------------------------------------------------------------------------
163// CWD and HOME stuff
164// ----------------------------------------------------------------------------
165
166void wxFileName::AssignCwd()
167{
168 AssignDir(wxFileName::GetCwd());
169}
170
171/* static */
172wxString wxFileName::GetCwd()
173{
174 return ::wxGetCwd();
175}
176
177bool wxFileName::SetCwd()
178{
179 return wxFileName::SetCwd( GetFullPath() );
180}
181
182bool wxFileName::SetCwd( const wxString &cwd )
183{
184 return ::wxSetWorkingDirectory( cwd );
185}
186
187void wxFileName::AssignHomeDir()
188{
189 AssignDir(wxFileName::GetHomeDir());
190}
191
192wxString wxFileName::GetHomeDir()
193{
194 return ::wxGetHomeDir();
195}
196
197void wxFileName::AssignTempFileName( const wxString &prefix )
198{
199 wxString fullname;
200 if ( wxGetTempFileName(prefix, fullname) )
201 {
202 Assign(fullname);
203 }
204 else // error
205 {
206 Clear();
207 }
208}
209
210// ----------------------------------------------------------------------------
211// directory operations
212// ----------------------------------------------------------------------------
213
214bool wxFileName::Mkdir( int perm, bool full )
215{
216 return wxFileName::Mkdir( GetFullPath(), perm, full );
217}
218
219bool wxFileName::Mkdir( const wxString &dir, int perm, bool full )
220{
221 if (full)
222 {
223 wxFileName filename(dir);
224 wxArrayString dirs = filename.GetDirs();
225 dirs.Add(filename.GetName());
226
227 size_t count = dirs.GetCount();
228 size_t i;
229 wxString currPath;
230 int noErrors = 0;
231 for ( i = 0; i < count; i++ )
232 {
233 currPath += dirs[i];
234
235 if (currPath.Last() == wxT(':'))
236 {
237 // Can't create a root directory so continue to next dir
238 currPath += wxFILE_SEP_PATH;
239 continue;
240 }
241
242 if (!DirExists(currPath))
243 if (!wxMkdir(currPath, perm))
244 noErrors ++;
245
246 if ( (i < (count-1)) )
247 currPath += wxFILE_SEP_PATH;
248 }
249
250 return (noErrors == 0);
251
252 }
253 else
254 return ::wxMkdir( dir, perm );
255}
256
257bool wxFileName::Rmdir()
258{
259 return wxFileName::Rmdir( GetFullPath() );
260}
261
262bool wxFileName::Rmdir( const wxString &dir )
263{
264 return ::wxRmdir( dir );
265}
266
267// ----------------------------------------------------------------------------
268// path normalization
269// ----------------------------------------------------------------------------
270
271bool wxFileName::Normalize(wxPathNormalize flags,
272 const wxString& cwd,
273 wxPathFormat format)
274{
275 // the existing path components
276 wxArrayString dirs = GetDirs();
277
278 // the path to prepend in front to make the path absolute
279 wxFileName curDir;
280
281 format = GetFormat(format);
282
283 // make the path absolute
284 if ( (flags & wxPATH_NORM_ABSOLUTE) && !IsAbsolute() )
285 {
286 if ( cwd.empty() )
287 curDir.AssignCwd();
288 else
289 curDir.AssignDir(cwd);
290 }
291
292 // handle ~ stuff under Unix only
293 if ( (format == wxPATH_UNIX) && (flags & wxPATH_NORM_TILDE) )
294 {
295 if ( !dirs.IsEmpty() )
296 {
297 wxString dir = dirs[0u];
298 if ( !dir.empty() && dir[0u] == _T('~') )
299 {
300 curDir.AssignDir(wxGetUserHome(dir.c_str() + 1));
301
302 dirs.RemoveAt(0u);
303 }
304 }
305 }
306
307 if ( curDir.IsOk() )
308 {
309 wxArrayString dirsNew = curDir.GetDirs();
310 size_t count = dirs.GetCount();
311 for ( size_t n = 0; n < count; n++ )
312 {
313 dirsNew.Add(dirs[n]);
314 }
315
316 dirs = dirsNew;
317 }
318
319 // now deal with ".", ".." and the rest
320 m_dirs.Empty();
321 size_t count = dirs.GetCount();
322 for ( size_t n = 0; n < count; n++ )
323 {
324 wxString dir = dirs[n];
325
326 if ( flags && wxPATH_NORM_DOTS )
327 {
328 if ( dir == wxT(".") )
329 {
330 // just ignore
331 continue;
332 }
333
334 if ( dir == wxT("..") )
335 {
336 if ( m_dirs.IsEmpty() )
337 {
338 wxLogError(_("The path '%s' contains too many \"..\"!"),
339 GetFullPath().c_str());
340 return FALSE;
341 }
342
343 m_dirs.Remove(m_dirs.GetCount() - 1);
344 continue;
345 }
346 }
347
348 if ( flags & wxPATH_NORM_ENV_VARS )
349 {
350 dir = wxExpandEnvVars(dir);
351 }
352
353 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
354 {
355 dir.MakeLower();
356 }
357
358 m_dirs.Add(dir);
359 }
360
361 if ( (flags & wxPATH_NORM_CASE) && !IsCaseSensitive(format) )
362 {
363 // VZ: expand env vars here too?
364
365 m_name.MakeLower();
366 m_ext.MakeLower();
367 }
368
369#if defined(__WXMSW__) && defined(__WIN32__)
370 if (flags & wxPATH_NORM_LONG)
371 {
372 Assign(GetLongPath());
373 }
374#endif
375
376 return TRUE;
377}
378
379// ----------------------------------------------------------------------------
380// filename kind tests
381// ----------------------------------------------------------------------------
382
383bool wxFileName::SameAs( const wxFileName &filepath, wxPathFormat format)
384{
385 wxFileName fn1 = *this,
386 fn2 = filepath;
387
388 // get cwd only once - small time saving
389 wxString cwd = wxGetCwd();
390 fn1.Normalize(wxPATH_NORM_ALL, cwd, format);
391 fn2.Normalize(wxPATH_NORM_ALL, cwd, format);
392
393 if ( fn1.GetFullPath() == fn2.GetFullPath() )
394 return TRUE;
395
396 // TODO: compare inodes for Unix, this works even when filenames are
397 // different but files are the same (symlinks) (VZ)
398
399 return FALSE;
400}
401
402/* static */
403bool wxFileName::IsCaseSensitive( wxPathFormat format )
404{
405 // only DOS filenames are case-sensitive
406 return GetFormat(format) != wxPATH_DOS;
407}
408
409bool wxFileName::IsRelative( wxPathFormat format )
410{
411 return !IsAbsolute(format);
412}
413
414bool wxFileName::IsAbsolute( wxPathFormat format )
415{
416 wxChar ch = m_dirs.IsEmpty() ? _T('\0') : m_dirs[0u][0u];
417
418 // Hack to cope with e.g. c:\thing - need something better
419 wxChar driveSep = _T('\0');
420 if (!m_dirs.IsEmpty() && m_dirs[0].Length() > 1)
421 driveSep = m_dirs[0u][1u];
422
423 // the path is absolute if it starts with a path separator or, only for
424 // Unix filenames, with "~" or "~user"
425 return IsPathSeparator(ch, format) ||
426 driveSep == _T(':') ||
427 (GetFormat(format) == wxPATH_UNIX && ch == _T('~') );
428}
429
430/* static */
431wxString wxFileName::GetPathSeparators(wxPathFormat format)
432{
433 wxString seps;
434 switch ( GetFormat(format) )
435 {
436 case wxPATH_DOS:
437 // accept both as native APIs do
438 seps << wxFILE_SEP_PATH_UNIX << wxFILE_SEP_PATH_DOS;
439 break;
440
441 default:
442 wxFAIL_MSG( _T("unknown wxPATH_XXX style") );
443 // fall through
444
445 case wxPATH_UNIX:
446 seps = wxFILE_SEP_PATH_UNIX;
447 break;
448
449 case wxPATH_MAC:
450 seps = wxFILE_SEP_PATH_MAC;
451 break;
452 }
453
454 return seps;
455}
456
457/* static */
458bool wxFileName::IsPathSeparator(wxChar ch, wxPathFormat format)
459{
460 return GetPathSeparators(format).Find(ch) != wxNOT_FOUND;
461}
462
463bool wxFileName::IsWild( wxPathFormat format )
464{
465 // FIXME: this is probably false for Mac and this is surely wrong for most
466 // of Unix shells (think about "[...]")
467 (void)format;
468 return m_name.find_first_of(_T("*?")) != wxString::npos;
469}
470
471// ----------------------------------------------------------------------------
472// path components manipulation
473// ----------------------------------------------------------------------------
474
475void wxFileName::AppendDir( const wxString &dir )
476{
477 m_dirs.Add( dir );
478}
479
480void wxFileName::PrependDir( const wxString &dir )
481{
482 m_dirs.Insert( dir, 0 );
483}
484
485void wxFileName::InsertDir( int before, const wxString &dir )
486{
487 m_dirs.Insert( dir, before );
488}
489
490void wxFileName::RemoveDir( int pos )
491{
492 m_dirs.Remove( (size_t)pos );
493}
494
495// ----------------------------------------------------------------------------
496// accessors
497// ----------------------------------------------------------------------------
498
499void wxFileName::SetFullName(const wxString& fullname)
500{
501 SplitPath(fullname, NULL /* no path */, &m_name, &m_ext);
502}
503
504wxString wxFileName::GetFullName() const
505{
506 wxString fullname = m_name;
507 if ( !m_ext.empty() )
508 {
509 fullname << wxFILE_SEP_EXT << m_ext;
510 }
511
512 return fullname;
513}
514
515wxString wxFileName::GetPath( bool add_separator, wxPathFormat format ) const
516{
517 format = GetFormat( format );
518
519 wxString ret;
520 size_t count = m_dirs.GetCount();
521 for ( size_t i = 0; i < count; i++ )
522 {
523 ret += m_dirs[i];
524 if ( add_separator || (i < count) )
525 ret += wxFILE_SEP_PATH;
526 }
527
528 return ret;
529}
530
531wxString wxFileName::GetFullPath( wxPathFormat format ) const
532{
533 format = GetFormat( format );
534
535 wxString ret;
536 if (format == wxPATH_DOS)
537 {
538 for (size_t i = 0; i < m_dirs.GetCount(); i++)
539 {
540 ret += m_dirs[i];
541 ret += '\\';
542 }
543 }
544 else
545 if (format == wxPATH_UNIX)
546 {
547 for (size_t i = 0; i < m_dirs.GetCount(); i++)
548 {
549 ret += m_dirs[i];
550 ret += '/';
551 }
552 }
553 else
554 {
555 for (size_t i = 0; i < m_dirs.GetCount(); i++)
556 {
557 ret += m_dirs[i];
558 ret += ':';
559 }
560 }
561
562 ret += m_name;
563
564 if (!m_ext.IsEmpty())
565 {
566 ret += '.';
567 ret += m_ext;
568 }
569
570 return ret;
571}
572
573// Return the short form of the path (returns identity on non-Windows platforms)
574wxString wxFileName::GetShortPath() const
575{
576#if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
577 wxString path(GetFullPath());
578 wxString pathOut;
579 DWORD sz = ::GetShortPathName(path, NULL, 0);
580 bool ok = sz != 0;
581 if ( ok )
582 {
583 ok = ::GetShortPathName
584 (
585 path,
586 pathOut.GetWriteBuf(sz),
587 sz
588 ) != 0;
589 pathOut.UngetWriteBuf();
590 }
591 if (ok)
592 return pathOut;
593
594 return path;
595#else
596 return GetFullPath();
597#endif
598}
599
600// Return the long form of the path (returns identity on non-Windows platforms)
601wxString wxFileName::GetLongPath() const
602{
603#if defined(__WXMSW__) && defined(__WIN32__) && !defined(__WXMICROWIN__)
604 wxString path(GetFullPath());
605 wxString pathOut;
606 bool success = FALSE;
607
608 // VZ: this code was disabled, why?
609#if 0 // wxUSE_DYNLIB_CLASS
610 typedef DWORD (*GET_LONG_PATH_NAME)(const wxChar *, wxChar *, DWORD);
611
612 static bool s_triedToLoad = FALSE;
613
614 if ( !s_triedToLoad )
615 {
616 s_triedToLoad = TRUE;
617 wxDllType dllKernel = wxDllLoader::LoadLibrary(_T("kernel32"));
618 if ( dllKernel )
619 {
620 // may succeed or fail depending on the Windows version
621 static GET_LONG_PATH_NAME s_pfnGetLongPathName = NULL;
622#ifdef _UNICODE
623 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) wxDllLoader::GetSymbol(dllKernel, _T("GetLongPathNameW"));
624#else
625 s_pfnGetLongPathName = (GET_LONG_PATH_NAME) wxDllLoader::GetSymbol(dllKernel, _T("GetLongPathNameA"));
626#endif
627
628 wxDllLoader::UnloadLibrary(dllKernel);
629
630 if ( s_pfnGetLongPathName )
631 {
632 DWORD dwSize = (*s_pfnGetLongPathName)(path, NULL, 0);
633 bool ok = dwSize > 0;
634
635 if ( ok )
636 {
637 DWORD sz = (*s_pfnGetLongPathName)(path, NULL, 0);
638 ok = sz != 0;
639 if ( ok )
640 {
641 ok = (*s_pfnGetLongPathName)
642 (
643 path,
644 pathOut.GetWriteBuf(sz),
645 sz
646 ) != 0;
647 pathOut.UngetWriteBuf();
648
649 success = TRUE;
650 }
651 }
652 }
653 }
654 }
655 if (success)
656 return pathOut;
657#endif // wxUSE_DYNLIB_CLASS
658
659 if (!success)
660 {
661 // The OS didn't support GetLongPathName, or some other error.
662 // We need to call FindFirstFile on each component in turn.
663
664 WIN32_FIND_DATA findFileData;
665 HANDLE hFind;
666 pathOut = wxEmptyString;
667
668 wxArrayString dirs = GetDirs();
669 dirs.Add(GetFullName());
670
671 size_t count = dirs.GetCount();
672 size_t i;
673 wxString tmpPath;
674
675 for ( i = 0; i < count; i++ )
676 {
677 // We're using pathOut to collect the long-name path,
678 // but using a temporary for appending the last path component which may be short-name
679 tmpPath = pathOut + dirs[i];
680
681 if (tmpPath.Last() == wxT(':'))
682 {
683 // Can't pass a drive and root dir to FindFirstFile,
684 // so continue to next dir
685 tmpPath += wxFILE_SEP_PATH;
686 pathOut = tmpPath;
687 continue;
688 }
689
690 hFind = ::FindFirstFile(tmpPath, &findFileData);
691 if (hFind == INVALID_HANDLE_VALUE)
692 {
693 // Error: return immediately with the original path
694 return path;
695 }
696 else
697 {
698 pathOut += findFileData.cFileName;
699 if ( (i < (count-1)) )
700 pathOut += wxFILE_SEP_PATH;
701
702 ::FindClose(hFind);
703 }
704 }
705 }
706
707 return pathOut;
708#else
709 return GetFullPath();
710#endif
711}
712
713wxPathFormat wxFileName::GetFormat( wxPathFormat format )
714{
715 if (format == wxPATH_NATIVE)
716 {
717#if defined(__WXMSW__) || defined(__WXPM__)
718 format = wxPATH_DOS;
719#elif defined(__WXMAC__)
720 format = wxPATH_MAC;
721#else
722 format = wxPATH_UNIX;
723#endif
724 }
725 return format;
726}
727
728// ----------------------------------------------------------------------------
729// path splitting function
730// ----------------------------------------------------------------------------
731
732void wxFileName::SplitPath(const wxString& fullpath,
733 wxString *pstrPath,
734 wxString *pstrName,
735 wxString *pstrExt,
736 wxPathFormat format)
737{
738 format = GetFormat(format);
739
740 // find the positions of the last dot and last path separator in the path
741 size_t posLastDot = fullpath.find_last_of(wxFILE_SEP_EXT);
742 size_t posLastSlash = fullpath.find_last_of(GetPathSeparators(format));
743
744 if ( (posLastDot != wxString::npos) && (format == wxPATH_UNIX) )
745 {
746 if ( (posLastDot == 0) ||
747 (fullpath[posLastDot - 1] == wxFILE_SEP_PATH_UNIX) )
748 {
749 // under Unix, dot may be (and commonly is) the first character of
750 // the filename, don't treat the entire filename as extension in
751 // this case
752 posLastDot = wxString::npos;
753 }
754 }
755
756 // if we do have a dot and a slash, check that the dot is in the name part
757 if ( (posLastDot != wxString::npos) &&
758 (posLastSlash != wxString::npos) &&
759 (posLastDot < posLastSlash) )
760 {
761 // the dot is part of the path, not the start of the extension
762 posLastDot = wxString::npos;
763 }
764
765 // now fill in the variables provided by user
766 if ( pstrPath )
767 {
768 if ( posLastSlash == wxString::npos )
769 {
770 // no path at all
771 pstrPath->Empty();
772 }
773 else
774 {
775 // take all until the separator
776 *pstrPath = fullpath.Left(posLastSlash);
777 }
778 }
779
780 if ( pstrName )
781 {
782 // take all characters starting from the one after the last slash and
783 // up to, but excluding, the last dot
784 size_t nStart = posLastSlash == wxString::npos ? 0 : posLastSlash + 1;
785 size_t count;
786 if ( posLastDot == wxString::npos )
787 {
788 // take all until the end
789 count = wxString::npos;
790 }
791 else if ( posLastSlash == wxString::npos )
792 {
793 count = posLastDot;
794 }
795 else // have both dot and slash
796 {
797 count = posLastDot - posLastSlash - 1;
798 }
799
800 *pstrName = fullpath.Mid(nStart, count);
801 }
802
803 if ( pstrExt )
804 {
805 if ( posLastDot == wxString::npos )
806 {
807 // no extension
808 pstrExt->Empty();
809 }
810 else
811 {
812 // take everything after the dot
813 *pstrExt = fullpath.Mid(posLastDot + 1);
814 }
815 }
816}