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