Remove possible double encoding from shareddir.dat
[amule.git] / src / libs / common / Path.cpp
blob0d6e90e7a6bddbfbaff9f077c17b33005dd399ef
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2008-2011 aMule Team ( admin@amule.org / http://www.amule.org )
5 //
6 // Any parts of this program derived from the xMule, lMule or eMule project,
7 // or contributed by third-party developers are copyrighted by their
8 // respective authors.
9 //
10 // This program is free software; you can redistribute it and/or modify
11 // it under the terms of the GNU General Public License as published by
12 // the Free Software Foundation; either version 2 of the License, or
13 // (at your option) any later version.
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include "Path.h"
26 #include "StringFunctions.h" // Needed for filename2char()
28 #include <wx/file.h>
29 #if defined __WINDOWS__ || defined __IRIX__
30 # include <wx/ffile.h>
31 #endif
32 #include <wx/utils.h>
33 #include <wx/filename.h>
34 #include <algorithm> // Needed for std::min
37 // Windows has case-insensitive paths, so we use a
38 // case-insensitive cmp for that platform. TODO:
39 // Perhaps it would be better to simply lowercase
40 // m_filesystem in the constructor ...
41 #ifdef __WINDOWS__
42 #define PATHCMP(a, b) wxStricmp(a, b)
43 #define PATHNCMP(a, b, n) wxStrnicmp(a, b, n)
44 #else
45 #define PATHCMP(a, b) wxStrcmp(a, b)
46 #define PATHNCMP(a, b, n) wxStrncmp(a, b, n)
47 #endif
50 ////////////////////////////////////////////////////////////
51 // Helper functions
54 /** Creates a deep copy of the string, avoiding its ref. counting. */
55 inline wxString DeepCopy(const wxString& str)
57 return wxString(str.c_str(), str.Length());
61 wxString Demangle(const wxCharBuffer& fn, const wxString& filename)
63 wxString result = wxConvUTF8.cMB2WC(fn);
65 // FIXME: Is this actually needed for osx/msw?
66 if (!result) {
67 // We only try to further demangle if the current locale is
68 // UTF-8, C or POSIX. This is because in any other case, the
69 // current locale is probably the best choice for printing.
70 static wxFontEncoding enc = wxLocale::GetSystemEncoding();
72 switch (enc) {
73 // SYSTEM is needed for ANSI encodings such as
74 // "POSIX" and "C", which are only 7bit.
75 case wxFONTENCODING_SYSTEM:
76 case wxFONTENCODING_UTF8:
77 result = wxConvISO8859_1.cMB2WC(fn);
78 break;
80 default:
81 // Nothing to do, the filename is probably Ok.
82 result = DeepCopy(filename);
86 return result;
90 /** Splits a full path into its path and filename component. */
91 inline void DoSplitPath(const wxString& strPath, wxString* path, wxString* name)
93 bool hasExt = false;
94 wxString ext, vol;
96 wxString* pVol = (path ? &vol : NULL);
97 wxString* pExt = (name ? &ext : NULL);
99 wxFileName::SplitPath(strPath, pVol, path, name, pExt, &hasExt);
101 if (hasExt && pExt) {
102 *name += wxT(".") + ext;
105 if (path && vol.Length()) {
106 *path = vol + wxFileName::GetVolumeSeparator() + *path;
111 /** Removes invalid chars from a filename. */
112 wxString DoCleanup(const wxString& filename, bool keepSpaces, bool isFAT32)
114 wxString result;
115 for (size_t i = 0; i < filename.Length(); i++) {
116 const wxChar c = filename[i];
118 switch (c) {
119 case wxT('/'):
120 continue;
122 case wxT('\"'):
123 case wxT('*'):
124 case wxT('<'):
125 case wxT('>'):
126 case wxT('?'):
127 case wxT('|'):
128 case wxT('\\'):
129 case wxT(':'):
130 if (isFAT32) {
131 continue;
134 default:
135 if ((c == wxT(' ')) && !keepSpaces) {
136 result += wxT("%20");
137 } else if (c >= 32) {
138 // Many illegal for filenames in windows
139 // below the 32th char (which is space).
140 result += filename[i];
145 return result;
149 /** Does the actual work of adding a postfix ... */
150 wxString DoAddPostfix(const wxString& src, const wxString& postfix)
152 const wxFileName srcFn(src);
153 wxString result = srcFn.GetName() + postfix;
155 if (srcFn.HasExt()) {
156 result += wxT(".") + srcFn.GetExt();
159 wxString path = srcFn.GetPath();
160 if (path.Length()) {
161 return path + wxFileName::GetPathSeparator() + result;
164 return result;
167 /** Removes the last extension of a filename. */
168 wxString DoRemoveExt(const wxString& path)
170 // Using wxFilename which handles paths, etc.
171 wxFileName tmp(path);
172 tmp.ClearExt();
174 return tmp.GetFullPath();
178 /** Readies a path for use with wxAccess.. */
179 wxString DoCleanPath(const wxString& path)
181 #ifdef __WINDOWS__
182 // stat fails on windows if there are trailing path-separators.
183 wxString cleanPath = StripSeparators(path, wxString::trailing);
185 // Root paths must end with a separator (X:\ rather than X:).
186 // See comments in wxDirExists.
187 if ((cleanPath.Length() == 2) && (cleanPath.Last() == wxT(':'))) {
188 cleanPath += wxFileName::GetPathSeparator();
191 return cleanPath;
192 #else
193 return path;
194 #endif
198 /** Returns true if the two paths are equal. */
199 bool IsSameAs(const wxString& a, const wxString& b)
201 // Cache the current directory
202 const wxString cwd = wxGetCwd();
204 // We normalize everything, except env. variables, which
205 // can cause problems when the string is not encodable
206 // using wxConvLibc which wxWidgets uses for the purpose.
207 const int flags = (wxPATH_NORM_ALL | wxPATH_NORM_CASE) & ~wxPATH_NORM_ENV_VARS;
209 // Let wxFileName handle the tricky stuff involved in actually
210 // comparing two paths ... Currently, a path ending with a path-
211 // seperator will be unequal to the same path without a path-
212 // seperator, which is probably for the best, but can could
213 // lead to some unexpected behavior.
214 wxFileName fn1(a);
215 wxFileName fn2(b);
217 fn1.Normalize(flags, cwd);
218 fn2.Normalize(flags, cwd);
220 return (fn1.GetFullPath() == fn2.GetFullPath());
224 ////////////////////////////////////////////////////////////
225 // CPath implementation
227 CPath::CPath()
232 CPath::CPath(const wxString& filename)
234 // Equivalent to the default constructor ...
235 if (!filename) {
236 return;
239 wxCharBuffer fn = filename2char(filename);
240 if (fn) {
241 // Filename is valid in the current locale. This means that
242 // it either originated from a (wx)system-call, or from a
243 // user with a properly setup system.
244 m_filesystem = DeepCopy(filename);
245 m_printable = Demangle(fn, filename);
246 } else {
247 // It's not a valid filename in the current locale, so we'll
248 // have to do some magic. This ensures that the filename is
249 // saved as UTF8, even if the system is not unicode enabled,
250 // preserving the original filename till the user has fixed
251 // his system ...
252 #ifdef __WINDOWS__
253 // Magic fails on Windows where we always work with wide char file names.
254 m_filesystem = DeepCopy(filename);
255 m_printable = m_filesystem;
256 #else
257 fn = filename.utf8_str();
258 m_filesystem = wxConvFile.cMB2WC(fn);
260 // There's no need to try to unmangle the filename here.
261 m_printable = DeepCopy(filename);
262 #endif
265 wxASSERT(m_filesystem.Length());
266 wxASSERT(m_printable.Length());
270 CPath::CPath(const CPath& other)
271 : m_printable(DeepCopy(other.m_printable))
272 , m_filesystem(DeepCopy(other.m_filesystem))
277 CPath CPath::FromUniv(const wxString& path)
279 wxCharBuffer fn = path.mb_str(wxConvISO8859_1);
280 return CPath(wxConvFile.cMB2WC(fn));
284 wxString CPath::ToUniv(const CPath& path)
286 // The logic behind this is that by saving the filename
287 // as a raw bytestream, we can always recreate the on-disk filename,
288 // as if we had read it using wx functions.
289 wxCharBuffer fn = path.m_filesystem.mb_str(wxConvFile);
290 return wxConvISO8859_1.cMB2WC(fn);
294 CPath& CPath::operator=(const CPath& other)
296 if (this != &other) {
297 m_printable = DeepCopy(other.m_printable);
298 m_filesystem = DeepCopy(other.m_filesystem);
301 return *this;
305 bool CPath::operator==(const CPath& other) const
307 return ::IsSameAs(m_filesystem, other.m_filesystem);
311 bool CPath::operator!=(const CPath& other) const
313 return !(*this == other);
317 bool CPath::operator<(const CPath& other) const
319 return PATHCMP(m_filesystem.c_str(), other.m_filesystem.c_str()) < 0;
323 bool CPath::IsOk() const
325 // Something is very wrong if one of the two is empty.
326 return m_printable.Length() && m_filesystem.Length();
330 bool CPath::FileExists() const
332 return wxFileName::FileExists(m_filesystem);
336 bool CPath::DirExists() const
338 return wxFileName::DirExists(DoCleanPath(m_filesystem));
342 bool CPath::IsDir(EAccess mode) const
344 wxString path = DoCleanPath(m_filesystem);
345 if (!wxFileName::DirExists(path)) {
346 return false;
347 } else if ((mode & writable) && !wxIsWritable(path)) {
348 return false;
349 } else if ((mode & readable) && !wxIsReadable(path)) {
350 return false;
353 return true;
357 bool CPath::IsFile(EAccess mode) const
359 if (!wxFileName::FileExists(m_filesystem)) {
360 return false;
361 } else if ((mode & writable) && !wxIsWritable(m_filesystem)) {
362 return false;
363 } else if ((mode & readable) && !wxIsReadable(m_filesystem)) {
364 return false;
367 return true;
371 wxString CPath::GetRaw() const
373 // Copy as c-strings to ensure that the CPath objects can safely
374 // be passed across threads (avoiding wxString ref. counting).
375 return DeepCopy(m_filesystem);
379 wxString CPath::GetPrintable() const
381 // Copy as c-strings to ensure that the CPath objects can safely
382 // be passed across threads (avoiding wxString ref. counting).
383 return DeepCopy(m_printable);
387 wxString CPath::GetExt() const
389 return wxFileName(m_filesystem).GetExt();
393 CPath CPath::GetPath() const
395 CPath path;
396 ::DoSplitPath(m_printable, &path.m_printable, NULL);
397 ::DoSplitPath(m_filesystem, &path.m_filesystem, NULL);
399 return path;
403 CPath CPath::GetFullName() const
405 CPath path;
406 ::DoSplitPath(m_printable, NULL, &path.m_printable);
407 ::DoSplitPath(m_filesystem, NULL, &path.m_filesystem);
409 return path;
414 sint64 CPath::GetFileSize() const
416 if (FileExists()) {
417 wxFile f(m_filesystem);
418 if (f.IsOpened()) {
419 return f.Length();
423 return wxInvalidOffset;
427 bool CPath::IsSameDir(const CPath& other) const
429 wxString a = m_filesystem;
430 wxString b = other.m_filesystem;
432 // This check is needed to avoid trouble in the
433 // case where one path is empty, and the other
434 // points to the root dir.
435 if (a.Length() && b.Length()) {
436 a = StripSeparators(a, wxString::trailing);
437 b = StripSeparators(b, wxString::trailing);
440 return ::IsSameAs(a, b);
444 CPath CPath::JoinPaths(const CPath& other) const
446 if (!IsOk()) {
447 return CPath(other);
448 } else if (!other.IsOk()) {
449 return CPath(*this);
452 CPath joinedPath;
453 // DeepCopy shouldn't be needed, as JoinPaths results in the creation of a new string.
454 joinedPath.m_printable = ::JoinPaths(m_printable, other.m_printable);
455 joinedPath.m_filesystem = ::JoinPaths(m_filesystem, other.m_filesystem);
457 return joinedPath;
461 CPath CPath::Cleanup(bool keepSpaces, bool isFAT32) const
463 CPath result;
464 result.m_printable = ::DoCleanup(m_printable, keepSpaces, isFAT32);
465 result.m_filesystem = ::DoCleanup(m_filesystem, keepSpaces, isFAT32);
467 return result;
471 CPath CPath::AddPostfix(const wxString& postfix) const
473 wxASSERT(postfix.IsAscii());
475 CPath result;
476 result.m_printable = ::DoAddPostfix(m_printable, postfix);
477 result.m_filesystem = ::DoAddPostfix(m_filesystem, postfix);
479 return result;
483 CPath CPath::AppendExt(const wxString& ext) const
485 wxASSERT(ext.IsAscii());
487 // Though technically, and empty extension would simply
488 // be another . at the end of the filename, we ignore them.
489 if (ext.IsEmpty()) {
490 return *this;
493 CPath result(*this);
494 if (ext[0] == wxT('.')) {
495 result.m_printable << ext;
496 result.m_filesystem << ext;
497 } else {
498 result.m_printable << wxT(".") << ext;
499 result.m_filesystem << wxT(".") << ext;
502 return result;
506 CPath CPath::RemoveExt() const
508 CPath result;
509 result.m_printable = DoRemoveExt(m_printable);
510 result.m_filesystem = DoRemoveExt(m_filesystem);
512 return result;
516 CPath CPath::RemoveAllExt() const
518 CPath last, current = RemoveExt();
520 // Loop until all extensions are removed
521 do {
522 last = current;
524 current = last.RemoveExt();
525 } while (last != current);
527 return current;
531 bool CPath::StartsWith(const CPath& other) const
533 // It doesn't make sense comparing invalid paths,
534 // especially since if 'other' was empty, it would
535 // be considered a prefix of any path.
536 if ((IsOk() && other.IsOk()) == false) {
537 return false;
540 // Adding an seperator to avoid partial matches, such as
541 // "/usr/bi" matching "/usr/bin". TODO: Paths should be
542 // normalized first (in the constructor).
543 const wxString a = StripSeparators(m_filesystem, wxString::trailing) + wxFileName::GetPathSeparator();
544 const wxString b = StripSeparators(other.m_filesystem, wxString::trailing) + wxFileName::GetPathSeparator();
546 if (a.Length() < b.Length()) {
547 // Cannot possibly be a prefix.
548 return false;
551 const size_t checkLen = std::min(a.Length(), b.Length());
552 return PATHNCMP(a.c_str(), b.c_str(), checkLen) == 0;
556 bool CPath::CloneFile(const CPath& src, const CPath& dst, bool overwrite)
558 return ::wxCopyFile(src.m_filesystem, dst.m_filesystem, overwrite);
562 bool CPath::RemoveFile(const CPath& file)
564 return ::wxRemoveFile(file.m_filesystem);
568 bool CPath::RenameFile(const CPath& src, const CPath& dst, bool overwrite)
570 return ::wxRenameFile(src.m_filesystem, dst.m_filesystem, overwrite);
574 bool CPath::BackupFile(const CPath& src, const wxString& appendix)
576 wxASSERT(appendix.IsAscii());
578 CPath dst = CPath(src.m_filesystem + appendix);
580 if (CPath::CloneFile(src, dst, true)) {
581 // Try to ensure that the backup gets physically written
582 #if defined __WINDOWS__ || defined __IRIX__
583 wxFFile backupFile;
584 #else
585 wxFile backupFile;
586 #endif
587 if (backupFile.Open(dst.m_filesystem)) {
588 backupFile.Flush();
591 return true;
594 return false;
598 bool CPath::RemoveDir(const CPath& file)
600 return ::wxRmdir(file.m_filesystem);
604 bool CPath::MakeDir(const CPath& file)
606 return ::wxMkdir(file.m_filesystem);
610 bool CPath::FileExists(const wxString& file)
612 return CPath(file).FileExists();
616 bool CPath::DirExists(const wxString& path)
618 return CPath(path).DirExists();
622 sint64 CPath::GetFileSize(const wxString& file)
624 return CPath(file).GetFileSize();
628 time_t CPath::GetModificationTime(const CPath& file)
630 return ::wxFileModificationTime(file.m_filesystem);
634 sint64 CPath::GetFreeSpaceAt(const CPath& path)
636 wxLongLong free;
637 if (::wxGetDiskSpace(path.m_filesystem, NULL, &free)) {
638 return free.GetValue();
641 return wxInvalidOffset;
645 wxString CPath::TruncatePath(size_t length, bool isFilePath) const
647 wxString file = GetPrintable();
649 // Check if there's anything to do
650 if (file.Length() <= length) {
651 return file;
654 // If the path is a file name, then prefer to remove from the path, rather than the filename
655 if (isFilePath) {
656 wxString path = wxFileName(file).GetPath();
657 file = wxFileName(file).GetFullName();
659 if (path.Length() >= length) {
660 path.Clear();
661 } else if (file.Length() >= length) {
662 path.Clear();
663 } else {
664 // Minus 6 for "[...]" + separator
665 int pathlen = (int)(length - file.Length() - 6);
667 if (pathlen > 0) {
668 path = wxT("[...]") + path.Right( pathlen );
669 } else {
670 path.Clear();
674 file = ::JoinPaths(path, file);
677 if (file.Length() > length) {
678 if (length > 5) {
679 file = file.Left(length - 5) + wxT("[...]");
680 } else {
681 file.Clear();
685 return file;
689 wxString StripSeparators(wxString path, wxString::stripType type)
691 wxASSERT((type == wxString::leading) || (type == wxString::trailing));
692 const wxString seps = wxFileName::GetPathSeparators();
694 while (!path.IsEmpty()) {
695 size_t pos = ((type == wxString::leading) ? 0 : path.Length() - 1);
697 if (seps.Contains(path.GetChar(pos))) {
698 path.Remove(pos, 1);
699 } else {
700 break;
704 return path;
708 wxString JoinPaths(const wxString& path, const wxString& file)
710 if (path.IsEmpty()) {
711 return file;
712 } else if (file.IsEmpty()) {
713 return path;
716 return StripSeparators(path, wxString::trailing)
717 + wxFileName::GetPathSeparator()
718 + StripSeparators(file, wxString::leading);