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/convert.h"
17 #include "support/debug.h"
18 #include "support/filetools.h"
19 #include "support/lassert.h"
20 #include "support/lstrings.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 #if defined(HAVE_MKSTEMP) && ! defined(HAVE_DECL_MKSTEMP)
64 extern "C" int mkstemp(char *);
67 #if !defined(HAVE_MKSTEMP) && defined(HAVE_MKTEMP)
71 # ifdef HAVE_PROCESS_H
76 // Three implementations of checksum(), depending on having mmap support or not.
77 #if defined(HAVE_MMAP) && defined(HAVE_MUNMAP)
80 #endif // SUM_WITH_MMAP
84 // OK, this is ugly, but it is the only workaround I found to compile
85 // with gcc (any version) on a system which uses a non-GNU toolchain.
86 // The problem is that gcc uses a weak symbol for a particular
87 // instantiation and that the system linker usually does not
88 // understand those weak symbols (seen on HP-UX, tru64, AIX and
89 // others). Thus we force an explicit instanciation of this particular
91 template struct boost::detail::crc_table_t<32, 0x04C11DB7, true>;
96 /////////////////////////////////////////////////////////////////////
100 /////////////////////////////////////////////////////////////////////
102 struct FileName::Private
106 Private(string const & abs_filename) : fi(toqstr(abs_filename))
108 fi.setCaching(fi.exists() ? true : false);
111 inline void refresh()
113 // There seems to be a bug in Qt >= 4.2.0, at least, that causes problems with
114 // QFileInfo::refresh() on *nix. So we recreate the object in that case.
115 // FIXME: When Trolltech fixes the bug, we will have to replace 0x999999 below
116 // with the actual working minimum version.
117 #if defined(_WIN32) || (QT_VERSION >= 0x999999)
120 fi = QFileInfo(fi.absoluteFilePath());
124 unsigned long checksum();
130 unsigned long FileName::Private::checksum()
132 #if QT_VERSION >= 0x040400
133 // First version of checksum uses Qt4.4 mmap support.
134 // FIXME: should we check if the MapExtension extension is supported?
135 // see QAbstractFileEngine::supportsExtension() and
136 // QAbstractFileEngine::MapExtension)
137 QFile qf(fi.filePath());
138 if (!qf.open(QIODevice::ReadOnly))
140 qint64 size = fi.size();
141 uchar * ubeg = qf.map(0, size);
142 uchar * uend = ubeg + size;
143 boost::crc_32_type ucrc;
144 ucrc.process_block(ubeg, uend);
145 return ucrc.checksum();
148 //FIXME: This doesn't work on Windows for non ascii file names. Provided that
149 // Windows package uses Qt4.4, this isn't a problem.
150 QByteArray const encoded = QFile::encodeName(fi.absoluteFilePath());
151 char const * file = encoded.constData();
154 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
156 int fd = open(file, O_RDONLY);
163 void * mm = mmap(0, info.st_size, PROT_READ,
165 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
166 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
171 char * beg = static_cast<char*>(mm);
172 char * end = beg + info.st_size;
174 boost::crc_32_type crc;
175 crc.process_block(beg, end);
176 unsigned long result = crc.checksum();
178 munmap(mm, info.st_size);
183 #else // no SUM_WITH_MMAP
185 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
186 ifstream ifs(file, ios_base::in | ios_base::binary);
190 istreambuf_iterator<char> beg(ifs);
191 istreambuf_iterator<char> end;
192 boost::crc_32_type crc;
193 crc = for_each(beg, end, crc);
194 return crc.checksum();
196 #endif // SUM_WITH_MMAP
199 /////////////////////////////////////////////////////////////////////
203 /////////////////////////////////////////////////////////////////////
206 FileName::FileName() : d(new Private)
211 FileName::FileName(string const & abs_filename)
212 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
217 FileName::~FileName()
223 FileName::FileName(FileName const & rhs) : d(new Private)
229 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
235 FileName & FileName::operator=(FileName const & rhs)
242 bool FileName::empty() const
244 return d->fi.absoluteFilePath().isEmpty();
248 bool FileName::isAbsolute() const
250 return d->fi.isAbsolute();
254 string FileName::absFilename() const
256 return fromqstr(d->fi.absoluteFilePath());
260 void FileName::set(string const & name)
262 d->fi.setFile(toqstr(name));
266 void FileName::set(FileName const & rhs, string const & suffix)
268 if (!rhs.d->fi.isDir())
269 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
271 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
275 void FileName::erase()
281 bool FileName::copyTo(FileName const & name) const
283 LYXERR(Debug::FILES, "Copying " << name);
284 QFile::remove(name.d->fi.absoluteFilePath());
285 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
287 LYXERR0("FileName::copyTo(): Could not copy file "
288 << *this << " to " << name);
293 bool FileName::renameTo(FileName const & name) const
295 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
297 LYXERR0("Could not rename file " << *this << " to " << name);
302 bool FileName::moveTo(FileName const & name) const
304 QFile::remove(name.d->fi.absoluteFilePath());
306 bool success = QFile::rename(d->fi.absoluteFilePath(),
307 name.d->fi.absoluteFilePath());
309 LYXERR0("Could not move file " << *this << " to " << name);
314 bool FileName::changePermission(unsigned long int mode) const
316 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
317 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
318 LYXERR0("File " << *this << ": cannot change permission to "
327 string FileName::toFilesystemEncoding() const
329 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
330 return string(encoded.begin(), encoded.end());
334 FileName FileName::fromFilesystemEncoding(string const & name)
336 QByteArray const encoded(name.c_str(), name.length());
337 return FileName(fromqstr(QFile::decodeName(encoded)));
341 bool FileName::exists() const
343 return d->fi.exists();
347 bool FileName::isSymLink() const
349 return d->fi.isSymLink();
353 bool FileName::isFileEmpty() const
355 return d->fi.size() == 0;
359 bool FileName::isDirectory() const
361 return d->fi.isDir();
365 bool FileName::isReadOnly() const
367 return d->fi.isReadable() && !d->fi.isWritable();
371 bool FileName::isReadableDirectory() const
373 return d->fi.isDir() && d->fi.isReadable();
377 string FileName::onlyFileName() const
379 return fromqstr(d->fi.fileName());
383 string FileName::onlyFileNameWithoutExt() const
385 return fromqstr(d->fi.baseName());
389 string FileName::extension() const
391 return fromqstr(d->fi.suffix());
395 FileName FileName::onlyPath() const
398 path.d->fi.setFile(d->fi.path());
403 bool FileName::isReadableFile() const
405 return d->fi.isFile() && d->fi.isReadable();
409 bool FileName::isWritable() const
411 return d->fi.isWritable();
415 bool FileName::isDirWritable() const
417 LASSERT(d->fi.isDir(), return false);
418 QFileInfo tmp(d->fi.absoluteDir(), "lyxwritetest");
419 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
421 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
424 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
429 FileNameList FileName::dirList(string const & ext) const
431 FileNameList dirlist;
432 if (!isDirectory()) {
433 LYXERR0("Directory '" << *this << "' does not exist!");
437 QDir dir = d->fi.absoluteDir();
442 case '.': filter = "*" + toqstr(ext); break;
443 case '*': filter = toqstr(ext); break;
444 default: filter = "*." + toqstr(ext);
446 dir.setNameFilters(QStringList(filter));
447 LYXERR(Debug::FILES, "filtering on extension "
448 << fromqstr(filter) << " is requested.");
451 QFileInfoList list = dir.entryInfoList();
452 for (int i = 0; i != list.size(); ++i) {
453 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
454 dirlist.push_back(fi);
455 LYXERR(Debug::FILES, "found file " << fi);
462 static string createTempFile(QString const & mask)
464 QTemporaryFile qt_tmp(mask);
466 string const temp_file = fromqstr(qt_tmp.fileName());
467 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
470 LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
471 << qt_tmp.fileTemplate());
476 FileName FileName::tempName(FileName const & temp_dir, string const & mask)
478 QFileInfo tmp_fi(QDir(temp_dir.d->fi.absoluteFilePath()), toqstr(mask));
479 LYXERR(Debug::FILES, "Temporary file in " << tmp_fi.absoluteFilePath());
480 return FileName(createTempFile(tmp_fi.absoluteFilePath()));
484 FileName FileName::tempName(string const & mask)
486 return tempName(package().temp_dir(), mask);
490 FileName FileName::getcwd()
492 return FileName(".");
496 FileName FileName::tempPath()
498 return FileName(fromqstr(QDir::tempPath()));
502 time_t FileName::lastModified() const
504 // QFileInfo caches information about the file. So, in case this file has
505 // been touched between the object creation and now, we refresh the file
508 return d->fi.lastModified().toTime_t();
512 bool FileName::chdir() const
514 return QDir::setCurrent(d->fi.absoluteFilePath());
518 unsigned long FileName::checksum() const
521 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
524 // a directory may be passed here so we need to test it. (bug 3622)
526 LYXERR0('"' << absFilename() << "\" is a directory!");
529 if (!lyxerr.debugging(Debug::FILES))
530 return d->checksum();
534 unsigned long r = d->checksum();
535 lyxerr << "Checksumming \"" << absFilename() << "\" "
536 << r << " lasted " << t.elapsed() << " ms." << endl;
541 bool FileName::removeFile() const
543 bool const success = QFile::remove(d->fi.absoluteFilePath());
544 if (!success && exists())
545 LYXERR0("Could not delete file " << *this);
550 static bool rmdir(QFileInfo const & fi)
552 QDir dir(fi.absoluteFilePath());
553 QFileInfoList list = dir.entryInfoList();
555 for (int i = 0; i != list.size(); ++i) {
556 if (list.at(i).fileName() == ".")
558 if (list.at(i).fileName() == "..")
561 if (list.at(i).isDir()) {
562 LYXERR(Debug::FILES, "Removing dir "
563 << fromqstr(list.at(i).absoluteFilePath()));
564 removed = rmdir(list.at(i));
567 LYXERR(Debug::FILES, "Removing file "
568 << fromqstr(list.at(i).absoluteFilePath()));
569 removed = dir.remove(list.at(i).fileName());
573 LYXERR0("Could not delete "
574 << fromqstr(list.at(i).absoluteFilePath()));
577 QDir parent = fi.absolutePath();
578 success &= parent.rmdir(fi.fileName());
583 bool FileName::destroyDirectory() const
585 bool const success = rmdir(d->fi);
587 LYXERR0("Could not delete " << *this);
593 static int mymkdir(char const * pathname, unsigned long int mode)
595 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
597 # if MKDIR_TAKES_ONE_ARG
599 return ::mkdir(pathname);
600 // FIXME: "Permissions of created directories are ignored on this system."
603 return ::mkdir(pathname, mode_t(mode));
605 #elif defined(_WIN32)
607 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
608 // FIXME: "Permissions of created directories are ignored on this system."
610 return ::_mkdir(pathname);
611 // FIXME: "Permissions of created directories are ignored on this system."
613 # error "Don't know how to create a directory on this system."
619 bool FileName::createDirectory(int permission) const
621 LASSERT(!empty(), /**/);
622 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
626 bool FileName::createPath() const
628 LASSERT(!empty(), /**/);
633 bool success = dir.mkpath(d->fi.absoluteFilePath());
635 LYXERR0("Cannot create path '" << *this << "'!");
640 docstring const FileName::absoluteFilePath() const
642 return qstring_to_ucs4(d->fi.absoluteFilePath());
646 docstring FileName::displayName(int threshold) const
648 return makeDisplayPath(absFilename(), threshold);
652 docstring FileName::fileContents(string const & encoding) const
654 if (!isReadableFile()) {
655 LYXERR0("File '" << *this << "' is not redable!");
659 QFile file(d->fi.absoluteFilePath());
660 if (!file.open(QIODevice::ReadOnly)) {
661 LYXERR0("File '" << *this
662 << "' could not be opened in read only mode!");
665 QByteArray contents = file.readAll();
668 if (contents.isEmpty()) {
669 LYXERR(Debug::FILES, "File '" << *this
670 << "' is either empty or some error happened while reading it.");
675 if (encoding.empty() || encoding == "UTF-8")
676 s = QString::fromUtf8(contents.data());
677 else if (encoding == "ascii")
678 s = QString::fromAscii(contents.data());
679 else if (encoding == "local8bit")
680 s = QString::fromLocal8Bit(contents.data());
681 else if (encoding == "latin1")
682 s = QString::fromLatin1(contents.data());
684 return qstring_to_ucs4(s);
688 void FileName::changeExtension(string const & extension)
690 // FIXME: use Qt native methods...
691 string const oldname = absFilename();
692 string::size_type const last_slash = oldname.rfind('/');
693 string::size_type last_dot = oldname.rfind('.');
694 if (last_dot < last_slash && last_slash != string::npos)
695 last_dot = string::npos;
698 // Make sure the extension starts with a dot
699 if (!extension.empty() && extension[0] != '.')
700 ext= '.' + extension;
704 set(oldname.substr(0, last_dot) + ext);
708 string FileName::guessFormatFromContents() const
710 // the different filetypes and what they contain in one of the first lines
711 // (dots are any characters). (Herbert 20020131)
714 // EPS %!PS-Adobe-3.0 EPSF...
721 // PBM P1... or P4 (B/W)
722 // PGM P2... or P5 (Grayscale)
723 // PPM P3... or P6 (color)
724 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
725 // SGI \001\332... (decimal 474)
727 // TIFF II... or MM...
729 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
730 // ...static char *...
731 // XWD \000\000\000\151 (0x00006900) decimal 105
733 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
734 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
735 // Z \037\235 UNIX compress
738 if (empty() || !isReadableFile())
741 ifstream ifs(toFilesystemEncoding().c_str());
743 // Couldn't open file...
747 static string const gzipStamp = "\037\213";
750 static string const zipStamp = "PK";
753 static string const compressStamp = "\037\235";
755 // Maximum strings to read
756 int const max_count = 50;
761 bool firstLine = true;
762 while ((count++ < max_count) && format.empty()) {
764 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
765 << "\tFile type not recognised before EOF!");
770 string const stamp = str.substr(0, 2);
771 if (firstLine && str.size() >= 2) {
772 // at first we check for a zipped file, because this
773 // information is saved in the first bytes of the file!
774 // also some graphic formats which save the information
775 // in the first line, too.
776 if (prefixIs(str, gzipStamp)) {
779 } else if (stamp == zipStamp) {
782 } else if (stamp == compressStamp) {
786 } else if (stamp == "BM") {
789 } else if (stamp == "\001\332") {
793 // Don't need to use str.at(0), str.at(1) because
794 // we already know that str.size() >= 2
795 } else if (str[0] == 'P') {
811 } else if ((stamp == "II") || (stamp == "MM")) {
814 } else if (prefixIs(str,"%TGIF")) {
817 } else if (prefixIs(str,"#FIG")) {
820 } else if (prefixIs(str,"GIF")) {
823 } else if (str.size() > 3) {
824 int const c = ((str[0] << 24) & (str[1] << 16) &
825 (str[2] << 8) & str[3]);
836 else if (contains(str,"EPSF"))
837 // dummy, if we have wrong file description like
838 // %!PS-Adobe-2.0EPSF"
841 else if (contains(str, "Grace"))
844 else if (contains(str, "JFIF"))
847 else if (contains(str, "%PDF"))
850 else if (contains(str, "PNG"))
853 else if (contains(str, "%!PS-Adobe")) {
856 if (contains(str,"EPSF"))
862 else if (contains(str, "_bits[]"))
865 else if (contains(str, "XPM") || contains(str, "static char *"))
868 else if (contains(str, "BITPIX"))
872 if (!format.empty()) {
873 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
877 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
878 << "\tCouldn't find a known format!");
883 bool FileName::isZippedFile() const
885 string const type = guessFormatFromContents();
886 return contains("gzip zip compress", type) && !type.empty();
890 docstring const FileName::relPath(string const & path) const
893 return makeRelPath(absoluteFilePath(), from_utf8(path));
897 bool operator==(FileName const & lhs, FileName const & rhs)
899 // FIXME: We need to solve this warning from Qt documentation:
900 // * Long and short file names that refer to the same file on Windows are
901 // treated as if they referred to different files.
902 // This is supposed to be fixed for Qt5.
905 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
909 // Avoid unnecessary checks below.
915 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink())
916 return lhs.d->fi == rhs.d->fi;
918 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
919 QFileInfo fi1(lhs.d->fi);
921 fi1 = QFileInfo(fi1.symLinkTarget());
922 QFileInfo fi2(rhs.d->fi);
924 fi2 = QFileInfo(fi2.symLinkTarget());
929 bool operator!=(FileName const & lhs, FileName const & rhs)
931 return !(operator==(lhs, rhs));
935 bool operator<(FileName const & lhs, FileName const & rhs)
937 return lhs.absFilename() < rhs.absFilename();
941 bool operator>(FileName const & lhs, FileName const & rhs)
943 return lhs.absFilename() > rhs.absFilename();
947 ostream & operator<<(ostream & os, FileName const & filename)
949 return os << filename.absFilename();
953 /////////////////////////////////////////////////////////////////////
957 /////////////////////////////////////////////////////////////////////
960 DocFileName::DocFileName()
961 : save_abs_path_(true)
965 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
966 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
970 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
971 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
975 void DocFileName::set(string const & name, string const & buffer_path)
978 bool const nameIsAbsolute = isAbsolute();
979 save_abs_path_ = nameIsAbsolute;
981 FileName::set(makeAbsPath(name, buffer_path).absFilename());
982 zipped_valid_ = false;
986 void DocFileName::erase()
989 zipped_valid_ = false;
993 string DocFileName::relFilename(string const & path) const
996 return to_utf8(relPath(path));
1000 string DocFileName::outputFilename(string const & path) const
1002 return save_abs_path_ ? absFilename() : relFilename(path);
1006 string DocFileName::mangledFilename(string const & dir) const
1008 // We need to make sure that every DocFileName instance for a given
1009 // filename returns the same mangled name.
1010 typedef map<string, string> MangledMap;
1011 static MangledMap mangledNames;
1012 MangledMap::const_iterator const it = mangledNames.find(absFilename());
1013 if (it != mangledNames.end())
1014 return (*it).second;
1016 string const name = absFilename();
1017 // Now the real work
1018 string mname = os::internal_path(name);
1019 // Remove the extension.
1020 mname = support::changeExtension(name, string());
1021 // The mangled name must be a valid LaTeX name.
1022 // The list of characters to keep is probably over-restrictive,
1023 // but it is not really a problem.
1024 // Apart from non-ASCII characters, at least the following characters
1025 // are forbidden: '/', '.', ' ', and ':'.
1026 // On windows it is not possible to create files with '<', '>' or '?'
1028 static string const keep = "abcdefghijklmnopqrstuvwxyz"
1029 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1031 string::size_type pos = 0;
1032 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
1034 // Add the extension back on
1035 mname = support::changeExtension(mname, getExtension(name));
1037 // Prepend a counter to the filename. This is necessary to make
1038 // the mangled name unique.
1039 static int counter = 0;
1041 s << counter++ << mname;
1044 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
1045 // is longer than about 160 characters. MiKTeX's pdflatex
1046 // is even pickier. A maximum length of 100 has been proven to work.
1047 // If dir.size() > max length, all bets are off for YAP. We truncate
1048 // the filename nevertheless, keeping a minimum of 10 chars.
1050 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
1052 // If the mangled file name is too long, hack it to fit.
1053 // We know we're guaranteed to have a unique file name because
1055 if (mname.size() > max_length) {
1056 int const half = (int(max_length) / 2) - 2;
1058 mname = mname.substr(0, half) + "___" +
1059 mname.substr(mname.size() - half);
1063 mangledNames[absFilename()] = mname;
1068 bool DocFileName::isZipped() const
1070 if (!zipped_valid_) {
1071 zipped_ = isZippedFile();
1072 zipped_valid_ = true;
1078 string DocFileName::unzippedFilename() const
1080 return unzippedFileName(absFilename());
1084 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1086 return static_cast<FileName const &>(lhs)
1087 == static_cast<FileName const &>(rhs)
1088 && lhs.saveAbsPath() == rhs.saveAbsPath();
1092 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1094 return !(lhs == rhs);
1097 } // namespace support