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)
104 return name == "~" ? Package::get_home_dir().absFileName() :
105 prefixIs(name, "~/") ? Package::get_home_dir().absFileName() + name.substr(1) :
109 /// The absolute file name in UTF-8 encoding.
115 /////////////////////////////////////////////////////////////////////
119 /////////////////////////////////////////////////////////////////////
122 FileName::FileName() : d(new Private)
127 FileName::FileName(string const & abs_filename)
128 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
130 //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
131 LATTEST(empty() || isAbsolute(d->name));
135 FileName::~FileName()
141 FileName::FileName(FileName const & rhs) : d(new Private)
143 d->name = rhs.d->name;
148 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
154 FileName & FileName::operator=(FileName const & rhs)
158 d->name = rhs.d->name;
164 bool FileName::empty() const
166 return d->name.empty();
170 bool FileName::isAbsolute(string const & name)
172 QFileInfo fi(toqstr(Private::handleTildeName(name)));
173 return fi.isAbsolute();
177 string FileName::absFileName() const
183 string FileName::realPath() const
185 return os::real_path(absFileName());
189 void FileName::set(string const & name)
191 d->fi.setFile(toqstr(Private::handleTildeName(name)));
192 d->name = fromqstr(d->fi.absoluteFilePath());
193 //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
194 LATTEST(empty() || isAbsolute(d->name));
198 void FileName::set(FileName const & rhs, string const & suffix)
200 if (!rhs.d->fi.isDir())
201 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
203 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
204 d->name = fromqstr(d->fi.absoluteFilePath());
205 //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
206 LATTEST(empty() || isAbsolute(d->name));
210 void FileName::erase()
217 bool FileName::copyTo(FileName const & name, bool keepsymlink) const
220 return copyTo(name, keepsymlink, visited);
224 bool FileName::copyTo(FileName const & name, bool keepsymlink,
225 FileName::FileNameSet & visited) const
227 LYXERR(Debug::FILES, "Copying " << name << " keep symlink: " << keepsymlink);
228 if (keepsymlink && name.isSymLink()) {
229 visited.insert(*this);
230 FileName const target(fromqstr(name.d->fi.symLinkTarget()));
231 if (visited.find(target) != visited.end()) {
232 LYXERR(Debug::FILES, "Found circular symlink: " << target);
235 return copyTo(target, true);
237 QFile::remove(name.d->fi.absoluteFilePath());
238 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
240 LYXERR0("FileName::copyTo(): Could not copy file "
241 << *this << " to " << name);
246 bool FileName::renameTo(FileName const & name) const
248 LYXERR(Debug::FILES, "Renaming " << name << " as " << *this);
249 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
251 LYXERR0("Could not rename file " << *this << " to " << name);
256 bool FileName::moveTo(FileName const & name) const
258 LYXERR(Debug::FILES, "Moving " << *this << " to " << name);
259 QFile::remove(name.d->fi.absoluteFilePath());
261 bool success = QFile::rename(d->fi.absoluteFilePath(),
262 name.d->fi.absoluteFilePath());
264 LYXERR0("Could not move file " << *this << " to " << name);
269 bool FileName::changePermission(unsigned long int mode) const
271 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
272 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
273 LYXERR0("File " << *this << ": cannot change permission to "
281 bool FileName::clonePermissions(FileName const & source)
283 QFile fin(toqstr(source.absFileName()));
284 QFile f(toqstr(absFileName()));
286 return f.setPermissions(fin.permissions());
289 string FileName::toFilesystemEncoding() const
291 // This doesn't work on Windows for non ascii file names.
292 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
293 return string(encoded.begin(), encoded.end());
297 string FileName::toSafeFilesystemEncoding(os::file_access how) const
299 // This will work on Windows for non ascii file names.
300 QString const safe_path =
301 toqstr(os::safe_internal_path(absFileName(), how));
302 QByteArray const encoded = QFile::encodeName(safe_path);
303 return string(encoded.begin(), encoded.end());
307 FileName FileName::fromFilesystemEncoding(string const & name)
309 QByteArray const encoded(name.c_str(), name.length());
310 return FileName(fromqstr(QFile::decodeName(encoded)));
314 bool FileName::exists() const
316 return !empty() && d->fi.exists();
320 bool FileName::isSymLink() const
322 return !empty() && d->fi.isSymLink();
326 //QFileInfo caching info might fool this test if file was changed meanwhile.
327 //refresh() helps, but we don't want to put it blindly here, because it might
328 //trigger slowdown on networked file systems.
329 bool FileName::isFileEmpty() const
331 LASSERT(!empty(), return true);
332 return d->fi.size() == 0;
336 bool FileName::isDirectory() const
338 return !empty() && d->fi.isDir();
342 bool FileName::isReadOnly() const
344 LASSERT(!empty(), return true);
345 return d->fi.isReadable() && !d->fi.isWritable();
349 bool FileName::isReadableDirectory() const
351 return isDirectory() && d->fi.isReadable();
355 string FileName::onlyFileName() const
357 return fromqstr(d->fi.fileName());
361 string FileName::onlyFileNameWithoutExt() const
363 return fromqstr(d->fi.completeBaseName());
367 string FileName::extension() const
369 return fromqstr(d->fi.suffix());
373 bool FileName::hasExtension(const string & ext)
375 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
379 FileName FileName::onlyPath() const
384 path.d->fi.setFile(d->fi.path());
385 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
390 FileName FileName::parentPath() const
393 // return empty path for parent of root dir
394 // parent of empty path is empty too
395 if (empty() || d->fi.isRoot())
397 path.d->fi.setFile(d->fi.path());
398 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
403 bool FileName::isReadableFile() const
405 return !empty() && d->fi.isFile() && d->fi.isReadable();
409 bool FileName::isWritable() const
411 return !empty() && d->fi.isWritable();
415 bool FileName::isDirWritable() const
417 LASSERT(isDirectory(), return false);
418 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
419 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
421 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
424 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
429 FileNameList FileName::dirList(string const & ext) const
431 FileNameList dirlist;
432 if (!isDirectory()) {
433 LYXERR0("Directory '" << *this << "' does not exist!");
437 // If the directory is specified without a trailing '/', absoluteDir()
438 // would return the parent dir, so we must use absoluteFilePath() here.
439 QDir dir = d->fi.absoluteFilePath();
444 case '.': filter = "*" + toqstr(ext); break;
445 case '*': filter = toqstr(ext); break;
446 default: filter = "*." + toqstr(ext);
448 dir.setNameFilters(QStringList(filter));
449 LYXERR(Debug::FILES, "filtering on extension "
450 << fromqstr(filter) << " is requested.");
453 QFileInfoList list = dir.entryInfoList();
454 for (int i = 0; i != list.size(); ++i) {
455 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
456 dirlist.push_back(fi);
457 LYXERR(Debug::FILES, "found file " << fi);
464 FileName FileName::getcwd()
466 // return makeAbsPath("."); would create an infinite loop
468 return FileName(fromqstr(fi.absoluteFilePath()));
472 FileName FileName::tempPath()
474 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
478 void FileName::refresh() const
484 time_t FileName::lastModified() const
486 // QFileInfo caches information about the file. So, in case this file has
487 // been touched between the object creation and now, we refresh the file
490 return d->fi.lastModified().toTime_t();
494 bool FileName::chdir() const
496 return QDir::setCurrent(d->fi.absoluteFilePath());
500 bool FileName::link(FileName const & name) const
502 return QFile::link(toqstr(absFileName()), toqstr(name.absFileName()));
506 unsigned long checksum_ifstream_fallback(char const * file)
508 unsigned long result = 0;
509 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
510 ifstream ifs(file, ios_base::in | ios_base::binary);
514 istreambuf_iterator<char> beg(ifs);
515 istreambuf_iterator<char> end;
516 boost::crc_32_type crc;
517 crc = for_each(beg, end, crc);
518 result = crc.checksum();
522 unsigned long FileName::checksum() const
524 unsigned long result = 0;
527 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
530 // a directory may be passed here so we need to test it. (bug 3622)
532 LYXERR0('"' << absFileName() << "\" is a directory!");
536 // This is used in the debug output at the end of the method.
538 if (lyxerr.debugging(Debug::FILES))
541 #if QT_VERSION >= 0x999999
542 // First version of checksum uses Qt4.4 mmap support.
543 // FIXME: This code is not ready with Qt4.4.2,
544 // see http://www.lyx.org/trac/ticket/5293
545 // FIXME: should we check if the MapExtension extension is supported?
546 // see QAbstractFileEngine::supportsExtension() and
547 // QAbstractFileEngine::MapExtension)
548 QFile qf(fi.filePath());
549 if (!qf.open(QIODevice::ReadOnly))
551 qint64 size = fi.size();
552 uchar * ubeg = qf.map(0, size);
553 uchar * uend = ubeg + size;
554 boost::crc_32_type ucrc;
555 ucrc.process_block(ubeg, uend);
558 result = ucrc.checksum();
562 string const encoded = toSafeFilesystemEncoding();
563 char const * file = encoded.c_str();
566 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
568 int fd = open(file, O_RDONLY);
573 if (fstat(fd, &info)){
574 // fstat fails on samba shares (bug 5891)
576 return checksum_ifstream_fallback(file);
579 void * mm = mmap(0, info.st_size, PROT_READ,
581 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
582 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
587 char * beg = static_cast<char*>(mm);
588 char * end = beg + info.st_size;
590 boost::crc_32_type crc;
591 crc.process_block(beg, end);
592 result = crc.checksum();
594 munmap(mm, info.st_size);
597 #else // no SUM_WITH_MMAP
598 result = checksum_ifstream_fallback(file);
599 #endif // SUM_WITH_MMAP
602 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
603 << result << " lasted " << t.elapsed() << " ms.");
608 bool FileName::removeFile() const
610 bool const success = QFile::remove(d->fi.absoluteFilePath());
612 if (!success && exists())
613 LYXERR0("Could not delete file " << *this);
618 static bool rmdir(QFileInfo const & fi)
620 QDir dir(fi.absoluteFilePath());
621 QFileInfoList list = dir.entryInfoList();
623 for (int i = 0; i != list.size(); ++i) {
624 if (list.at(i).fileName() == ".")
626 if (list.at(i).fileName() == "..")
629 if (list.at(i).isDir()) {
630 LYXERR(Debug::FILES, "Removing dir "
631 << fromqstr(list.at(i).absoluteFilePath()));
632 removed = rmdir(list.at(i));
635 LYXERR(Debug::FILES, "Removing file "
636 << fromqstr(list.at(i).absoluteFilePath()));
637 removed = dir.remove(list.at(i).fileName());
641 LYXERR0("Could not delete "
642 << fromqstr(list.at(i).absoluteFilePath()));
645 QDir parent = fi.absolutePath();
646 success &= parent.rmdir(fi.fileName());
651 bool FileName::destroyDirectory() const
653 bool const success = rmdir(d->fi);
655 LYXERR0("Could not delete " << *this);
661 // Only used in non Win32 platforms
662 static int mymkdir(char const * pathname, unsigned long int mode)
664 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
666 # if MKDIR_TAKES_ONE_ARG
668 return ::mkdir(pathname);
669 // FIXME: "Permissions of created directories are ignored on this system."
672 return ::mkdir(pathname, mode_t(mode));
674 #elif defined(_WIN32)
676 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
677 // FIXME: "Permissions of created directories are ignored on this system."
679 return ::_mkdir(pathname);
680 // FIXME: "Permissions of created directories are ignored on this system."
682 # error "Don't know how to create a directory on this system."
688 bool FileName::createDirectory(int permission) const
690 LASSERT(!empty(), return false);
692 // FIXME: "Permissions of created directories are ignored on this system."
695 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
700 bool FileName::createPath() const
702 LASSERT(!empty(), return false);
703 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
708 bool success = dir.mkpath(d->fi.absoluteFilePath());
710 LYXERR0("Cannot create path '" << *this << "'!");
715 docstring const FileName::absoluteFilePath() const
717 return qstring_to_ucs4(d->fi.absoluteFilePath());
721 docstring FileName::displayName(int threshold) const
723 return makeDisplayPath(absFileName(), threshold);
727 docstring FileName::fileContents(string const & encoding) const
729 if (!isReadableFile()) {
730 LYXERR0("File '" << *this << "' is not readable!");
734 QFile file(d->fi.absoluteFilePath());
735 if (!file.open(QIODevice::ReadOnly)) {
736 LYXERR0("File '" << *this
737 << "' could not be opened in read only mode!");
740 QByteArray contents = file.readAll();
743 if (contents.isEmpty()) {
744 LYXERR(Debug::FILES, "File '" << *this
745 << "' is either empty or some error happened while reading it.");
750 if (encoding.empty() || encoding == "UTF-8")
751 s = QString::fromUtf8(contents.data());
752 else if (encoding == "ascii")
753 #if (QT_VERSION < 0x050000)
754 s = QString::fromAscii(contents.data());
756 s = QString::fromLatin1(contents.data());
758 else if (encoding == "local8bit")
759 s = QString::fromLocal8Bit(contents.data());
760 else if (encoding == "latin1")
761 s = QString::fromLatin1(contents.data());
763 return qstring_to_ucs4(s);
767 void FileName::changeExtension(string const & extension)
769 // FIXME: use Qt native methods...
770 string const oldname = absFileName();
771 string::size_type const last_slash = oldname.rfind('/');
772 string::size_type last_dot = oldname.rfind('.');
773 if (last_dot < last_slash && last_slash != string::npos)
774 last_dot = string::npos;
777 // Make sure the extension starts with a dot
778 if (!extension.empty() && extension[0] != '.')
779 ext= '.' + extension;
783 set(oldname.substr(0, last_dot) + ext);
787 docstring const FileName::relPath(string const & path) const
790 return makeRelPath(absoluteFilePath(), from_utf8(path));
794 // Note: According to Qt, QFileInfo::operator== is undefined when
795 // both files do not exist (Qt4.5 gives true for all non-existent
796 // files, while Qt4.4 compares the filenames).
798 // http://www.qtsoftware.com/developer/task-tracker/
799 // index_html?id=248471&method=entry.
800 bool equivalent(FileName const & l, FileName const & r)
802 // FIXME: In future use Qt.
803 // Qt 4.4: We need to solve this warning from Qt documentation:
804 // * Long and short file names that refer to the same file on Windows are
805 // treated as if they referred to different files.
806 // This is supposed to be fixed for Qt5.
807 FileName const lhs(os::internal_path(l.absFileName()));
808 FileName const rhs(os::internal_path(r.absFileName()));
811 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
815 // Avoid unnecessary checks below.
821 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
822 // Qt already checks if the filesystem is case sensitive or not.
823 // see note above why the extra check with fileName is needed.
824 return lhs.d->fi == rhs.d->fi
825 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
828 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
829 QFileInfo fi1(lhs.d->fi);
831 fi1 = QFileInfo(fi1.symLinkTarget());
832 QFileInfo fi2(rhs.d->fi);
834 fi2 = QFileInfo(fi2.symLinkTarget());
835 // see note above why the extra check with fileName is needed.
836 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
840 bool operator==(FileName const & lhs, FileName const & rhs)
842 return os::isFilesystemCaseSensitive()
843 ? lhs.absFileName() == rhs.absFileName()
844 : !QString::compare(toqstr(lhs.absFileName()),
845 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
849 bool operator!=(FileName const & lhs, FileName const & rhs)
851 return !(operator==(lhs, rhs));
855 bool operator<(FileName const & lhs, FileName const & rhs)
857 return lhs.absFileName() < rhs.absFileName();
861 bool operator>(FileName const & lhs, FileName const & rhs)
863 return lhs.absFileName() > rhs.absFileName();
867 ostream & operator<<(ostream & os, FileName const & filename)
869 return os << filename.absFileName();
873 /////////////////////////////////////////////////////////////////////
877 /////////////////////////////////////////////////////////////////////
880 DocFileName::DocFileName()
881 : save_abs_path_(true)
885 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
886 : FileName(abs_filename), save_abs_path_(save_abs)
890 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
891 : FileName(abs_filename), save_abs_path_(save_abs)
895 void DocFileName::set(string const & name, string const & buffer_path)
897 save_abs_path_ = isAbsolute(name);
901 FileName::set(makeAbsPath(name, buffer_path).absFileName());
905 void DocFileName::erase()
911 string DocFileName::relFileName(string const & path) const
914 return to_utf8(relPath(path));
918 string DocFileName::outputFileName(string const & path) const
920 return save_abs_path_ ? absFileName() : relFileName(path);
924 string DocFileName::mangledFileName(string const & dir) const
926 // Concurrent access to these variables is possible.
928 // We need to make sure that every DocFileName instance for a given
929 // filename returns the same mangled name.
930 typedef map<string, string> MangledMap;
931 static MangledMap mangledNames;
932 static Mutex mangledMutex;
933 // this locks both access to mangledNames and counter below
934 Mutex::Locker lock(&mangledMutex);
935 MangledMap::const_iterator const it = mangledNames.find(absFileName());
936 if (it != mangledNames.end())
939 string const name = absFileName();
941 string mname = os::internal_path(name);
942 // Remove the extension.
943 mname = support::changeExtension(name, string());
944 // The mangled name must be a valid LaTeX name.
945 // The list of characters to keep is probably over-restrictive,
946 // but it is not really a problem.
947 // Apart from non-ASCII characters, at least the following characters
948 // are forbidden: '/', '.', ' ', and ':'.
949 // On windows it is not possible to create files with '<', '>' or '?'
951 static string const keep = "abcdefghijklmnopqrstuvwxyz"
952 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
954 string::size_type pos = 0;
955 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
957 // Add the extension back on
958 mname = support::changeExtension(mname, getExtension(name));
960 // Prepend a counter to the filename. This is necessary to make
961 // the mangled name unique.
962 static int counter = 0;
964 s << counter++ << mname;
967 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
968 // is longer than about 160 characters. MiKTeX's pdflatex
969 // is even pickier. A maximum length of 100 has been proven to work.
970 // If dir.size() > max length, all bets are off for YAP. We truncate
971 // the filename nevertheless, keeping a minimum of 10 chars.
973 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
975 // If the mangled file name is too long, hack it to fit.
976 // We know we're guaranteed to have a unique file name because
978 if (mname.size() > max_length) {
979 int const half = (int(max_length) / 2) - 2;
981 mname = mname.substr(0, half) + "___" +
982 mname.substr(mname.size() - half);
986 mangledNames[absFileName()] = mname;
991 string DocFileName::unzippedFileName() const
993 return support::unzippedFileName(absFileName());
997 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
999 return static_cast<FileName const &>(lhs)
1000 == static_cast<FileName const &>(rhs)
1001 && lhs.saveAbsPath() == rhs.saveAbsPath();
1005 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1007 return !(lhs == rhs);
1010 } // namespace support