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;
73 /////////////////////////////////////////////////////////////////////
77 /////////////////////////////////////////////////////////////////////
79 struct FileName::Private
83 Private(string const & abs_filename) : fi(toqstr(handleTildeName(abs_filename)))
85 name = fromqstr(fi.absoluteFilePath());
86 fi.setCaching(fi.exists() ? true : false);
95 bool isFilesystemEqual(QString const & lhs, QString const & rhs)
97 return QString::compare(lhs, rhs, os::isFilesystemCaseSensitive() ?
98 Qt::CaseSensitive : Qt::CaseInsensitive) == 0;
102 string const handleTildeName(string const & name)
106 resname = Package::get_home_dir().absFileName();
107 else if ( prefixIs(name, "~/"))
108 resname = Package::get_home_dir().absFileName() + name.substr(1);
109 else if ( prefixIs(name, "~:s/"))
110 resname = package().system_support().absFileName() + name.substr(3);
116 /// The absolute file name in UTF-8 encoding.
122 /////////////////////////////////////////////////////////////////////
126 /////////////////////////////////////////////////////////////////////
129 FileName::FileName() : d(new Private)
134 FileName::FileName(string const & abs_filename)
135 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
137 //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
138 LATTEST(empty() || isAbsolute(d->name));
142 FileName::~FileName()
148 FileName::FileName(FileName const & rhs) : d(new Private)
150 d->name = rhs.d->name;
155 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
161 FileName & FileName::operator=(FileName const & rhs)
165 d->name = rhs.d->name;
171 bool FileName::empty() const
173 return d->name.empty();
177 bool FileName::isAbsolute(string const & name)
179 QFileInfo fi(toqstr(Private::handleTildeName(name)));
180 return fi.isAbsolute();
184 string FileName::absFileName() const
190 string FileName::realPath() const
192 return os::real_path(absFileName());
196 void FileName::set(string const & name)
198 d->fi.setFile(toqstr(Private::handleTildeName(name)));
199 d->name = fromqstr(d->fi.absoluteFilePath());
200 //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
201 LATTEST(empty() || isAbsolute(d->name));
205 void FileName::set(FileName const & rhs, string const & suffix)
207 if (!rhs.d->fi.isDir())
208 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
210 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
211 d->name = fromqstr(d->fi.absoluteFilePath());
212 //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
213 LATTEST(empty() || isAbsolute(d->name));
217 void FileName::erase()
224 bool FileName::copyTo(FileName const & name, bool keepsymlink) const
227 return copyTo(name, keepsymlink, visited);
231 bool FileName::copyTo(FileName const & name, bool keepsymlink,
232 FileName::FileNameSet & visited) const
234 LYXERR(Debug::FILES, "Copying " << name << " keep symlink: " << keepsymlink);
235 if (keepsymlink && name.isSymLink()) {
236 visited.insert(*this);
237 FileName const target(fromqstr(name.d->fi.symLinkTarget()));
238 if (visited.find(target) != visited.end()) {
239 LYXERR(Debug::FILES, "Found circular symlink: " << target);
242 return copyTo(target, true);
244 QFile::remove(name.d->fi.absoluteFilePath());
245 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
247 LYXERR0("FileName::copyTo(): Could not copy file "
248 << *this << " to " << name);
253 bool FileName::renameTo(FileName const & name) const
255 LYXERR(Debug::FILES, "Renaming " << name << " as " << *this);
256 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
258 LYXERR0("Could not rename file " << *this << " to " << name);
263 bool FileName::moveTo(FileName const & name) const
265 LYXERR(Debug::FILES, "Moving " << *this << " to " << name);
266 QFile::remove(name.d->fi.absoluteFilePath());
268 bool success = QFile::rename(d->fi.absoluteFilePath(),
269 name.d->fi.absoluteFilePath());
271 LYXERR0("Could not move file " << *this << " to " << name);
276 bool FileName::changePermission(unsigned long int mode) const
278 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
279 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
280 LYXERR0("File " << *this << ": cannot change permission to "
291 bool FileName::clonePermissions(FileName const & source)
293 QFile fin(toqstr(source.absFileName()));
294 QFile f(toqstr(absFileName()));
296 return f.setPermissions(fin.permissions());
299 string FileName::toFilesystemEncoding() const
301 // This doesn't work on Windows for non ascii file names.
302 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
303 return string(encoded.begin(), encoded.end());
307 string FileName::toSafeFilesystemEncoding(os::file_access how) const
309 // This will work on Windows for non ascii file names.
310 QString const safe_path =
311 toqstr(os::safe_internal_path(absFileName(), how));
312 QByteArray const encoded = QFile::encodeName(safe_path);
313 return string(encoded.begin(), encoded.end());
317 FileName FileName::fromFilesystemEncoding(string const & name)
319 QByteArray const encoded(name.c_str(), name.length());
320 return FileName(fromqstr(QFile::decodeName(encoded)));
324 bool FileName::exists() const
326 return !empty() && d->fi.exists();
330 bool FileName::isSymLink() const
332 return !empty() && d->fi.isSymLink();
336 //QFileInfo caching info might fool this test if file was changed meanwhile.
337 //refresh() helps, but we don't want to put it blindly here, because it might
338 //trigger slowdown on networked file systems.
339 bool FileName::isFileEmpty() const
341 LASSERT(!empty(), return true);
342 return d->fi.size() == 0;
346 bool FileName::isDirectory() const
348 return !empty() && d->fi.isDir();
352 bool FileName::isReadOnly() const
354 LASSERT(!empty(), return true);
355 return d->fi.isReadable() && !d->fi.isWritable();
359 bool FileName::isReadableDirectory() const
361 return isDirectory() && d->fi.isReadable();
365 string FileName::onlyFileName() const
367 return fromqstr(d->fi.fileName());
371 string FileName::onlyFileNameWithoutExt() const
373 return fromqstr(d->fi.completeBaseName());
377 string FileName::extension() const
379 return fromqstr(d->fi.suffix());
383 bool FileName::hasExtension(const string & ext)
385 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
389 FileName FileName::onlyPath() const
394 path.d->fi.setFile(d->fi.path());
395 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
400 FileName FileName::parentPath() const
403 // return empty path for parent of root dir
404 // parent of empty path is empty too
405 if (empty() || d->fi.isRoot())
407 path.d->fi.setFile(d->fi.path());
408 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
413 bool FileName::isReadableFile() const
415 return !empty() && d->fi.isFile() && d->fi.isReadable();
419 bool FileName::isWritable() const
421 return !empty() && d->fi.isWritable();
425 bool FileName::isDirWritable() const
427 LASSERT(isDirectory(), return false);
428 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
429 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
431 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
434 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
439 FileNameList FileName::dirList(string const & ext) const
441 FileNameList dirlist;
442 if (!isDirectory()) {
443 LYXERR0("Directory '" << *this << "' does not exist!");
447 // If the directory is specified without a trailing '/', absoluteDir()
448 // would return the parent dir, so we must use absoluteFilePath() here.
449 QDir dir = d->fi.absoluteFilePath();
454 case '.': filter = "*" + toqstr(ext); break;
455 case '*': filter = toqstr(ext); break;
456 default: filter = "*." + toqstr(ext);
458 dir.setNameFilters(QStringList(filter));
459 LYXERR(Debug::FILES, "filtering on extension "
460 << fromqstr(filter) << " is requested.");
463 QFileInfoList list = dir.entryInfoList();
464 for (int i = 0; i != list.size(); ++i) {
465 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
466 dirlist.push_back(fi);
467 LYXERR(Debug::FILES, "found file " << fi);
474 FileName FileName::getcwd()
476 // return makeAbsPath("."); would create an infinite loop
478 return FileName(fromqstr(fi.absoluteFilePath()));
482 FileName FileName::tempPath()
484 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
488 void FileName::refresh() const
494 time_t FileName::lastModified() const
496 // QFileInfo caches information about the file. So, in case this file has
497 // been touched between the object creation and now, we refresh the file
500 return d->fi.lastModified().toTime_t();
504 bool FileName::chdir() const
506 return QDir::setCurrent(d->fi.absoluteFilePath());
510 bool FileName::link(FileName const & name) const
512 return QFile::link(toqstr(absFileName()), toqstr(name.absFileName()));
516 unsigned long checksum_ifstream_fallback(char const * file)
518 unsigned long result = 0;
519 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
520 ifstream ifs(file, ios_base::in | ios_base::binary);
524 istreambuf_iterator<char> beg(ifs);
525 istreambuf_iterator<char> end;
526 boost::crc_32_type crc;
527 crc = for_each(beg, end, crc);
528 result = crc.checksum();
532 unsigned long FileName::checksum() const
534 unsigned long result = 0;
537 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
540 // a directory may be passed here so we need to test it. (bug 3622)
542 LYXERR0('"' << absFileName() << "\" is a directory!");
546 // This is used in the debug output at the end of the method.
548 if (lyxerr.debugging(Debug::FILES))
551 #if QT_VERSION >= 0x999999
552 // First version of checksum uses Qt4.4 mmap support.
553 // FIXME: This code is not ready with Qt4.4.2,
554 // see http://www.lyx.org/trac/ticket/5293
555 // FIXME: should we check if the MapExtension extension is supported?
556 // see QAbstractFileEngine::supportsExtension() and
557 // QAbstractFileEngine::MapExtension)
558 QFile qf(fi.filePath());
559 if (!qf.open(QIODevice::ReadOnly))
561 qint64 size = fi.size();
562 uchar * ubeg = qf.map(0, size);
563 uchar * uend = ubeg + size;
564 boost::crc_32_type ucrc;
565 ucrc.process_block(ubeg, uend);
568 result = ucrc.checksum();
572 string const encoded = toSafeFilesystemEncoding();
573 char const * file = encoded.c_str();
576 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
578 int fd = open(file, O_RDONLY);
583 if (fstat(fd, &info)){
584 // fstat fails on samba shares (bug 5891)
586 return checksum_ifstream_fallback(file);
589 void * mm = mmap(0, info.st_size, PROT_READ,
591 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
592 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
597 char * beg = static_cast<char*>(mm);
598 char * end = beg + info.st_size;
600 boost::crc_32_type crc;
601 crc.process_block(beg, end);
602 result = crc.checksum();
604 munmap(mm, info.st_size);
607 #else // no SUM_WITH_MMAP
608 result = checksum_ifstream_fallback(file);
609 #endif // SUM_WITH_MMAP
612 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
613 << result << " lasted " << t.elapsed() << " ms.");
618 bool FileName::removeFile() const
620 bool const success = QFile::remove(d->fi.absoluteFilePath());
622 if (!success && exists())
623 LYXERR0("Could not delete file " << *this);
628 static bool rmdir(QFileInfo const & fi)
630 QDir dir(fi.absoluteFilePath());
631 QFileInfoList list = dir.entryInfoList();
633 for (int i = 0; i != list.size(); ++i) {
634 if (list.at(i).fileName() == ".")
636 if (list.at(i).fileName() == "..")
639 if (list.at(i).isDir()) {
640 LYXERR(Debug::FILES, "Removing dir "
641 << fromqstr(list.at(i).absoluteFilePath()));
642 removed = rmdir(list.at(i));
645 LYXERR(Debug::FILES, "Removing file "
646 << fromqstr(list.at(i).absoluteFilePath()));
647 removed = dir.remove(list.at(i).fileName());
651 LYXERR0("Could not delete "
652 << fromqstr(list.at(i).absoluteFilePath()));
655 QDir parent = fi.absolutePath();
656 success &= parent.rmdir(fi.fileName());
661 bool FileName::destroyDirectory() const
663 bool const success = rmdir(d->fi);
665 LYXERR0("Could not delete " << *this);
671 // Only used in non Win32 platforms
673 static int mymkdir(char const * pathname, unsigned long int mode)
675 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
677 # if MKDIR_TAKES_ONE_ARG
679 return ::mkdir(pathname);
680 // FIXME: "Permissions of created directories are ignored on this system."
683 return ::mkdir(pathname, mode_t(mode));
685 # elif defined(_WIN32)
687 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
688 // FIXME: "Permissions of created directories are ignored on this system."
690 return ::_mkdir(pathname);
691 // FIXME: "Permissions of created directories are ignored on this system."
693 # error "Don't know how to create a directory on this system."
699 bool FileName::createDirectory(int permission) const
701 LASSERT(!empty(), return false);
703 // FIXME: "Permissions of created directories are ignored on this system."
707 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
712 bool FileName::createPath() const
714 LASSERT(!empty(), return false);
715 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
720 bool success = dir.mkpath(d->fi.absoluteFilePath());
722 LYXERR0("Cannot create path '" << *this << "'!");
727 docstring const FileName::absoluteFilePath() const
729 return qstring_to_ucs4(d->fi.absoluteFilePath());
733 docstring FileName::displayName(int threshold) const
735 return makeDisplayPath(absFileName(), threshold);
739 docstring FileName::fileContents(string const & encoding) const
741 if (!isReadableFile()) {
742 LYXERR0("File '" << *this << "' is not readable!");
746 QFile file(d->fi.absoluteFilePath());
747 if (!file.open(QIODevice::ReadOnly)) {
748 LYXERR0("File '" << *this
749 << "' could not be opened in read only mode!");
752 QByteArray contents = file.readAll();
755 if (contents.isEmpty()) {
756 LYXERR(Debug::FILES, "File '" << *this
757 << "' is either empty or some error happened while reading it.");
762 if (encoding.empty() || encoding == "UTF-8")
763 s = QString::fromUtf8(contents.data());
764 else if (encoding == "ascii")
765 #if (QT_VERSION < 0x050000)
766 s = QString::fromAscii(contents.data());
768 s = QString::fromLatin1(contents.data());
770 else if (encoding == "local8bit")
771 s = QString::fromLocal8Bit(contents.data());
772 else if (encoding == "latin1")
773 s = QString::fromLatin1(contents.data());
775 return qstring_to_ucs4(s);
779 void FileName::changeExtension(string const & extension)
781 // FIXME: use Qt native methods...
782 string const oldname = absFileName();
783 string::size_type const last_slash = oldname.rfind('/');
784 string::size_type last_dot = oldname.rfind('.');
785 if (last_dot < last_slash && last_slash != string::npos)
786 last_dot = string::npos;
789 // Make sure the extension starts with a dot
790 if (!extension.empty() && extension[0] != '.')
791 ext= '.' + extension;
795 set(oldname.substr(0, last_dot) + ext);
799 docstring const FileName::relPath(string const & path) const
802 return makeRelPath(absoluteFilePath(), from_utf8(path));
806 // Note: According to Qt, QFileInfo::operator== is undefined when
807 // both files do not exist (Qt4.5 gives true for all non-existent
808 // files, while Qt4.4 compares the filenames).
810 // http://www.qtsoftware.com/developer/task-tracker/
811 // index_html?id=248471&method=entry.
812 bool equivalent(FileName const & l, FileName const & r)
814 // FIXME: In future use Qt.
815 // Qt 4.4: We need to solve this warning from Qt documentation:
816 // * Long and short file names that refer to the same file on Windows are
817 // treated as if they referred to different files.
818 // This is supposed to be fixed for Qt5.
819 FileName const lhs(os::internal_path(l.absFileName()));
820 FileName const rhs(os::internal_path(r.absFileName()));
823 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
827 // Avoid unnecessary checks below.
833 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
834 // Qt already checks if the filesystem is case sensitive or not.
835 // see note above why the extra check with fileName is needed.
836 return lhs.d->fi == rhs.d->fi
837 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
840 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
841 QFileInfo fi1(lhs.d->fi);
843 fi1 = QFileInfo(fi1.symLinkTarget());
844 QFileInfo fi2(rhs.d->fi);
846 fi2 = QFileInfo(fi2.symLinkTarget());
847 // see note above why the extra check with fileName is needed.
848 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
852 bool operator==(FileName const & lhs, FileName const & rhs)
854 return os::isFilesystemCaseSensitive()
855 ? lhs.absFileName() == rhs.absFileName()
856 : !QString::compare(toqstr(lhs.absFileName()),
857 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
861 bool operator!=(FileName const & lhs, FileName const & rhs)
863 return !(operator==(lhs, rhs));
867 bool operator<(FileName const & lhs, FileName const & rhs)
869 return lhs.absFileName() < rhs.absFileName();
873 bool operator>(FileName const & lhs, FileName const & rhs)
875 return lhs.absFileName() > rhs.absFileName();
879 ostream & operator<<(ostream & os, FileName const & filename)
881 return os << filename.absFileName();
885 /////////////////////////////////////////////////////////////////////
889 /////////////////////////////////////////////////////////////////////
892 DocFileName::DocFileName()
893 : save_abs_path_(true)
897 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
898 : FileName(abs_filename), save_abs_path_(save_abs)
902 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
903 : FileName(abs_filename), save_abs_path_(save_abs)
907 void DocFileName::set(string const & name, string const & buffer_path)
909 save_abs_path_ = isAbsolute(name);
913 FileName::set(makeAbsPath(name, buffer_path).absFileName());
917 void DocFileName::erase()
923 string DocFileName::relFileName(string const & path) const
926 return to_utf8(relPath(path));
930 string DocFileName::outputFileName(string const & path) const
932 return save_abs_path_ ? absFileName() : relFileName(path);
936 string DocFileName::mangledFileName(string const & dir) const
938 // Concurrent access to these variables is possible.
940 // We need to make sure that every DocFileName instance for a given
941 // filename returns the same mangled name.
942 typedef map<string, string> MangledMap;
943 static MangledMap mangledNames;
944 static Mutex mangledMutex;
945 // this locks both access to mangledNames and counter below
946 Mutex::Locker lock(&mangledMutex);
947 MangledMap::const_iterator const it = mangledNames.find(absFileName());
948 if (it != mangledNames.end())
951 string const name = absFileName();
953 string mname = os::internal_path(name);
954 // Remove the extension.
955 mname = support::changeExtension(name, string());
956 // The mangled name must be a valid LaTeX name.
957 // The list of characters to keep is probably over-restrictive,
958 // but it is not really a problem.
959 // Apart from non-ASCII characters, at least the following characters
960 // are forbidden: '/', '.', ' ', and ':'.
961 // On windows it is not possible to create files with '<', '>' or '?'
963 static string const keep = "abcdefghijklmnopqrstuvwxyz"
964 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
966 string::size_type pos = 0;
967 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
969 // Add the extension back on
970 mname = support::changeExtension(mname, getExtension(name));
972 // Prepend a counter to the filename. This is necessary to make
973 // the mangled name unique.
974 static int counter = 0;
976 s << counter++ << mname;
979 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
980 // is longer than about 160 characters. MiKTeX's pdflatex
981 // is even pickier. A maximum length of 100 has been proven to work.
982 // If dir.size() > max length, all bets are off for YAP. We truncate
983 // the filename nevertheless, keeping a minimum of 10 chars.
985 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
987 // If the mangled file name is too long, hack it to fit.
988 // We know we're guaranteed to have a unique file name because
990 if (mname.size() > max_length) {
991 int const half = (int(max_length) / 2) - 2;
993 mname = mname.substr(0, half) + "___" +
994 mname.substr(mname.size() - half);
998 mangledNames[absFileName()] = mname;
1003 string DocFileName::unzippedFileName() const
1005 return support::unzippedFileName(absFileName());
1009 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1011 return static_cast<FileName const &>(lhs)
1012 == static_cast<FileName const &>(rhs)
1013 && lhs.saveAbsPath() == rhs.saveAbsPath();
1017 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1019 return !(lhs == rhs);
1022 } // namespace support