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 <boost/crc.hpp>
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 const & rhs, string const & suffix) : d(new Private)
167 FileName & FileName::operator=(FileName const & rhs)
171 d->name = rhs.d->name;
177 bool FileName::empty() const
179 return d->name.empty();
183 bool FileName::isAbsolute(string const & name)
185 QFileInfo fi(toqstr(Private::handleTildeName(name)));
186 return fi.isAbsolute();
190 string FileName::absFileName() const
196 string FileName::realPath() const
198 return os::real_path(absFileName());
202 void FileName::set(string const & name)
204 d->fi.setFile(toqstr(Private::handleTildeName(name)));
205 d->name = fromqstr(d->fi.absoluteFilePath());
206 //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
207 LATTEST(empty() || isAbsolute(d->name));
211 void FileName::set(FileName const & rhs, string const & suffix)
213 if (!rhs.d->fi.isDir())
214 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
216 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
217 d->name = fromqstr(d->fi.absoluteFilePath());
218 //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
219 LATTEST(empty() || isAbsolute(d->name));
223 void FileName::erase()
230 bool FileName::copyTo(FileName const & name, bool keepsymlink) const
233 return copyTo(name, keepsymlink, visited);
237 bool FileName::copyTo(FileName const & name, bool keepsymlink,
238 FileName::FileNameSet & visited) const
240 LYXERR(Debug::FILES, "Copying " << name << " keep symlink: " << keepsymlink);
241 if (keepsymlink && name.isSymLink()) {
242 visited.insert(*this);
243 FileName const target(fromqstr(name.d->fi.symLinkTarget()));
244 if (visited.find(target) != visited.end()) {
245 LYXERR(Debug::FILES, "Found circular symlink: " << target);
248 return copyTo(target, true);
250 QFile::remove(name.d->fi.absoluteFilePath());
251 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
253 LYXERR0("FileName::copyTo(): Could not copy file "
254 << *this << " to " << name);
259 bool FileName::renameTo(FileName const & name) const
261 LYXERR(Debug::FILES, "Renaming " << name << " as " << *this);
262 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
265 LYXERR0("Could not rename file " << *this << " to " << name);
270 bool FileName::moveTo(FileName const & name) const
272 LYXERR(Debug::FILES, "Moving " << *this << " to " << name);
274 // there's a locking problem on Windows sometimes, so
275 // we will keep trying for five seconds, in the hope
279 bool removed = name.removeFile();
281 while (!removed && tries < 6) {
283 removed = name.removeFile();
288 QFile::remove(name.d->fi.absoluteFilePath());
291 bool const success = renameTo(name);
293 LYXERR0("Could not move file " << *this << " to " << name);
298 bool FileName::changePermission(unsigned long int mode) const
300 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
301 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
302 LYXERR0("File " << *this << ": cannot change permission to "
313 bool FileName::clonePermissions(FileName const & source)
315 QFile fin(toqstr(source.absFileName()));
316 QFile f(toqstr(absFileName()));
318 return f.setPermissions(fin.permissions());
321 string FileName::toFilesystemEncoding() const
323 // This doesn't work on Windows for non ascii file names.
324 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
325 return string(encoded.begin(), encoded.end());
329 string FileName::toSafeFilesystemEncoding(os::file_access how) const
331 // This will work on Windows for non ascii file names.
332 QString const safe_path =
333 toqstr(os::safe_internal_path(absFileName(), how));
334 QByteArray const encoded = QFile::encodeName(safe_path);
335 return string(encoded.begin(), encoded.end());
339 FileName FileName::fromFilesystemEncoding(string const & name)
341 QByteArray const encoded(name.c_str(), name.length());
342 return FileName(fromqstr(QFile::decodeName(encoded)));
346 bool FileName::exists() const
348 return !empty() && d->fi.exists();
352 bool FileName::isSymLink() const
354 return !empty() && d->fi.isSymLink();
358 //QFileInfo caching info might fool this test if file was changed meanwhile.
359 //refresh() helps, but we don't want to put it blindly here, because it might
360 //trigger slowdown on networked file systems.
361 bool FileName::isFileEmpty() const
363 LASSERT(!empty(), return true);
364 return d->fi.size() == 0;
368 bool FileName::isDirectory() const
370 return !empty() && d->fi.isDir();
374 bool FileName::isReadOnly() const
376 LASSERT(!empty(), return true);
377 return d->fi.isReadable() && !d->fi.isWritable();
381 bool FileName::isReadableDirectory() const
383 return isDirectory() && d->fi.isReadable();
387 string FileName::onlyFileName() const
389 return fromqstr(d->fi.fileName());
393 string FileName::onlyFileNameWithoutExt() const
395 return fromqstr(d->fi.completeBaseName());
399 string FileName::extension() const
401 return fromqstr(d->fi.suffix());
405 bool FileName::hasExtension(const string & ext)
407 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
411 FileName FileName::onlyPath() const
416 path.d->fi.setFile(d->fi.path());
417 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
422 FileName FileName::parentPath() const
425 // return empty path for parent of root dir
426 // parent of empty path is empty too
427 if (empty() || d->fi.isRoot())
429 path.d->fi.setFile(d->fi.path());
430 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
435 bool FileName::isReadableFile() const
437 return !empty() && d->fi.isFile() && d->fi.isReadable();
441 bool FileName::isWritable() const
443 return !empty() && d->fi.isWritable();
447 bool FileName::isDirWritable() const
449 LASSERT(isDirectory(), return false);
450 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
451 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
453 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
456 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
461 FileNameList FileName::dirList(string const & ext) const
463 FileNameList dirlist;
464 if (!isDirectory()) {
465 LYXERR0("Directory '" << *this << "' does not exist!");
469 // If the directory is specified without a trailing '/', absoluteDir()
470 // would return the parent dir, so we must use absoluteFilePath() here.
471 QDir dir = d->fi.absoluteFilePath();
476 case '.': filter = "*" + toqstr(ext); break;
477 case '*': filter = toqstr(ext); break;
478 default: filter = "*." + toqstr(ext);
480 dir.setNameFilters(QStringList(filter));
481 LYXERR(Debug::FILES, "filtering on extension "
482 << fromqstr(filter) << " is requested.");
485 QFileInfoList list = dir.entryInfoList();
486 for (int i = 0; i != list.size(); ++i) {
487 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
488 dirlist.push_back(fi);
489 LYXERR(Debug::FILES, "found file " << fi);
496 FileName FileName::getcwd()
498 // return makeAbsPath("."); would create an infinite loop
500 return FileName(fromqstr(fi.absoluteFilePath()));
504 FileName FileName::tempPath()
506 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
510 void FileName::refresh() const
516 time_t FileName::lastModified() const
518 // QFileInfo caches information about the file. So, in case this file has
519 // been touched between the object creation and now, we refresh the file
522 return d->fi.lastModified().toTime_t();
526 bool FileName::chdir() const
528 return QDir::setCurrent(d->fi.absoluteFilePath());
532 bool FileName::link(FileName const & name) const
534 return QFile::link(toqstr(absFileName()), toqstr(name.absFileName()));
538 unsigned long checksum_ifstream_fallback(char const * file)
540 unsigned long result = 0;
541 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
542 ifstream ifs(file, ios_base::in | ios_base::binary);
546 istreambuf_iterator<char> beg(ifs);
547 istreambuf_iterator<char> end;
548 boost::crc_32_type crc;
549 crc = for_each(beg, end, crc);
550 result = crc.checksum();
554 unsigned long FileName::checksum() const
557 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
560 // a directory may be passed here so we need to test it. (bug 3622)
562 LYXERR0('"' << absFileName() << "\" is a directory!");
566 // This is used in the debug output at the end of the method.
567 static QElapsedTimer t;
568 if (lyxerr.debugging(Debug::FILES))
571 unsigned long result = 0;
573 #if QT_VERSION >= 0x999999
574 // First version of checksum uses Qt4.4 mmap support.
575 // FIXME: This code is not ready with Qt4.4.2,
576 // see http://www.lyx.org/trac/ticket/5293
577 // FIXME: should we check if the MapExtension extension is supported?
578 // see QAbstractFileEngine::supportsExtension() and
579 // QAbstractFileEngine::MapExtension)
580 QFile qf(fi.filePath());
581 if (!qf.open(QIODevice::ReadOnly))
583 qint64 size = fi.size();
584 uchar * ubeg = qf.map(0, size);
585 uchar * uend = ubeg + size;
586 boost::crc_32_type ucrc;
587 ucrc.process_block(ubeg, uend);
590 result = ucrc.checksum();
594 string const encoded = toSafeFilesystemEncoding();
595 char const * file = encoded.c_str();
598 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
600 int fd = open(file, O_RDONLY);
605 if (fstat(fd, &info)){
606 // fstat fails on samba shares (bug 5891)
608 return checksum_ifstream_fallback(file);
611 void * mm = mmap(0, info.st_size, PROT_READ,
613 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
614 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
619 char * beg = static_cast<char*>(mm);
620 char * end = beg + info.st_size;
622 boost::crc_32_type crc;
623 crc.process_block(beg, end);
624 result = crc.checksum();
626 munmap(mm, info.st_size);
629 #else // no SUM_WITH_MMAP
630 result = checksum_ifstream_fallback(file);
631 #endif // SUM_WITH_MMAP
634 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
635 << result << " lasted " << t.elapsed() << " ms.");
640 bool FileName::removeFile() const
642 bool const success = QFile::remove(d->fi.absoluteFilePath());
644 if (!success && exists())
645 LYXERR0("Could not delete file " << *this);
650 static bool rmdir(QFileInfo const & fi)
652 QDir dir(fi.absoluteFilePath());
653 QFileInfoList list = dir.entryInfoList();
655 for (int i = 0; i != list.size(); ++i) {
656 if (list.at(i).fileName() == ".")
658 if (list.at(i).fileName() == "..")
661 if (list.at(i).isDir()) {
662 LYXERR(Debug::FILES, "Removing dir "
663 << fromqstr(list.at(i).absoluteFilePath()));
664 removed = rmdir(list.at(i));
667 LYXERR(Debug::FILES, "Removing file "
668 << fromqstr(list.at(i).absoluteFilePath()));
669 removed = dir.remove(list.at(i).fileName());
673 LYXERR0("Could not delete "
674 << fromqstr(list.at(i).absoluteFilePath()));
677 QDir parent = fi.absolutePath();
678 success &= parent.rmdir(fi.fileName());
683 bool FileName::destroyDirectory() const
685 bool const success = rmdir(d->fi);
687 LYXERR0("Could not delete " << *this);
693 // Only used in non Win32 platforms
695 static int mymkdir(char const * pathname, unsigned long int mode)
697 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
699 # if MKDIR_TAKES_ONE_ARG
701 return ::mkdir(pathname);
702 // FIXME: "Permissions of created directories are ignored on this system."
705 return ::mkdir(pathname, mode_t(mode));
707 # elif defined(_WIN32)
709 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
710 // FIXME: "Permissions of created directories are ignored on this system."
712 return ::_mkdir(pathname);
713 // FIXME: "Permissions of created directories are ignored on this system."
715 # error "Don't know how to create a directory on this system."
721 bool FileName::createDirectory(int permission) const
723 LASSERT(!empty(), return false);
725 // FIXME: "Permissions of created directories are ignored on this system."
729 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
734 bool FileName::createPath() const
736 LASSERT(!empty(), return false);
737 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
742 bool success = dir.mkpath(d->fi.absoluteFilePath());
744 LYXERR0("Cannot create path '" << *this << "'!");
749 docstring const FileName::absoluteFilePath() const
751 return qstring_to_ucs4(d->fi.absoluteFilePath());
755 docstring FileName::displayName(int threshold) const
757 return makeDisplayPath(absFileName(), threshold);
761 docstring FileName::fileContents(string const & encoding) const
763 if (!isReadableFile()) {
764 LYXERR0("File '" << *this << "' is not readable!");
768 QFile file(d->fi.absoluteFilePath());
769 if (!file.open(QIODevice::ReadOnly)) {
770 LYXERR0("File '" << *this
771 << "' could not be opened in read only mode!");
774 QByteArray contents = file.readAll();
777 if (contents.isEmpty()) {
778 LYXERR(Debug::FILES, "File '" << *this
779 << "' is either empty or some error happened while reading it.");
784 if (encoding.empty() || encoding == "UTF-8")
785 s = QString::fromUtf8(contents.data());
786 else if (encoding == "ascii")
787 #if (QT_VERSION < 0x050000)
788 s = QString::fromAscii(contents.data());
790 s = QString::fromLatin1(contents.data());
792 else if (encoding == "local8bit")
793 s = QString::fromLocal8Bit(contents.data());
794 else if (encoding == "latin1")
795 s = QString::fromLatin1(contents.data());
797 return qstring_to_ucs4(s);
801 void FileName::changeExtension(string const & extension)
803 // FIXME: use Qt native methods...
804 string const oldname = absFileName();
805 string::size_type const last_slash = oldname.rfind('/');
806 string::size_type last_dot = oldname.rfind('.');
807 if (last_dot < last_slash && last_slash != string::npos)
808 last_dot = string::npos;
811 // Make sure the extension starts with a dot
812 if (!extension.empty() && extension[0] != '.')
813 ext= '.' + extension;
817 set(oldname.substr(0, last_dot) + ext);
821 docstring const FileName::relPath(string const & path) const
824 return makeRelPath(absoluteFilePath(), from_utf8(path));
828 // Note: According to Qt, QFileInfo::operator== is undefined when
829 // both files do not exist (Qt4.5 gives true for all non-existent
830 // files, while Qt4.4 compares the filenames).
832 // http://www.qtsoftware.com/developer/task-tracker/
833 // index_html?id=248471&method=entry.
834 bool equivalent(FileName const & l, FileName const & r)
836 // FIXME: In future use Qt.
837 // Qt 4.4: We need to solve this warning from Qt documentation:
838 // * Long and short file names that refer to the same file on Windows are
839 // treated as if they referred to different files.
840 // This is supposed to be fixed for Qt5.
841 FileName const lhs(os::internal_path(l.absFileName()));
842 FileName const rhs(os::internal_path(r.absFileName()));
845 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
849 // Avoid unnecessary checks below.
855 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
856 // Qt already checks if the filesystem is case sensitive or not.
857 // see note above why the extra check with fileName is needed.
858 return lhs.d->fi == rhs.d->fi
859 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
862 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
863 QFileInfo fi1(lhs.d->fi);
865 fi1 = QFileInfo(fi1.symLinkTarget());
866 QFileInfo fi2(rhs.d->fi);
868 fi2 = QFileInfo(fi2.symLinkTarget());
869 // see note above why the extra check with fileName is needed.
870 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
874 bool operator==(FileName const & lhs, FileName const & rhs)
876 return os::isFilesystemCaseSensitive()
877 ? lhs.absFileName() == rhs.absFileName()
878 : !QString::compare(toqstr(lhs.absFileName()),
879 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
883 bool operator!=(FileName const & lhs, FileName const & rhs)
885 return !(operator==(lhs, rhs));
889 bool operator<(FileName const & lhs, FileName const & rhs)
891 return lhs.absFileName() < rhs.absFileName();
895 bool operator>(FileName const & lhs, FileName const & rhs)
897 return lhs.absFileName() > rhs.absFileName();
901 ostream & operator<<(ostream & os, FileName const & filename)
903 return os << filename.absFileName();
907 /////////////////////////////////////////////////////////////////////
911 /////////////////////////////////////////////////////////////////////
914 DocFileName::DocFileName()
915 : save_abs_path_(true)
919 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
920 : FileName(abs_filename), save_abs_path_(save_abs)
924 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
925 : FileName(abs_filename), save_abs_path_(save_abs)
929 void DocFileName::set(string const & name, string const & buffer_path)
931 save_abs_path_ = isAbsolute(name);
935 FileName::set(makeAbsPath(name, buffer_path).absFileName());
939 void DocFileName::erase()
945 string DocFileName::relFileName(string const & path) const
948 return to_utf8(relPath(path));
952 string DocFileName::outputFileName(string const & path) const
954 return save_abs_path_ ? absFileName() : relFileName(path);
958 string DocFileName::mangledFileName(string const & dir) const
960 return mangledFileName(dir, true, false);
963 string DocFileName::mangledFileName(string const & dir, bool use_counter, bool encrypt_path) const
965 // Concurrent access to these variables is possible.
967 // We need to make sure that every DocFileName instance for a given
968 // filename returns the same mangled name.
969 typedef map<string, string> MangledMap;
970 static MangledMap mangledNames;
971 static Mutex mangledMutex;
972 // this locks both access to mangledNames and counter below
973 Mutex::Locker lock(&mangledMutex);
974 MangledMap::const_iterator const it = mangledNames.find(absFileName());
975 if (it != mangledNames.end())
978 string const name = absFileName();
979 // Now the real work. Remove the extension.
980 string mname = support::changeExtension(name, string());
983 QString qname = toqstr(mname);
984 #if QT_VERSION >= 0x050000
985 QByteArray hash = QCryptographicHash::hash(qname.toLocal8Bit(),QCryptographicHash::Sha256);
987 QByteArray hash = QCryptographicHash::hash(qname.toLocal8Bit(),QCryptographicHash::Sha1);
990 mname = fromqstr(QString(hash));
991 mname = mname + "_" + onlyFileName();
994 // The mangled name must be a valid LaTeX name.
995 // The list of characters to keep is probably over-restrictive,
996 // but it is not really a problem.
997 // Apart from non-ASCII characters, at least the following characters
998 // are forbidden: '/', '.', ' ', and ':'.
999 // On windows it is not possible to create files with '<', '>' or '?'
1001 static string const keep = "abcdefghijklmnopqrstuvwxyz"
1002 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1004 string::size_type pos = 0;
1005 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
1007 // Add the extension back on
1008 mname = support::changeExtension(mname, getExtension(name));
1010 // Prepend a counter to the filename. This is necessary to make
1011 // the mangled name unique.
1012 static int counter = 0;
1016 s << counter++ << mname;
1020 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
1021 // is longer than about 160 characters. MiKTeX's pdflatex
1022 // is even pickier. A maximum length of 100 has been proven to work.
1023 // If dir.size() > max length, all bets are off for YAP. We truncate
1024 // the filename nevertheless, keeping a minimum of 10 chars.
1026 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
1028 // If the mangled file name is too long, hack it to fit.
1029 // We know we're guaranteed to have a unique file name because
1031 if (mname.size() > max_length) {
1032 int const half = (int(max_length) / 2) - 2;
1034 mname = mname.substr(0, half) + "___" +
1035 mname.substr(mname.size() - half);
1039 mangledNames[absFileName()] = mname;
1044 string DocFileName::unzippedFileName() const
1046 return support::unzippedFileName(absFileName());
1050 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1052 return static_cast<FileName const &>(lhs)
1053 == static_cast<FileName const &>(rhs)
1054 && lhs.saveAbsPath() == rhs.saveAbsPath();
1058 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1060 return !(lhs == rhs);
1063 } // namespace support