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"
25 #include <QCryptographicHash>
31 #include <QTemporaryFile>
32 #include <QElapsedTimer>
38 #include "support/checksum.h"
47 #ifdef HAVE_SYS_TYPES_H
48 # include <sys/types.h>
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
66 // Three implementations of checksum(), depending on having mmap support or not.
67 #if defined(HAVE_MMAP) && defined(HAVE_MUNMAP)
70 #endif // SUM_WITH_MMAP
73 using namespace lyx::support;
78 /////////////////////////////////////////////////////////////////////
82 /////////////////////////////////////////////////////////////////////
84 struct FileName::Private
88 explicit Private(string const & abs_filename)
89 : fi(toqstr(handleTildeName(abs_filename)))
91 name = fromqstr(fi.absoluteFilePath());
92 fi.setCaching(fi.exists());
101 bool isFilesystemEqual(QString const & lhs, QString const & rhs)
103 return QString::compare(lhs, rhs, os::isFilesystemCaseSensitive() ?
104 Qt::CaseSensitive : Qt::CaseInsensitive) == 0;
108 string const handleTildeName(string const & name)
112 resname = Package::get_home_dir().absFileName();
113 else if ( prefixIs(name, "~/"))
114 resname = Package::get_home_dir().absFileName() + name.substr(1);
115 else if ( prefixIs(name, "~:s/"))
116 resname = package().system_support().absFileName() + name.substr(3);
122 /// The absolute file name in UTF-8 encoding.
128 /////////////////////////////////////////////////////////////////////
132 /////////////////////////////////////////////////////////////////////
135 FileName::FileName() : d(new Private)
140 FileName::FileName(string const & abs_filename)
141 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
143 //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
144 LATTEST(empty() || isAbsolute(d->name));
148 FileName::~FileName()
154 FileName::FileName(FileName const & rhs) : d(new Private)
156 d->name = rhs.d->name;
161 FileName::FileName(FileName && rhs) noexcept
168 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
174 FileName & FileName::operator=(FileName const & rhs)
178 d->name = rhs.d->name;
184 FileName & FileName::operator=(FileName && rhs) noexcept
193 bool FileName::empty() const
195 return d->name.empty();
199 bool FileName::isAbsolute(string const & name)
201 QFileInfo fi(toqstr(Private::handleTildeName(name)));
202 return fi.isAbsolute();
206 string FileName::absFileName() const
212 string FileName::realPath() const
214 return os::real_path(absFileName());
218 void FileName::set(string const & name)
220 d->fi.setFile(toqstr(Private::handleTildeName(name)));
221 d->name = fromqstr(d->fi.absoluteFilePath());
222 //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
223 LATTEST(empty() || isAbsolute(d->name));
227 void FileName::set(FileName const & rhs, string const & suffix)
229 if (!rhs.d->fi.isDir())
230 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
232 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
233 d->name = fromqstr(d->fi.absoluteFilePath());
234 //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
235 LATTEST(empty() || isAbsolute(d->name));
239 void FileName::erase()
246 bool FileName::copyTo(FileName const & name, bool keepsymlink) const
249 return copyTo(name, keepsymlink, visited);
253 bool FileName::copyTo(FileName const & name, bool keepsymlink,
254 FileName::FileNameSet & visited) const
256 LYXERR(Debug::FILES, "Copying " << name << " keep symlink: " << keepsymlink);
257 if (keepsymlink && name.isSymLink()) {
258 visited.insert(*this);
259 FileName const target(fromqstr(name.d->fi.symLinkTarget()));
260 if (visited.find(target) != visited.end()) {
261 LYXERR(Debug::FILES, "Found circular symlink: " << target);
264 return copyTo(target, true);
266 QFile::remove(name.d->fi.absoluteFilePath());
267 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
269 LYXERR0("FileName::copyTo(): Could not copy file "
270 << *this << " to " << name);
275 bool FileName::renameTo(FileName const & name) const
277 LYXERR(Debug::FILES, "Renaming " << name << " as " << *this);
278 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
281 LYXERR0("Could not rename file " << *this << " to " << name);
286 bool FileName::moveTo(FileName const & name) const
288 LYXERR(Debug::FILES, "Moving " << *this << " to " << name);
290 // there's a locking problem on Windows sometimes, so
291 // we will keep trying for five seconds, in the hope
295 bool removed = name.removeFile();
297 while (!removed && tries < 6) {
299 removed = name.removeFile();
304 QFile::remove(name.d->fi.absoluteFilePath());
307 bool const success = renameTo(name);
309 LYXERR0("Could not move file " << *this << " to " << name);
314 bool FileName::changePermission(unsigned long int mode) const
316 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
317 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
318 LYXERR0("File " << *this << ": cannot change permission to "
329 bool FileName::clonePermissions(FileName const & source)
331 QFile fin(toqstr(source.absFileName()));
332 QFile f(toqstr(absFileName()));
334 return f.setPermissions(fin.permissions());
337 string FileName::toFilesystemEncoding() const
339 // This doesn't work on Windows for non ascii file names.
340 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
341 return string(encoded.begin(), encoded.end());
345 string FileName::toSafeFilesystemEncoding(os::file_access how) const
347 // This will work on Windows for non ascii file names.
348 QString const safe_path =
349 toqstr(os::safe_internal_path(absFileName(), how));
350 QByteArray const encoded = QFile::encodeName(safe_path);
351 return string(encoded.begin(), encoded.end());
355 FileName FileName::fromFilesystemEncoding(string const & name)
357 QByteArray const encoded(name.c_str(), name.length());
358 return FileName(fromqstr(QFile::decodeName(encoded)));
362 bool FileName::exists() const
364 return !empty() && d->fi.exists();
368 bool FileName::isSymLink() const
370 return !empty() && d->fi.isSymLink();
374 //QFileInfo caching info might fool this test if file was changed meanwhile.
375 //refresh() helps, but we don't want to put it blindly here, because it might
376 //trigger slowdown on networked file systems.
377 bool FileName::isFileEmpty() const
379 LASSERT(!empty(), return true);
380 return d->fi.size() == 0;
384 bool FileName::isDirectory() const
386 return !empty() && d->fi.isDir();
390 bool FileName::isReadOnly() const
392 LASSERT(!empty(), return true);
393 return d->fi.isReadable() && !d->fi.isWritable();
397 bool FileName::isReadableDirectory() const
399 return isDirectory() && d->fi.isReadable();
403 string FileName::onlyFileName() const
405 return fromqstr(d->fi.fileName());
409 string FileName::onlyFileNameWithoutExt() const
411 return fromqstr(d->fi.completeBaseName());
415 string FileName::extension() const
417 return fromqstr(d->fi.suffix());
421 bool FileName::hasExtension(const string & ext)
423 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
427 FileName FileName::onlyPath() const
432 path.d->fi.setFile(d->fi.path());
433 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
438 FileName FileName::parentPath() const
441 // return empty path for parent of root dir
442 // parent of empty path is empty too
443 if (empty() || d->fi.isRoot())
445 path.d->fi.setFile(d->fi.path());
446 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
451 bool FileName::isReadableFile() const
453 return !empty() && d->fi.isFile() && d->fi.isReadable();
457 bool FileName::isWritable() const
459 return !empty() && d->fi.isWritable();
463 bool FileName::isDirWritable() const
465 LASSERT(isDirectory(), return false);
466 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
467 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
469 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
472 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
477 FileNameList FileName::dirList(string const & ext) const
479 FileNameList dirlist;
480 if (!isDirectory()) {
481 LYXERR0("Directory '" << *this << "' does not exist!");
485 // If the directory is specified without a trailing '/', absoluteDir()
486 // would return the parent dir, so we must use absoluteFilePath() here.
487 QDir dir = d->fi.absoluteFilePath();
492 case '.': filter = "*" + toqstr(ext); break;
493 case '*': filter = toqstr(ext); break;
494 default: filter = "*." + toqstr(ext);
496 dir.setNameFilters(QStringList(filter));
497 LYXERR(Debug::FILES, "filtering on extension "
498 << fromqstr(filter) << " is requested.");
501 QFileInfoList list = dir.entryInfoList();
502 for (int i = 0; i != list.size(); ++i) {
503 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
504 dirlist.push_back(fi);
505 LYXERR(Debug::FILES, "found file " << fi);
512 FileName FileName::getcwd()
514 // return makeAbsPath("."); would create an infinite loop
516 return FileName(fromqstr(fi.absoluteFilePath()));
520 FileName FileName::tempPath()
522 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
526 void FileName::refresh() const
532 time_t FileName::lastModified() const
534 // QFileInfo caches information about the file. So, in case this file has
535 // been touched between the object creation and now, we refresh the file
538 return d->fi.lastModified().toTime_t();
542 bool FileName::chdir() const
544 return QDir::setCurrent(d->fi.absoluteFilePath());
548 bool FileName::link(FileName const & name) const
550 return QFile::link(toqstr(absFileName()), toqstr(name.absFileName()));
554 unsigned long checksum_ifstream_fallback(char const * file)
556 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
557 ifstream ifs(file, ios_base::in | ios_base::binary);
560 return support::checksum(ifs);
564 unsigned long FileName::checksum() const
567 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
570 // a directory may be passed here so we need to test it. (bug 3622)
572 LYXERR0('"' << absFileName() << "\" is a directory!");
576 // This is used in the debug output at the end of the method.
577 static QElapsedTimer t;
578 if (lyxerr.debugging(Debug::FILES))
581 unsigned long result = 0;
583 #if QT_VERSION >= 0x999999
584 // First version of checksum uses Qt4.4 mmap support.
585 // FIXME: This code is not ready with Qt4.4.2,
586 // see http://www.lyx.org/trac/ticket/5293
587 // FIXME: should we check if the MapExtension extension is supported?
588 // see QAbstractFileEngine::supportsExtension() and
589 // QAbstractFileEngine::MapExtension)
590 QFile qf(fi.filePath());
591 if (!qf.open(QIODevice::ReadOnly))
593 qint64 size = fi.size();
594 uchar * ubeg = qf.map(0, size);
595 uchar * uend = ubeg + size;
596 result = support::checksum(ubeg, uend);
602 string const encoded = toSafeFilesystemEncoding();
603 char const * file = encoded.c_str();
606 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
608 int fd = open(file, O_RDONLY);
613 if (fstat(fd, &info)){
614 // fstat fails on samba shares (bug 5891)
616 return checksum_ifstream_fallback(file);
619 void * mm = mmap(0, info.st_size, PROT_READ,
621 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
622 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
627 unsigned char * beg = static_cast<unsigned char*>(mm);
628 unsigned char * end = beg + info.st_size;
630 result = support::checksum(beg, end);
632 munmap(mm, info.st_size);
635 #else // no SUM_WITH_MMAP
636 result = checksum_ifstream_fallback(file);
637 #endif // SUM_WITH_MMAP
640 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
641 << result << " lasted " << t.elapsed() << " ms.");
646 bool FileName::removeFile() const
648 bool const success = QFile::remove(d->fi.absoluteFilePath());
650 if (!success && exists())
651 LYXERR0("Could not delete file " << *this);
656 static bool rmdir(QFileInfo const & fi)
658 QDir dir(fi.absoluteFilePath());
659 QFileInfoList list = dir.entryInfoList();
661 for (int i = 0; i != list.size(); ++i) {
662 if (list.at(i).fileName() == ".")
664 if (list.at(i).fileName() == "..")
667 if (list.at(i).isDir()) {
668 LYXERR(Debug::FILES, "Removing dir "
669 << fromqstr(list.at(i).absoluteFilePath()));
670 removed = rmdir(list.at(i));
673 LYXERR(Debug::FILES, "Removing file "
674 << fromqstr(list.at(i).absoluteFilePath()));
675 removed = dir.remove(list.at(i).fileName());
679 LYXERR0("Could not delete "
680 << fromqstr(list.at(i).absoluteFilePath()));
683 QDir parent = fi.absolutePath();
684 success &= parent.rmdir(fi.fileName());
689 bool FileName::destroyDirectory() const
691 bool const success = rmdir(d->fi);
693 LYXERR0("Could not delete " << *this);
699 // Only used in non Win32 platforms
701 static int mymkdir(char const * pathname, unsigned long int mode)
703 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
705 # if MKDIR_TAKES_ONE_ARG
707 return ::mkdir(pathname);
708 // FIXME: "Permissions of created directories are ignored on this system."
711 return ::mkdir(pathname, mode_t(mode));
713 # elif defined(_WIN32)
715 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
716 // FIXME: "Permissions of created directories are ignored on this system."
718 return ::_mkdir(pathname);
719 // FIXME: "Permissions of created directories are ignored on this system."
721 # error "Don't know how to create a directory on this system."
727 bool FileName::createDirectory(int permission) const
729 LASSERT(!empty(), return false);
731 // FIXME: "Permissions of created directories are ignored on this system."
735 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
740 bool FileName::createPath() const
742 LASSERT(!empty(), return false);
743 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
748 bool success = dir.mkpath(d->fi.absoluteFilePath());
750 LYXERR0("Cannot create path '" << *this << "'!");
755 docstring const FileName::absoluteFilePath() const
757 return qstring_to_ucs4(d->fi.absoluteFilePath());
761 docstring FileName::displayName(int threshold) const
763 return makeDisplayPath(absFileName(), threshold);
767 docstring FileName::fileContents(string const & encoding) const
769 if (!isReadableFile()) {
770 LYXERR0("File '" << *this << "' is not readable!");
774 QFile file(d->fi.absoluteFilePath());
775 if (!file.open(QIODevice::ReadOnly)) {
776 LYXERR0("File '" << *this
777 << "' could not be opened in read only mode!");
780 QByteArray contents = file.readAll();
783 if (contents.isEmpty()) {
784 LYXERR(Debug::FILES, "File '" << *this
785 << "' is either empty or some error happened while reading it.");
790 if (encoding.empty() || encoding == "UTF-8")
791 s = QString::fromUtf8(contents.data());
792 else if (encoding == "ascii")
793 #if (QT_VERSION < 0x050000)
794 s = QString::fromAscii(contents.data());
796 s = QString::fromLatin1(contents.data());
798 else if (encoding == "local8bit")
799 s = QString::fromLocal8Bit(contents.data());
800 else if (encoding == "latin1")
801 s = QString::fromLatin1(contents.data());
803 return qstring_to_ucs4(s);
807 void FileName::changeExtension(string const & extension)
809 // FIXME: use Qt native methods...
810 string const oldname = absFileName();
811 string::size_type const last_slash = oldname.rfind('/');
812 string::size_type last_dot = oldname.rfind('.');
813 if (last_dot < last_slash && last_slash != string::npos)
814 last_dot = string::npos;
817 // Make sure the extension starts with a dot
818 if (!extension.empty() && extension[0] != '.')
819 ext= '.' + extension;
823 set(oldname.substr(0, last_dot) + ext);
827 docstring const FileName::relPath(string const & path) const
830 return makeRelPath(absoluteFilePath(), from_utf8(path));
834 // Note: According to Qt, QFileInfo::operator== is undefined when
835 // both files do not exist (Qt4.5 gives true for all non-existent
836 // files, while Qt4.4 compares the filenames).
838 // http://www.qtsoftware.com/developer/task-tracker/
839 // index_html?id=248471&method=entry.
840 bool equivalent(FileName const & l, FileName const & r)
842 // FIXME: In future use Qt.
843 // Qt 4.4: We need to solve this warning from Qt documentation:
844 // * Long and short file names that refer to the same file on Windows are
845 // treated as if they referred to different files.
846 // This is supposed to be fixed for Qt5.
847 FileName const lhs(os::internal_path(l.absFileName()));
848 FileName const rhs(os::internal_path(r.absFileName()));
851 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
855 // Avoid unnecessary checks below.
861 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
862 // Qt already checks if the filesystem is case sensitive or not.
863 // see note above why the extra check with fileName is needed.
864 return lhs.d->fi == rhs.d->fi
865 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
868 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
869 QFileInfo fi1(lhs.d->fi);
871 fi1 = QFileInfo(fi1.symLinkTarget());
872 QFileInfo fi2(rhs.d->fi);
874 fi2 = QFileInfo(fi2.symLinkTarget());
875 // see note above why the extra check with fileName is needed.
876 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
880 bool operator==(FileName const & lhs, FileName const & rhs)
882 return os::isFilesystemCaseSensitive()
883 ? lhs.absFileName() == rhs.absFileName()
884 : !QString::compare(toqstr(lhs.absFileName()),
885 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
889 bool operator!=(FileName const & lhs, FileName const & rhs)
891 return !(operator==(lhs, rhs));
895 bool operator<(FileName const & lhs, FileName const & rhs)
897 return lhs.absFileName() < rhs.absFileName();
901 bool operator>(FileName const & lhs, FileName const & rhs)
903 return lhs.absFileName() > rhs.absFileName();
907 ostream & operator<<(ostream & os, FileName const & filename)
909 return os << filename.absFileName();
913 /////////////////////////////////////////////////////////////////////
917 /////////////////////////////////////////////////////////////////////
920 DocFileName::DocFileName()
921 : save_abs_path_(true)
925 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
926 : FileName(abs_filename), save_abs_path_(save_abs)
930 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
931 : FileName(abs_filename), save_abs_path_(save_abs)
935 void DocFileName::set(string const & name, string const & buffer_path)
937 save_abs_path_ = isAbsolute(name);
941 FileName::set(makeAbsPath(name, buffer_path).absFileName());
945 void DocFileName::erase()
951 string DocFileName::relFileName(string const & path) const
954 return to_utf8(relPath(path));
958 string DocFileName::outputFileName(string const & path) const
960 return save_abs_path_ ? absFileName() : relFileName(path);
964 string DocFileName::mangledFileName(string const & dir) const
966 return mangledFileName(dir, true, false);
969 string DocFileName::mangledFileName(string const & dir, bool use_counter, bool encrypt_path) const
971 // Concurrent access to these variables is possible.
973 // We need to make sure that every DocFileName instance for a given
974 // filename returns the same mangled name.
975 typedef map<string, string> MangledMap;
976 static MangledMap mangledNames;
977 static Mutex mangledMutex;
978 // this locks both access to mangledNames and counter below
979 Mutex::Locker lock(&mangledMutex);
980 MangledMap::const_iterator const it = mangledNames.find(absFileName());
981 if (it != mangledNames.end())
984 string const name = absFileName();
985 // Now the real work. Remove the extension.
986 string mname = support::changeExtension(name, string());
989 QString qname = toqstr(mname);
990 #if QT_VERSION >= 0x050000
991 QByteArray hash = QCryptographicHash::hash(qname.toLocal8Bit(),QCryptographicHash::Sha256);
993 QByteArray hash = QCryptographicHash::hash(qname.toLocal8Bit(),QCryptographicHash::Sha1);
996 mname = fromqstr(QString(hash));
997 mname = mname + "_" + onlyFileName();
1000 // The mangled name must be a valid LaTeX name.
1001 // The list of characters to keep is probably over-restrictive,
1002 // but it is not really a problem.
1003 // Apart from non-ASCII characters, at least the following characters
1004 // are forbidden: '/', '.', ' ', and ':'.
1005 // On windows it is not possible to create files with '<', '>' or '?'
1007 static string const keep = "abcdefghijklmnopqrstuvwxyz"
1008 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1010 string::size_type pos = 0;
1011 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
1013 // Add the extension back on
1014 mname = support::changeExtension(mname, getExtension(name));
1016 // Prepend a counter to the filename. This is necessary to make
1017 // the mangled name unique.
1018 static int counter = 0;
1022 s << counter++ << mname;
1026 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
1027 // is longer than about 160 characters. MiKTeX's pdflatex
1028 // is even pickier. A maximum length of 100 has been proven to work.
1029 // If dir.size() > max length, all bets are off for YAP. We truncate
1030 // the filename nevertheless, keeping a minimum of 10 chars.
1032 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
1034 // If the mangled file name is too long, hack it to fit.
1035 // We know we're guaranteed to have a unique file name because
1037 if (mname.size() > max_length) {
1038 int const half = (int(max_length) / 2) - 2;
1040 mname = mname.substr(0, half) + "___" +
1041 mname.substr(mname.size() - half);
1045 mangledNames[absFileName()] = mname;
1050 string DocFileName::unzippedFileName() const
1052 return support::unzippedFileName(absFileName());
1056 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1058 return static_cast<FileName const &>(lhs)
1059 == static_cast<FileName const &>(rhs)
1060 && lhs.saveAbsPath() == rhs.saveAbsPath();
1064 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1066 return !(lhs == rhs);
1069 } // namespace support