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>
34 #include <boost/scoped_array.hpp>
43 #ifdef HAVE_SYS_TYPES_H
44 # include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
62 // Three implementations of checksum(), depending on having mmap support or not.
63 #if defined(HAVE_MMAP) && defined(HAVE_MUNMAP)
66 #endif // SUM_WITH_MMAP
69 using namespace lyx::support;
71 // OK, this is ugly, but it is the only workaround I found to compile
72 // with gcc (any version) on a system which uses a non-GNU toolchain.
73 // The problem is that gcc uses a weak symbol for a particular
74 // instantiation and that the system linker usually does not
75 // understand those weak symbols (seen on HP-UX, tru64, AIX and
76 // others). Thus we force an explicit instanciation of this particular
78 template struct boost::detail::crc_table_t<32, 0x04C11DB7, true>;
83 /////////////////////////////////////////////////////////////////////
87 /////////////////////////////////////////////////////////////////////
89 struct FileName::Private
93 Private(string const & abs_filename) : fi(toqstr(abs_filename))
95 name = fromqstr(fi.absoluteFilePath());
96 fi.setCaching(fi.exists() ? true : false);
106 bool isFilesystemEqual(QString const & lhs, QString const & rhs)
108 return QString::compare(lhs, rhs, os::isFilesystemCaseSensitive() ?
109 Qt::CaseSensitive : Qt::CaseInsensitive) == 0;
112 /// The absolute file name in UTF-8 encoding.
118 /////////////////////////////////////////////////////////////////////
122 /////////////////////////////////////////////////////////////////////
125 FileName::FileName() : d(new Private)
130 FileName::FileName(string const & abs_filename)
131 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
133 //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
134 LATTEST(empty() || isAbsolute(d->name));
138 FileName::~FileName()
144 FileName::FileName(FileName const & rhs) : d(new Private)
146 d->name = rhs.d->name;
151 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
157 FileName & FileName::operator=(FileName const & rhs)
161 d->name = rhs.d->name;
167 bool FileName::empty() const
169 return d->name.empty();
173 bool FileName::isAbsolute(string const & name)
175 QFileInfo fi(toqstr(name));
176 return fi.isAbsolute();
180 string FileName::absFileName() const
186 string FileName::realPath() const
188 return os::real_path(absFileName());
192 void FileName::set(string const & name)
194 d->fi.setFile(toqstr(name));
195 d->name = fromqstr(d->fi.absoluteFilePath());
196 //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
197 LATTEST(empty() || isAbsolute(d->name));
201 void FileName::set(FileName const & rhs, string const & suffix)
203 if (!rhs.d->fi.isDir())
204 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
206 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
207 d->name = fromqstr(d->fi.absoluteFilePath());
208 //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
209 LATTEST(empty() || isAbsolute(d->name));
213 void FileName::erase()
220 bool FileName::copyTo(FileName const & name, bool keepsymlink) const
223 return copyTo(name, keepsymlink, visited);
227 bool FileName::copyTo(FileName const & name, bool keepsymlink,
228 FileName::FileNameSet & visited) const
230 LYXERR(Debug::FILES, "Copying " << name << " keep symlink: " << keepsymlink);
231 if (keepsymlink && name.isSymLink()) {
232 visited.insert(*this);
233 FileName const target(fromqstr(name.d->fi.symLinkTarget()));
234 if (visited.find(target) != visited.end()) {
235 LYXERR(Debug::FILES, "Found circular symlink: " << target);
238 return copyTo(target, true);
240 QFile::remove(name.d->fi.absoluteFilePath());
241 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
243 LYXERR0("FileName::copyTo(): Could not copy file "
244 << *this << " to " << name);
249 bool FileName::renameTo(FileName const & name) const
251 LYXERR(Debug::FILES, "Renaming " << name << " as " << *this);
252 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
254 LYXERR0("Could not rename file " << *this << " to " << name);
259 bool FileName::moveTo(FileName const & name) const
261 LYXERR(Debug::FILES, "Moving " << name << " to " << *this);
262 QFile::remove(name.d->fi.absoluteFilePath());
264 bool success = QFile::rename(d->fi.absoluteFilePath(),
265 name.d->fi.absoluteFilePath());
267 LYXERR0("Could not move file " << *this << " to " << name);
272 bool FileName::changePermission(unsigned long int mode) const
274 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
275 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
276 LYXERR0("File " << *this << ": cannot change permission to "
285 string FileName::toFilesystemEncoding() const
287 // This doesn't work on Windows for non ascii file names.
288 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
289 return string(encoded.begin(), encoded.end());
293 string FileName::toSafeFilesystemEncoding(os::file_access how) const
295 // This will work on Windows for non ascii file names.
296 QString const safe_path =
297 toqstr(os::safe_internal_path(absFileName(), how));
298 QByteArray const encoded = QFile::encodeName(safe_path);
299 return string(encoded.begin(), encoded.end());
303 FileName FileName::fromFilesystemEncoding(string const & name)
305 QByteArray const encoded(name.c_str(), name.length());
306 return FileName(fromqstr(QFile::decodeName(encoded)));
310 bool FileName::exists() const
312 return !empty() && d->fi.exists();
316 bool FileName::isSymLink() const
318 return !empty() && d->fi.isSymLink();
322 bool FileName::isFileEmpty() const
324 LASSERT(!empty(), return true);
325 return d->fi.size() == 0;
329 bool FileName::isDirectory() const
331 return !empty() && d->fi.isDir();
335 bool FileName::isReadOnly() const
337 LASSERT(!empty(), return true);
338 return d->fi.isReadable() && !d->fi.isWritable();
342 bool FileName::isReadableDirectory() const
344 return isDirectory() && d->fi.isReadable();
348 string FileName::onlyFileName() const
350 return fromqstr(d->fi.fileName());
354 string FileName::onlyFileNameWithoutExt() const
356 return fromqstr(d->fi.completeBaseName());
360 string FileName::extension() const
362 return fromqstr(d->fi.suffix());
366 bool FileName::hasExtension(const string & ext)
368 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
372 FileName FileName::onlyPath() const
377 path.d->fi.setFile(d->fi.path());
378 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
383 FileName FileName::parentPath() const
386 // return empty path for parent of root dir
387 // parent of empty path is empty too
388 if (empty() || d->fi.isRoot())
390 path.d->fi.setFile(d->fi.path());
391 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
396 bool FileName::isReadableFile() const
398 return !empty() && d->fi.isFile() && d->fi.isReadable();
402 bool FileName::isWritable() const
404 return !empty() && d->fi.isWritable();
408 bool FileName::isDirWritable() const
410 LASSERT(isDirectory(), return false);
411 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
412 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
414 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
417 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
422 FileNameList FileName::dirList(string const & ext) const
424 FileNameList dirlist;
425 if (!isDirectory()) {
426 LYXERR0("Directory '" << *this << "' does not exist!");
430 // If the directory is specified without a trailing '/', absoluteDir()
431 // would return the parent dir, so we must use absoluteFilePath() here.
432 QDir dir = d->fi.absoluteFilePath();
437 case '.': filter = "*" + toqstr(ext); break;
438 case '*': filter = toqstr(ext); break;
439 default: filter = "*." + toqstr(ext);
441 dir.setNameFilters(QStringList(filter));
442 LYXERR(Debug::FILES, "filtering on extension "
443 << fromqstr(filter) << " is requested.");
446 QFileInfoList list = dir.entryInfoList();
447 for (int i = 0; i != list.size(); ++i) {
448 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
449 dirlist.push_back(fi);
450 LYXERR(Debug::FILES, "found file " << fi);
457 FileName FileName::getcwd()
459 // return makeAbsPath("."); would create an infinite loop
461 return FileName(fromqstr(fi.absoluteFilePath()));
465 FileName FileName::tempPath()
467 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
471 void FileName::refresh() const
477 time_t FileName::lastModified() const
479 // QFileInfo caches information about the file. So, in case this file has
480 // been touched between the object creation and now, we refresh the file
483 return d->fi.lastModified().toTime_t();
487 bool FileName::chdir() const
489 return QDir::setCurrent(d->fi.absoluteFilePath());
493 bool FileName::link(FileName const & name) const
495 return QFile::link(toqstr(absFileName()), toqstr(name.absFileName()));
499 unsigned long checksum_ifstream_fallback(char const * file)
501 unsigned long result = 0;
502 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
503 ifstream ifs(file, ios_base::in | ios_base::binary);
507 istreambuf_iterator<char> beg(ifs);
508 istreambuf_iterator<char> end;
509 boost::crc_32_type crc;
510 crc = for_each(beg, end, crc);
511 result = crc.checksum();
515 unsigned long FileName::checksum() const
517 unsigned long result = 0;
520 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
523 // a directory may be passed here so we need to test it. (bug 3622)
525 LYXERR0('"' << absFileName() << "\" is a directory!");
529 // This is used in the debug output at the end of the method.
531 if (lyxerr.debugging(Debug::FILES))
534 #if QT_VERSION >= 0x999999
535 // First version of checksum uses Qt4.4 mmap support.
536 // FIXME: This code is not ready with Qt4.4.2,
537 // see http://www.lyx.org/trac/ticket/5293
538 // FIXME: should we check if the MapExtension extension is supported?
539 // see QAbstractFileEngine::supportsExtension() and
540 // QAbstractFileEngine::MapExtension)
541 QFile qf(fi.filePath());
542 if (!qf.open(QIODevice::ReadOnly))
544 qint64 size = fi.size();
545 uchar * ubeg = qf.map(0, size);
546 uchar * uend = ubeg + size;
547 boost::crc_32_type ucrc;
548 ucrc.process_block(ubeg, uend);
551 result = ucrc.checksum();
555 string const encoded = toSafeFilesystemEncoding();
556 char const * file = encoded.c_str();
559 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
561 int fd = open(file, O_RDONLY);
566 if (fstat(fd, &info)){
567 // fstat fails on samba shares (bug 5891)
569 return checksum_ifstream_fallback(file);
572 void * mm = mmap(0, info.st_size, PROT_READ,
574 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
575 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
580 char * beg = static_cast<char*>(mm);
581 char * end = beg + info.st_size;
583 boost::crc_32_type crc;
584 crc.process_block(beg, end);
585 result = crc.checksum();
587 munmap(mm, info.st_size);
590 #else // no SUM_WITH_MMAP
591 result = checksum_ifstream_fallback(file);
592 #endif // SUM_WITH_MMAP
595 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
596 << result << " lasted " << t.elapsed() << " ms.");
601 bool FileName::removeFile() const
603 bool const success = QFile::remove(d->fi.absoluteFilePath());
605 if (!success && exists())
606 LYXERR0("Could not delete file " << *this);
611 static bool rmdir(QFileInfo const & fi)
613 QDir dir(fi.absoluteFilePath());
614 QFileInfoList list = dir.entryInfoList();
616 for (int i = 0; i != list.size(); ++i) {
617 if (list.at(i).fileName() == ".")
619 if (list.at(i).fileName() == "..")
622 if (list.at(i).isDir()) {
623 LYXERR(Debug::FILES, "Removing dir "
624 << fromqstr(list.at(i).absoluteFilePath()));
625 removed = rmdir(list.at(i));
628 LYXERR(Debug::FILES, "Removing file "
629 << fromqstr(list.at(i).absoluteFilePath()));
630 removed = dir.remove(list.at(i).fileName());
634 LYXERR0("Could not delete "
635 << fromqstr(list.at(i).absoluteFilePath()));
638 QDir parent = fi.absolutePath();
639 success &= parent.rmdir(fi.fileName());
644 bool FileName::destroyDirectory() const
646 bool const success = rmdir(d->fi);
648 LYXERR0("Could not delete " << *this);
654 // Only used in non Win32 platforms
655 static int mymkdir(char const * pathname, unsigned long int mode)
657 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
659 # if MKDIR_TAKES_ONE_ARG
661 return ::mkdir(pathname);
662 // FIXME: "Permissions of created directories are ignored on this system."
665 return ::mkdir(pathname, mode_t(mode));
667 #elif defined(_WIN32)
669 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
670 // FIXME: "Permissions of created directories are ignored on this system."
672 return ::_mkdir(pathname);
673 // FIXME: "Permissions of created directories are ignored on this system."
675 # error "Don't know how to create a directory on this system."
681 bool FileName::createDirectory(int permission) const
683 LASSERT(!empty(), return false);
685 // FIXME: "Permissions of created directories are ignored on this system."
688 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
693 bool FileName::createPath() const
695 LASSERT(!empty(), return false);
696 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
701 bool success = dir.mkpath(d->fi.absoluteFilePath());
703 LYXERR0("Cannot create path '" << *this << "'!");
708 docstring const FileName::absoluteFilePath() const
710 return qstring_to_ucs4(d->fi.absoluteFilePath());
714 docstring FileName::displayName(int threshold) const
716 return makeDisplayPath(absFileName(), threshold);
720 docstring FileName::fileContents(string const & encoding) const
722 if (!isReadableFile()) {
723 LYXERR0("File '" << *this << "' is not readable!");
727 QFile file(d->fi.absoluteFilePath());
728 if (!file.open(QIODevice::ReadOnly)) {
729 LYXERR0("File '" << *this
730 << "' could not be opened in read only mode!");
733 QByteArray contents = file.readAll();
736 if (contents.isEmpty()) {
737 LYXERR(Debug::FILES, "File '" << *this
738 << "' is either empty or some error happened while reading it.");
743 if (encoding.empty() || encoding == "UTF-8")
744 s = QString::fromUtf8(contents.data());
745 else if (encoding == "ascii")
746 #if (QT_VERSION < 0x050000)
747 s = QString::fromAscii(contents.data());
749 s = QString::fromLatin1(contents.data());
751 else if (encoding == "local8bit")
752 s = QString::fromLocal8Bit(contents.data());
753 else if (encoding == "latin1")
754 s = QString::fromLatin1(contents.data());
756 return qstring_to_ucs4(s);
760 void FileName::changeExtension(string const & extension)
762 // FIXME: use Qt native methods...
763 string const oldname = absFileName();
764 string::size_type const last_slash = oldname.rfind('/');
765 string::size_type last_dot = oldname.rfind('.');
766 if (last_dot < last_slash && last_slash != string::npos)
767 last_dot = string::npos;
770 // Make sure the extension starts with a dot
771 if (!extension.empty() && extension[0] != '.')
772 ext= '.' + extension;
776 set(oldname.substr(0, last_dot) + ext);
780 docstring const FileName::relPath(string const & path) const
783 return makeRelPath(absoluteFilePath(), from_utf8(path));
787 // Note: According to Qt, QFileInfo::operator== is undefined when
788 // both files do not exist (Qt4.5 gives true for all non-existent
789 // files, while Qt4.4 compares the filenames).
791 // http://www.qtsoftware.com/developer/task-tracker/
792 // index_html?id=248471&method=entry.
793 bool equivalent(FileName const & l, FileName const & r)
795 // FIXME: In future use Qt.
796 // Qt 4.4: We need to solve this warning from Qt documentation:
797 // * Long and short file names that refer to the same file on Windows are
798 // treated as if they referred to different files.
799 // This is supposed to be fixed for Qt5.
800 FileName const lhs(os::internal_path(l.absFileName()));
801 FileName const rhs(os::internal_path(r.absFileName()));
804 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
808 // Avoid unnecessary checks below.
814 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
815 // Qt already checks if the filesystem is case sensitive or not.
816 // see note above why the extra check with fileName is needed.
817 return lhs.d->fi == rhs.d->fi
818 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
821 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
822 QFileInfo fi1(lhs.d->fi);
824 fi1 = QFileInfo(fi1.symLinkTarget());
825 QFileInfo fi2(rhs.d->fi);
827 fi2 = QFileInfo(fi2.symLinkTarget());
828 // see note above why the extra check with fileName is needed.
829 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
833 bool operator==(FileName const & lhs, FileName const & rhs)
835 return os::isFilesystemCaseSensitive()
836 ? lhs.absFileName() == rhs.absFileName()
837 : !QString::compare(toqstr(lhs.absFileName()),
838 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
842 bool operator!=(FileName const & lhs, FileName const & rhs)
844 return !(operator==(lhs, rhs));
848 bool operator<(FileName const & lhs, FileName const & rhs)
850 return lhs.absFileName() < rhs.absFileName();
854 bool operator>(FileName const & lhs, FileName const & rhs)
856 return lhs.absFileName() > rhs.absFileName();
860 ostream & operator<<(ostream & os, FileName const & filename)
862 return os << filename.absFileName();
866 /////////////////////////////////////////////////////////////////////
870 /////////////////////////////////////////////////////////////////////
873 DocFileName::DocFileName()
874 : save_abs_path_(true)
878 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
879 : FileName(abs_filename), save_abs_path_(save_abs)
883 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
884 : FileName(abs_filename), save_abs_path_(save_abs)
888 void DocFileName::set(string const & name, string const & buffer_path)
890 save_abs_path_ = isAbsolute(name);
894 FileName::set(makeAbsPath(name, buffer_path).absFileName());
898 void DocFileName::erase()
904 string DocFileName::relFileName(string const & path) const
907 return to_utf8(relPath(path));
911 string DocFileName::outputFileName(string const & path) const
913 return save_abs_path_ ? absFileName() : relFileName(path);
917 string DocFileName::mangledFileName(string const & dir) const
919 // Concurrent access to these variables is possible.
921 // We need to make sure that every DocFileName instance for a given
922 // filename returns the same mangled name.
923 typedef map<string, string> MangledMap;
924 static MangledMap mangledNames;
925 static Mutex mangledMutex;
926 // this locks both access to mangledNames and counter below
927 Mutex::Locker lock(&mangledMutex);
928 MangledMap::const_iterator const it = mangledNames.find(absFileName());
929 if (it != mangledNames.end())
932 string const name = absFileName();
934 string mname = os::internal_path(name);
935 // Remove the extension.
936 mname = support::changeExtension(name, string());
937 // The mangled name must be a valid LaTeX name.
938 // The list of characters to keep is probably over-restrictive,
939 // but it is not really a problem.
940 // Apart from non-ASCII characters, at least the following characters
941 // are forbidden: '/', '.', ' ', and ':'.
942 // On windows it is not possible to create files with '<', '>' or '?'
944 static string const keep = "abcdefghijklmnopqrstuvwxyz"
945 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
947 string::size_type pos = 0;
948 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
950 // Add the extension back on
951 mname = support::changeExtension(mname, getExtension(name));
953 // Prepend a counter to the filename. This is necessary to make
954 // the mangled name unique.
955 static int counter = 0;
957 s << counter++ << mname;
960 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
961 // is longer than about 160 characters. MiKTeX's pdflatex
962 // is even pickier. A maximum length of 100 has been proven to work.
963 // If dir.size() > max length, all bets are off for YAP. We truncate
964 // the filename nevertheless, keeping a minimum of 10 chars.
966 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
968 // If the mangled file name is too long, hack it to fit.
969 // We know we're guaranteed to have a unique file name because
971 if (mname.size() > max_length) {
972 int const half = (int(max_length) / 2) - 2;
974 mname = mname.substr(0, half) + "___" +
975 mname.substr(mname.size() - half);
979 mangledNames[absFileName()] = mname;
984 string DocFileName::unzippedFileName() const
986 return support::unzippedFileName(absFileName());
990 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
992 return static_cast<FileName const &>(lhs)
993 == static_cast<FileName const &>(rhs)
994 && lhs.saveAbsPath() == rhs.saveAbsPath();
998 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1000 return !(lhs == rhs);
1003 } // namespace support