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/qstring_helpers.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) const
222 LYXERR(Debug::FILES, "Copying " << name);
223 QFile::remove(name.d->fi.absoluteFilePath());
224 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
226 LYXERR0("FileName::copyTo(): Could not copy file "
227 << *this << " to " << name);
232 bool FileName::renameTo(FileName const & name) const
234 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
236 LYXERR0("Could not rename file " << *this << " to " << name);
241 bool FileName::moveTo(FileName const & name) const
243 QFile::remove(name.d->fi.absoluteFilePath());
245 bool success = QFile::rename(d->fi.absoluteFilePath(),
246 name.d->fi.absoluteFilePath());
248 LYXERR0("Could not move file " << *this << " to " << name);
253 bool FileName::changePermission(unsigned long int mode) const
255 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
256 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
257 LYXERR0("File " << *this << ": cannot change permission to "
266 string FileName::toFilesystemEncoding() const
268 // This doesn't work on Windows for non ascii file names.
269 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
270 return string(encoded.begin(), encoded.end());
274 string FileName::toSafeFilesystemEncoding(os::file_access how) const
276 // This will work on Windows for non ascii file names.
277 QString const safe_path =
278 toqstr(os::safe_internal_path(absFileName(), how));
279 QByteArray const encoded = QFile::encodeName(safe_path);
280 return string(encoded.begin(), encoded.end());
284 FileName FileName::fromFilesystemEncoding(string const & name)
286 QByteArray const encoded(name.c_str(), name.length());
287 return FileName(fromqstr(QFile::decodeName(encoded)));
291 bool FileName::exists() const
293 return !empty() && d->fi.exists();
297 bool FileName::isSymLink() const
299 return !empty() && d->fi.isSymLink();
303 bool FileName::isFileEmpty() const
305 LASSERT(!empty(), return true);
306 return d->fi.size() == 0;
310 bool FileName::isDirectory() const
312 return !empty() && d->fi.isDir();
316 bool FileName::isReadOnly() const
318 LASSERT(!empty(), return true);
319 return d->fi.isReadable() && !d->fi.isWritable();
323 bool FileName::isReadableDirectory() const
325 return isDirectory() && d->fi.isReadable();
329 string FileName::onlyFileName() const
331 return fromqstr(d->fi.fileName());
335 string FileName::onlyFileNameWithoutExt() const
337 return fromqstr(d->fi.completeBaseName());
341 string FileName::extension() const
343 return fromqstr(d->fi.suffix());
347 bool FileName::hasExtension(const string & ext)
349 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
353 FileName FileName::onlyPath() const
358 path.d->fi.setFile(d->fi.path());
359 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
364 FileName FileName::parentPath() const
367 // return empty path for parent of root dir
368 // parent of empty path is empty too
369 if (empty() || d->fi.isRoot())
371 path.d->fi.setFile(d->fi.path());
372 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
377 bool FileName::isReadableFile() const
379 return !empty() && d->fi.isFile() && d->fi.isReadable();
383 bool FileName::isWritable() const
385 return !empty() && d->fi.isWritable();
389 bool FileName::isDirWritable() const
391 LASSERT(isDirectory(), return false);
392 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
393 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
395 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
398 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
403 FileNameList FileName::dirList(string const & ext) const
405 FileNameList dirlist;
406 if (!isDirectory()) {
407 LYXERR0("Directory '" << *this << "' does not exist!");
411 // If the directory is specified without a trailing '/', absoluteDir()
412 // would return the parent dir, so we must use absoluteFilePath() here.
413 QDir dir = d->fi.absoluteFilePath();
418 case '.': filter = "*" + toqstr(ext); break;
419 case '*': filter = toqstr(ext); break;
420 default: filter = "*." + toqstr(ext);
422 dir.setNameFilters(QStringList(filter));
423 LYXERR(Debug::FILES, "filtering on extension "
424 << fromqstr(filter) << " is requested.");
427 QFileInfoList list = dir.entryInfoList();
428 for (int i = 0; i != list.size(); ++i) {
429 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
430 dirlist.push_back(fi);
431 LYXERR(Debug::FILES, "found file " << fi);
438 static string createTempFile(QString const & mask)
440 // FIXME: This is not safe. QTemporaryFile creates a file in open(),
441 // but the file is deleted when qt_tmp goes out of scope.
442 // Therefore the next call to createTempFile() may create the
443 // same file again. To make this safe the QTemporaryFile object
444 // needs to be kept for the whole life time of the temp file name.
445 // This can be achieved by using the TempFile class.
446 QTemporaryFile qt_tmp(mask + ".XXXXXXXXXXXX");
448 string const temp_file = fromqstr(qt_tmp.fileName());
449 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
452 LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
453 << qt_tmp.fileTemplate());
458 FileName FileName::tempName(FileName const & temp_dir, string const & mask)
460 QFileInfo tmp_fi(QDir(temp_dir.d->fi.absoluteFilePath()), toqstr(mask));
461 LYXERR(Debug::FILES, "Temporary file in " << tmp_fi.absoluteFilePath());
462 return FileName(createTempFile(tmp_fi.absoluteFilePath()));
466 FileName FileName::tempName(string const & mask)
468 return tempName(package().temp_dir(), mask);
472 FileName FileName::getcwd()
474 // return makeAbsPath("."); would create an infinite loop
476 return FileName(fromqstr(fi.absoluteFilePath()));
480 FileName FileName::tempPath()
482 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
486 void FileName::refresh() const
492 time_t FileName::lastModified() const
494 // QFileInfo caches information about the file. So, in case this file has
495 // been touched between the object creation and now, we refresh the file
498 return d->fi.lastModified().toTime_t();
502 bool FileName::chdir() const
504 return QDir::setCurrent(d->fi.absoluteFilePath());
508 unsigned long checksum_ifstream_fallback(char const * file)
510 unsigned long result = 0;
511 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
512 ifstream ifs(file, ios_base::in | ios_base::binary);
516 istreambuf_iterator<char> beg(ifs);
517 istreambuf_iterator<char> end;
518 boost::crc_32_type crc;
519 crc = for_each(beg, end, crc);
520 result = crc.checksum();
524 unsigned long FileName::checksum() const
526 unsigned long result = 0;
529 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
532 // a directory may be passed here so we need to test it. (bug 3622)
534 LYXERR0('"' << absFileName() << "\" is a directory!");
538 // This is used in the debug output at the end of the method.
540 if (lyxerr.debugging(Debug::FILES))
543 #if QT_VERSION >= 0x999999
544 // First version of checksum uses Qt4.4 mmap support.
545 // FIXME: This code is not ready with Qt4.4.2,
546 // see http://www.lyx.org/trac/ticket/5293
547 // FIXME: should we check if the MapExtension extension is supported?
548 // see QAbstractFileEngine::supportsExtension() and
549 // QAbstractFileEngine::MapExtension)
550 QFile qf(fi.filePath());
551 if (!qf.open(QIODevice::ReadOnly))
553 qint64 size = fi.size();
554 uchar * ubeg = qf.map(0, size);
555 uchar * uend = ubeg + size;
556 boost::crc_32_type ucrc;
557 ucrc.process_block(ubeg, uend);
560 result = ucrc.checksum();
564 string const encoded = toSafeFilesystemEncoding();
565 char const * file = encoded.c_str();
568 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
570 int fd = open(file, O_RDONLY);
575 if (fstat(fd, &info)){
576 // fstat fails on samba shares (bug 5891)
578 return checksum_ifstream_fallback(file);
581 void * mm = mmap(0, info.st_size, PROT_READ,
583 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
584 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
589 char * beg = static_cast<char*>(mm);
590 char * end = beg + info.st_size;
592 boost::crc_32_type crc;
593 crc.process_block(beg, end);
594 result = crc.checksum();
596 munmap(mm, info.st_size);
599 #else // no SUM_WITH_MMAP
600 result = checksum_ifstream_fallback(file);
601 #endif // SUM_WITH_MMAP
604 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
605 << result << " lasted " << t.elapsed() << " ms.");
610 bool FileName::removeFile() const
612 bool const success = QFile::remove(d->fi.absoluteFilePath());
614 if (!success && exists())
615 LYXERR0("Could not delete file " << *this);
620 static bool rmdir(QFileInfo const & fi)
622 QDir dir(fi.absoluteFilePath());
623 QFileInfoList list = dir.entryInfoList();
625 for (int i = 0; i != list.size(); ++i) {
626 if (list.at(i).fileName() == ".")
628 if (list.at(i).fileName() == "..")
631 if (list.at(i).isDir()) {
632 LYXERR(Debug::FILES, "Removing dir "
633 << fromqstr(list.at(i).absoluteFilePath()));
634 removed = rmdir(list.at(i));
637 LYXERR(Debug::FILES, "Removing file "
638 << fromqstr(list.at(i).absoluteFilePath()));
639 removed = dir.remove(list.at(i).fileName());
643 LYXERR0("Could not delete "
644 << fromqstr(list.at(i).absoluteFilePath()));
647 QDir parent = fi.absolutePath();
648 success &= parent.rmdir(fi.fileName());
653 bool FileName::destroyDirectory() const
655 bool const success = rmdir(d->fi);
657 LYXERR0("Could not delete " << *this);
663 // Only used in non Win32 platforms
664 static int mymkdir(char const * pathname, unsigned long int mode)
666 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
668 # if MKDIR_TAKES_ONE_ARG
670 return ::mkdir(pathname);
671 // FIXME: "Permissions of created directories are ignored on this system."
674 return ::mkdir(pathname, mode_t(mode));
676 #elif defined(_WIN32)
678 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
679 // FIXME: "Permissions of created directories are ignored on this system."
681 return ::_mkdir(pathname);
682 // FIXME: "Permissions of created directories are ignored on this system."
684 # error "Don't know how to create a directory on this system."
690 bool FileName::createDirectory(int permission) const
692 LASSERT(!empty(), return false);
694 // FIXME: "Permissions of created directories are ignored on this system."
697 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
702 bool FileName::createPath() const
704 LASSERT(!empty(), return false);
705 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
710 bool success = dir.mkpath(d->fi.absoluteFilePath());
712 LYXERR0("Cannot create path '" << *this << "'!");
717 docstring const FileName::absoluteFilePath() const
719 return qstring_to_ucs4(d->fi.absoluteFilePath());
723 docstring FileName::displayName(int threshold) const
725 return makeDisplayPath(absFileName(), threshold);
729 docstring FileName::fileContents(string const & encoding) const
731 if (!isReadableFile()) {
732 LYXERR0("File '" << *this << "' is not readable!");
736 QFile file(d->fi.absoluteFilePath());
737 if (!file.open(QIODevice::ReadOnly)) {
738 LYXERR0("File '" << *this
739 << "' could not be opened in read only mode!");
742 QByteArray contents = file.readAll();
745 if (contents.isEmpty()) {
746 LYXERR(Debug::FILES, "File '" << *this
747 << "' is either empty or some error happened while reading it.");
752 if (encoding.empty() || encoding == "UTF-8")
753 s = QString::fromUtf8(contents.data());
754 else if (encoding == "ascii")
755 #if (QT_VERSION < 0x050000)
756 s = QString::fromAscii(contents.data());
758 s = QString::fromLatin1(contents.data());
760 else if (encoding == "local8bit")
761 s = QString::fromLocal8Bit(contents.data());
762 else if (encoding == "latin1")
763 s = QString::fromLatin1(contents.data());
765 return qstring_to_ucs4(s);
769 void FileName::changeExtension(string const & extension)
771 // FIXME: use Qt native methods...
772 string const oldname = absFileName();
773 string::size_type const last_slash = oldname.rfind('/');
774 string::size_type last_dot = oldname.rfind('.');
775 if (last_dot < last_slash && last_slash != string::npos)
776 last_dot = string::npos;
779 // Make sure the extension starts with a dot
780 if (!extension.empty() && extension[0] != '.')
781 ext= '.' + extension;
785 set(oldname.substr(0, last_dot) + ext);
789 docstring const FileName::relPath(string const & path) const
792 return makeRelPath(absoluteFilePath(), from_utf8(path));
796 // Note: According to Qt, QFileInfo::operator== is undefined when
797 // both files do not exist (Qt4.5 gives true for all non-existent
798 // files, while Qt4.4 compares the filenames).
800 // http://www.qtsoftware.com/developer/task-tracker/
801 // index_html?id=248471&method=entry.
802 bool equivalent(FileName const & l, FileName const & r)
804 // FIXME: In future use Qt.
805 // Qt 4.4: We need to solve this warning from Qt documentation:
806 // * Long and short file names that refer to the same file on Windows are
807 // treated as if they referred to different files.
808 // This is supposed to be fixed for Qt5.
809 FileName const lhs(os::internal_path(l.absFileName()));
810 FileName const rhs(os::internal_path(r.absFileName()));
813 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
817 // Avoid unnecessary checks below.
823 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
824 // Qt already checks if the filesystem is case sensitive or not.
825 // see note above why the extra check with fileName is needed.
826 return lhs.d->fi == rhs.d->fi
827 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
830 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
831 QFileInfo fi1(lhs.d->fi);
833 fi1 = QFileInfo(fi1.symLinkTarget());
834 QFileInfo fi2(rhs.d->fi);
836 fi2 = QFileInfo(fi2.symLinkTarget());
837 // see note above why the extra check with fileName is needed.
838 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
842 bool operator==(FileName const & lhs, FileName const & rhs)
844 return os::isFilesystemCaseSensitive()
845 ? lhs.absFileName() == rhs.absFileName()
846 : !QString::compare(toqstr(lhs.absFileName()),
847 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
851 bool operator!=(FileName const & lhs, FileName const & rhs)
853 return !(operator==(lhs, rhs));
857 bool operator<(FileName const & lhs, FileName const & rhs)
859 return lhs.absFileName() < rhs.absFileName();
863 bool operator>(FileName const & lhs, FileName const & rhs)
865 return lhs.absFileName() > rhs.absFileName();
869 ostream & operator<<(ostream & os, FileName const & filename)
871 return os << filename.absFileName();
875 /////////////////////////////////////////////////////////////////////
879 /////////////////////////////////////////////////////////////////////
882 DocFileName::DocFileName()
883 : save_abs_path_(true)
887 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
888 : FileName(abs_filename), save_abs_path_(save_abs)
892 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
893 : FileName(abs_filename), save_abs_path_(save_abs)
897 void DocFileName::set(string const & name, string const & buffer_path)
899 save_abs_path_ = isAbsolute(name);
903 FileName::set(makeAbsPath(name, buffer_path).absFileName());
907 void DocFileName::erase()
913 string DocFileName::relFileName(string const & path) const
916 return to_utf8(relPath(path));
920 string DocFileName::outputFileName(string const & path) const
922 return save_abs_path_ ? absFileName() : relFileName(path);
926 string DocFileName::mangledFileName(string const & dir) const
929 // Concurrent access to these variables is possible.
931 // We need to make sure that every DocFileName instance for a given
932 // filename returns the same mangled name.
933 typedef map<string, string> MangledMap;
934 static MangledMap mangledNames;
935 MangledMap::const_iterator const it = mangledNames.find(absFileName());
936 if (it != mangledNames.end())
939 string const name = absFileName();
941 string mname = os::internal_path(name);
942 // Remove the extension.
943 mname = support::changeExtension(name, string());
944 // The mangled name must be a valid LaTeX name.
945 // The list of characters to keep is probably over-restrictive,
946 // but it is not really a problem.
947 // Apart from non-ASCII characters, at least the following characters
948 // are forbidden: '/', '.', ' ', and ':'.
949 // On windows it is not possible to create files with '<', '>' or '?'
951 static string const keep = "abcdefghijklmnopqrstuvwxyz"
952 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
954 string::size_type pos = 0;
955 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
957 // Add the extension back on
958 mname = support::changeExtension(mname, getExtension(name));
961 // Prepend a counter to the filename. This is necessary to make
962 // the mangled name unique.
963 static int counter = 0;
965 s << counter++ << mname;
968 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
969 // is longer than about 160 characters. MiKTeX's pdflatex
970 // is even pickier. A maximum length of 100 has been proven to work.
971 // If dir.size() > max length, all bets are off for YAP. We truncate
972 // the filename nevertheless, keeping a minimum of 10 chars.
974 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
976 // If the mangled file name is too long, hack it to fit.
977 // We know we're guaranteed to have a unique file name because
979 if (mname.size() > max_length) {
980 int const half = (int(max_length) / 2) - 2;
982 mname = mname.substr(0, half) + "___" +
983 mname.substr(mname.size() - half);
987 mangledNames[absFileName()] = mname;
992 string DocFileName::unzippedFileName() const
994 return support::unzippedFileName(absFileName());
998 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1000 return static_cast<FileName const &>(lhs)
1001 == static_cast<FileName const &>(rhs)
1002 && lhs.saveAbsPath() == rhs.saveAbsPath();
1006 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1008 return !(lhs == rhs);
1011 } // namespace support