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)
115 resname = Package::get_home_dir().absFileName();
116 else if ( prefixIs(name, "~/"))
117 resname = Package::get_home_dir().absFileName() + name.substr(1);
118 else if ( prefixIs(name, "~:s/"))
119 resname = package().system_support().absFileName() + name.substr(3);
125 /// The absolute file name in UTF-8 encoding.
131 /////////////////////////////////////////////////////////////////////
135 /////////////////////////////////////////////////////////////////////
138 FileName::FileName() : d(new Private)
143 FileName::FileName(string const & abs_filename)
144 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
146 //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
147 LATTEST(empty() || isAbsolute(d->name));
151 FileName::~FileName()
157 FileName::FileName(FileName const & rhs) : d(new Private)
159 d->name = rhs.d->name;
164 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
170 FileName & FileName::operator=(FileName const & rhs)
174 d->name = rhs.d->name;
180 bool FileName::empty() const
182 return d->name.empty();
186 bool FileName::isAbsolute(string const & name)
188 QFileInfo fi(toqstr(Private::handleTildeName(name)));
189 return fi.isAbsolute();
193 string FileName::absFileName() const
199 string FileName::realPath() const
201 return os::real_path(absFileName());
205 void FileName::set(string const & name)
207 d->fi.setFile(toqstr(Private::handleTildeName(name)));
208 d->name = fromqstr(d->fi.absoluteFilePath());
209 //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
210 LATTEST(empty() || isAbsolute(d->name));
214 void FileName::set(FileName const & rhs, string const & suffix)
216 if (!rhs.d->fi.isDir())
217 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
219 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
220 d->name = fromqstr(d->fi.absoluteFilePath());
221 //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
222 LATTEST(empty() || isAbsolute(d->name));
226 void FileName::erase()
233 bool FileName::copyTo(FileName const & name, bool keepsymlink) const
236 return copyTo(name, keepsymlink, visited);
240 bool FileName::copyTo(FileName const & name, bool keepsymlink,
241 FileName::FileNameSet & visited) const
243 LYXERR(Debug::FILES, "Copying " << name << " keep symlink: " << keepsymlink);
244 if (keepsymlink && name.isSymLink()) {
245 visited.insert(*this);
246 FileName const target(fromqstr(name.d->fi.symLinkTarget()));
247 if (visited.find(target) != visited.end()) {
248 LYXERR(Debug::FILES, "Found circular symlink: " << target);
251 return copyTo(target, true);
253 QFile::remove(name.d->fi.absoluteFilePath());
254 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
256 LYXERR0("FileName::copyTo(): Could not copy file "
257 << *this << " to " << name);
262 bool FileName::renameTo(FileName const & name) const
264 LYXERR(Debug::FILES, "Renaming " << name << " as " << *this);
265 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
267 LYXERR0("Could not rename file " << *this << " to " << name);
272 bool FileName::moveTo(FileName const & name) const
274 LYXERR(Debug::FILES, "Moving " << *this << " to " << name);
275 QFile::remove(name.d->fi.absoluteFilePath());
277 bool success = QFile::rename(d->fi.absoluteFilePath(),
278 name.d->fi.absoluteFilePath());
280 LYXERR0("Could not move file " << *this << " to " << name);
285 bool FileName::changePermission(unsigned long int mode) const
287 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
288 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
289 LYXERR0("File " << *this << ": cannot change permission to "
301 string FileName::toFilesystemEncoding() const
303 // This doesn't work on Windows for non ascii file names.
304 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
305 return string(encoded.begin(), encoded.end());
309 string FileName::toSafeFilesystemEncoding(os::file_access how) const
311 // This will work on Windows for non ascii file names.
312 QString const safe_path =
313 toqstr(os::safe_internal_path(absFileName(), how));
314 QByteArray const encoded = QFile::encodeName(safe_path);
315 return string(encoded.begin(), encoded.end());
319 FileName FileName::fromFilesystemEncoding(string const & name)
321 QByteArray const encoded(name.c_str(), name.length());
322 return FileName(fromqstr(QFile::decodeName(encoded)));
326 bool FileName::exists() const
328 return !empty() && d->fi.exists();
332 bool FileName::isSymLink() const
334 return !empty() && d->fi.isSymLink();
338 //QFileInfo caching info might fool this test if file was changed meanwhile.
339 //refresh() helps, but we don't want to put it blindly here, because it might
340 //trigger slowdown on networked file systems.
341 bool FileName::isFileEmpty() const
343 LASSERT(!empty(), return true);
344 return d->fi.size() == 0;
348 bool FileName::isDirectory() const
350 return !empty() && d->fi.isDir();
354 bool FileName::isReadOnly() const
356 LASSERT(!empty(), return true);
357 return d->fi.isReadable() && !d->fi.isWritable();
361 bool FileName::isReadableDirectory() const
363 return isDirectory() && d->fi.isReadable();
367 string FileName::onlyFileName() const
369 return fromqstr(d->fi.fileName());
373 string FileName::onlyFileNameWithoutExt() const
375 return fromqstr(d->fi.completeBaseName());
379 string FileName::extension() const
381 return fromqstr(d->fi.suffix());
385 bool FileName::hasExtension(const string & ext)
387 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
391 FileName FileName::onlyPath() const
396 path.d->fi.setFile(d->fi.path());
397 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
402 FileName FileName::parentPath() const
405 // return empty path for parent of root dir
406 // parent of empty path is empty too
407 if (empty() || d->fi.isRoot())
409 path.d->fi.setFile(d->fi.path());
410 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
415 bool FileName::isReadableFile() const
417 return !empty() && d->fi.isFile() && d->fi.isReadable();
421 bool FileName::isWritable() const
423 return !empty() && d->fi.isWritable();
427 bool FileName::isDirWritable() const
429 LASSERT(isDirectory(), return false);
430 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
431 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
433 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
436 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
441 FileNameList FileName::dirList(string const & ext) const
443 FileNameList dirlist;
444 if (!isDirectory()) {
445 LYXERR0("Directory '" << *this << "' does not exist!");
449 // If the directory is specified without a trailing '/', absoluteDir()
450 // would return the parent dir, so we must use absoluteFilePath() here.
451 QDir dir = d->fi.absoluteFilePath();
456 case '.': filter = "*" + toqstr(ext); break;
457 case '*': filter = toqstr(ext); break;
458 default: filter = "*." + toqstr(ext);
460 dir.setNameFilters(QStringList(filter));
461 LYXERR(Debug::FILES, "filtering on extension "
462 << fromqstr(filter) << " is requested.");
465 QFileInfoList list = dir.entryInfoList();
466 for (int i = 0; i != list.size(); ++i) {
467 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
468 dirlist.push_back(fi);
469 LYXERR(Debug::FILES, "found file " << fi);
476 FileName FileName::getcwd()
478 // return makeAbsPath("."); would create an infinite loop
480 return FileName(fromqstr(fi.absoluteFilePath()));
484 FileName FileName::tempPath()
486 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
490 void FileName::refresh() const
496 time_t FileName::lastModified() const
498 // QFileInfo caches information about the file. So, in case this file has
499 // been touched between the object creation and now, we refresh the file
502 return d->fi.lastModified().toTime_t();
506 bool FileName::chdir() const
508 return QDir::setCurrent(d->fi.absoluteFilePath());
512 bool FileName::link(FileName const & name) const
514 return QFile::link(toqstr(absFileName()), toqstr(name.absFileName()));
518 unsigned long checksum_ifstream_fallback(char const * file)
520 unsigned long result = 0;
521 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
522 ifstream ifs(file, ios_base::in | ios_base::binary);
526 istreambuf_iterator<char> beg(ifs);
527 istreambuf_iterator<char> end;
528 boost::crc_32_type crc;
529 crc = for_each(beg, end, crc);
530 result = crc.checksum();
534 unsigned long FileName::checksum() const
536 unsigned long result = 0;
539 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
542 // a directory may be passed here so we need to test it. (bug 3622)
544 LYXERR0('"' << absFileName() << "\" is a directory!");
548 // This is used in the debug output at the end of the method.
550 if (lyxerr.debugging(Debug::FILES))
553 #if QT_VERSION >= 0x999999
554 // First version of checksum uses Qt4.4 mmap support.
555 // FIXME: This code is not ready with Qt4.4.2,
556 // see http://www.lyx.org/trac/ticket/5293
557 // FIXME: should we check if the MapExtension extension is supported?
558 // see QAbstractFileEngine::supportsExtension() and
559 // QAbstractFileEngine::MapExtension)
560 QFile qf(fi.filePath());
561 if (!qf.open(QIODevice::ReadOnly))
563 qint64 size = fi.size();
564 uchar * ubeg = qf.map(0, size);
565 uchar * uend = ubeg + size;
566 boost::crc_32_type ucrc;
567 ucrc.process_block(ubeg, uend);
570 result = ucrc.checksum();
574 string const encoded = toSafeFilesystemEncoding();
575 char const * file = encoded.c_str();
578 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
580 int fd = open(file, O_RDONLY);
585 if (fstat(fd, &info)){
586 // fstat fails on samba shares (bug 5891)
588 return checksum_ifstream_fallback(file);
591 void * mm = mmap(0, info.st_size, PROT_READ,
593 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
594 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
599 char * beg = static_cast<char*>(mm);
600 char * end = beg + info.st_size;
602 boost::crc_32_type crc;
603 crc.process_block(beg, end);
604 result = crc.checksum();
606 munmap(mm, info.st_size);
609 #else // no SUM_WITH_MMAP
610 result = checksum_ifstream_fallback(file);
611 #endif // SUM_WITH_MMAP
614 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
615 << result << " lasted " << t.elapsed() << " ms.");
620 bool FileName::removeFile() const
622 bool const success = QFile::remove(d->fi.absoluteFilePath());
624 if (!success && exists())
625 LYXERR0("Could not delete file " << *this);
630 static bool rmdir(QFileInfo const & fi)
632 QDir dir(fi.absoluteFilePath());
633 QFileInfoList list = dir.entryInfoList();
635 for (int i = 0; i != list.size(); ++i) {
636 if (list.at(i).fileName() == ".")
638 if (list.at(i).fileName() == "..")
641 if (list.at(i).isDir()) {
642 LYXERR(Debug::FILES, "Removing dir "
643 << fromqstr(list.at(i).absoluteFilePath()));
644 removed = rmdir(list.at(i));
647 LYXERR(Debug::FILES, "Removing file "
648 << fromqstr(list.at(i).absoluteFilePath()));
649 removed = dir.remove(list.at(i).fileName());
653 LYXERR0("Could not delete "
654 << fromqstr(list.at(i).absoluteFilePath()));
657 QDir parent = fi.absolutePath();
658 success &= parent.rmdir(fi.fileName());
663 bool FileName::destroyDirectory() const
665 bool const success = rmdir(d->fi);
667 LYXERR0("Could not delete " << *this);
673 // Only used in non Win32 platforms
675 static int mymkdir(char const * pathname, unsigned long int mode)
677 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
679 # if MKDIR_TAKES_ONE_ARG
681 return ::mkdir(pathname);
682 // FIXME: "Permissions of created directories are ignored on this system."
685 return ::mkdir(pathname, mode_t(mode));
687 # elif defined(_WIN32)
689 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
690 // FIXME: "Permissions of created directories are ignored on this system."
692 return ::_mkdir(pathname);
693 // FIXME: "Permissions of created directories are ignored on this system."
695 # error "Don't know how to create a directory on this system."
701 bool FileName::createDirectory(int permission) const
703 LASSERT(!empty(), return false);
705 // FIXME: "Permissions of created directories are ignored on this system."
709 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
714 bool FileName::createPath() const
716 LASSERT(!empty(), return false);
717 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
722 bool success = dir.mkpath(d->fi.absoluteFilePath());
724 LYXERR0("Cannot create path '" << *this << "'!");
729 docstring const FileName::absoluteFilePath() const
731 return qstring_to_ucs4(d->fi.absoluteFilePath());
735 docstring FileName::displayName(int threshold) const
737 return makeDisplayPath(absFileName(), threshold);
741 docstring FileName::fileContents(string const & encoding) const
743 if (!isReadableFile()) {
744 LYXERR0("File '" << *this << "' is not readable!");
748 QFile file(d->fi.absoluteFilePath());
749 if (!file.open(QIODevice::ReadOnly)) {
750 LYXERR0("File '" << *this
751 << "' could not be opened in read only mode!");
754 QByteArray contents = file.readAll();
757 if (contents.isEmpty()) {
758 LYXERR(Debug::FILES, "File '" << *this
759 << "' is either empty or some error happened while reading it.");
764 if (encoding.empty() || encoding == "UTF-8")
765 s = QString::fromUtf8(contents.data());
766 else if (encoding == "ascii")
767 #if (QT_VERSION < 0x050000)
768 s = QString::fromAscii(contents.data());
770 s = QString::fromLatin1(contents.data());
772 else if (encoding == "local8bit")
773 s = QString::fromLocal8Bit(contents.data());
774 else if (encoding == "latin1")
775 s = QString::fromLatin1(contents.data());
777 return qstring_to_ucs4(s);
781 void FileName::changeExtension(string const & extension)
783 // FIXME: use Qt native methods...
784 string const oldname = absFileName();
785 string::size_type const last_slash = oldname.rfind('/');
786 string::size_type last_dot = oldname.rfind('.');
787 if (last_dot < last_slash && last_slash != string::npos)
788 last_dot = string::npos;
791 // Make sure the extension starts with a dot
792 if (!extension.empty() && extension[0] != '.')
793 ext= '.' + extension;
797 set(oldname.substr(0, last_dot) + ext);
801 docstring const FileName::relPath(string const & path) const
804 return makeRelPath(absoluteFilePath(), from_utf8(path));
808 // Note: According to Qt, QFileInfo::operator== is undefined when
809 // both files do not exist (Qt4.5 gives true for all non-existent
810 // files, while Qt4.4 compares the filenames).
812 // http://www.qtsoftware.com/developer/task-tracker/
813 // index_html?id=248471&method=entry.
814 bool equivalent(FileName const & l, FileName const & r)
816 // FIXME: In future use Qt.
817 // Qt 4.4: We need to solve this warning from Qt documentation:
818 // * Long and short file names that refer to the same file on Windows are
819 // treated as if they referred to different files.
820 // This is supposed to be fixed for Qt5.
821 FileName const lhs(os::internal_path(l.absFileName()));
822 FileName const rhs(os::internal_path(r.absFileName()));
825 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
829 // Avoid unnecessary checks below.
835 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
836 // Qt already checks if the filesystem is case sensitive or not.
837 // see note above why the extra check with fileName is needed.
838 return lhs.d->fi == rhs.d->fi
839 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
842 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
843 QFileInfo fi1(lhs.d->fi);
845 fi1 = QFileInfo(fi1.symLinkTarget());
846 QFileInfo fi2(rhs.d->fi);
848 fi2 = QFileInfo(fi2.symLinkTarget());
849 // see note above why the extra check with fileName is needed.
850 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
854 bool operator==(FileName const & lhs, FileName const & rhs)
856 return os::isFilesystemCaseSensitive()
857 ? lhs.absFileName() == rhs.absFileName()
858 : !QString::compare(toqstr(lhs.absFileName()),
859 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
863 bool operator!=(FileName const & lhs, FileName const & rhs)
865 return !(operator==(lhs, rhs));
869 bool operator<(FileName const & lhs, FileName const & rhs)
871 return lhs.absFileName() < rhs.absFileName();
875 bool operator>(FileName const & lhs, FileName const & rhs)
877 return lhs.absFileName() > rhs.absFileName();
881 ostream & operator<<(ostream & os, FileName const & filename)
883 return os << filename.absFileName();
887 /////////////////////////////////////////////////////////////////////
891 /////////////////////////////////////////////////////////////////////
894 DocFileName::DocFileName()
895 : save_abs_path_(true)
899 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
900 : FileName(abs_filename), save_abs_path_(save_abs)
904 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
905 : FileName(abs_filename), save_abs_path_(save_abs)
909 void DocFileName::set(string const & name, string const & buffer_path)
911 save_abs_path_ = isAbsolute(name);
915 FileName::set(makeAbsPath(name, buffer_path).absFileName());
919 void DocFileName::erase()
925 string DocFileName::relFileName(string const & path) const
928 return to_utf8(relPath(path));
932 string DocFileName::outputFileName(string const & path) const
934 return save_abs_path_ ? absFileName() : relFileName(path);
938 string DocFileName::mangledFileName(string const & dir) const
940 // Concurrent access to these variables is possible.
942 // We need to make sure that every DocFileName instance for a given
943 // filename returns the same mangled name.
944 typedef map<string, string> MangledMap;
945 static MangledMap mangledNames;
946 static Mutex mangledMutex;
947 // this locks both access to mangledNames and counter below
948 Mutex::Locker lock(&mangledMutex);
949 MangledMap::const_iterator const it = mangledNames.find(absFileName());
950 if (it != mangledNames.end())
953 string const name = absFileName();
955 string mname = os::internal_path(name);
956 // Remove the extension.
957 mname = support::changeExtension(name, string());
958 // The mangled name must be a valid LaTeX name.
959 // The list of characters to keep is probably over-restrictive,
960 // but it is not really a problem.
961 // Apart from non-ASCII characters, at least the following characters
962 // are forbidden: '/', '.', ' ', and ':'.
963 // On windows it is not possible to create files with '<', '>' or '?'
965 static string const keep = "abcdefghijklmnopqrstuvwxyz"
966 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
968 string::size_type pos = 0;
969 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
971 // Add the extension back on
972 mname = support::changeExtension(mname, getExtension(name));
974 // Prepend a counter to the filename. This is necessary to make
975 // the mangled name unique.
976 static int counter = 0;
978 s << counter++ << mname;
981 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
982 // is longer than about 160 characters. MiKTeX's pdflatex
983 // is even pickier. A maximum length of 100 has been proven to work.
984 // If dir.size() > max length, all bets are off for YAP. We truncate
985 // the filename nevertheless, keeping a minimum of 10 chars.
987 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
989 // If the mangled file name is too long, hack it to fit.
990 // We know we're guaranteed to have a unique file name because
992 if (mname.size() > max_length) {
993 int const half = (int(max_length) / 2) - 2;
995 mname = mname.substr(0, half) + "___" +
996 mname.substr(mname.size() - half);
1000 mangledNames[absFileName()] = mname;
1005 string DocFileName::unzippedFileName() const
1007 return support::unzippedFileName(absFileName());
1011 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1013 return static_cast<FileName const &>(lhs)
1014 == static_cast<FileName const &>(rhs)
1015 && lhs.saveAbsPath() == rhs.saveAbsPath();
1019 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1021 return !(lhs == rhs);
1024 } // namespace support