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