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;
70 // OK, this is ugly, but it is the only workaround I found to compile
71 // with gcc (any version) on a system which uses a non-GNU toolchain.
72 // The problem is that gcc uses a weak symbol for a particular
73 // instantiation and that the system linker usually does not
74 // understand those weak symbols (seen on HP-UX, tru64, AIX and
75 // others). Thus we force an explicit instanciation of this particular
77 template struct boost::detail::crc_table_t<32, 0x04C11DB7, true>;
82 /////////////////////////////////////////////////////////////////////
86 /////////////////////////////////////////////////////////////////////
88 struct FileName::Private
92 Private(string const & abs_filename) : fi(toqstr(handleTildeName(abs_filename)))
94 name = fromqstr(fi.absoluteFilePath());
95 fi.setCaching(fi.exists() ? true : false);
104 bool isFilesystemEqual(QString const & lhs, QString const & rhs)
106 return QString::compare(lhs, rhs, os::isFilesystemCaseSensitive() ?
107 Qt::CaseSensitive : Qt::CaseInsensitive) == 0;
111 string const handleTildeName(string const & name)
113 return name == "~" ? Package::get_home_dir().absFileName() :
114 prefixIs(name, "~/") ? Package::get_home_dir().absFileName() + name.substr(1) :
118 /// The absolute file name in UTF-8 encoding.
124 /////////////////////////////////////////////////////////////////////
128 /////////////////////////////////////////////////////////////////////
131 FileName::FileName() : d(new Private)
136 FileName::FileName(string const & abs_filename)
137 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
139 //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
140 LATTEST(empty() || isAbsolute(d->name));
144 FileName::~FileName()
150 FileName::FileName(FileName const & rhs) : d(new Private)
152 d->name = rhs.d->name;
157 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
163 FileName & FileName::operator=(FileName const & rhs)
167 d->name = rhs.d->name;
173 bool FileName::empty() const
175 return d->name.empty();
179 bool FileName::isAbsolute(string const & name)
181 QFileInfo fi(toqstr(Private::handleTildeName(name)));
182 return fi.isAbsolute();
186 string FileName::absFileName() const
192 string FileName::realPath() const
194 return os::real_path(absFileName());
198 void FileName::set(string const & name)
200 d->fi.setFile(toqstr(Private::handleTildeName(name)));
201 d->name = fromqstr(d->fi.absoluteFilePath());
202 //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
203 LATTEST(empty() || isAbsolute(d->name));
207 void FileName::set(FileName const & rhs, string const & suffix)
209 if (!rhs.d->fi.isDir())
210 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
212 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
213 d->name = fromqstr(d->fi.absoluteFilePath());
214 //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
215 LATTEST(empty() || isAbsolute(d->name));
219 void FileName::erase()
226 bool FileName::copyTo(FileName const & name, bool keepsymlink) const
229 return copyTo(name, keepsymlink, visited);
233 bool FileName::copyTo(FileName const & name, bool keepsymlink,
234 FileName::FileNameSet & visited) const
236 LYXERR(Debug::FILES, "Copying " << name << " keep symlink: " << keepsymlink);
237 if (keepsymlink && name.isSymLink()) {
238 visited.insert(*this);
239 FileName const target(fromqstr(name.d->fi.symLinkTarget()));
240 if (visited.find(target) != visited.end()) {
241 LYXERR(Debug::FILES, "Found circular symlink: " << target);
244 return copyTo(target, true);
246 QFile::remove(name.d->fi.absoluteFilePath());
247 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
249 LYXERR0("FileName::copyTo(): Could not copy file "
250 << *this << " to " << name);
255 bool FileName::renameTo(FileName const & name) const
257 LYXERR(Debug::FILES, "Renaming " << name << " as " << *this);
258 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
260 LYXERR0("Could not rename file " << *this << " to " << name);
265 bool FileName::moveTo(FileName const & name) const
267 LYXERR(Debug::FILES, "Moving " << *this << " to " << name);
268 QFile::remove(name.d->fi.absoluteFilePath());
270 bool success = QFile::rename(d->fi.absoluteFilePath(),
271 name.d->fi.absoluteFilePath());
273 LYXERR0("Could not move file " << *this << " to " << name);
278 bool FileName::changePermission(unsigned long int mode) const
280 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
281 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
282 LYXERR0("File " << *this << ": cannot change permission to "
294 string FileName::toFilesystemEncoding() const
296 // This doesn't work on Windows for non ascii file names.
297 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
298 return string(encoded.begin(), encoded.end());
302 string FileName::toSafeFilesystemEncoding(os::file_access how) const
304 // This will work on Windows for non ascii file names.
305 QString const safe_path =
306 toqstr(os::safe_internal_path(absFileName(), how));
307 QByteArray const encoded = QFile::encodeName(safe_path);
308 return string(encoded.begin(), encoded.end());
312 FileName FileName::fromFilesystemEncoding(string const & name)
314 QByteArray const encoded(name.c_str(), name.length());
315 return FileName(fromqstr(QFile::decodeName(encoded)));
319 bool FileName::exists() const
321 return !empty() && d->fi.exists();
325 bool FileName::isSymLink() const
327 return !empty() && d->fi.isSymLink();
331 //QFileInfo caching info might fool this test if file was changed meanwhile.
332 //refresh() helps, but we don't want to put it blindly here, because it might
333 //trigger slowdown on networked file systems.
334 bool FileName::isFileEmpty() const
336 LASSERT(!empty(), return true);
337 return d->fi.size() == 0;
341 bool FileName::isDirectory() const
343 return !empty() && d->fi.isDir();
347 bool FileName::isReadOnly() const
349 LASSERT(!empty(), return true);
350 return d->fi.isReadable() && !d->fi.isWritable();
354 bool FileName::isReadableDirectory() const
356 return isDirectory() && d->fi.isReadable();
360 string FileName::onlyFileName() const
362 return fromqstr(d->fi.fileName());
366 string FileName::onlyFileNameWithoutExt() const
368 return fromqstr(d->fi.completeBaseName());
372 string FileName::extension() const
374 return fromqstr(d->fi.suffix());
378 bool FileName::hasExtension(const string & ext)
380 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
384 FileName FileName::onlyPath() const
389 path.d->fi.setFile(d->fi.path());
390 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
395 FileName FileName::parentPath() const
398 // return empty path for parent of root dir
399 // parent of empty path is empty too
400 if (empty() || d->fi.isRoot())
402 path.d->fi.setFile(d->fi.path());
403 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
408 bool FileName::isReadableFile() const
410 return !empty() && d->fi.isFile() && d->fi.isReadable();
414 bool FileName::isWritable() const
416 return !empty() && d->fi.isWritable();
420 bool FileName::isDirWritable() const
422 LASSERT(isDirectory(), return false);
423 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
424 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
426 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
429 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
434 FileNameList FileName::dirList(string const & ext) const
436 FileNameList dirlist;
437 if (!isDirectory()) {
438 LYXERR0("Directory '" << *this << "' does not exist!");
442 // If the directory is specified without a trailing '/', absoluteDir()
443 // would return the parent dir, so we must use absoluteFilePath() here.
444 QDir dir = d->fi.absoluteFilePath();
449 case '.': filter = "*" + toqstr(ext); break;
450 case '*': filter = toqstr(ext); break;
451 default: filter = "*." + toqstr(ext);
453 dir.setNameFilters(QStringList(filter));
454 LYXERR(Debug::FILES, "filtering on extension "
455 << fromqstr(filter) << " is requested.");
458 QFileInfoList list = dir.entryInfoList();
459 for (int i = 0; i != list.size(); ++i) {
460 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
461 dirlist.push_back(fi);
462 LYXERR(Debug::FILES, "found file " << fi);
469 FileName FileName::getcwd()
471 // return makeAbsPath("."); would create an infinite loop
473 return FileName(fromqstr(fi.absoluteFilePath()));
477 FileName FileName::tempPath()
479 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
483 void FileName::refresh() const
489 time_t FileName::lastModified() const
491 // QFileInfo caches information about the file. So, in case this file has
492 // been touched between the object creation and now, we refresh the file
495 return d->fi.lastModified().toTime_t();
499 bool FileName::chdir() const
501 return QDir::setCurrent(d->fi.absoluteFilePath());
505 bool FileName::link(FileName const & name) const
507 return QFile::link(toqstr(absFileName()), toqstr(name.absFileName()));
511 unsigned long checksum_ifstream_fallback(char const * file)
513 unsigned long result = 0;
514 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
515 ifstream ifs(file, ios_base::in | ios_base::binary);
519 istreambuf_iterator<char> beg(ifs);
520 istreambuf_iterator<char> end;
521 boost::crc_32_type crc;
522 crc = for_each(beg, end, crc);
523 result = crc.checksum();
527 unsigned long FileName::checksum() const
529 unsigned long result = 0;
532 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
535 // a directory may be passed here so we need to test it. (bug 3622)
537 LYXERR0('"' << absFileName() << "\" is a directory!");
541 // This is used in the debug output at the end of the method.
543 if (lyxerr.debugging(Debug::FILES))
546 #if QT_VERSION >= 0x999999
547 // First version of checksum uses Qt4.4 mmap support.
548 // FIXME: This code is not ready with Qt4.4.2,
549 // see http://www.lyx.org/trac/ticket/5293
550 // FIXME: should we check if the MapExtension extension is supported?
551 // see QAbstractFileEngine::supportsExtension() and
552 // QAbstractFileEngine::MapExtension)
553 QFile qf(fi.filePath());
554 if (!qf.open(QIODevice::ReadOnly))
556 qint64 size = fi.size();
557 uchar * ubeg = qf.map(0, size);
558 uchar * uend = ubeg + size;
559 boost::crc_32_type ucrc;
560 ucrc.process_block(ubeg, uend);
563 result = ucrc.checksum();
567 string const encoded = toSafeFilesystemEncoding();
568 char const * file = encoded.c_str();
571 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
573 int fd = open(file, O_RDONLY);
578 if (fstat(fd, &info)){
579 // fstat fails on samba shares (bug 5891)
581 return checksum_ifstream_fallback(file);
584 void * mm = mmap(0, info.st_size, PROT_READ,
586 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
587 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
592 char * beg = static_cast<char*>(mm);
593 char * end = beg + info.st_size;
595 boost::crc_32_type crc;
596 crc.process_block(beg, end);
597 result = crc.checksum();
599 munmap(mm, info.st_size);
602 #else // no SUM_WITH_MMAP
603 result = checksum_ifstream_fallback(file);
604 #endif // SUM_WITH_MMAP
607 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
608 << result << " lasted " << t.elapsed() << " ms.");
613 bool FileName::removeFile() const
615 bool const success = QFile::remove(d->fi.absoluteFilePath());
617 if (!success && exists())
618 LYXERR0("Could not delete file " << *this);
623 static bool rmdir(QFileInfo const & fi)
625 QDir dir(fi.absoluteFilePath());
626 QFileInfoList list = dir.entryInfoList();
628 for (int i = 0; i != list.size(); ++i) {
629 if (list.at(i).fileName() == ".")
631 if (list.at(i).fileName() == "..")
634 if (list.at(i).isDir()) {
635 LYXERR(Debug::FILES, "Removing dir "
636 << fromqstr(list.at(i).absoluteFilePath()));
637 removed = rmdir(list.at(i));
640 LYXERR(Debug::FILES, "Removing file "
641 << fromqstr(list.at(i).absoluteFilePath()));
642 removed = dir.remove(list.at(i).fileName());
646 LYXERR0("Could not delete "
647 << fromqstr(list.at(i).absoluteFilePath()));
650 QDir parent = fi.absolutePath();
651 success &= parent.rmdir(fi.fileName());
656 bool FileName::destroyDirectory() const
658 bool const success = rmdir(d->fi);
660 LYXERR0("Could not delete " << *this);
666 // Only used in non Win32 platforms
667 static int mymkdir(char const * pathname, unsigned long int mode)
669 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
671 # if MKDIR_TAKES_ONE_ARG
673 return ::mkdir(pathname);
674 // FIXME: "Permissions of created directories are ignored on this system."
677 return ::mkdir(pathname, mode_t(mode));
679 #elif defined(_WIN32)
681 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
682 // FIXME: "Permissions of created directories are ignored on this system."
684 return ::_mkdir(pathname);
685 // FIXME: "Permissions of created directories are ignored on this system."
687 # error "Don't know how to create a directory on this system."
695 bool FileName::createDirectory(int permission) const
697 LASSERT(!empty(), return false);
699 // FIXME: "Permissions of created directories are ignored on this system."
703 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
708 bool FileName::createPath() const
710 LASSERT(!empty(), return false);
711 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
716 bool success = dir.mkpath(d->fi.absoluteFilePath());
718 LYXERR0("Cannot create path '" << *this << "'!");
723 docstring const FileName::absoluteFilePath() const
725 return qstring_to_ucs4(d->fi.absoluteFilePath());
729 docstring FileName::displayName(int threshold) const
731 return makeDisplayPath(absFileName(), threshold);
735 docstring FileName::fileContents(string const & encoding) const
737 if (!isReadableFile()) {
738 LYXERR0("File '" << *this << "' is not readable!");
742 QFile file(d->fi.absoluteFilePath());
743 if (!file.open(QIODevice::ReadOnly)) {
744 LYXERR0("File '" << *this
745 << "' could not be opened in read only mode!");
748 QByteArray contents = file.readAll();
751 if (contents.isEmpty()) {
752 LYXERR(Debug::FILES, "File '" << *this
753 << "' is either empty or some error happened while reading it.");
758 if (encoding.empty() || encoding == "UTF-8")
759 s = QString::fromUtf8(contents.data());
760 else if (encoding == "ascii")
761 #if (QT_VERSION < 0x050000)
762 s = QString::fromAscii(contents.data());
764 s = QString::fromLatin1(contents.data());
766 else if (encoding == "local8bit")
767 s = QString::fromLocal8Bit(contents.data());
768 else if (encoding == "latin1")
769 s = QString::fromLatin1(contents.data());
771 return qstring_to_ucs4(s);
775 void FileName::changeExtension(string const & extension)
777 // FIXME: use Qt native methods...
778 string const oldname = absFileName();
779 string::size_type const last_slash = oldname.rfind('/');
780 string::size_type last_dot = oldname.rfind('.');
781 if (last_dot < last_slash && last_slash != string::npos)
782 last_dot = string::npos;
785 // Make sure the extension starts with a dot
786 if (!extension.empty() && extension[0] != '.')
787 ext= '.' + extension;
791 set(oldname.substr(0, last_dot) + ext);
795 docstring const FileName::relPath(string const & path) const
798 return makeRelPath(absoluteFilePath(), from_utf8(path));
802 // Note: According to Qt, QFileInfo::operator== is undefined when
803 // both files do not exist (Qt4.5 gives true for all non-existent
804 // files, while Qt4.4 compares the filenames).
806 // http://www.qtsoftware.com/developer/task-tracker/
807 // index_html?id=248471&method=entry.
808 bool equivalent(FileName const & l, FileName const & r)
810 // FIXME: In future use Qt.
811 // Qt 4.4: We need to solve this warning from Qt documentation:
812 // * Long and short file names that refer to the same file on Windows are
813 // treated as if they referred to different files.
814 // This is supposed to be fixed for Qt5.
815 FileName const lhs(os::internal_path(l.absFileName()));
816 FileName const rhs(os::internal_path(r.absFileName()));
819 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
823 // Avoid unnecessary checks below.
829 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
830 // Qt already checks if the filesystem is case sensitive or not.
831 // see note above why the extra check with fileName is needed.
832 return lhs.d->fi == rhs.d->fi
833 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
836 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
837 QFileInfo fi1(lhs.d->fi);
839 fi1 = QFileInfo(fi1.symLinkTarget());
840 QFileInfo fi2(rhs.d->fi);
842 fi2 = QFileInfo(fi2.symLinkTarget());
843 // see note above why the extra check with fileName is needed.
844 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
848 bool operator==(FileName const & lhs, FileName const & rhs)
850 return os::isFilesystemCaseSensitive()
851 ? lhs.absFileName() == rhs.absFileName()
852 : !QString::compare(toqstr(lhs.absFileName()),
853 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
857 bool operator!=(FileName const & lhs, FileName const & rhs)
859 return !(operator==(lhs, rhs));
863 bool operator<(FileName const & lhs, FileName const & rhs)
865 return lhs.absFileName() < rhs.absFileName();
869 bool operator>(FileName const & lhs, FileName const & rhs)
871 return lhs.absFileName() > rhs.absFileName();
875 ostream & operator<<(ostream & os, FileName const & filename)
877 return os << filename.absFileName();
881 /////////////////////////////////////////////////////////////////////
885 /////////////////////////////////////////////////////////////////////
888 DocFileName::DocFileName()
889 : save_abs_path_(true)
893 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
894 : FileName(abs_filename), save_abs_path_(save_abs)
898 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
899 : FileName(abs_filename), save_abs_path_(save_abs)
903 void DocFileName::set(string const & name, string const & buffer_path)
905 save_abs_path_ = isAbsolute(name);
909 FileName::set(makeAbsPath(name, buffer_path).absFileName());
913 void DocFileName::erase()
919 string DocFileName::relFileName(string const & path) const
922 return to_utf8(relPath(path));
926 string DocFileName::outputFileName(string const & path) const
928 return save_abs_path_ ? absFileName() : relFileName(path);
932 string DocFileName::mangledFileName(string const & dir) const
934 // Concurrent access to these variables is possible.
936 // We need to make sure that every DocFileName instance for a given
937 // filename returns the same mangled name.
938 typedef map<string, string> MangledMap;
939 static MangledMap mangledNames;
940 static Mutex mangledMutex;
941 // this locks both access to mangledNames and counter below
942 Mutex::Locker lock(&mangledMutex);
943 MangledMap::const_iterator const it = mangledNames.find(absFileName());
944 if (it != mangledNames.end())
947 string const name = absFileName();
949 string mname = os::internal_path(name);
950 // Remove the extension.
951 mname = support::changeExtension(name, string());
952 // The mangled name must be a valid LaTeX name.
953 // The list of characters to keep is probably over-restrictive,
954 // but it is not really a problem.
955 // Apart from non-ASCII characters, at least the following characters
956 // are forbidden: '/', '.', ' ', and ':'.
957 // On windows it is not possible to create files with '<', '>' or '?'
959 static string const keep = "abcdefghijklmnopqrstuvwxyz"
960 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
962 string::size_type pos = 0;
963 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
965 // Add the extension back on
966 mname = support::changeExtension(mname, getExtension(name));
968 // Prepend a counter to the filename. This is necessary to make
969 // the mangled name unique.
970 static int counter = 0;
972 s << counter++ << mname;
975 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
976 // is longer than about 160 characters. MiKTeX's pdflatex
977 // is even pickier. A maximum length of 100 has been proven to work.
978 // If dir.size() > max length, all bets are off for YAP. We truncate
979 // the filename nevertheless, keeping a minimum of 10 chars.
981 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
983 // If the mangled file name is too long, hack it to fit.
984 // We know we're guaranteed to have a unique file name because
986 if (mname.size() > max_length) {
987 int const half = (int(max_length) / 2) - 2;
989 mname = mname.substr(0, half) + "___" +
990 mname.substr(mname.size() - half);
994 mangledNames[absFileName()] = mname;
999 string DocFileName::unzippedFileName() const
1001 return support::unzippedFileName(absFileName());
1005 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1007 return static_cast<FileName const &>(lhs)
1008 == static_cast<FileName const &>(rhs)
1009 && lhs.saveAbsPath() == rhs.saveAbsPath();
1013 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1015 return !(lhs == rhs);
1018 } // namespace support