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());
128 /////////////////////////////////////////////////////////////////////
132 /////////////////////////////////////////////////////////////////////
135 FileName::FileName() : d(new Private)
140 FileName::FileName(string const & abs_filename)
141 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
146 FileName::~FileName()
152 FileName::FileName(FileName const & rhs) : d(new Private)
158 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
164 FileName & FileName::operator=(FileName const & rhs)
171 bool FileName::empty() const
173 return d->fi.absoluteFilePath().isEmpty();
177 bool FileName::isAbsolute() const
179 return d->fi.isAbsolute();
183 string FileName::absFilename() const
185 return fromqstr(d->fi.absoluteFilePath());
189 void FileName::set(string const & name)
191 d->fi.setFile(toqstr(name));
195 void FileName::set(FileName const & rhs, string const & suffix)
197 if (!rhs.d->fi.isDir())
198 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
200 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
204 void FileName::erase()
210 bool FileName::copyTo(FileName const & name) const
212 LYXERR(Debug::FILES, "Copying " << name);
213 QFile::remove(name.d->fi.absoluteFilePath());
214 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
216 LYXERR0("FileName::copyTo(): Could not copy file "
217 << *this << " to " << name);
222 bool FileName::renameTo(FileName const & name) const
224 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
226 LYXERR0("Could not rename file " << *this << " to " << name);
231 bool FileName::moveTo(FileName const & name) const
233 QFile::remove(name.d->fi.absoluteFilePath());
235 bool success = QFile::rename(d->fi.absoluteFilePath(),
236 name.d->fi.absoluteFilePath());
238 LYXERR0("Could not move file " << *this << " to " << name);
243 bool FileName::changePermission(unsigned long int mode) const
245 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
246 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
247 LYXERR0("File " << *this << ": cannot change permission to "
256 string FileName::toFilesystemEncoding() const
258 // FIXME: This doesn't work on Windows for non ascii file names with Qt < 4.4.
259 // Provided that Windows package uses Qt4.4, this isn't a problem.
260 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
261 return string(encoded.begin(), encoded.end());
265 FileName FileName::fromFilesystemEncoding(string const & name)
267 QByteArray const encoded(name.c_str(), name.length());
268 return FileName(fromqstr(QFile::decodeName(encoded)));
272 bool FileName::exists() const
274 return d->fi.exists();
278 bool FileName::isSymLink() const
280 return d->fi.isSymLink();
284 bool FileName::isFileEmpty() const
286 return d->fi.size() == 0;
290 bool FileName::isDirectory() const
292 return d->fi.isDir();
296 bool FileName::isReadOnly() const
298 return d->fi.isReadable() && !d->fi.isWritable();
302 bool FileName::isReadableDirectory() const
304 return d->fi.isDir() && d->fi.isReadable();
308 string FileName::onlyFileName() const
310 return fromqstr(d->fi.fileName());
314 string FileName::onlyFileNameWithoutExt() const
316 return fromqstr(d->fi.baseName());
320 string FileName::extension() const
322 return fromqstr(d->fi.suffix());
326 FileName FileName::onlyPath() const
329 path.d->fi.setFile(d->fi.path());
334 bool FileName::isReadableFile() const
336 return d->fi.isFile() && d->fi.isReadable();
340 bool FileName::isWritable() const
342 return d->fi.isWritable();
346 bool FileName::isDirWritable() const
348 LASSERT(d->fi.isDir(), return false);
349 QFileInfo tmp(d->fi.absoluteDir(), "lyxwritetest");
350 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
352 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
355 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
360 FileNameList FileName::dirList(string const & ext) const
362 FileNameList dirlist;
363 if (!isDirectory()) {
364 LYXERR0("Directory '" << *this << "' does not exist!");
368 QDir dir = d->fi.absoluteDir();
373 case '.': filter = "*" + toqstr(ext); break;
374 case '*': filter = toqstr(ext); break;
375 default: filter = "*." + toqstr(ext);
377 dir.setNameFilters(QStringList(filter));
378 LYXERR(Debug::FILES, "filtering on extension "
379 << fromqstr(filter) << " is requested.");
382 QFileInfoList list = dir.entryInfoList();
383 for (int i = 0; i != list.size(); ++i) {
384 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
385 dirlist.push_back(fi);
386 LYXERR(Debug::FILES, "found file " << fi);
393 static string createTempFile(QString const & mask)
395 QTemporaryFile qt_tmp(mask);
397 string const temp_file = fromqstr(qt_tmp.fileName());
398 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
401 LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
402 << qt_tmp.fileTemplate());
407 FileName FileName::tempName(FileName const & temp_dir, string const & mask)
409 QFileInfo tmp_fi(QDir(temp_dir.d->fi.absoluteFilePath()), toqstr(mask));
410 LYXERR(Debug::FILES, "Temporary file in " << tmp_fi.absoluteFilePath());
411 return FileName(createTempFile(tmp_fi.absoluteFilePath()));
415 FileName FileName::tempName(string const & mask)
417 return tempName(package().temp_dir(), mask);
421 FileName FileName::getcwd()
423 return FileName(".");
427 FileName FileName::tempPath()
429 return FileName(fromqstr(QDir::tempPath()));
433 time_t FileName::lastModified() const
435 // QFileInfo caches information about the file. So, in case this file has
436 // been touched between the object creation and now, we refresh the file
439 return d->fi.lastModified().toTime_t();
443 bool FileName::chdir() const
445 return QDir::setCurrent(d->fi.absoluteFilePath());
449 unsigned long FileName::checksum() const
451 unsigned long result = 0;
454 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
457 // a directory may be passed here so we need to test it. (bug 3622)
459 LYXERR0('"' << absFilename() << "\" is a directory!");
463 // This is used in the debug output at the end of the method.
465 if (lyxerr.debugging(Debug::FILES))
468 #if QT_VERSION >= 0x999999
469 // First version of checksum uses Qt4.4 mmap support.
470 // FIXME: This code is not ready with Qt4.4.2,
471 // see http://bugzilla.lyx.org/show_bug.cgi?id=5293
472 // FIXME: should we check if the MapExtension extension is supported?
473 // see QAbstractFileEngine::supportsExtension() and
474 // QAbstractFileEngine::MapExtension)
475 QFile qf(fi.filePath());
476 if (!qf.open(QIODevice::ReadOnly))
478 qint64 size = fi.size();
479 uchar * ubeg = qf.map(0, size);
480 uchar * uend = ubeg + size;
481 boost::crc_32_type ucrc;
482 ucrc.process_block(ubeg, uend);
485 result = ucrc.checksum();
489 string const encoded = toFilesystemEncoding();
490 char const * file = encoded.c_str();
493 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
495 int fd = open(file, O_RDONLY);
502 void * mm = mmap(0, info.st_size, PROT_READ,
504 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
505 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
510 char * beg = static_cast<char*>(mm);
511 char * end = beg + info.st_size;
513 boost::crc_32_type crc;
514 crc.process_block(beg, end);
515 result = crc.checksum();
517 munmap(mm, info.st_size);
520 #else // no SUM_WITH_MMAP
522 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
523 ifstream ifs(file, ios_base::in | ios_base::binary);
527 istreambuf_iterator<char> beg(ifs);
528 istreambuf_iterator<char> end;
529 boost::crc_32_type crc;
530 crc = for_each(beg, end, crc);
531 result = crc.checksum();
533 #endif // SUM_WITH_MMAP
536 LYXERR(Debug::FILES, "Checksumming \"" << absFilename() << "\" "
537 << result << " lasted " << t.elapsed() << " ms.");
542 bool FileName::removeFile() const
544 bool const success = QFile::remove(d->fi.absoluteFilePath());
545 if (!success && exists())
546 LYXERR0("Could not delete file " << *this);
551 static bool rmdir(QFileInfo const & fi)
553 QDir dir(fi.absoluteFilePath());
554 QFileInfoList list = dir.entryInfoList();
556 for (int i = 0; i != list.size(); ++i) {
557 if (list.at(i).fileName() == ".")
559 if (list.at(i).fileName() == "..")
562 if (list.at(i).isDir()) {
563 LYXERR(Debug::FILES, "Removing dir "
564 << fromqstr(list.at(i).absoluteFilePath()));
565 removed = rmdir(list.at(i));
568 LYXERR(Debug::FILES, "Removing file "
569 << fromqstr(list.at(i).absoluteFilePath()));
570 removed = dir.remove(list.at(i).fileName());
574 LYXERR0("Could not delete "
575 << fromqstr(list.at(i).absoluteFilePath()));
578 QDir parent = fi.absolutePath();
579 success &= parent.rmdir(fi.fileName());
584 bool FileName::destroyDirectory() const
586 bool const success = rmdir(d->fi);
588 LYXERR0("Could not delete " << *this);
594 static int mymkdir(char const * pathname, unsigned long int mode)
596 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
598 # if MKDIR_TAKES_ONE_ARG
600 return ::mkdir(pathname);
601 // FIXME: "Permissions of created directories are ignored on this system."
604 return ::mkdir(pathname, mode_t(mode));
606 #elif defined(_WIN32)
608 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
609 // FIXME: "Permissions of created directories are ignored on this system."
611 return ::_mkdir(pathname);
612 // FIXME: "Permissions of created directories are ignored on this system."
614 # error "Don't know how to create a directory on this system."
620 bool FileName::createDirectory(int permission) const
622 LASSERT(!empty(), /**/);
623 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
627 bool FileName::createPath() const
629 LASSERT(!empty(), /**/);
634 bool success = dir.mkpath(d->fi.absoluteFilePath());
636 LYXERR0("Cannot create path '" << *this << "'!");
641 docstring const FileName::absoluteFilePath() const
643 return qstring_to_ucs4(d->fi.absoluteFilePath());
647 docstring FileName::displayName(int threshold) const
649 return makeDisplayPath(absFilename(), threshold);
653 docstring FileName::fileContents(string const & encoding) const
655 if (!isReadableFile()) {
656 LYXERR0("File '" << *this << "' is not redable!");
660 QFile file(d->fi.absoluteFilePath());
661 if (!file.open(QIODevice::ReadOnly)) {
662 LYXERR0("File '" << *this
663 << "' could not be opened in read only mode!");
666 QByteArray contents = file.readAll();
669 if (contents.isEmpty()) {
670 LYXERR(Debug::FILES, "File '" << *this
671 << "' is either empty or some error happened while reading it.");
676 if (encoding.empty() || encoding == "UTF-8")
677 s = QString::fromUtf8(contents.data());
678 else if (encoding == "ascii")
679 s = QString::fromAscii(contents.data());
680 else if (encoding == "local8bit")
681 s = QString::fromLocal8Bit(contents.data());
682 else if (encoding == "latin1")
683 s = QString::fromLatin1(contents.data());
685 return qstring_to_ucs4(s);
689 void FileName::changeExtension(string const & extension)
691 // FIXME: use Qt native methods...
692 string const oldname = absFilename();
693 string::size_type const last_slash = oldname.rfind('/');
694 string::size_type last_dot = oldname.rfind('.');
695 if (last_dot < last_slash && last_slash != string::npos)
696 last_dot = string::npos;
699 // Make sure the extension starts with a dot
700 if (!extension.empty() && extension[0] != '.')
701 ext= '.' + extension;
705 set(oldname.substr(0, last_dot) + ext);
709 string FileName::guessFormatFromContents() const
711 // the different filetypes and what they contain in one of the first lines
712 // (dots are any characters). (Herbert 20020131)
715 // EPS %!PS-Adobe-3.0 EPSF...
722 // PBM P1... or P4 (B/W)
723 // PGM P2... or P5 (Grayscale)
724 // PPM P3... or P6 (color)
725 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
726 // SGI \001\332... (decimal 474)
728 // TIFF II... or MM...
730 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
731 // ...static char *...
732 // XWD \000\000\000\151 (0x00006900) decimal 105
734 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
735 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
736 // Z \037\235 UNIX compress
739 if (empty() || !isReadableFile())
742 ifstream ifs(toFilesystemEncoding().c_str());
744 // Couldn't open file...
748 static string const gzipStamp = "\037\213";
751 static string const zipStamp = "PK";
754 static string const compressStamp = "\037\235";
756 // Maximum strings to read
757 int const max_count = 50;
762 bool firstLine = true;
763 while ((count++ < max_count) && format.empty()) {
765 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
766 << "\tFile type not recognised before EOF!");
771 string const stamp = str.substr(0, 2);
772 if (firstLine && str.size() >= 2) {
773 // at first we check for a zipped file, because this
774 // information is saved in the first bytes of the file!
775 // also some graphic formats which save the information
776 // in the first line, too.
777 if (prefixIs(str, gzipStamp)) {
780 } else if (stamp == zipStamp) {
783 } else if (stamp == compressStamp) {
787 } else if (stamp == "BM") {
790 } else if (stamp == "\001\332") {
794 // Don't need to use str.at(0), str.at(1) because
795 // we already know that str.size() >= 2
796 } else if (str[0] == 'P') {
812 } else if ((stamp == "II") || (stamp == "MM")) {
815 } else if (prefixIs(str,"%TGIF")) {
818 } else if (prefixIs(str,"#FIG")) {
821 } else if (prefixIs(str,"GIF")) {
824 } else if (str.size() > 3) {
825 int const c = ((str[0] << 24) & (str[1] << 16) &
826 (str[2] << 8) & str[3]);
837 else if (contains(str,"EPSF"))
838 // dummy, if we have wrong file description like
839 // %!PS-Adobe-2.0EPSF"
842 else if (contains(str, "Grace"))
845 else if (contains(str, "JFIF"))
848 else if (contains(str, "%PDF"))
851 else if (contains(str, "PNG"))
854 else if (contains(str, "%!PS-Adobe")) {
857 if (contains(str,"EPSF"))
863 else if (contains(str, "_bits[]"))
866 else if (contains(str, "XPM") || contains(str, "static char *"))
869 else if (contains(str, "BITPIX"))
873 if (!format.empty()) {
874 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
878 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
879 << "\tCouldn't find a known format!");
884 bool FileName::isZippedFile() const
886 string const type = guessFormatFromContents();
887 return contains("gzip zip compress", type) && !type.empty();
891 docstring const FileName::relPath(string const & path) const
894 return makeRelPath(absoluteFilePath(), from_utf8(path));
898 bool operator==(FileName const & lhs, FileName const & rhs)
900 // FIXME: We need to solve this warning from Qt documentation:
901 // * Long and short file names that refer to the same file on Windows are
902 // treated as if they referred to different files.
903 // This is supposed to be fixed for Qt5.
906 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
910 // Avoid unnecessary checks below.
916 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink())
917 return lhs.d->fi == rhs.d->fi;
919 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
920 QFileInfo fi1(lhs.d->fi);
922 fi1 = QFileInfo(fi1.symLinkTarget());
923 QFileInfo fi2(rhs.d->fi);
925 fi2 = QFileInfo(fi2.symLinkTarget());
930 bool operator!=(FileName const & lhs, FileName const & rhs)
932 return !(operator==(lhs, rhs));
936 bool operator<(FileName const & lhs, FileName const & rhs)
938 return lhs.absFilename() < rhs.absFilename();
942 bool operator>(FileName const & lhs, FileName const & rhs)
944 return lhs.absFilename() > rhs.absFilename();
948 ostream & operator<<(ostream & os, FileName const & filename)
950 return os << filename.absFilename();
954 /////////////////////////////////////////////////////////////////////
958 /////////////////////////////////////////////////////////////////////
961 DocFileName::DocFileName()
962 : save_abs_path_(true)
966 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
967 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
971 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
972 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
976 void DocFileName::set(string const & name, string const & buffer_path)
979 bool const nameIsAbsolute = isAbsolute();
980 save_abs_path_ = nameIsAbsolute;
982 FileName::set(makeAbsPath(name, buffer_path).absFilename());
983 zipped_valid_ = false;
987 void DocFileName::erase()
990 zipped_valid_ = false;
994 string DocFileName::relFilename(string const & path) const
997 return to_utf8(relPath(path));
1001 string DocFileName::outputFilename(string const & path) const
1003 return save_abs_path_ ? absFilename() : relFilename(path);
1007 string DocFileName::mangledFilename(string const & dir) const
1009 // We need to make sure that every DocFileName instance for a given
1010 // filename returns the same mangled name.
1011 typedef map<string, string> MangledMap;
1012 static MangledMap mangledNames;
1013 MangledMap::const_iterator const it = mangledNames.find(absFilename());
1014 if (it != mangledNames.end())
1015 return (*it).second;
1017 string const name = absFilename();
1018 // Now the real work
1019 string mname = os::internal_path(name);
1020 // Remove the extension.
1021 mname = support::changeExtension(name, string());
1022 // The mangled name must be a valid LaTeX name.
1023 // The list of characters to keep is probably over-restrictive,
1024 // but it is not really a problem.
1025 // Apart from non-ASCII characters, at least the following characters
1026 // are forbidden: '/', '.', ' ', and ':'.
1027 // On windows it is not possible to create files with '<', '>' or '?'
1029 static string const keep = "abcdefghijklmnopqrstuvwxyz"
1030 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1032 string::size_type pos = 0;
1033 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
1035 // Add the extension back on
1036 mname = support::changeExtension(mname, getExtension(name));
1038 // Prepend a counter to the filename. This is necessary to make
1039 // the mangled name unique.
1040 static int counter = 0;
1042 s << counter++ << mname;
1045 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
1046 // is longer than about 160 characters. MiKTeX's pdflatex
1047 // is even pickier. A maximum length of 100 has been proven to work.
1048 // If dir.size() > max length, all bets are off for YAP. We truncate
1049 // the filename nevertheless, keeping a minimum of 10 chars.
1051 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
1053 // If the mangled file name is too long, hack it to fit.
1054 // We know we're guaranteed to have a unique file name because
1056 if (mname.size() > max_length) {
1057 int const half = (int(max_length) / 2) - 2;
1059 mname = mname.substr(0, half) + "___" +
1060 mname.substr(mname.size() - half);
1064 mangledNames[absFilename()] = mname;
1069 bool DocFileName::isZipped() const
1071 if (!zipped_valid_) {
1072 zipped_ = isZippedFile();
1073 zipped_valid_ = true;
1079 string DocFileName::unzippedFilename() const
1081 return unzippedFileName(absFilename());
1085 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1087 return static_cast<FileName const &>(lhs)
1088 == static_cast<FileName const &>(rhs)
1089 && lhs.saveAbsPath() == rhs.saveAbsPath();
1093 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1095 return !(lhs == rhs);
1098 } // namespace support