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