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>
37 #include <boost/crc.hpp>
46 #ifdef HAVE_SYS_TYPES_H
47 # include <sys/types.h>
49 #ifdef HAVE_SYS_STAT_H
50 # include <sys/stat.h>
65 // Three implementations of checksum(), depending on having mmap support or not.
66 #if defined(HAVE_MMAP) && defined(HAVE_MUNMAP)
69 #endif // SUM_WITH_MMAP
72 using namespace lyx::support;
77 /////////////////////////////////////////////////////////////////////
81 /////////////////////////////////////////////////////////////////////
83 struct FileName::Private
87 Private(string const & abs_filename) : fi(toqstr(handleTildeName(abs_filename)))
89 name = fromqstr(fi.absoluteFilePath());
90 fi.setCaching(fi.exists() ? true : false);
99 bool isFilesystemEqual(QString const & lhs, QString const & rhs)
101 return QString::compare(lhs, rhs, os::isFilesystemCaseSensitive() ?
102 Qt::CaseSensitive : Qt::CaseInsensitive) == 0;
106 string const handleTildeName(string const & name)
110 resname = Package::get_home_dir().absFileName();
111 else if ( prefixIs(name, "~/"))
112 resname = Package::get_home_dir().absFileName() + name.substr(1);
113 else if ( prefixIs(name, "~:s/"))
114 resname = package().system_support().absFileName() + name.substr(3);
120 /// The absolute file name in UTF-8 encoding.
126 /////////////////////////////////////////////////////////////////////
130 /////////////////////////////////////////////////////////////////////
133 FileName::FileName() : d(new Private)
138 FileName::FileName(string const & abs_filename)
139 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
141 //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
142 LATTEST(empty() || isAbsolute(d->name));
146 FileName::~FileName()
152 FileName::FileName(FileName const & rhs) : d(new Private)
154 d->name = rhs.d->name;
159 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
165 FileName & FileName::operator=(FileName const & rhs)
169 d->name = rhs.d->name;
175 bool FileName::empty() const
177 return d->name.empty();
181 bool FileName::isAbsolute(string const & name)
183 QFileInfo fi(toqstr(Private::handleTildeName(name)));
184 return fi.isAbsolute();
188 string FileName::absFileName() const
194 string FileName::realPath() const
196 return os::real_path(absFileName());
200 void FileName::set(string const & name)
202 d->fi.setFile(toqstr(Private::handleTildeName(name)));
203 d->name = fromqstr(d->fi.absoluteFilePath());
204 //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
205 LATTEST(empty() || isAbsolute(d->name));
209 void FileName::set(FileName const & rhs, string const & suffix)
211 if (!rhs.d->fi.isDir())
212 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
214 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
215 d->name = fromqstr(d->fi.absoluteFilePath());
216 //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
217 LATTEST(empty() || isAbsolute(d->name));
221 void FileName::erase()
228 bool FileName::copyTo(FileName const & name, bool keepsymlink) const
231 return copyTo(name, keepsymlink, visited);
235 bool FileName::copyTo(FileName const & name, bool keepsymlink,
236 FileName::FileNameSet & visited) const
238 LYXERR(Debug::FILES, "Copying " << name << " keep symlink: " << keepsymlink);
239 if (keepsymlink && name.isSymLink()) {
240 visited.insert(*this);
241 FileName const target(fromqstr(name.d->fi.symLinkTarget()));
242 if (visited.find(target) != visited.end()) {
243 LYXERR(Debug::FILES, "Found circular symlink: " << target);
246 return copyTo(target, true);
248 QFile::remove(name.d->fi.absoluteFilePath());
249 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
251 LYXERR0("FileName::copyTo(): Could not copy file "
252 << *this << " to " << name);
257 bool FileName::renameTo(FileName const & name) const
259 LYXERR(Debug::FILES, "Renaming " << name << " as " << *this);
260 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
262 LYXERR0("Could not rename file " << *this << " to " << name);
267 bool FileName::moveTo(FileName const & name) const
269 LYXERR(Debug::FILES, "Moving " << *this << " to " << name);
271 // there's a locking problem on Windows sometimes, so
272 // we will keep trying for five seconds, in the hope
274 bool removed = QFile::remove(name.d->fi.absoluteFilePath());
276 while (!removed && tries < 6) {
278 removed = QFile::remove(name.d->fi.absoluteFilePath());
282 QFile::remove(name.d->fi.absoluteFilePath());
285 bool const success = QFile::rename(d->fi.absoluteFilePath(),
286 name.d->fi.absoluteFilePath());
288 LYXERR0("Could not move file " << *this << " to " << name);
293 bool FileName::changePermission(unsigned long int mode) const
295 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
296 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
297 LYXERR0("File " << *this << ": cannot change permission to "
308 bool FileName::clonePermissions(FileName const & source)
310 QFile fin(toqstr(source.absFileName()));
311 QFile f(toqstr(absFileName()));
313 return f.setPermissions(fin.permissions());
316 string FileName::toFilesystemEncoding() const
318 // This doesn't work on Windows for non ascii file names.
319 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
320 return string(encoded.begin(), encoded.end());
324 string FileName::toSafeFilesystemEncoding(os::file_access how) const
326 // This will work on Windows for non ascii file names.
327 QString const safe_path =
328 toqstr(os::safe_internal_path(absFileName(), how));
329 QByteArray const encoded = QFile::encodeName(safe_path);
330 return string(encoded.begin(), encoded.end());
334 FileName FileName::fromFilesystemEncoding(string const & name)
336 QByteArray const encoded(name.c_str(), name.length());
337 return FileName(fromqstr(QFile::decodeName(encoded)));
341 bool FileName::exists() const
343 return !empty() && d->fi.exists();
347 bool FileName::isSymLink() const
349 return !empty() && d->fi.isSymLink();
353 //QFileInfo caching info might fool this test if file was changed meanwhile.
354 //refresh() helps, but we don't want to put it blindly here, because it might
355 //trigger slowdown on networked file systems.
356 bool FileName::isFileEmpty() const
358 LASSERT(!empty(), return true);
359 return d->fi.size() == 0;
363 bool FileName::isDirectory() const
365 return !empty() && d->fi.isDir();
369 bool FileName::isReadOnly() const
371 LASSERT(!empty(), return true);
372 return d->fi.isReadable() && !d->fi.isWritable();
376 bool FileName::isReadableDirectory() const
378 return isDirectory() && d->fi.isReadable();
382 string FileName::onlyFileName() const
384 return fromqstr(d->fi.fileName());
388 string FileName::onlyFileNameWithoutExt() const
390 return fromqstr(d->fi.completeBaseName());
394 string FileName::extension() const
396 return fromqstr(d->fi.suffix());
400 bool FileName::hasExtension(const string & ext)
402 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
406 FileName FileName::onlyPath() const
411 path.d->fi.setFile(d->fi.path());
412 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
417 FileName FileName::parentPath() const
420 // return empty path for parent of root dir
421 // parent of empty path is empty too
422 if (empty() || d->fi.isRoot())
424 path.d->fi.setFile(d->fi.path());
425 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
430 bool FileName::isReadableFile() const
432 return !empty() && d->fi.isFile() && d->fi.isReadable();
436 bool FileName::isWritable() const
438 return !empty() && d->fi.isWritable();
442 bool FileName::isDirWritable() const
444 LASSERT(isDirectory(), return false);
445 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
446 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
448 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
451 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
456 FileNameList FileName::dirList(string const & ext) const
458 FileNameList dirlist;
459 if (!isDirectory()) {
460 LYXERR0("Directory '" << *this << "' does not exist!");
464 // If the directory is specified without a trailing '/', absoluteDir()
465 // would return the parent dir, so we must use absoluteFilePath() here.
466 QDir dir = d->fi.absoluteFilePath();
471 case '.': filter = "*" + toqstr(ext); break;
472 case '*': filter = toqstr(ext); break;
473 default: filter = "*." + toqstr(ext);
475 dir.setNameFilters(QStringList(filter));
476 LYXERR(Debug::FILES, "filtering on extension "
477 << fromqstr(filter) << " is requested.");
480 QFileInfoList list = dir.entryInfoList();
481 for (int i = 0; i != list.size(); ++i) {
482 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
483 dirlist.push_back(fi);
484 LYXERR(Debug::FILES, "found file " << fi);
491 FileName FileName::getcwd()
493 // return makeAbsPath("."); would create an infinite loop
495 return FileName(fromqstr(fi.absoluteFilePath()));
499 FileName FileName::tempPath()
501 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
505 void FileName::refresh() const
511 time_t FileName::lastModified() const
513 // QFileInfo caches information about the file. So, in case this file has
514 // been touched between the object creation and now, we refresh the file
517 return d->fi.lastModified().toTime_t();
521 bool FileName::chdir() const
523 return QDir::setCurrent(d->fi.absoluteFilePath());
527 bool FileName::link(FileName const & name) const
529 return QFile::link(toqstr(absFileName()), toqstr(name.absFileName()));
533 unsigned long checksum_ifstream_fallback(char const * file)
535 unsigned long result = 0;
536 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
537 ifstream ifs(file, ios_base::in | ios_base::binary);
541 istreambuf_iterator<char> beg(ifs);
542 istreambuf_iterator<char> end;
543 boost::crc_32_type crc;
544 crc = for_each(beg, end, crc);
545 result = crc.checksum();
549 unsigned long FileName::checksum() const
551 unsigned long result = 0;
554 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
557 // a directory may be passed here so we need to test it. (bug 3622)
559 LYXERR0('"' << absFileName() << "\" is a directory!");
563 // This is used in the debug output at the end of the method.
565 if (lyxerr.debugging(Debug::FILES))
568 #if QT_VERSION >= 0x999999
569 // First version of checksum uses Qt4.4 mmap support.
570 // FIXME: This code is not ready with Qt4.4.2,
571 // see http://www.lyx.org/trac/ticket/5293
572 // FIXME: should we check if the MapExtension extension is supported?
573 // see QAbstractFileEngine::supportsExtension() and
574 // QAbstractFileEngine::MapExtension)
575 QFile qf(fi.filePath());
576 if (!qf.open(QIODevice::ReadOnly))
578 qint64 size = fi.size();
579 uchar * ubeg = qf.map(0, size);
580 uchar * uend = ubeg + size;
581 boost::crc_32_type ucrc;
582 ucrc.process_block(ubeg, uend);
585 result = ucrc.checksum();
589 string const encoded = toSafeFilesystemEncoding();
590 char const * file = encoded.c_str();
593 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
595 int fd = open(file, O_RDONLY);
600 if (fstat(fd, &info)){
601 // fstat fails on samba shares (bug 5891)
603 return checksum_ifstream_fallback(file);
606 void * mm = mmap(0, info.st_size, PROT_READ,
608 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
609 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
614 char * beg = static_cast<char*>(mm);
615 char * end = beg + info.st_size;
617 boost::crc_32_type crc;
618 crc.process_block(beg, end);
619 result = crc.checksum();
621 munmap(mm, info.st_size);
624 #else // no SUM_WITH_MMAP
625 result = checksum_ifstream_fallback(file);
626 #endif // SUM_WITH_MMAP
629 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
630 << result << " lasted " << t.elapsed() << " ms.");
635 bool FileName::removeFile() const
637 bool const success = QFile::remove(d->fi.absoluteFilePath());
639 if (!success && exists())
640 LYXERR0("Could not delete file " << *this);
645 static bool rmdir(QFileInfo const & fi)
647 QDir dir(fi.absoluteFilePath());
648 QFileInfoList list = dir.entryInfoList();
650 for (int i = 0; i != list.size(); ++i) {
651 if (list.at(i).fileName() == ".")
653 if (list.at(i).fileName() == "..")
656 if (list.at(i).isDir()) {
657 LYXERR(Debug::FILES, "Removing dir "
658 << fromqstr(list.at(i).absoluteFilePath()));
659 removed = rmdir(list.at(i));
662 LYXERR(Debug::FILES, "Removing file "
663 << fromqstr(list.at(i).absoluteFilePath()));
664 removed = dir.remove(list.at(i).fileName());
668 LYXERR0("Could not delete "
669 << fromqstr(list.at(i).absoluteFilePath()));
672 QDir parent = fi.absolutePath();
673 success &= parent.rmdir(fi.fileName());
678 bool FileName::destroyDirectory() const
680 bool const success = rmdir(d->fi);
682 LYXERR0("Could not delete " << *this);
688 // Only used in non Win32 platforms
690 static int mymkdir(char const * pathname, unsigned long int mode)
692 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
694 # if MKDIR_TAKES_ONE_ARG
696 return ::mkdir(pathname);
697 // FIXME: "Permissions of created directories are ignored on this system."
700 return ::mkdir(pathname, mode_t(mode));
702 # elif defined(_WIN32)
704 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
705 // FIXME: "Permissions of created directories are ignored on this system."
707 return ::_mkdir(pathname);
708 // FIXME: "Permissions of created directories are ignored on this system."
710 # error "Don't know how to create a directory on this system."
716 bool FileName::createDirectory(int permission) const
718 LASSERT(!empty(), return false);
720 // FIXME: "Permissions of created directories are ignored on this system."
724 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
729 bool FileName::createPath() const
731 LASSERT(!empty(), return false);
732 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
737 bool success = dir.mkpath(d->fi.absoluteFilePath());
739 LYXERR0("Cannot create path '" << *this << "'!");
744 docstring const FileName::absoluteFilePath() const
746 return qstring_to_ucs4(d->fi.absoluteFilePath());
750 docstring FileName::displayName(int threshold) const
752 return makeDisplayPath(absFileName(), threshold);
756 docstring FileName::fileContents(string const & encoding) const
758 if (!isReadableFile()) {
759 LYXERR0("File '" << *this << "' is not readable!");
763 QFile file(d->fi.absoluteFilePath());
764 if (!file.open(QIODevice::ReadOnly)) {
765 LYXERR0("File '" << *this
766 << "' could not be opened in read only mode!");
769 QByteArray contents = file.readAll();
772 if (contents.isEmpty()) {
773 LYXERR(Debug::FILES, "File '" << *this
774 << "' is either empty or some error happened while reading it.");
779 if (encoding.empty() || encoding == "UTF-8")
780 s = QString::fromUtf8(contents.data());
781 else if (encoding == "ascii")
782 #if (QT_VERSION < 0x050000)
783 s = QString::fromAscii(contents.data());
785 s = QString::fromLatin1(contents.data());
787 else if (encoding == "local8bit")
788 s = QString::fromLocal8Bit(contents.data());
789 else if (encoding == "latin1")
790 s = QString::fromLatin1(contents.data());
792 return qstring_to_ucs4(s);
796 void FileName::changeExtension(string const & extension)
798 // FIXME: use Qt native methods...
799 string const oldname = absFileName();
800 string::size_type const last_slash = oldname.rfind('/');
801 string::size_type last_dot = oldname.rfind('.');
802 if (last_dot < last_slash && last_slash != string::npos)
803 last_dot = string::npos;
806 // Make sure the extension starts with a dot
807 if (!extension.empty() && extension[0] != '.')
808 ext= '.' + extension;
812 set(oldname.substr(0, last_dot) + ext);
816 docstring const FileName::relPath(string const & path) const
819 return makeRelPath(absoluteFilePath(), from_utf8(path));
823 // Note: According to Qt, QFileInfo::operator== is undefined when
824 // both files do not exist (Qt4.5 gives true for all non-existent
825 // files, while Qt4.4 compares the filenames).
827 // http://www.qtsoftware.com/developer/task-tracker/
828 // index_html?id=248471&method=entry.
829 bool equivalent(FileName const & l, FileName const & r)
831 // FIXME: In future use Qt.
832 // Qt 4.4: We need to solve this warning from Qt documentation:
833 // * Long and short file names that refer to the same file on Windows are
834 // treated as if they referred to different files.
835 // This is supposed to be fixed for Qt5.
836 FileName const lhs(os::internal_path(l.absFileName()));
837 FileName const rhs(os::internal_path(r.absFileName()));
840 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
844 // Avoid unnecessary checks below.
850 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
851 // Qt already checks if the filesystem is case sensitive or not.
852 // see note above why the extra check with fileName is needed.
853 return lhs.d->fi == rhs.d->fi
854 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
857 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
858 QFileInfo fi1(lhs.d->fi);
860 fi1 = QFileInfo(fi1.symLinkTarget());
861 QFileInfo fi2(rhs.d->fi);
863 fi2 = QFileInfo(fi2.symLinkTarget());
864 // see note above why the extra check with fileName is needed.
865 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
869 bool operator==(FileName const & lhs, FileName const & rhs)
871 return os::isFilesystemCaseSensitive()
872 ? lhs.absFileName() == rhs.absFileName()
873 : !QString::compare(toqstr(lhs.absFileName()),
874 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
878 bool operator!=(FileName const & lhs, FileName const & rhs)
880 return !(operator==(lhs, rhs));
884 bool operator<(FileName const & lhs, FileName const & rhs)
886 return lhs.absFileName() < rhs.absFileName();
890 bool operator>(FileName const & lhs, FileName const & rhs)
892 return lhs.absFileName() > rhs.absFileName();
896 ostream & operator<<(ostream & os, FileName const & filename)
898 return os << filename.absFileName();
902 /////////////////////////////////////////////////////////////////////
906 /////////////////////////////////////////////////////////////////////
909 DocFileName::DocFileName()
910 : save_abs_path_(true)
914 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
915 : FileName(abs_filename), save_abs_path_(save_abs)
919 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
920 : FileName(abs_filename), save_abs_path_(save_abs)
924 void DocFileName::set(string const & name, string const & buffer_path)
926 save_abs_path_ = isAbsolute(name);
930 FileName::set(makeAbsPath(name, buffer_path).absFileName());
934 void DocFileName::erase()
940 string DocFileName::relFileName(string const & path) const
943 return to_utf8(relPath(path));
947 string DocFileName::outputFileName(string const & path) const
949 return save_abs_path_ ? absFileName() : relFileName(path);
953 string DocFileName::mangledFileName(string const & dir) const
955 // Concurrent access to these variables is possible.
957 // We need to make sure that every DocFileName instance for a given
958 // filename returns the same mangled name.
959 typedef map<string, string> MangledMap;
960 static MangledMap mangledNames;
961 static Mutex mangledMutex;
962 // this locks both access to mangledNames and counter below
963 Mutex::Locker lock(&mangledMutex);
964 MangledMap::const_iterator const it = mangledNames.find(absFileName());
965 if (it != mangledNames.end())
968 string const name = absFileName();
970 string mname = os::internal_path(name);
971 // Remove the extension.
972 mname = support::changeExtension(name, string());
973 // The mangled name must be a valid LaTeX name.
974 // The list of characters to keep is probably over-restrictive,
975 // but it is not really a problem.
976 // Apart from non-ASCII characters, at least the following characters
977 // are forbidden: '/', '.', ' ', and ':'.
978 // On windows it is not possible to create files with '<', '>' or '?'
980 static string const keep = "abcdefghijklmnopqrstuvwxyz"
981 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
983 string::size_type pos = 0;
984 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
986 // Add the extension back on
987 mname = support::changeExtension(mname, getExtension(name));
989 // Prepend a counter to the filename. This is necessary to make
990 // the mangled name unique.
991 static int counter = 0;
993 s << counter++ << mname;
996 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
997 // is longer than about 160 characters. MiKTeX's pdflatex
998 // is even pickier. A maximum length of 100 has been proven to work.
999 // If dir.size() > max length, all bets are off for YAP. We truncate
1000 // the filename nevertheless, keeping a minimum of 10 chars.
1002 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
1004 // If the mangled file name is too long, hack it to fit.
1005 // We know we're guaranteed to have a unique file name because
1007 if (mname.size() > max_length) {
1008 int const half = (int(max_length) / 2) - 2;
1010 mname = mname.substr(0, half) + "___" +
1011 mname.substr(mname.size() - half);
1015 mangledNames[absFileName()] = mname;
1020 string DocFileName::unzippedFileName() const
1022 return support::unzippedFileName(absFileName());
1026 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1028 return static_cast<FileName const &>(lhs)
1029 == static_cast<FileName const &>(rhs)
1030 && lhs.saveAbsPath() == rhs.saveAbsPath();
1034 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1036 return !(lhs == rhs);
1039 } // namespace support