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>
68 #if defined(HAVE_MKSTEMP) && ! defined(HAVE_DECL_MKSTEMP)
69 extern "C" int mkstemp(char *);
72 #if !defined(HAVE_MKSTEMP) && defined(HAVE_MKTEMP)
76 # ifdef HAVE_PROCESS_H
81 // Various implementations of sum(), depending on what methods
82 // are available. Order is faster to slowest.
83 #if defined(HAVE_MMAP) && defined(HAVE_MUNMAP)
85 #ifdef HAVE_SYS_TYPES_H
86 # include <sys/types.h>
88 #ifdef HAVE_SYS_STAT_H
89 # include <sys/stat.h>
96 #endif // SUM_WITH_MMAP
100 // OK, this is ugly, but it is the only workaround I found to compile
101 // with gcc (any version) on a system which uses a non-GNU toolchain.
102 // The problem is that gcc uses a weak symbol for a particular
103 // instantiation and that the system linker usually does not
104 // understand those weak symbols (seen on HP-UX, tru64, AIX and
105 // others). Thus we force an explicit instanciation of this particular
107 template struct boost::detail::crc_table_t<32, 0x04C11DB7, true>;
112 static unsigned long sum(char const * file)
115 //LYXERR(Debug::FILES, "lyx::sum() using mmap (lightning fast)");
117 int fd = open(file, O_RDONLY);
124 void * mm = mmap(0, info.st_size, PROT_READ,
126 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
127 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
132 char * beg = static_cast<char*>(mm);
133 char * end = beg + info.st_size;
135 boost::crc_32_type crc;
136 crc.process_block(beg, end);
137 unsigned long result = crc.checksum();
139 munmap(mm, info.st_size);
144 #else // no SUM_WITH_MMAP
146 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
147 ifstream ifs(file, ios_base::in | ios_base::binary);
151 istreambuf_iterator<char> beg(ifs);
152 istreambuf_iterator<char> end;
153 boost::crc_32_type crc;
154 crc = for_each(beg, end, crc);
155 return crc.checksum();
157 #endif // SUM_WITH_MMAP
161 /////////////////////////////////////////////////////////////////////
165 /////////////////////////////////////////////////////////////////////
167 struct FileName::Private
171 Private(string const & abs_filename) : fi(toqstr(abs_filename))
173 fi.setCaching(fi.exists() ? true : false);
176 inline void refresh()
178 // There seems to be a bug in Qt >= 4.2.0, at least, that causes problems with
179 // QFileInfo::refresh() on *nix. So we recreate the object in that case.
180 // FIXME: When Trolltech fixes the bug, we will have to replace 0x999999 below
181 // with the actual working minimum version.
182 #if defined(_WIN32) || (QT_VERSION >= 0x999999)
185 fi = QFileInfo(fi.absoluteFilePath());
192 /////////////////////////////////////////////////////////////////////
196 /////////////////////////////////////////////////////////////////////
199 FileName::FileName() : d(new Private)
204 FileName::FileName(string const & abs_filename)
205 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
210 FileName::~FileName()
216 FileName::FileName(FileName const & rhs) : d(new Private)
222 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
228 FileName & FileName::operator=(FileName const & rhs)
235 bool FileName::empty() const
237 return d->fi.absoluteFilePath().isEmpty();
241 bool FileName::isAbsolute() const
243 return d->fi.isAbsolute();
247 string FileName::absFilename() const
249 return fromqstr(d->fi.absoluteFilePath());
253 void FileName::set(string const & name)
255 d->fi.setFile(toqstr(name));
259 void FileName::set(FileName const & rhs, string const & suffix)
261 if (!rhs.d->fi.isDir())
262 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
264 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
268 void FileName::erase()
274 bool FileName::copyTo(FileName const & name) const
276 LYXERR(Debug::FILES, "Copying " << name);
277 QFile::remove(name.d->fi.absoluteFilePath());
278 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
280 LYXERR0("FileName::copyTo(): Could not copy file "
281 << *this << " to " << name);
286 bool FileName::renameTo(FileName const & name) const
288 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
290 LYXERR0("Could not rename file " << *this << " to " << name);
295 bool FileName::moveTo(FileName const & name) const
297 QFile::remove(name.d->fi.absoluteFilePath());
299 bool success = QFile::rename(d->fi.absoluteFilePath(),
300 name.d->fi.absoluteFilePath());
302 LYXERR0("Could not move file " << *this << " to " << name);
307 bool FileName::changePermission(unsigned long int mode) const
309 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
310 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
311 LYXERR0("File " << *this << ": cannot change permission to "
320 string FileName::toFilesystemEncoding() const
322 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
323 return string(encoded.begin(), encoded.end());
327 FileName FileName::fromFilesystemEncoding(string const & name)
329 QByteArray const encoded(name.c_str(), name.length());
330 return FileName(fromqstr(QFile::decodeName(encoded)));
334 bool FileName::exists() const
336 return d->fi.exists();
340 bool FileName::isSymLink() const
342 return d->fi.isSymLink();
346 bool FileName::isFileEmpty() const
348 return d->fi.size() == 0;
352 bool FileName::isDirectory() const
354 return d->fi.isDir();
358 bool FileName::isReadOnly() const
360 return d->fi.isReadable() && !d->fi.isWritable();
364 bool FileName::isReadableDirectory() const
366 return d->fi.isDir() && d->fi.isReadable();
370 string FileName::onlyFileName() const
372 return fromqstr(d->fi.fileName());
376 string FileName::onlyFileNameWithoutExt() const
378 return fromqstr(d->fi.baseName());
382 string FileName::extension() const
384 return fromqstr(d->fi.suffix());
388 FileName FileName::onlyPath() const
391 path.d->fi.setFile(d->fi.path());
396 bool FileName::isReadableFile() const
398 return d->fi.isFile() && d->fi.isReadable();
402 bool FileName::isWritable() const
404 return d->fi.isWritable();
408 bool FileName::isDirWritable() const
410 LASSERT(d->fi.isDir(), return false);
411 QFileInfo tmp(d->fi.absoluteDir(), "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 QDir dir = d->fi.absoluteDir();
435 case '.': filter = "*" + toqstr(ext); break;
436 case '*': filter = toqstr(ext); break;
437 default: filter = "*." + toqstr(ext);
439 dir.setNameFilters(QStringList(filter));
440 LYXERR(Debug::FILES, "filtering on extension "
441 << fromqstr(filter) << " is requested.");
444 QFileInfoList list = dir.entryInfoList();
445 for (int i = 0; i != list.size(); ++i) {
446 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
447 dirlist.push_back(fi);
448 LYXERR(Debug::FILES, "found file " << fi);
455 static string createTempFile(QString const & mask)
457 QTemporaryFile qt_tmp(mask);
459 string const temp_file = fromqstr(qt_tmp.fileName());
460 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
463 LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
464 << qt_tmp.fileTemplate());
469 FileName FileName::tempName(FileName const & temp_dir, string const & mask)
471 QFileInfo tmp_fi(QDir(temp_dir.d->fi.absoluteFilePath()), toqstr(mask));
472 LYXERR(Debug::FILES, "Temporary file in " << tmp_fi.absoluteFilePath());
473 return FileName(createTempFile(tmp_fi.absoluteFilePath()));
477 FileName FileName::tempName(string const & mask)
479 return tempName(package().temp_dir(), mask);
483 FileName FileName::getcwd()
485 return FileName(".");
489 FileName FileName::tempPath()
491 return FileName(fromqstr(QDir::tempPath()));
495 time_t FileName::lastModified() const
497 // QFileInfo caches information about the file. So, in case this file has
498 // been touched between the object creation and now, we refresh the file
501 return d->fi.lastModified().toTime_t();
505 bool FileName::chdir() const
507 return QDir::setCurrent(d->fi.absoluteFilePath());
511 unsigned long FileName::checksum() const
514 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
517 // a directory may be passed here so we need to test it. (bug 3622)
519 LYXERR0('"' << absFilename() << "\" is a directory!");
522 if (!lyxerr.debugging(Debug::FILES))
523 return sum(absFilename().c_str());
527 unsigned long r = sum(absFilename().c_str());
528 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
529 << t.elapsed() << " ms." << endl;
534 bool FileName::removeFile() const
536 bool const success = QFile::remove(d->fi.absoluteFilePath());
537 if (!success && exists())
538 LYXERR0("Could not delete file " << *this);
543 static bool rmdir(QFileInfo const & fi)
545 QDir dir(fi.absoluteFilePath());
546 QFileInfoList list = dir.entryInfoList();
548 for (int i = 0; i != list.size(); ++i) {
549 if (list.at(i).fileName() == ".")
551 if (list.at(i).fileName() == "..")
554 if (list.at(i).isDir()) {
555 LYXERR(Debug::FILES, "Removing dir "
556 << fromqstr(list.at(i).absoluteFilePath()));
557 removed = rmdir(list.at(i));
560 LYXERR(Debug::FILES, "Removing file "
561 << fromqstr(list.at(i).absoluteFilePath()));
562 removed = dir.remove(list.at(i).fileName());
566 LYXERR0("Could not delete "
567 << fromqstr(list.at(i).absoluteFilePath()));
570 QDir parent = fi.absolutePath();
571 success &= parent.rmdir(fi.fileName());
576 bool FileName::destroyDirectory() const
578 bool const success = rmdir(d->fi);
580 LYXERR0("Could not delete " << *this);
586 static int mymkdir(char const * pathname, unsigned long int mode)
588 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
590 # if MKDIR_TAKES_ONE_ARG
592 return ::mkdir(pathname);
593 // FIXME: "Permissions of created directories are ignored on this system."
596 return ::mkdir(pathname, mode_t(mode));
598 #elif defined(_WIN32)
600 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
601 // FIXME: "Permissions of created directories are ignored on this system."
603 return ::_mkdir(pathname);
604 // FIXME: "Permissions of created directories are ignored on this system."
606 # error "Don't know how to create a directory on this system."
612 bool FileName::createDirectory(int permission) const
614 LASSERT(!empty(), /**/);
615 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
619 bool FileName::createPath() const
621 LASSERT(!empty(), /**/);
626 bool success = dir.mkpath(d->fi.absoluteFilePath());
628 LYXERR0("Cannot create path '" << *this << "'!");
633 docstring const FileName::absoluteFilePath() const
635 return qstring_to_ucs4(d->fi.absoluteFilePath());
639 docstring FileName::displayName(int threshold) const
641 return makeDisplayPath(absFilename(), threshold);
645 docstring FileName::fileContents(string const & encoding) const
647 if (!isReadableFile()) {
648 LYXERR0("File '" << *this << "' is not redable!");
652 QFile file(d->fi.absoluteFilePath());
653 if (!file.open(QIODevice::ReadOnly)) {
654 LYXERR0("File '" << *this
655 << "' could not be opened in read only mode!");
658 QByteArray contents = file.readAll();
661 if (contents.isEmpty()) {
662 LYXERR(Debug::FILES, "File '" << *this
663 << "' is either empty or some error happened while reading it.");
668 if (encoding.empty() || encoding == "UTF-8")
669 s = QString::fromUtf8(contents.data());
670 else if (encoding == "ascii")
671 s = QString::fromAscii(contents.data());
672 else if (encoding == "local8bit")
673 s = QString::fromLocal8Bit(contents.data());
674 else if (encoding == "latin1")
675 s = QString::fromLatin1(contents.data());
677 return qstring_to_ucs4(s);
681 void FileName::changeExtension(string const & extension)
683 // FIXME: use Qt native methods...
684 string const oldname = absFilename();
685 string::size_type const last_slash = oldname.rfind('/');
686 string::size_type last_dot = oldname.rfind('.');
687 if (last_dot < last_slash && last_slash != string::npos)
688 last_dot = string::npos;
691 // Make sure the extension starts with a dot
692 if (!extension.empty() && extension[0] != '.')
693 ext= '.' + extension;
697 set(oldname.substr(0, last_dot) + ext);
701 string FileName::guessFormatFromContents() const
703 // the different filetypes and what they contain in one of the first lines
704 // (dots are any characters). (Herbert 20020131)
707 // EPS %!PS-Adobe-3.0 EPSF...
714 // PBM P1... or P4 (B/W)
715 // PGM P2... or P5 (Grayscale)
716 // PPM P3... or P6 (color)
717 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
718 // SGI \001\332... (decimal 474)
720 // TIFF II... or MM...
722 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
723 // ...static char *...
724 // XWD \000\000\000\151 (0x00006900) decimal 105
726 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
727 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
728 // Z \037\235 UNIX compress
731 if (empty() || !isReadableFile())
734 ifstream ifs(toFilesystemEncoding().c_str());
736 // Couldn't open file...
740 static string const gzipStamp = "\037\213";
743 static string const zipStamp = "PK";
746 static string const compressStamp = "\037\235";
748 // Maximum strings to read
749 int const max_count = 50;
754 bool firstLine = true;
755 while ((count++ < max_count) && format.empty()) {
757 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
758 << "\tFile type not recognised before EOF!");
763 string const stamp = str.substr(0, 2);
764 if (firstLine && str.size() >= 2) {
765 // at first we check for a zipped file, because this
766 // information is saved in the first bytes of the file!
767 // also some graphic formats which save the information
768 // in the first line, too.
769 if (prefixIs(str, gzipStamp)) {
772 } else if (stamp == zipStamp) {
775 } else if (stamp == compressStamp) {
779 } else if (stamp == "BM") {
782 } else if (stamp == "\001\332") {
786 // Don't need to use str.at(0), str.at(1) because
787 // we already know that str.size() >= 2
788 } else if (str[0] == 'P') {
804 } else if ((stamp == "II") || (stamp == "MM")) {
807 } else if (prefixIs(str,"%TGIF")) {
810 } else if (prefixIs(str,"#FIG")) {
813 } else if (prefixIs(str,"GIF")) {
816 } else if (str.size() > 3) {
817 int const c = ((str[0] << 24) & (str[1] << 16) &
818 (str[2] << 8) & str[3]);
829 else if (contains(str,"EPSF"))
830 // dummy, if we have wrong file description like
831 // %!PS-Adobe-2.0EPSF"
834 else if (contains(str, "Grace"))
837 else if (contains(str, "JFIF"))
840 else if (contains(str, "%PDF"))
843 else if (contains(str, "PNG"))
846 else if (contains(str, "%!PS-Adobe")) {
849 if (contains(str,"EPSF"))
855 else if (contains(str, "_bits[]"))
858 else if (contains(str, "XPM") || contains(str, "static char *"))
861 else if (contains(str, "BITPIX"))
865 if (!format.empty()) {
866 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
870 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
871 << "\tCouldn't find a known format!");
876 bool FileName::isZippedFile() const
878 string const type = guessFormatFromContents();
879 return contains("gzip zip compress", type) && !type.empty();
883 docstring const FileName::relPath(string const & path) const
886 return makeRelPath(absoluteFilePath(), from_utf8(path));
890 bool operator==(FileName const & lhs, FileName const & rhs)
892 // FIXME: We need to solve this warning from Qt documentation:
893 // * Long and short file names that refer to the same file on Windows are
894 // treated as if they referred to different files.
895 // This is supposed to be fixed for Qt5.
898 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
902 // Avoid unnecessary checks below.
908 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink())
909 return lhs.d->fi == rhs.d->fi;
911 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
912 QFileInfo fi1(lhs.d->fi);
914 fi1 = QFileInfo(fi1.symLinkTarget());
915 QFileInfo fi2(rhs.d->fi);
917 fi2 = QFileInfo(fi2.symLinkTarget());
922 bool operator!=(FileName const & lhs, FileName const & rhs)
924 return !(operator==(lhs, rhs));
928 bool operator<(FileName const & lhs, FileName const & rhs)
930 return lhs.absFilename() < rhs.absFilename();
934 bool operator>(FileName const & lhs, FileName const & rhs)
936 return lhs.absFilename() > rhs.absFilename();
940 ostream & operator<<(ostream & os, FileName const & filename)
942 return os << filename.absFilename();
946 /////////////////////////////////////////////////////////////////////
950 /////////////////////////////////////////////////////////////////////
953 DocFileName::DocFileName()
954 : save_abs_path_(true)
958 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
959 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
963 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
964 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
968 void DocFileName::set(string const & name, string const & buffer_path)
971 bool const nameIsAbsolute = isAbsolute();
972 save_abs_path_ = nameIsAbsolute;
974 FileName::set(makeAbsPath(name, buffer_path).absFilename());
975 zipped_valid_ = false;
979 void DocFileName::erase()
982 zipped_valid_ = false;
986 string DocFileName::relFilename(string const & path) const
989 return to_utf8(relPath(path));
993 string DocFileName::outputFilename(string const & path) const
995 return save_abs_path_ ? absFilename() : relFilename(path);
999 string DocFileName::mangledFilename(string const & dir) const
1001 // We need to make sure that every DocFileName instance for a given
1002 // filename returns the same mangled name.
1003 typedef map<string, string> MangledMap;
1004 static MangledMap mangledNames;
1005 MangledMap::const_iterator const it = mangledNames.find(absFilename());
1006 if (it != mangledNames.end())
1007 return (*it).second;
1009 string const name = absFilename();
1010 // Now the real work
1011 string mname = os::internal_path(name);
1012 // Remove the extension.
1013 mname = support::changeExtension(name, string());
1014 // The mangled name must be a valid LaTeX name.
1015 // The list of characters to keep is probably over-restrictive,
1016 // but it is not really a problem.
1017 // Apart from non-ASCII characters, at least the following characters
1018 // are forbidden: '/', '.', ' ', and ':'.
1019 // On windows it is not possible to create files with '<', '>' or '?'
1021 static string const keep = "abcdefghijklmnopqrstuvwxyz"
1022 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1024 string::size_type pos = 0;
1025 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
1027 // Add the extension back on
1028 mname = support::changeExtension(mname, getExtension(name));
1030 // Prepend a counter to the filename. This is necessary to make
1031 // the mangled name unique.
1032 static int counter = 0;
1034 s << counter++ << mname;
1037 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
1038 // is longer than about 160 characters. MiKTeX's pdflatex
1039 // is even pickier. A maximum length of 100 has been proven to work.
1040 // If dir.size() > max length, all bets are off for YAP. We truncate
1041 // the filename nevertheless, keeping a minimum of 10 chars.
1043 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
1045 // If the mangled file name is too long, hack it to fit.
1046 // We know we're guaranteed to have a unique file name because
1048 if (mname.size() > max_length) {
1049 int const half = (int(max_length) / 2) - 2;
1051 mname = mname.substr(0, half) + "___" +
1052 mname.substr(mname.size() - half);
1056 mangledNames[absFilename()] = mname;
1061 bool DocFileName::isZipped() const
1063 if (!zipped_valid_) {
1064 zipped_ = isZippedFile();
1065 zipped_valid_ = true;
1071 string DocFileName::unzippedFilename() const
1073 return unzippedFileName(absFilename());
1077 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1079 return static_cast<FileName const &>(lhs)
1080 == static_cast<FileName const &>(rhs)
1081 && lhs.saveAbsPath() == rhs.saveAbsPath();
1085 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1087 return !(lhs == rhs);
1090 } // namespace support