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/qstring_helpers.h"
22 #include "support/os.h"
23 #include "support/Package.h"
24 #include "support/qstring_helpers.h"
31 #include <QTemporaryFile>
34 #include <boost/crc.hpp>
35 #include <boost/scoped_array.hpp>
44 #ifdef HAVE_SYS_TYPES_H
45 # include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
63 // Three implementations of checksum(), depending on having mmap support or not.
64 #if defined(HAVE_MMAP) && defined(HAVE_MUNMAP)
67 #endif // SUM_WITH_MMAP
70 using namespace lyx::support;
72 // OK, this is ugly, but it is the only workaround I found to compile
73 // with gcc (any version) on a system which uses a non-GNU toolchain.
74 // The problem is that gcc uses a weak symbol for a particular
75 // instantiation and that the system linker usually does not
76 // understand those weak symbols (seen on HP-UX, tru64, AIX and
77 // others). Thus we force an explicit instanciation of this particular
79 template struct boost::detail::crc_table_t<32, 0x04C11DB7, true>;
84 /////////////////////////////////////////////////////////////////////
88 /////////////////////////////////////////////////////////////////////
90 struct FileName::Private
94 Private(string const & abs_filename) : fi(toqstr(abs_filename))
96 name = fromqstr(fi.absoluteFilePath());
97 fi.setCaching(fi.exists() ? true : false);
100 inline void refresh()
107 bool isFilesystemEqual(QString const & lhs, QString const & rhs)
109 return QString::compare(lhs, rhs, os::isFilesystemCaseSensitive() ?
110 Qt::CaseSensitive : Qt::CaseInsensitive) == 0;
113 /// The absolute file name in UTF-8 encoding.
119 /////////////////////////////////////////////////////////////////////
123 /////////////////////////////////////////////////////////////////////
126 FileName::FileName() : d(new Private)
131 FileName::FileName(string const & abs_filename)
132 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
134 //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
135 LATTEST(empty() || isAbsolute(d->name));
139 FileName::~FileName()
145 FileName::FileName(FileName const & rhs) : d(new Private)
147 d->name = rhs.d->name;
152 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
158 FileName & FileName::operator=(FileName const & rhs)
162 d->name = rhs.d->name;
168 bool FileName::empty() const
170 return d->name.empty();
174 bool FileName::isAbsolute(string const & name)
176 QFileInfo fi(toqstr(name));
177 return fi.isAbsolute();
181 string FileName::absFileName() const
187 string FileName::realPath() const
189 return os::real_path(absFileName());
193 void FileName::set(string const & name)
195 d->fi.setFile(toqstr(name));
196 d->name = fromqstr(d->fi.absoluteFilePath());
197 //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
198 LATTEST(empty() || isAbsolute(d->name));
202 void FileName::set(FileName const & rhs, string const & suffix)
204 if (!rhs.d->fi.isDir())
205 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
207 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
208 d->name = fromqstr(d->fi.absoluteFilePath());
209 //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
210 LATTEST(empty() || isAbsolute(d->name));
214 void FileName::erase()
221 bool FileName::copyTo(FileName const & name, bool keepsymlink) const
224 return copyTo(name, keepsymlink, visited);
228 bool FileName::copyTo(FileName const & name, bool keepsymlink,
229 FileName::FileNameSet & visited) const
231 LYXERR(Debug::FILES, "Copying " << name << " keep symlink: " << keepsymlink);
232 if (keepsymlink && name.isSymLink()) {
233 visited.insert(*this);
234 FileName const target(fromqstr(name.d->fi.symLinkTarget()));
235 if (visited.find(target) != visited.end()) {
236 LYXERR(Debug::FILES, "Found circular symlink: " << target);
239 return copyTo(target, true);
241 QFile::remove(name.d->fi.absoluteFilePath());
242 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
244 LYXERR0("FileName::copyTo(): Could not copy file "
245 << *this << " to " << name);
250 bool FileName::renameTo(FileName const & name) const
252 LYXERR(Debug::FILES, "Renaming " << name);
253 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
255 LYXERR0("Could not rename file " << *this << " to " << name);
260 bool FileName::moveTo(FileName const & name) const
262 LYXERR(Debug::FILES, "Moving " << name);
263 QFile::remove(name.d->fi.absoluteFilePath());
265 bool success = QFile::rename(d->fi.absoluteFilePath(),
266 name.d->fi.absoluteFilePath());
268 LYXERR0("Could not move file " << *this << " to " << name);
273 bool FileName::changePermission(unsigned long int mode) const
275 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
276 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
277 LYXERR0("File " << *this << ": cannot change permission to "
286 string FileName::toFilesystemEncoding() const
288 // This doesn't work on Windows for non ascii file names.
289 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
290 return string(encoded.begin(), encoded.end());
294 string FileName::toSafeFilesystemEncoding(os::file_access how) const
296 // This will work on Windows for non ascii file names.
297 QString const safe_path =
298 toqstr(os::safe_internal_path(absFileName(), how));
299 QByteArray const encoded = QFile::encodeName(safe_path);
300 return string(encoded.begin(), encoded.end());
304 FileName FileName::fromFilesystemEncoding(string const & name)
306 QByteArray const encoded(name.c_str(), name.length());
307 return FileName(fromqstr(QFile::decodeName(encoded)));
311 bool FileName::exists() const
313 return !empty() && d->fi.exists();
317 bool FileName::isSymLink() const
319 return !empty() && d->fi.isSymLink();
323 bool FileName::isFileEmpty() const
325 LASSERT(!empty(), return true);
326 return d->fi.size() == 0;
330 bool FileName::isDirectory() const
332 return !empty() && d->fi.isDir();
336 bool FileName::isReadOnly() const
338 LASSERT(!empty(), return true);
339 return d->fi.isReadable() && !d->fi.isWritable();
343 bool FileName::isReadableDirectory() const
345 return isDirectory() && d->fi.isReadable();
349 string FileName::onlyFileName() const
351 return fromqstr(d->fi.fileName());
355 string FileName::onlyFileNameWithoutExt() const
357 return fromqstr(d->fi.completeBaseName());
361 string FileName::extension() const
363 return fromqstr(d->fi.suffix());
367 bool FileName::hasExtension(const string & ext)
369 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
373 FileName FileName::onlyPath() const
378 path.d->fi.setFile(d->fi.path());
379 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
384 FileName FileName::parentPath() const
387 // return empty path for parent of root dir
388 // parent of empty path is empty too
389 if (empty() || d->fi.isRoot())
391 path.d->fi.setFile(d->fi.path());
392 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
397 bool FileName::isReadableFile() const
399 return !empty() && d->fi.isFile() && d->fi.isReadable();
403 bool FileName::isWritable() const
405 return !empty() && d->fi.isWritable();
409 bool FileName::isDirWritable() const
411 LASSERT(isDirectory(), return false);
412 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
413 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
415 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
418 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
423 FileNameList FileName::dirList(string const & ext) const
425 FileNameList dirlist;
426 if (!isDirectory()) {
427 LYXERR0("Directory '" << *this << "' does not exist!");
431 // If the directory is specified without a trailing '/', absoluteDir()
432 // would return the parent dir, so we must use absoluteFilePath() here.
433 QDir dir = d->fi.absoluteFilePath();
438 case '.': filter = "*" + toqstr(ext); break;
439 case '*': filter = toqstr(ext); break;
440 default: filter = "*." + toqstr(ext);
442 dir.setNameFilters(QStringList(filter));
443 LYXERR(Debug::FILES, "filtering on extension "
444 << fromqstr(filter) << " is requested.");
447 QFileInfoList list = dir.entryInfoList();
448 for (int i = 0; i != list.size(); ++i) {
449 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
450 dirlist.push_back(fi);
451 LYXERR(Debug::FILES, "found file " << fi);
458 FileName FileName::getcwd()
460 // return makeAbsPath("."); would create an infinite loop
462 return FileName(fromqstr(fi.absoluteFilePath()));
466 FileName FileName::tempPath()
468 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
472 void FileName::refresh() const
478 time_t FileName::lastModified() const
480 // QFileInfo caches information about the file. So, in case this file has
481 // been touched between the object creation and now, we refresh the file
484 return d->fi.lastModified().toTime_t();
488 bool FileName::chdir() const
490 return QDir::setCurrent(d->fi.absoluteFilePath());
494 unsigned long checksum_ifstream_fallback(char const * file)
496 unsigned long result = 0;
497 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
498 ifstream ifs(file, ios_base::in | ios_base::binary);
502 istreambuf_iterator<char> beg(ifs);
503 istreambuf_iterator<char> end;
504 boost::crc_32_type crc;
505 crc = for_each(beg, end, crc);
506 result = crc.checksum();
510 unsigned long FileName::checksum() const
512 unsigned long result = 0;
515 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
518 // a directory may be passed here so we need to test it. (bug 3622)
520 LYXERR0('"' << absFileName() << "\" is a directory!");
524 // This is used in the debug output at the end of the method.
526 if (lyxerr.debugging(Debug::FILES))
529 #if QT_VERSION >= 0x999999
530 // First version of checksum uses Qt4.4 mmap support.
531 // FIXME: This code is not ready with Qt4.4.2,
532 // see http://www.lyx.org/trac/ticket/5293
533 // FIXME: should we check if the MapExtension extension is supported?
534 // see QAbstractFileEngine::supportsExtension() and
535 // QAbstractFileEngine::MapExtension)
536 QFile qf(fi.filePath());
537 if (!qf.open(QIODevice::ReadOnly))
539 qint64 size = fi.size();
540 uchar * ubeg = qf.map(0, size);
541 uchar * uend = ubeg + size;
542 boost::crc_32_type ucrc;
543 ucrc.process_block(ubeg, uend);
546 result = ucrc.checksum();
550 string const encoded = toSafeFilesystemEncoding();
551 char const * file = encoded.c_str();
554 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
556 int fd = open(file, O_RDONLY);
561 if (fstat(fd, &info)){
562 // fstat fails on samba shares (bug 5891)
564 return checksum_ifstream_fallback(file);
567 void * mm = mmap(0, info.st_size, PROT_READ,
569 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
570 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
575 char * beg = static_cast<char*>(mm);
576 char * end = beg + info.st_size;
578 boost::crc_32_type crc;
579 crc.process_block(beg, end);
580 result = crc.checksum();
582 munmap(mm, info.st_size);
585 #else // no SUM_WITH_MMAP
586 result = checksum_ifstream_fallback(file);
587 #endif // SUM_WITH_MMAP
590 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
591 << result << " lasted " << t.elapsed() << " ms.");
596 bool FileName::removeFile() const
598 bool const success = QFile::remove(d->fi.absoluteFilePath());
600 if (!success && exists())
601 LYXERR0("Could not delete file " << *this);
606 static bool rmdir(QFileInfo const & fi)
608 QDir dir(fi.absoluteFilePath());
609 QFileInfoList list = dir.entryInfoList();
611 for (int i = 0; i != list.size(); ++i) {
612 if (list.at(i).fileName() == ".")
614 if (list.at(i).fileName() == "..")
617 if (list.at(i).isDir()) {
618 LYXERR(Debug::FILES, "Removing dir "
619 << fromqstr(list.at(i).absoluteFilePath()));
620 removed = rmdir(list.at(i));
623 LYXERR(Debug::FILES, "Removing file "
624 << fromqstr(list.at(i).absoluteFilePath()));
625 removed = dir.remove(list.at(i).fileName());
629 LYXERR0("Could not delete "
630 << fromqstr(list.at(i).absoluteFilePath()));
633 QDir parent = fi.absolutePath();
634 success &= parent.rmdir(fi.fileName());
639 bool FileName::destroyDirectory() const
641 bool const success = rmdir(d->fi);
643 LYXERR0("Could not delete " << *this);
649 // Only used in non Win32 platforms
650 static int mymkdir(char const * pathname, unsigned long int mode)
652 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
654 # if MKDIR_TAKES_ONE_ARG
656 return ::mkdir(pathname);
657 // FIXME: "Permissions of created directories are ignored on this system."
660 return ::mkdir(pathname, mode_t(mode));
662 #elif defined(_WIN32)
664 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
665 // FIXME: "Permissions of created directories are ignored on this system."
667 return ::_mkdir(pathname);
668 // FIXME: "Permissions of created directories are ignored on this system."
670 # error "Don't know how to create a directory on this system."
676 bool FileName::createDirectory(int permission) const
678 LASSERT(!empty(), return false);
680 // FIXME: "Permissions of created directories are ignored on this system."
683 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
688 bool FileName::createPath() const
690 LASSERT(!empty(), return false);
691 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
696 bool success = dir.mkpath(d->fi.absoluteFilePath());
698 LYXERR0("Cannot create path '" << *this << "'!");
703 docstring const FileName::absoluteFilePath() const
705 return qstring_to_ucs4(d->fi.absoluteFilePath());
709 docstring FileName::displayName(int threshold) const
711 return makeDisplayPath(absFileName(), threshold);
715 docstring FileName::fileContents(string const & encoding) const
717 if (!isReadableFile()) {
718 LYXERR0("File '" << *this << "' is not readable!");
722 QFile file(d->fi.absoluteFilePath());
723 if (!file.open(QIODevice::ReadOnly)) {
724 LYXERR0("File '" << *this
725 << "' could not be opened in read only mode!");
728 QByteArray contents = file.readAll();
731 if (contents.isEmpty()) {
732 LYXERR(Debug::FILES, "File '" << *this
733 << "' is either empty or some error happened while reading it.");
738 if (encoding.empty() || encoding == "UTF-8")
739 s = QString::fromUtf8(contents.data());
740 else if (encoding == "ascii")
741 #if (QT_VERSION < 0x050000)
742 s = QString::fromAscii(contents.data());
744 s = QString::fromLatin1(contents.data());
746 else if (encoding == "local8bit")
747 s = QString::fromLocal8Bit(contents.data());
748 else if (encoding == "latin1")
749 s = QString::fromLatin1(contents.data());
751 return qstring_to_ucs4(s);
755 void FileName::changeExtension(string const & extension)
757 // FIXME: use Qt native methods...
758 string const oldname = absFileName();
759 string::size_type const last_slash = oldname.rfind('/');
760 string::size_type last_dot = oldname.rfind('.');
761 if (last_dot < last_slash && last_slash != string::npos)
762 last_dot = string::npos;
765 // Make sure the extension starts with a dot
766 if (!extension.empty() && extension[0] != '.')
767 ext= '.' + extension;
771 set(oldname.substr(0, last_dot) + ext);
775 docstring const FileName::relPath(string const & path) const
778 return makeRelPath(absoluteFilePath(), from_utf8(path));
782 // Note: According to Qt, QFileInfo::operator== is undefined when
783 // both files do not exist (Qt4.5 gives true for all non-existent
784 // files, while Qt4.4 compares the filenames).
786 // http://www.qtsoftware.com/developer/task-tracker/
787 // index_html?id=248471&method=entry.
788 bool equivalent(FileName const & l, FileName const & r)
790 // FIXME: In future use Qt.
791 // Qt 4.4: We need to solve this warning from Qt documentation:
792 // * Long and short file names that refer to the same file on Windows are
793 // treated as if they referred to different files.
794 // This is supposed to be fixed for Qt5.
795 FileName const lhs(os::internal_path(l.absFileName()));
796 FileName const rhs(os::internal_path(r.absFileName()));
799 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
803 // Avoid unnecessary checks below.
809 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
810 // Qt already checks if the filesystem is case sensitive or not.
811 // see note above why the extra check with fileName is needed.
812 return lhs.d->fi == rhs.d->fi
813 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
816 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
817 QFileInfo fi1(lhs.d->fi);
819 fi1 = QFileInfo(fi1.symLinkTarget());
820 QFileInfo fi2(rhs.d->fi);
822 fi2 = QFileInfo(fi2.symLinkTarget());
823 // see note above why the extra check with fileName is needed.
824 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
828 bool operator==(FileName const & lhs, FileName const & rhs)
830 return os::isFilesystemCaseSensitive()
831 ? lhs.absFileName() == rhs.absFileName()
832 : !QString::compare(toqstr(lhs.absFileName()),
833 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
837 bool operator!=(FileName const & lhs, FileName const & rhs)
839 return !(operator==(lhs, rhs));
843 bool operator<(FileName const & lhs, FileName const & rhs)
845 return lhs.absFileName() < rhs.absFileName();
849 bool operator>(FileName const & lhs, FileName const & rhs)
851 return lhs.absFileName() > rhs.absFileName();
855 ostream & operator<<(ostream & os, FileName const & filename)
857 return os << filename.absFileName();
861 /////////////////////////////////////////////////////////////////////
865 /////////////////////////////////////////////////////////////////////
868 DocFileName::DocFileName()
869 : save_abs_path_(true)
873 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
874 : FileName(abs_filename), save_abs_path_(save_abs)
878 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
879 : FileName(abs_filename), save_abs_path_(save_abs)
883 void DocFileName::set(string const & name, string const & buffer_path)
885 save_abs_path_ = isAbsolute(name);
889 FileName::set(makeAbsPath(name, buffer_path).absFileName());
893 void DocFileName::erase()
899 string DocFileName::relFileName(string const & path) const
902 return to_utf8(relPath(path));
906 string DocFileName::outputFileName(string const & path) const
908 return save_abs_path_ ? absFileName() : relFileName(path);
912 string DocFileName::mangledFileName(string const & dir) const
914 // Concurrent access to these variables is possible.
916 // We need to make sure that every DocFileName instance for a given
917 // filename returns the same mangled name.
918 typedef map<string, string> MangledMap;
919 static MangledMap mangledNames;
920 static Mutex mangledMutex;
921 // this locks both access to mangledNames and counter below
922 Mutex::Locker lock(&mangledMutex);
923 MangledMap::const_iterator const it = mangledNames.find(absFileName());
924 if (it != mangledNames.end())
927 string const name = absFileName();
929 string mname = os::internal_path(name);
930 // Remove the extension.
931 mname = support::changeExtension(name, string());
932 // The mangled name must be a valid LaTeX name.
933 // The list of characters to keep is probably over-restrictive,
934 // but it is not really a problem.
935 // Apart from non-ASCII characters, at least the following characters
936 // are forbidden: '/', '.', ' ', and ':'.
937 // On windows it is not possible to create files with '<', '>' or '?'
939 static string const keep = "abcdefghijklmnopqrstuvwxyz"
940 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
942 string::size_type pos = 0;
943 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
945 // Add the extension back on
946 mname = support::changeExtension(mname, getExtension(name));
948 // Prepend a counter to the filename. This is necessary to make
949 // the mangled name unique.
950 static int counter = 0;
952 s << counter++ << mname;
955 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
956 // is longer than about 160 characters. MiKTeX's pdflatex
957 // is even pickier. A maximum length of 100 has been proven to work.
958 // If dir.size() > max length, all bets are off for YAP. We truncate
959 // the filename nevertheless, keeping a minimum of 10 chars.
961 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
963 // If the mangled file name is too long, hack it to fit.
964 // We know we're guaranteed to have a unique file name because
966 if (mname.size() > max_length) {
967 int const half = (int(max_length) / 2) - 2;
969 mname = mname.substr(0, half) + "___" +
970 mname.substr(mname.size() - half);
974 mangledNames[absFileName()] = mname;
979 string DocFileName::unzippedFileName() const
981 return support::unzippedFileName(absFileName());
985 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
987 return static_cast<FileName const &>(lhs)
988 == static_cast<FileName const &>(rhs)
989 && lhs.saveAbsPath() == rhs.saveAbsPath();
993 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
995 return !(lhs == rhs);
998 } // namespace support