Upstream tarball 20080304
[amule.git] / src / libs / common / Path.cpp
blobb78b99c4cc3c9b380c07eca338db923397bf08fd
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2008 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.
19 //
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 "MuleDebug.h"
27 #include "StringFunctions.h"
29 #include <wx/file.h>
30 #include <wx/utils.h>
31 #include <wx/filename.h>
34 // This is required in order to ensure that wx can "handle" filenames
35 // using a different encoding than the current system-wide setting. If
36 // this is not done, such filenames will fail during convertion to/from
37 // multibyte (as in cWC2MB/cMB2WC).
38 #if !wxUSE_GUI && !defined(__WXMSW__)
39 void* setFNConv()
41 // This uses the same method as wxApp::Initialize under GTK2
42 wxString encName = wxLocale::GetSystemEncodingName().Upper();
43 if (encName.IsEmpty() || (encName == wxT("US-ASCII"))) {
44 encName = wxT("UTF-8");
47 return wxConvFileName = new wxConvBrokenFileNames(encName);
50 // Ensure intialization
51 static void* s_foo = setFNConv();
52 #endif
55 // Windows has case-insensitive paths, so we use a
56 // case-insensitive cmp for that platform. TODO:
57 // Perhaps it would be better to simply lowercase
58 // m_filesystem in the contructor ...
59 #ifdef __WXMSW__
60 #define PATHCMP(a, b) wxStricmp(a, b)
61 #define PATHNCMP(a, b, n) wxStrnicmp(a, b, n)
62 #else
63 #define PATHCMP(a, b) wxStrcmp(a, b)
64 #define PATHNCMP(a, b, n) wxStrncmp(a, b, n)
65 #endif
68 ////////////////////////////////////////////////////////////
69 // Helper functions
72 /** Creates a deep copy of the string, avoiding its ref. counting. */
73 inline wxString DeepCopy(const wxString& str)
75 return wxString(str.c_str(), str.Length());
79 wxString Demangle(const wxCharBuffer& fn, const wxString& filename)
81 wxString result = wxConvUTF8.cMB2WC(fn);
83 // FIXME: Is this actually needed for osx/msw?
84 if (!result) {
85 // We only try to further demangle if the current locale is
86 // UTF-8, C or POSIX. This is because in any other case, the
87 // current locale is probably the best choice for printing.
88 static wxFontEncoding enc = wxLocale::GetSystemEncoding();
90 switch (enc) {
91 // SYSTEM is needed for ANSI encodings such as
92 // "POSIX" and "C", which are only 7bit.
93 case wxFONTENCODING_SYSTEM:
94 case wxFONTENCODING_UTF8:
95 result = wxConvISO8859_1.cMB2WC(fn);
96 break;
98 default:
99 // Nothing to do, the filename is probably Ok.
100 result = DeepCopy(filename);
104 return result;
108 /** Splits a full path into its path and filename component. */
109 inline void DoSplitPath(const wxString& strPath, wxString* path, wxString* name)
111 bool hasExt = false;
112 wxString ext, vol;
114 wxString* pVol = (path ? &vol : NULL);
115 wxString* pExt = (name ? &ext : NULL);
117 wxFileName::SplitPath(strPath, pVol, path, name, pExt, &hasExt);
119 if (hasExt && pExt) {
120 *name += wxT(".") + ext;
123 if (path && vol.Length()) {
124 *path = vol + wxFileName::GetVolumeSeparator() + *path;
129 /** Removes invalid chars from a filename. */
130 wxString DoCleanup(const wxString& filename, bool keepSpaces, bool isFAT32)
132 wxString result;
133 for (size_t i = 0; i < filename.Length(); i++) {
134 const wxChar c = filename[i];
136 switch (c) {
137 case wxT('/'):
138 continue;
140 case wxT('\"'):
141 case wxT('*'):
142 case wxT('<'):
143 case wxT('>'):
144 case wxT('?'):
145 case wxT('|'):
146 case wxT('\\'):
147 case wxT(':'):
148 if (isFAT32) {
149 continue;
152 default:
153 if ((c == wxT(' ')) && !keepSpaces) {
154 result += wxT("%20");
155 } else if (c >= 32) {
156 // Many illegal for filenames in windows
157 // below the 32th char (which is space).
158 result += filename[i];
163 return result;
167 /** Does the actual work of adding a postfix ... */
168 wxString DoAddPostfix(const wxString& src, const wxString& postfix)
170 const wxFileName srcFn(src);
171 wxString result = srcFn.GetName() + postfix;
173 if (srcFn.HasExt()) {
174 result += wxT(".") + srcFn.GetExt();
177 wxString path = srcFn.GetPath();
178 if (path.Length()) {
179 return path + wxFileName::GetPathSeparator() + result;
182 return result;
185 /** Removes the last extension of a filename. */
186 wxString DoRemoveExt(const wxString& path)
188 // Using wxFilename which handles paths, etc.
189 wxFileName tmp(path);
190 tmp.ClearExt();
192 return tmp.GetFullPath();
196 /** Readies a path for use with wxAccess.. */
197 wxString DoCleanPath(const wxString& path)
199 #ifdef __WXMSW__
200 // stat fails on windows if there are trailing path-separators.
201 wxString cleanPath = StripSeparators(path, wxString::trailing);
203 // Root paths must end with a separator (X:\ rather than X:).
204 // See comments in wxDirExists.
205 if ((cleanPath.Length() == 2) && (cleanPath.Last() == wxT(':'))) {
206 cleanPath += wxFileName::GetPathSeparator();
209 return cleanPath;
210 #else
211 return path;
212 #endif
216 /** Returns true if the two paths are equal. */
217 bool IsSameAs(const wxString& a, const wxString& b)
219 // Cache the current directory
220 const wxString cwd = wxGetCwd();
222 // We normalize everything, except env. variables, which
223 // can cause problems when the string is not encodable
224 // using wxConvLibc which wxWidgets uses for the purpose.
225 const int flags = (wxPATH_NORM_ALL | wxPATH_NORM_CASE) & ~wxPATH_NORM_ENV_VARS;
227 // Let wxFileName handle the tricky stuff involved in actually
228 // comparing two paths ... Currently, a path ending with a path-
229 // seperator will be unequal to the same path without a path-
230 // seperator, which is probably for the best, but can could
231 // lead to some unexpected behavior.
232 wxFileName fn1(a);
233 wxFileName fn2(b);
235 fn1.Normalize(flags, cwd);
236 fn2.Normalize(flags, cwd);
238 return (fn1.GetFullPath() == fn2.GetFullPath());
242 ////////////////////////////////////////////////////////////
243 // CPath implementation
245 CPath::CPath()
250 CPath::CPath(const wxString& filename)
252 // Equivalent to the default constructor ...
253 if (!filename) {
254 return;
257 wxCharBuffer fn = filename2char(filename);
258 if (fn) {
259 // Filename is valid in the current locale. This means that
260 // it either originated from a (wx)system-call, or from a
261 // user with a properly setup system.
262 m_filesystem = DeepCopy(filename);
263 m_printable = Demangle(fn, filename);
264 } else {
265 // It's not a valid filename in the current locale, so we'll
266 // have to do some magic. This ensures that the filename is
267 // saved as UTF8, even if the system is not unicode enabled,
268 // preserving the original filename till the user has fixed
269 // his system ...
270 fn = wxConvUTF8.cWC2MB(filename);
271 m_filesystem = wxConvFile.cMB2WC(fn);
273 // There's no need to try to unmangle the filename here.
274 m_printable = DeepCopy(filename);
277 wxASSERT(m_filesystem.Length());
278 wxASSERT(m_printable.Length());
282 CPath::CPath(const CPath& other)
283 : CPrintable()
284 , m_printable(DeepCopy(other.m_printable))
285 , m_filesystem(DeepCopy(other.m_filesystem))
290 CPath::~CPath()
295 CPath CPath::FromUniv(const wxString& path)
297 wxCharBuffer fn = wxConvISO8859_1.cWC2MB(path);
299 return CPath(wxConvFile.cMB2WC(fn));
304 wxString CPath::ToUniv(const CPath& path)
306 // The logic behind this is that by saving the filename
307 // as a raw bytestream (which is what ISO8859-1 amounts
308 // to), we can always recreate the on-disk filename, as
309 // if we had read it using wx functions.
310 wxCharBuffer fn = wxConvFile.cWC2MB(path.m_filesystem);
312 return wxConvISO8859_1.cMB2WC(fn);
316 CPath& CPath::operator=(const CPath& other)
318 if (this != &other) {
319 m_printable = DeepCopy(other.m_printable);
320 m_filesystem = DeepCopy(other.m_filesystem);
323 return *this;
327 bool CPath::operator==(const CPath& other) const
329 return ::IsSameAs(m_filesystem, other.m_filesystem);
333 bool CPath::operator!=(const CPath& other) const
335 return !(*this == other);
339 bool CPath::operator<(const CPath& other) const
341 return PATHCMP(m_filesystem.c_str(), other.m_filesystem.c_str()) < 0;
345 bool CPath::IsOk() const
347 // Something is very wrong if one of the two is empty.
348 return m_printable.Length() && m_filesystem.Length();
352 bool CPath::FileExists() const
354 return wxFileName::FileExists(m_filesystem);
358 bool CPath::DirExists() const
360 return wxFileName::DirExists(DoCleanPath(m_filesystem));
364 bool CPath::IsDir(EAccess mode) const
366 wxString path = DoCleanPath(m_filesystem);
367 if (!wxFileName::DirExists(path)) {
368 return false;
369 } else if ((mode & writable) && !wxIsWritable(path)) {
370 return false;
371 } else if ((mode & readable) && !wxIsReadable(path)) {
372 return false;
375 return true;
379 bool CPath::IsFile(EAccess mode) const
381 if (!wxFileName::FileExists(m_filesystem)) {
382 return false;
383 } else if ((mode & writable) && !wxIsWritable(m_filesystem)) {
384 return false;
385 } else if ((mode & readable) && !wxIsReadable(m_filesystem)) {
386 return false;
389 return true;
393 wxString CPath::GetRaw() const
395 // Copy as c-strings to ensure that the CPath objects can safely
396 // be passed across threads (avoiding wxString ref. counting).
397 return DeepCopy(m_filesystem);
401 wxString CPath::GetPrintable() const
403 // Copy as c-strings to ensure that the CPath objects can safely
404 // be passed across threads (avoiding wxString ref. counting).
405 return DeepCopy(m_printable);
409 wxString CPath::GetExt() const
411 return wxFileName(m_filesystem).GetExt();
415 CPath CPath::GetPath() const
417 CPath path;
418 ::DoSplitPath(m_printable, &path.m_printable, NULL);
419 ::DoSplitPath(m_filesystem, &path.m_filesystem, NULL);
421 return path;
425 CPath CPath::GetFullName() const
427 CPath path;
428 ::DoSplitPath(m_printable, NULL, &path.m_printable);
429 ::DoSplitPath(m_filesystem, NULL, &path.m_filesystem);
431 return path;
436 sint64 CPath::GetFileSize() const
438 if (FileExists()) {
439 wxFile f(m_filesystem);
440 if (f.IsOpened()) {
441 return f.Length();
445 return wxInvalidOffset;
449 bool CPath::IsSameDir(const CPath& other) const
451 wxString a = m_filesystem;
452 wxString b = other.m_filesystem;
454 // This check is needed to avoid trouble in the
455 // case where one path is empty, and the other
456 // points to the root dir.
457 if (a.Length() && b.Length()) {
458 a = StripSeparators(a, wxString::trailing);
459 b = StripSeparators(b, wxString::trailing);
462 return ::IsSameAs(a, b);
466 CPath CPath::JoinPaths(const CPath& other) const
468 if (!IsOk()) {
469 return CPath(other);
470 } else if (!other.IsOk()) {
471 return CPath(*this);
474 CPath joinedPath;
475 // DeepCopy shouldn't be needed, as JoinPaths results in the creation of a new string.
476 joinedPath.m_printable = ::JoinPaths(m_printable, other.m_printable);
477 joinedPath.m_filesystem = ::JoinPaths(m_filesystem, other.m_filesystem);
479 return joinedPath;
483 CPath CPath::Cleanup(bool keepSpaces, bool isFAT32) const
485 CPath result;
486 result.m_printable = ::DoCleanup(m_printable, keepSpaces, isFAT32);
487 result.m_filesystem = ::DoCleanup(m_filesystem, keepSpaces, isFAT32);
489 return result;
493 CPath CPath::AddPostfix(const wxString& postfix) const
495 wxASSERT(postfix.IsAscii());
497 CPath result;
498 result.m_printable = ::DoAddPostfix(m_printable, postfix);
499 result.m_filesystem = ::DoAddPostfix(m_filesystem, postfix);
501 return result;
505 CPath CPath::AppendExt(const wxString& ext) const
507 wxASSERT(ext.IsAscii());
509 // Though technically, and empty extension would simply
510 // be another . at the end of the filename, we ignore them.
511 if (ext.IsEmpty()) {
512 return *this;
515 CPath result(*this);
516 if (ext[0] == wxT('.')) {
517 result.m_printable << ext;
518 result.m_filesystem << ext;
519 } else {
520 result.m_printable << wxT(".") << ext;
521 result.m_filesystem << wxT(".") << ext;
524 return result;
528 CPath CPath::RemoveExt() const
530 CPath result;
531 result.m_printable = DoRemoveExt(m_printable);
532 result.m_filesystem = DoRemoveExt(m_filesystem);
534 return result;
538 CPath CPath::RemoveAllExt() const
540 CPath last, current = RemoveExt();
542 // Loop untill all extensions are removed
543 do {
544 last = current;
546 current = last.RemoveExt();
547 } while (last != current);
549 return current;
553 bool CPath::StartsWith(const CPath& other) const
555 // It doesn't make sense comparing invalid paths,
556 // especially since if 'other' was empty, it would
557 // be considered a prefix of any path.
558 if ((IsOk() && other.IsOk()) == false) {
559 return false;
562 // Adding an seperator to avoid partial matches, such as
563 // "/usr/bi" matching "/usr/bin". TODO: Paths should be
564 // normalized first (in the constructor).
565 const wxString a = StripSeparators(m_filesystem, wxString::trailing) + wxFileName::GetPathSeparator();
566 const wxString b = StripSeparators(other.m_filesystem, wxString::trailing) + wxFileName::GetPathSeparator();
568 if (a.Length() < b.Length()) {
569 // Cannot possibly be a prefix.
570 return false;
573 const size_t checkLen = std::min(a.Length(), b.Length());
574 return PATHNCMP(a.c_str(), b.c_str(), checkLen) == 0;
578 wxString CPath::GetPrintableString() const
580 return DeepCopy(m_printable);
584 bool CPath::CloneFile(const CPath& src, const CPath& dst, bool overwrite)
586 return ::wxCopyFile(src.m_filesystem, dst.m_filesystem, overwrite);
590 bool CPath::RemoveFile(const CPath& file)
592 return ::wxRemoveFile(file.m_filesystem);
596 bool CPath::RenameFile(const CPath& src, const CPath& dst, bool overwrite)
598 return ::wxRenameFile(src.m_filesystem, dst.m_filesystem, overwrite);
602 bool CPath::BackupFile(const CPath& src, const wxString& appendix)
604 wxASSERT(appendix.IsAscii());
606 CPath dst = CPath(src.m_filesystem + appendix);
608 if (CPath::CloneFile(src, dst, true)) {
609 // Try to ensure that the backup gets physically written
610 wxFile backupFile;
611 if (backupFile.Open(dst.m_filesystem)) {
612 backupFile.Flush();
615 return true;
618 return false;
622 bool CPath::RemoveDir(const CPath& file)
624 return ::wxRmdir(file.m_filesystem);
628 bool CPath::MakeDir(const CPath& file)
630 return ::wxMkdir(file.m_filesystem);
634 bool CPath::FileExists(const wxString& file)
636 return CPath(file).FileExists();
640 bool CPath::DirExists(const wxString& path)
642 return CPath(path).DirExists();
646 sint64 CPath::GetFileSize(const wxString& file)
648 return CPath(file).GetFileSize();
652 time_t CPath::GetModificationTime(const CPath& file)
654 return ::wxFileModificationTime(file.m_filesystem);
658 sint64 CPath::GetFreeSpaceAt(const CPath& path)
660 wxLongLong free;
661 if (::wxGetDiskSpace(path.m_filesystem, NULL, &free)) {
662 return free.GetValue();
665 return wxInvalidOffset;