3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
8 * Full author contact details are available in file CREDITS.
13 #include "support/FileName.h"
14 #include "support/FileNameList.h"
16 #include "support/debug.h"
17 #include "support/filetools.h"
18 #include "support/lassert.h"
19 #include "support/lstrings.h"
20 #include "support/mutex.h"
21 #include "support/os.h"
22 #include "support/Package.h"
23 #include "support/qstring_helpers.h"
30 #include <QTemporaryFile>
33 #include <boost/crc.hpp>
42 #ifdef HAVE_SYS_TYPES_H
43 # include <sys/types.h>
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
61 // Three implementations of checksum(), depending on having mmap support or not.
62 #if defined(HAVE_MMAP) && defined(HAVE_MUNMAP)
65 #endif // SUM_WITH_MMAP
68 using namespace lyx::support;
70 // OK, this is ugly, but it is the only workaround I found to compile
71 // with gcc (any version) on a system which uses a non-GNU toolchain.
72 // The problem is that gcc uses a weak symbol for a particular
73 // instantiation and that the system linker usually does not
74 // understand those weak symbols (seen on HP-UX, tru64, AIX and
75 // others). Thus we force an explicit instanciation of this particular
77 template struct boost::detail::crc_table_t<32, 0x04C11DB7, true>;
82 /////////////////////////////////////////////////////////////////////
86 /////////////////////////////////////////////////////////////////////
88 struct FileName::Private
92 Private(string const & abs_filename) : fi(toqstr(abs_filename))
94 name = fromqstr(fi.absoluteFilePath());
95 fi.setCaching(fi.exists() ? true : false);
105 bool isFilesystemEqual(QString const & lhs, QString const & rhs)
107 return QString::compare(lhs, rhs, os::isFilesystemCaseSensitive() ?
108 Qt::CaseSensitive : Qt::CaseInsensitive) == 0;
111 /// The absolute file name in UTF-8 encoding.
117 /////////////////////////////////////////////////////////////////////
121 /////////////////////////////////////////////////////////////////////
124 FileName::FileName() : d(new Private)
129 FileName::FileName(string const & abs_filename)
130 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
132 //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
133 LATTEST(empty() || isAbsolute(d->name));
137 FileName::~FileName()
143 FileName::FileName(FileName const & rhs) : d(new Private)
145 d->name = rhs.d->name;
150 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
156 FileName & FileName::operator=(FileName const & rhs)
160 d->name = rhs.d->name;
166 bool FileName::empty() const
168 return d->name.empty();
172 bool FileName::isAbsolute(string const & name)
174 QFileInfo fi(toqstr(name));
175 return fi.isAbsolute();
179 string FileName::absFileName() const
185 string FileName::realPath() const
187 return os::real_path(absFileName());
191 void FileName::set(string const & name)
193 d->fi.setFile(toqstr(name));
194 d->name = fromqstr(d->fi.absoluteFilePath());
195 //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
196 LATTEST(empty() || isAbsolute(d->name));
200 void FileName::set(FileName const & rhs, string const & suffix)
202 if (!rhs.d->fi.isDir())
203 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
205 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
206 d->name = fromqstr(d->fi.absoluteFilePath());
207 //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
208 LATTEST(empty() || isAbsolute(d->name));
212 void FileName::erase()
219 bool FileName::copyTo(FileName const & name, bool keepsymlink) const
222 return copyTo(name, keepsymlink, visited);
226 bool FileName::copyTo(FileName const & name, bool keepsymlink,
227 FileName::FileNameSet & visited) const
229 LYXERR(Debug::FILES, "Copying " << name << " keep symlink: " << keepsymlink);
230 if (keepsymlink && name.isSymLink()) {
231 visited.insert(*this);
232 FileName const target(fromqstr(name.d->fi.symLinkTarget()));
233 if (visited.find(target) != visited.end()) {
234 LYXERR(Debug::FILES, "Found circular symlink: " << target);
237 return copyTo(target, true);
239 QFile::remove(name.d->fi.absoluteFilePath());
240 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
242 LYXERR0("FileName::copyTo(): Could not copy file "
243 << *this << " to " << name);
248 bool FileName::renameTo(FileName const & name) const
250 LYXERR(Debug::FILES, "Renaming " << name << " as " << *this);
251 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
253 LYXERR0("Could not rename file " << *this << " to " << name);
258 bool FileName::moveTo(FileName const & name) const
260 LYXERR(Debug::FILES, "Moving " << name << " to " << *this);
261 QFile::remove(name.d->fi.absoluteFilePath());
263 bool success = QFile::rename(d->fi.absoluteFilePath(),
264 name.d->fi.absoluteFilePath());
266 LYXERR0("Could not move file " << *this << " to " << name);
271 bool FileName::changePermission(unsigned long int mode) const
273 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
274 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
275 LYXERR0("File " << *this << ": cannot change permission to "
284 string FileName::toFilesystemEncoding() const
286 // This doesn't work on Windows for non ascii file names.
287 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
288 return string(encoded.begin(), encoded.end());
292 string FileName::toSafeFilesystemEncoding(os::file_access how) const
294 // This will work on Windows for non ascii file names.
295 QString const safe_path =
296 toqstr(os::safe_internal_path(absFileName(), how));
297 QByteArray const encoded = QFile::encodeName(safe_path);
298 return string(encoded.begin(), encoded.end());
302 FileName FileName::fromFilesystemEncoding(string const & name)
304 QByteArray const encoded(name.c_str(), name.length());
305 return FileName(fromqstr(QFile::decodeName(encoded)));
309 bool FileName::exists() const
311 return !empty() && d->fi.exists();
315 bool FileName::isSymLink() const
317 return !empty() && d->fi.isSymLink();
321 //QFileInfo caching info might fool this test if file was changed meanwhile.
322 //refresh() helps, but we don't want to put it blindly here, because it might
323 //trigger slowdown on networked file systems.
324 bool FileName::isFileEmpty() const
326 LASSERT(!empty(), return true);
327 return d->fi.size() == 0;
331 bool FileName::isDirectory() const
333 return !empty() && d->fi.isDir();
337 bool FileName::isReadOnly() const
339 LASSERT(!empty(), return true);
340 return d->fi.isReadable() && !d->fi.isWritable();
344 bool FileName::isReadableDirectory() const
346 return isDirectory() && d->fi.isReadable();
350 string FileName::onlyFileName() const
352 return fromqstr(d->fi.fileName());
356 string FileName::onlyFileNameWithoutExt() const
358 return fromqstr(d->fi.completeBaseName());
362 string FileName::extension() const
364 return fromqstr(d->fi.suffix());
368 bool FileName::hasExtension(const string & ext)
370 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
374 FileName FileName::onlyPath() const
379 path.d->fi.setFile(d->fi.path());
380 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
385 FileName FileName::parentPath() const
388 // return empty path for parent of root dir
389 // parent of empty path is empty too
390 if (empty() || d->fi.isRoot())
392 path.d->fi.setFile(d->fi.path());
393 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
398 bool FileName::isReadableFile() const
400 return !empty() && d->fi.isFile() && d->fi.isReadable();
404 bool FileName::isWritable() const
406 return !empty() && d->fi.isWritable();
410 bool FileName::isDirWritable() const
412 LASSERT(isDirectory(), return false);
413 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
414 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
416 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
419 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
424 FileNameList FileName::dirList(string const & ext) const
426 FileNameList dirlist;
427 if (!isDirectory()) {
428 LYXERR0("Directory '" << *this << "' does not exist!");
432 // If the directory is specified without a trailing '/', absoluteDir()
433 // would return the parent dir, so we must use absoluteFilePath() here.
434 QDir dir = d->fi.absoluteFilePath();
439 case '.': filter = "*" + toqstr(ext); break;
440 case '*': filter = toqstr(ext); break;
441 default: filter = "*." + toqstr(ext);
443 dir.setNameFilters(QStringList(filter));
444 LYXERR(Debug::FILES, "filtering on extension "
445 << fromqstr(filter) << " is requested.");
448 QFileInfoList list = dir.entryInfoList();
449 for (int i = 0; i != list.size(); ++i) {
450 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
451 dirlist.push_back(fi);
452 LYXERR(Debug::FILES, "found file " << fi);
459 FileName FileName::getcwd()
461 // return makeAbsPath("."); would create an infinite loop
463 return FileName(fromqstr(fi.absoluteFilePath()));
467 FileName FileName::tempPath()
469 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
473 void FileName::refresh() const
479 time_t FileName::lastModified() const
481 // QFileInfo caches information about the file. So, in case this file has
482 // been touched between the object creation and now, we refresh the file
485 return d->fi.lastModified().toTime_t();
489 bool FileName::chdir() const
491 return QDir::setCurrent(d->fi.absoluteFilePath());
495 bool FileName::link(FileName const & name) const
497 return QFile::link(toqstr(absFileName()), toqstr(name.absFileName()));
501 unsigned long checksum_ifstream_fallback(char const * file)
503 unsigned long result = 0;
504 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
505 ifstream ifs(file, ios_base::in | ios_base::binary);
509 istreambuf_iterator<char> beg(ifs);
510 istreambuf_iterator<char> end;
511 boost::crc_32_type crc;
512 crc = for_each(beg, end, crc);
513 result = crc.checksum();
517 unsigned long FileName::checksum() const
519 unsigned long result = 0;
522 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
525 // a directory may be passed here so we need to test it. (bug 3622)
527 LYXERR0('"' << absFileName() << "\" is a directory!");
531 // This is used in the debug output at the end of the method.
533 if (lyxerr.debugging(Debug::FILES))
536 #if QT_VERSION >= 0x999999
537 // First version of checksum uses Qt4.4 mmap support.
538 // FIXME: This code is not ready with Qt4.4.2,
539 // see http://www.lyx.org/trac/ticket/5293
540 // FIXME: should we check if the MapExtension extension is supported?
541 // see QAbstractFileEngine::supportsExtension() and
542 // QAbstractFileEngine::MapExtension)
543 QFile qf(fi.filePath());
544 if (!qf.open(QIODevice::ReadOnly))
546 qint64 size = fi.size();
547 uchar * ubeg = qf.map(0, size);
548 uchar * uend = ubeg + size;
549 boost::crc_32_type ucrc;
550 ucrc.process_block(ubeg, uend);
553 result = ucrc.checksum();
557 string const encoded = toSafeFilesystemEncoding();
558 char const * file = encoded.c_str();
561 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
563 int fd = open(file, O_RDONLY);
568 if (fstat(fd, &info)){
569 // fstat fails on samba shares (bug 5891)
571 return checksum_ifstream_fallback(file);
574 void * mm = mmap(0, info.st_size, PROT_READ,
576 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
577 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
582 char * beg = static_cast<char*>(mm);
583 char * end = beg + info.st_size;
585 boost::crc_32_type crc;
586 crc.process_block(beg, end);
587 result = crc.checksum();
589 munmap(mm, info.st_size);
592 #else // no SUM_WITH_MMAP
593 result = checksum_ifstream_fallback(file);
594 #endif // SUM_WITH_MMAP
597 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
598 << result << " lasted " << t.elapsed() << " ms.");
603 bool FileName::removeFile() const
605 bool const success = QFile::remove(d->fi.absoluteFilePath());
607 if (!success && exists())
608 LYXERR0("Could not delete file " << *this);
613 static bool rmdir(QFileInfo const & fi)
615 QDir dir(fi.absoluteFilePath());
616 QFileInfoList list = dir.entryInfoList();
618 for (int i = 0; i != list.size(); ++i) {
619 if (list.at(i).fileName() == ".")
621 if (list.at(i).fileName() == "..")
624 if (list.at(i).isDir()) {
625 LYXERR(Debug::FILES, "Removing dir "
626 << fromqstr(list.at(i).absoluteFilePath()));
627 removed = rmdir(list.at(i));
630 LYXERR(Debug::FILES, "Removing file "
631 << fromqstr(list.at(i).absoluteFilePath()));
632 removed = dir.remove(list.at(i).fileName());
636 LYXERR0("Could not delete "
637 << fromqstr(list.at(i).absoluteFilePath()));
640 QDir parent = fi.absolutePath();
641 success &= parent.rmdir(fi.fileName());
646 bool FileName::destroyDirectory() const
648 bool const success = rmdir(d->fi);
650 LYXERR0("Could not delete " << *this);
656 // Only used in non Win32 platforms
657 static int mymkdir(char const * pathname, unsigned long int mode)
659 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
661 # if MKDIR_TAKES_ONE_ARG
663 return ::mkdir(pathname);
664 // FIXME: "Permissions of created directories are ignored on this system."
667 return ::mkdir(pathname, mode_t(mode));
669 #elif defined(_WIN32)
671 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
672 // FIXME: "Permissions of created directories are ignored on this system."
674 return ::_mkdir(pathname);
675 // FIXME: "Permissions of created directories are ignored on this system."
677 # error "Don't know how to create a directory on this system."
683 bool FileName::createDirectory(int permission) const
685 LASSERT(!empty(), return false);
687 // FIXME: "Permissions of created directories are ignored on this system."
690 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
695 bool FileName::createPath() const
697 LASSERT(!empty(), return false);
698 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
703 bool success = dir.mkpath(d->fi.absoluteFilePath());
705 LYXERR0("Cannot create path '" << *this << "'!");
710 docstring const FileName::absoluteFilePath() const
712 return qstring_to_ucs4(d->fi.absoluteFilePath());
716 docstring FileName::displayName(int threshold) const
718 return makeDisplayPath(absFileName(), threshold);
722 docstring FileName::fileContents(string const & encoding) const
724 if (!isReadableFile()) {
725 LYXERR0("File '" << *this << "' is not readable!");
729 QFile file(d->fi.absoluteFilePath());
730 if (!file.open(QIODevice::ReadOnly)) {
731 LYXERR0("File '" << *this
732 << "' could not be opened in read only mode!");
735 QByteArray contents = file.readAll();
738 if (contents.isEmpty()) {
739 LYXERR(Debug::FILES, "File '" << *this
740 << "' is either empty or some error happened while reading it.");
745 if (encoding.empty() || encoding == "UTF-8")
746 s = QString::fromUtf8(contents.data());
747 else if (encoding == "ascii")
748 #if (QT_VERSION < 0x050000)
749 s = QString::fromAscii(contents.data());
751 s = QString::fromLatin1(contents.data());
753 else if (encoding == "local8bit")
754 s = QString::fromLocal8Bit(contents.data());
755 else if (encoding == "latin1")
756 s = QString::fromLatin1(contents.data());
758 return qstring_to_ucs4(s);
762 void FileName::changeExtension(string const & extension)
764 // FIXME: use Qt native methods...
765 string const oldname = absFileName();
766 string::size_type const last_slash = oldname.rfind('/');
767 string::size_type last_dot = oldname.rfind('.');
768 if (last_dot < last_slash && last_slash != string::npos)
769 last_dot = string::npos;
772 // Make sure the extension starts with a dot
773 if (!extension.empty() && extension[0] != '.')
774 ext= '.' + extension;
778 set(oldname.substr(0, last_dot) + ext);
782 docstring const FileName::relPath(string const & path) const
785 return makeRelPath(absoluteFilePath(), from_utf8(path));
789 // Note: According to Qt, QFileInfo::operator== is undefined when
790 // both files do not exist (Qt4.5 gives true for all non-existent
791 // files, while Qt4.4 compares the filenames).
793 // http://www.qtsoftware.com/developer/task-tracker/
794 // index_html?id=248471&method=entry.
795 bool equivalent(FileName const & l, FileName const & r)
797 // FIXME: In future use Qt.
798 // Qt 4.4: We need to solve this warning from Qt documentation:
799 // * Long and short file names that refer to the same file on Windows are
800 // treated as if they referred to different files.
801 // This is supposed to be fixed for Qt5.
802 FileName const lhs(os::internal_path(l.absFileName()));
803 FileName const rhs(os::internal_path(r.absFileName()));
806 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
810 // Avoid unnecessary checks below.
816 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
817 // Qt already checks if the filesystem is case sensitive or not.
818 // see note above why the extra check with fileName is needed.
819 return lhs.d->fi == rhs.d->fi
820 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
823 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
824 QFileInfo fi1(lhs.d->fi);
826 fi1 = QFileInfo(fi1.symLinkTarget());
827 QFileInfo fi2(rhs.d->fi);
829 fi2 = QFileInfo(fi2.symLinkTarget());
830 // see note above why the extra check with fileName is needed.
831 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
835 bool operator==(FileName const & lhs, FileName const & rhs)
837 return os::isFilesystemCaseSensitive()
838 ? lhs.absFileName() == rhs.absFileName()
839 : !QString::compare(toqstr(lhs.absFileName()),
840 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
844 bool operator!=(FileName const & lhs, FileName const & rhs)
846 return !(operator==(lhs, rhs));
850 bool operator<(FileName const & lhs, FileName const & rhs)
852 return lhs.absFileName() < rhs.absFileName();
856 bool operator>(FileName const & lhs, FileName const & rhs)
858 return lhs.absFileName() > rhs.absFileName();
862 ostream & operator<<(ostream & os, FileName const & filename)
864 return os << filename.absFileName();
868 /////////////////////////////////////////////////////////////////////
872 /////////////////////////////////////////////////////////////////////
875 DocFileName::DocFileName()
876 : save_abs_path_(true)
880 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
881 : FileName(abs_filename), save_abs_path_(save_abs)
885 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
886 : FileName(abs_filename), save_abs_path_(save_abs)
890 void DocFileName::set(string const & name, string const & buffer_path)
892 save_abs_path_ = isAbsolute(name);
896 FileName::set(makeAbsPath(name, buffer_path).absFileName());
900 void DocFileName::erase()
906 string DocFileName::relFileName(string const & path) const
909 return to_utf8(relPath(path));
913 string DocFileName::outputFileName(string const & path) const
915 return save_abs_path_ ? absFileName() : relFileName(path);
919 string DocFileName::mangledFileName(string const & dir) const
921 // Concurrent access to these variables is possible.
923 // We need to make sure that every DocFileName instance for a given
924 // filename returns the same mangled name.
925 typedef map<string, string> MangledMap;
926 static MangledMap mangledNames;
927 static Mutex mangledMutex;
928 // this locks both access to mangledNames and counter below
929 Mutex::Locker lock(&mangledMutex);
930 MangledMap::const_iterator const it = mangledNames.find(absFileName());
931 if (it != mangledNames.end())
934 string const name = absFileName();
936 string mname = os::internal_path(name);
937 // Remove the extension.
938 mname = support::changeExtension(name, string());
939 // The mangled name must be a valid LaTeX name.
940 // The list of characters to keep is probably over-restrictive,
941 // but it is not really a problem.
942 // Apart from non-ASCII characters, at least the following characters
943 // are forbidden: '/', '.', ' ', and ':'.
944 // On windows it is not possible to create files with '<', '>' or '?'
946 static string const keep = "abcdefghijklmnopqrstuvwxyz"
947 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
949 string::size_type pos = 0;
950 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
952 // Add the extension back on
953 mname = support::changeExtension(mname, getExtension(name));
955 // Prepend a counter to the filename. This is necessary to make
956 // the mangled name unique.
957 static int counter = 0;
959 s << counter++ << mname;
962 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
963 // is longer than about 160 characters. MiKTeX's pdflatex
964 // is even pickier. A maximum length of 100 has been proven to work.
965 // If dir.size() > max length, all bets are off for YAP. We truncate
966 // the filename nevertheless, keeping a minimum of 10 chars.
968 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
970 // If the mangled file name is too long, hack it to fit.
971 // We know we're guaranteed to have a unique file name because
973 if (mname.size() > max_length) {
974 int const half = (int(max_length) / 2) - 2;
976 mname = mname.substr(0, half) + "___" +
977 mname.substr(mname.size() - half);
981 mangledNames[absFileName()] = mname;
986 string DocFileName::unzippedFileName() const
988 return support::unzippedFileName(absFileName());
992 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
994 return static_cast<FileName const &>(lhs)
995 == static_cast<FileName const &>(rhs)
996 && lhs.saveAbsPath() == rhs.saveAbsPath();
1000 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1002 return !(lhs == rhs);
1005 } // namespace support