2 // This file is part of the aMule Project.
4 // Copyright (c) 2008-2011 aMule Team ( admin@amule.org / http://www.amule.org )
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
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
26 #include "StringFunctions.h" // Needed for filename2char()
29 #if defined __WINDOWS__ || defined __IRIX__
30 # include <wx/ffile.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 ...
42 #define PATHCMP(a, b) wxStricmp(a, b)
43 #define PATHNCMP(a, b, n) wxStrnicmp(a, b, n)
45 #define PATHCMP(a, b) wxStrcmp(a, b)
46 #define PATHNCMP(a, b, n) wxStrncmp(a, b, n)
50 ////////////////////////////////////////////////////////////
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?
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();
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
);
81 // Nothing to do, the filename is probably Ok.
82 result
= DeepCopy(filename
);
90 /** Splits a full path into its path and filename component. */
91 inline void DoSplitPath(const wxString
& strPath
, wxString
* path
, wxString
* name
)
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
)
115 for (size_t i
= 0; i
< filename
.Length(); i
++) {
116 const wxChar c
= filename
[i
];
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
];
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();
161 return path
+ wxFileName::GetPathSeparator() + 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
);
174 return tmp
.GetFullPath();
178 /** Readies a path for use with wxAccess.. */
179 wxString
DoCleanPath(const wxString
& path
)
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();
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.
217 fn1
.Normalize(flags
, cwd
);
218 fn2
.Normalize(flags
, cwd
);
220 return (fn1
.GetFullPath() == fn2
.GetFullPath());
224 ////////////////////////////////////////////////////////////
225 // CPath implementation
232 CPath::CPath(const wxString
& filename
)
234 // Equivalent to the default constructor ...
239 wxCharBuffer fn
= filename2char(filename
);
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
);
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
253 // Magic fails on Windows where we always work with wide char file names.
254 m_filesystem
= DeepCopy(filename
);
255 m_printable
= m_filesystem
;
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
);
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
);
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
)) {
347 } else if ((mode
& writable
) && !wxIsWritable(path
)) {
349 } else if ((mode
& readable
) && !wxIsReadable(path
)) {
357 bool CPath::IsFile(EAccess mode
) const
359 if (!wxFileName::FileExists(m_filesystem
)) {
361 } else if ((mode
& writable
) && !wxIsWritable(m_filesystem
)) {
363 } else if ((mode
& readable
) && !wxIsReadable(m_filesystem
)) {
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
396 ::DoSplitPath(m_printable
, &path
.m_printable
, NULL
);
397 ::DoSplitPath(m_filesystem
, &path
.m_filesystem
, NULL
);
403 CPath
CPath::GetFullName() const
406 ::DoSplitPath(m_printable
, NULL
, &path
.m_printable
);
407 ::DoSplitPath(m_filesystem
, NULL
, &path
.m_filesystem
);
414 sint64
CPath::GetFileSize() const
417 wxFile
f(m_filesystem
);
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
448 } else if (!other
.IsOk()) {
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
);
461 CPath
CPath::Cleanup(bool keepSpaces
, bool isFAT32
) const
464 result
.m_printable
= ::DoCleanup(m_printable
, keepSpaces
, isFAT32
);
465 result
.m_filesystem
= ::DoCleanup(m_filesystem
, keepSpaces
, isFAT32
);
471 CPath
CPath::AddPostfix(const wxString
& postfix
) const
473 wxASSERT(postfix
.IsAscii());
476 result
.m_printable
= ::DoAddPostfix(m_printable
, postfix
);
477 result
.m_filesystem
= ::DoAddPostfix(m_filesystem
, postfix
);
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.
494 if (ext
[0] == wxT('.')) {
495 result
.m_printable
<< ext
;
496 result
.m_filesystem
<< ext
;
498 result
.m_printable
<< wxT(".") << ext
;
499 result
.m_filesystem
<< wxT(".") << ext
;
506 CPath
CPath::RemoveExt() const
509 result
.m_printable
= DoRemoveExt(m_printable
);
510 result
.m_filesystem
= DoRemoveExt(m_filesystem
);
516 CPath
CPath::RemoveAllExt() const
518 CPath last
, current
= RemoveExt();
520 // Loop until all extensions are removed
524 current
= last
.RemoveExt();
525 } while (last
!= 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) {
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.
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__
587 if (backupFile
.Open(dst
.m_filesystem
)) {
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
)
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
) {
654 // If the path is a file name, then prefer to remove from the path, rather than the filename
656 wxString path
= wxFileName(file
).GetPath();
657 file
= wxFileName(file
).GetFullName();
659 if (path
.Length() >= length
) {
661 } else if (file
.Length() >= length
) {
664 // Minus 6 for "[...]" + separator
665 int pathlen
= (int)(length
- file
.Length() - 6);
668 path
= wxT("[...]") + path
.Right( pathlen
);
674 file
= ::JoinPaths(path
, file
);
677 if (file
.Length() > length
) {
679 file
= file
.Left(length
- 5) + wxT("[...]");
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
))) {
708 wxString
JoinPaths(const wxString
& path
, const wxString
& file
)
710 if (path
.IsEmpty()) {
712 } else if (file
.IsEmpty()) {
716 return StripSeparators(path
, wxString::trailing
)
717 + wxFileName::GetPathSeparator()
718 + StripSeparators(file
, wxString::leading
);