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>
36 // This is required in order to ensure that wx can "handle" filenames
37 // using a different encoding than the current system-wide setting. If
38 // this is not done, such filenames will fail during conversion to/from
39 // multibyte (as in cWC2MB/cMB2WC).
40 #if !wxUSE_GUI && !defined(__WINDOWS__ )
43 // This uses the same method as wxApp::Initialize under GTK2
44 wxString encName
= wxLocale::GetSystemEncodingName().Upper();
45 if (encName
.IsEmpty() || (encName
== wxT("US-ASCII"))) {
46 encName
= wxT("UTF-8");
49 return wxConvFileName
= new wxConvBrokenFileNames(encName
);
52 // Ensure intialization
53 static void* s_foo
= setFNConv();
57 // Windows has case-insensitive paths, so we use a
58 // case-insensitive cmp for that platform. TODO:
59 // Perhaps it would be better to simply lowercase
60 // m_filesystem in the constructor ...
62 #define PATHCMP(a, b) wxStricmp(a, b)
63 #define PATHNCMP(a, b, n) wxStrnicmp(a, b, n)
65 #define PATHCMP(a, b) wxStrcmp(a, b)
66 #define PATHNCMP(a, b, n) wxStrncmp(a, b, n)
70 ////////////////////////////////////////////////////////////
74 /** Creates a deep copy of the string, avoiding its ref. counting. */
75 inline wxString
DeepCopy(const wxString
& str
)
77 return wxString(str
.c_str(), str
.Length());
81 wxString
Demangle(const wxCharBuffer
& fn
, const wxString
& filename
)
83 wxString result
= wxConvUTF8
.cMB2WC(fn
);
85 // FIXME: Is this actually needed for osx/msw?
87 // We only try to further demangle if the current locale is
88 // UTF-8, C or POSIX. This is because in any other case, the
89 // current locale is probably the best choice for printing.
90 static wxFontEncoding enc
= wxLocale::GetSystemEncoding();
93 // SYSTEM is needed for ANSI encodings such as
94 // "POSIX" and "C", which are only 7bit.
95 case wxFONTENCODING_SYSTEM
:
96 case wxFONTENCODING_UTF8
:
97 result
= wxConvISO8859_1
.cMB2WC(fn
);
101 // Nothing to do, the filename is probably Ok.
102 result
= DeepCopy(filename
);
110 /** Splits a full path into its path and filename component. */
111 inline void DoSplitPath(const wxString
& strPath
, wxString
* path
, wxString
* name
)
116 wxString
* pVol
= (path
? &vol
: NULL
);
117 wxString
* pExt
= (name
? &ext
: NULL
);
119 wxFileName::SplitPath(strPath
, pVol
, path
, name
, pExt
, &hasExt
);
121 if (hasExt
&& pExt
) {
122 *name
+= wxT(".") + ext
;
125 if (path
&& vol
.Length()) {
126 *path
= vol
+ wxFileName::GetVolumeSeparator() + *path
;
131 /** Removes invalid chars from a filename. */
132 wxString
DoCleanup(const wxString
& filename
, bool keepSpaces
, bool isFAT32
)
135 for (size_t i
= 0; i
< filename
.Length(); i
++) {
136 const wxChar c
= filename
[i
];
155 if ((c
== wxT(' ')) && !keepSpaces
) {
156 result
+= wxT("%20");
157 } else if (c
>= 32) {
158 // Many illegal for filenames in windows
159 // below the 32th char (which is space).
160 result
+= filename
[i
];
169 /** Does the actual work of adding a postfix ... */
170 wxString
DoAddPostfix(const wxString
& src
, const wxString
& postfix
)
172 const wxFileName
srcFn(src
);
173 wxString result
= srcFn
.GetName() + postfix
;
175 if (srcFn
.HasExt()) {
176 result
+= wxT(".") + srcFn
.GetExt();
179 wxString path
= srcFn
.GetPath();
181 return path
+ wxFileName::GetPathSeparator() + result
;
187 /** Removes the last extension of a filename. */
188 wxString
DoRemoveExt(const wxString
& path
)
190 // Using wxFilename which handles paths, etc.
191 wxFileName
tmp(path
);
194 return tmp
.GetFullPath();
198 /** Readies a path for use with wxAccess.. */
199 wxString
DoCleanPath(const wxString
& path
)
202 // stat fails on windows if there are trailing path-separators.
203 wxString cleanPath
= StripSeparators(path
, wxString::trailing
);
205 // Root paths must end with a separator (X:\ rather than X:).
206 // See comments in wxDirExists.
207 if ((cleanPath
.Length() == 2) && (cleanPath
.Last() == wxT(':'))) {
208 cleanPath
+= wxFileName::GetPathSeparator();
218 /** Returns true if the two paths are equal. */
219 bool IsSameAs(const wxString
& a
, const wxString
& b
)
221 // Cache the current directory
222 const wxString cwd
= wxGetCwd();
224 // We normalize everything, except env. variables, which
225 // can cause problems when the string is not encodable
226 // using wxConvLibc which wxWidgets uses for the purpose.
227 const int flags
= (wxPATH_NORM_ALL
| wxPATH_NORM_CASE
) & ~wxPATH_NORM_ENV_VARS
;
229 // Let wxFileName handle the tricky stuff involved in actually
230 // comparing two paths ... Currently, a path ending with a path-
231 // seperator will be unequal to the same path without a path-
232 // seperator, which is probably for the best, but can could
233 // lead to some unexpected behavior.
237 fn1
.Normalize(flags
, cwd
);
238 fn2
.Normalize(flags
, cwd
);
240 return (fn1
.GetFullPath() == fn2
.GetFullPath());
244 ////////////////////////////////////////////////////////////
245 // CPath implementation
252 CPath::CPath(const wxString
& filename
)
254 // Equivalent to the default constructor ...
259 wxCharBuffer fn
= filename2char(filename
);
261 // Filename is valid in the current locale. This means that
262 // it either originated from a (wx)system-call, or from a
263 // user with a properly setup system.
264 m_filesystem
= DeepCopy(filename
);
265 m_printable
= Demangle(fn
, filename
);
267 // It's not a valid filename in the current locale, so we'll
268 // have to do some magic. This ensures that the filename is
269 // saved as UTF8, even if the system is not unicode enabled,
270 // preserving the original filename till the user has fixed
273 // Magic fails on Windows where we always work with wide char file names.
274 m_filesystem
= DeepCopy(filename
);
275 m_printable
= m_filesystem
;
277 fn
= wxConvUTF8
.cWC2MB(filename
);
278 m_filesystem
= wxConvFile
.cMB2WC(fn
);
280 // There's no need to try to unmangle the filename here.
281 m_printable
= DeepCopy(filename
);
285 wxASSERT(m_filesystem
.Length());
286 wxASSERT(m_printable
.Length());
290 CPath::CPath(const CPath
& other
)
291 : m_printable(DeepCopy(other
.m_printable
))
292 , m_filesystem(DeepCopy(other
.m_filesystem
))
297 CPath
CPath::FromUniv(const wxString
& path
)
299 wxCharBuffer fn
= wxConvISO8859_1
.cWC2MB(path
);
301 return CPath(wxConvFile
.cMB2WC(fn
));
306 wxString
CPath::ToUniv(const CPath
& path
)
308 // The logic behind this is that by saving the filename
309 // as a raw bytestream (which is what ISO8859-1 amounts
310 // to), we can always recreate the on-disk filename, as
311 // if we had read it using wx functions.
312 wxCharBuffer fn
= wxConvFile
.cWC2MB(path
.m_filesystem
);
314 return wxConvISO8859_1
.cMB2WC(fn
);
318 CPath
& CPath::operator=(const CPath
& other
)
320 if (this != &other
) {
321 m_printable
= DeepCopy(other
.m_printable
);
322 m_filesystem
= DeepCopy(other
.m_filesystem
);
329 bool CPath::operator==(const CPath
& other
) const
331 return ::IsSameAs(m_filesystem
, other
.m_filesystem
);
335 bool CPath::operator!=(const CPath
& other
) const
337 return !(*this == other
);
341 bool CPath::operator<(const CPath
& other
) const
343 return PATHCMP(m_filesystem
.c_str(), other
.m_filesystem
.c_str()) < 0;
347 bool CPath::IsOk() const
349 // Something is very wrong if one of the two is empty.
350 return m_printable
.Length() && m_filesystem
.Length();
354 bool CPath::FileExists() const
356 return wxFileName::FileExists(m_filesystem
);
360 bool CPath::DirExists() const
362 return wxFileName::DirExists(DoCleanPath(m_filesystem
));
366 bool CPath::IsDir(EAccess mode
) const
368 wxString path
= DoCleanPath(m_filesystem
);
369 if (!wxFileName::DirExists(path
)) {
371 } else if ((mode
& writable
) && !wxIsWritable(path
)) {
373 } else if ((mode
& readable
) && !wxIsReadable(path
)) {
381 bool CPath::IsFile(EAccess mode
) const
383 if (!wxFileName::FileExists(m_filesystem
)) {
385 } else if ((mode
& writable
) && !wxIsWritable(m_filesystem
)) {
387 } else if ((mode
& readable
) && !wxIsReadable(m_filesystem
)) {
395 wxString
CPath::GetRaw() const
397 // Copy as c-strings to ensure that the CPath objects can safely
398 // be passed across threads (avoiding wxString ref. counting).
399 return DeepCopy(m_filesystem
);
403 wxString
CPath::GetPrintable() const
405 // Copy as c-strings to ensure that the CPath objects can safely
406 // be passed across threads (avoiding wxString ref. counting).
407 return DeepCopy(m_printable
);
411 wxString
CPath::GetExt() const
413 return wxFileName(m_filesystem
).GetExt();
417 CPath
CPath::GetPath() const
420 ::DoSplitPath(m_printable
, &path
.m_printable
, NULL
);
421 ::DoSplitPath(m_filesystem
, &path
.m_filesystem
, NULL
);
427 CPath
CPath::GetFullName() const
430 ::DoSplitPath(m_printable
, NULL
, &path
.m_printable
);
431 ::DoSplitPath(m_filesystem
, NULL
, &path
.m_filesystem
);
438 sint64
CPath::GetFileSize() const
441 wxFile
f(m_filesystem
);
447 return wxInvalidOffset
;
451 bool CPath::IsSameDir(const CPath
& other
) const
453 wxString a
= m_filesystem
;
454 wxString b
= other
.m_filesystem
;
456 // This check is needed to avoid trouble in the
457 // case where one path is empty, and the other
458 // points to the root dir.
459 if (a
.Length() && b
.Length()) {
460 a
= StripSeparators(a
, wxString::trailing
);
461 b
= StripSeparators(b
, wxString::trailing
);
464 return ::IsSameAs(a
, b
);
468 CPath
CPath::JoinPaths(const CPath
& other
) const
472 } else if (!other
.IsOk()) {
477 // DeepCopy shouldn't be needed, as JoinPaths results in the creation of a new string.
478 joinedPath
.m_printable
= ::JoinPaths(m_printable
, other
.m_printable
);
479 joinedPath
.m_filesystem
= ::JoinPaths(m_filesystem
, other
.m_filesystem
);
485 CPath
CPath::Cleanup(bool keepSpaces
, bool isFAT32
) const
488 result
.m_printable
= ::DoCleanup(m_printable
, keepSpaces
, isFAT32
);
489 result
.m_filesystem
= ::DoCleanup(m_filesystem
, keepSpaces
, isFAT32
);
495 CPath
CPath::AddPostfix(const wxString
& postfix
) const
497 wxASSERT(postfix
.IsAscii());
500 result
.m_printable
= ::DoAddPostfix(m_printable
, postfix
);
501 result
.m_filesystem
= ::DoAddPostfix(m_filesystem
, postfix
);
507 CPath
CPath::AppendExt(const wxString
& ext
) const
509 wxASSERT(ext
.IsAscii());
511 // Though technically, and empty extension would simply
512 // be another . at the end of the filename, we ignore them.
518 if (ext
[0] == wxT('.')) {
519 result
.m_printable
<< ext
;
520 result
.m_filesystem
<< ext
;
522 result
.m_printable
<< wxT(".") << ext
;
523 result
.m_filesystem
<< wxT(".") << ext
;
530 CPath
CPath::RemoveExt() const
533 result
.m_printable
= DoRemoveExt(m_printable
);
534 result
.m_filesystem
= DoRemoveExt(m_filesystem
);
540 CPath
CPath::RemoveAllExt() const
542 CPath last
, current
= RemoveExt();
544 // Loop until all extensions are removed
548 current
= last
.RemoveExt();
549 } while (last
!= current
);
555 bool CPath::StartsWith(const CPath
& other
) const
557 // It doesn't make sense comparing invalid paths,
558 // especially since if 'other' was empty, it would
559 // be considered a prefix of any path.
560 if ((IsOk() && other
.IsOk()) == false) {
564 // Adding an seperator to avoid partial matches, such as
565 // "/usr/bi" matching "/usr/bin". TODO: Paths should be
566 // normalized first (in the constructor).
567 const wxString a
= StripSeparators(m_filesystem
, wxString::trailing
) + wxFileName::GetPathSeparator();
568 const wxString b
= StripSeparators(other
.m_filesystem
, wxString::trailing
) + wxFileName::GetPathSeparator();
570 if (a
.Length() < b
.Length()) {
571 // Cannot possibly be a prefix.
575 const size_t checkLen
= std::min(a
.Length(), b
.Length());
576 return PATHNCMP(a
.c_str(), b
.c_str(), checkLen
) == 0;
580 bool CPath::CloneFile(const CPath
& src
, const CPath
& dst
, bool overwrite
)
582 return ::wxCopyFile(src
.m_filesystem
, dst
.m_filesystem
, overwrite
);
586 bool CPath::RemoveFile(const CPath
& file
)
588 return ::wxRemoveFile(file
.m_filesystem
);
592 bool CPath::RenameFile(const CPath
& src
, const CPath
& dst
, bool overwrite
)
594 return ::wxRenameFile(src
.m_filesystem
, dst
.m_filesystem
, overwrite
);
598 bool CPath::BackupFile(const CPath
& src
, const wxString
& appendix
)
600 wxASSERT(appendix
.IsAscii());
602 CPath dst
= CPath(src
.m_filesystem
+ appendix
);
604 if (CPath::CloneFile(src
, dst
, true)) {
605 // Try to ensure that the backup gets physically written
606 #if defined __WINDOWS__ || defined __IRIX__
611 if (backupFile
.Open(dst
.m_filesystem
)) {
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
)
661 if (::wxGetDiskSpace(path
.m_filesystem
, NULL
, &free
)) {
662 return free
.GetValue();
665 return wxInvalidOffset
;
669 wxString
CPath::TruncatePath(size_t length
, bool isFilePath
) const
671 wxString file
= GetPrintable();
673 // Check if there's anything to do
674 if (file
.Length() <= length
) {
678 // If the path is a file name, then prefer to remove from the path, rather than the filename
680 wxString path
= wxFileName(file
).GetPath();
681 file
= wxFileName(file
).GetFullName();
683 if (path
.Length() >= length
) {
685 } else if (file
.Length() >= length
) {
688 // Minus 6 for "[...]" + separator
689 int pathlen
= (int)(length
- file
.Length() - 6);
692 path
= wxT("[...]") + path
.Right( pathlen
);
698 file
= ::JoinPaths(path
, file
);
701 if (file
.Length() > length
) {
703 file
= file
.Left(length
- 5) + wxT("[...]");
713 wxString
StripSeparators(wxString path
, wxString::stripType type
)
715 wxASSERT((type
== wxString::leading
) || (type
== wxString::trailing
));
716 const wxString seps
= wxFileName::GetPathSeparators();
718 while (!path
.IsEmpty()) {
719 size_t pos
= ((type
== wxString::leading
) ? 0 : path
.Length() - 1);
721 if (seps
.Contains(path
.GetChar(pos
))) {
732 wxString
JoinPaths(const wxString
& path
, const wxString
& file
)
734 if (path
.IsEmpty()) {
736 } else if (file
.IsEmpty()) {
740 return StripSeparators(path
, wxString::trailing
)
741 + wxFileName::GetPathSeparator()
742 + StripSeparators(file
, wxString::leading
);