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);
101 // There seems to be a bug in Qt >= 4.2.0 and < 4.5.0, that causes problems with
102 // QFileInfo::refresh() on *nix. So we recreate the object in that case.
103 #if defined(_WIN32) || (QT_VERSION >= 0x040500)
106 fi = QFileInfo(fi.absoluteFilePath());
112 bool isFilesystemEqual(QString const & lhs, QString const & rhs)
114 return QString::compare(lhs, rhs, os::isFilesystemCaseSensitive() ?
115 Qt::CaseSensitive : Qt::CaseInsensitive) == 0;
118 /// The absolute file name in UTF-8 encoding.
124 /////////////////////////////////////////////////////////////////////
128 /////////////////////////////////////////////////////////////////////
131 FileName::FileName() : d(new Private)
136 FileName::FileName(string const & abs_filename)
137 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
139 //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
140 LASSERT(empty() || isAbsolute(d->name), /**/);
144 FileName::~FileName()
150 FileName::FileName(FileName const & rhs) : d(new Private)
152 d->name = rhs.d->name;
157 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
163 FileName & FileName::operator=(FileName const & rhs)
167 d->name = rhs.d->name;
173 bool FileName::empty() const
175 return d->name.empty();
179 bool FileName::isAbsolute(string const & name)
181 QFileInfo fi(toqstr(name));
182 return fi.isAbsolute();
186 string FileName::absFileName() const
192 string FileName::realPath() const
194 return os::real_path(absFileName());
198 void FileName::set(string const & name)
200 d->fi.setFile(toqstr(name));
201 d->name = fromqstr(d->fi.absoluteFilePath());
202 //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
203 LASSERT(empty() || isAbsolute(d->name), /**/);
207 void FileName::set(FileName const & rhs, string const & suffix)
209 if (!rhs.d->fi.isDir())
210 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
212 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
213 d->name = fromqstr(d->fi.absoluteFilePath());
214 //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
215 LASSERT(empty() || isAbsolute(d->name), /**/);
219 void FileName::erase()
226 bool FileName::copyTo(FileName const & name) const
228 LYXERR(Debug::FILES, "Copying " << name);
229 QFile::remove(name.d->fi.absoluteFilePath());
230 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
232 LYXERR0("FileName::copyTo(): Could not copy file "
233 << *this << " to " << name);
238 bool FileName::renameTo(FileName const & name) const
240 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
242 LYXERR0("Could not rename file " << *this << " to " << name);
247 bool FileName::moveTo(FileName const & name) const
249 QFile::remove(name.d->fi.absoluteFilePath());
251 bool success = QFile::rename(d->fi.absoluteFilePath(),
252 name.d->fi.absoluteFilePath());
254 LYXERR0("Could not move file " << *this << " to " << name);
259 bool FileName::changePermission(unsigned long int mode) const
261 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
262 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
263 LYXERR0("File " << *this << ": cannot change permission to "
272 string FileName::toFilesystemEncoding() const
274 // This doesn't work on Windows for non ascii file names.
275 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
276 return string(encoded.begin(), encoded.end());
280 string FileName::toSafeFilesystemEncoding(os::file_access how) const
282 // This will work on Windows for non ascii file names.
283 QString const safe_path =
284 toqstr(os::safe_internal_path(absFileName(), how));
285 QByteArray const encoded = QFile::encodeName(safe_path);
286 return string(encoded.begin(), encoded.end());
290 FileName FileName::fromFilesystemEncoding(string const & name)
292 QByteArray const encoded(name.c_str(), name.length());
293 return FileName(fromqstr(QFile::decodeName(encoded)));
297 bool FileName::exists() const
299 return !empty() && d->fi.exists();
303 bool FileName::isSymLink() const
305 return !empty() && d->fi.isSymLink();
309 bool FileName::isFileEmpty() const
311 LASSERT(!empty(), return true);
312 return d->fi.size() == 0;
316 bool FileName::isDirectory() const
318 return !empty() && d->fi.isDir();
322 bool FileName::isReadOnly() const
324 LASSERT(!empty(), return true);
325 return d->fi.isReadable() && !d->fi.isWritable();
329 bool FileName::isReadableDirectory() const
331 return isDirectory() && d->fi.isReadable();
335 string FileName::onlyFileName() const
337 return fromqstr(d->fi.fileName());
341 string FileName::onlyFileNameWithoutExt() const
343 return fromqstr(d->fi.completeBaseName());
347 string FileName::extension() const
349 return fromqstr(d->fi.suffix());
353 bool FileName::hasExtension(const string & ext)
355 return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
359 FileName FileName::onlyPath() const
364 path.d->fi.setFile(d->fi.path());
365 path.d->name = fromqstr(path.d->fi.absoluteFilePath());
370 bool FileName::isReadableFile() const
372 return !empty() && d->fi.isFile() && d->fi.isReadable();
376 bool FileName::isWritable() const
378 return !empty() && d->fi.isWritable();
382 bool FileName::isDirWritable() const
384 LASSERT(isDirectory(), return false);
385 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
386 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
388 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
391 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
396 FileNameList FileName::dirList(string const & ext) const
398 FileNameList dirlist;
399 if (!isDirectory()) {
400 LYXERR0("Directory '" << *this << "' does not exist!");
404 // If the directory is specified without a trailing '/', absoluteDir()
405 // would return the parent dir, so we must use absoluteFilePath() here.
406 QDir dir = d->fi.absoluteFilePath();
411 case '.': filter = "*" + toqstr(ext); break;
412 case '*': filter = toqstr(ext); break;
413 default: filter = "*." + toqstr(ext);
415 dir.setNameFilters(QStringList(filter));
416 LYXERR(Debug::FILES, "filtering on extension "
417 << fromqstr(filter) << " is requested.");
420 QFileInfoList list = dir.entryInfoList();
421 for (int i = 0; i != list.size(); ++i) {
422 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
423 dirlist.push_back(fi);
424 LYXERR(Debug::FILES, "found file " << fi);
431 static string createTempFile(QString const & mask)
433 QTemporaryFile qt_tmp(mask);
435 string const temp_file = fromqstr(qt_tmp.fileName());
436 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
439 LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
440 << qt_tmp.fileTemplate());
445 FileName FileName::tempName(FileName const & temp_dir, string const & mask)
447 QFileInfo tmp_fi(QDir(temp_dir.d->fi.absoluteFilePath()), toqstr(mask));
448 LYXERR(Debug::FILES, "Temporary file in " << tmp_fi.absoluteFilePath());
449 return FileName(createTempFile(tmp_fi.absoluteFilePath()));
453 FileName FileName::tempName(string const & mask)
455 return tempName(package().temp_dir(), mask);
459 FileName FileName::getcwd()
461 // return makeAbsPath("."); would create an infinite loop
463 return FileName(fromqstr(fi.absoluteFilePath()));
467 FileName FileName::tempPath()
469 return FileName(os::internal_path(fromqstr(QDir::tempPath())));
473 void FileName::refresh() const
479 time_t FileName::lastModified() const
481 // QFileInfo caches information about the file. So, in case this file has
482 // been touched between the object creation and now, we refresh the file
485 return d->fi.lastModified().toTime_t();
489 bool FileName::chdir() const
491 return QDir::setCurrent(d->fi.absoluteFilePath());
495 unsigned long checksum_ifstream_fallback(char const * file)
497 unsigned long result = 0;
498 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
499 ifstream ifs(file, ios_base::in | ios_base::binary);
503 istreambuf_iterator<char> beg(ifs);
504 istreambuf_iterator<char> end;
505 boost::crc_32_type crc;
506 crc = for_each(beg, end, crc);
507 result = crc.checksum();
511 unsigned long FileName::checksum() const
513 unsigned long result = 0;
516 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
519 // a directory may be passed here so we need to test it. (bug 3622)
521 LYXERR0('"' << absFileName() << "\" is a directory!");
525 // This is used in the debug output at the end of the method.
527 if (lyxerr.debugging(Debug::FILES))
530 #if QT_VERSION >= 0x999999
531 // First version of checksum uses Qt4.4 mmap support.
532 // FIXME: This code is not ready with Qt4.4.2,
533 // see http://www.lyx.org/trac/ticket/5293
534 // FIXME: should we check if the MapExtension extension is supported?
535 // see QAbstractFileEngine::supportsExtension() and
536 // QAbstractFileEngine::MapExtension)
537 QFile qf(fi.filePath());
538 if (!qf.open(QIODevice::ReadOnly))
540 qint64 size = fi.size();
541 uchar * ubeg = qf.map(0, size);
542 uchar * uend = ubeg + size;
543 boost::crc_32_type ucrc;
544 ucrc.process_block(ubeg, uend);
547 result = ucrc.checksum();
551 string const encoded = toSafeFilesystemEncoding();
552 char const * file = encoded.c_str();
555 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
557 int fd = open(file, O_RDONLY);
562 if (fstat(fd, &info)){
563 // fstat fails on samba shares (bug 5891)
565 return checksum_ifstream_fallback(file);
568 void * mm = mmap(0, info.st_size, PROT_READ,
570 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
571 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
576 char * beg = static_cast<char*>(mm);
577 char * end = beg + info.st_size;
579 boost::crc_32_type crc;
580 crc.process_block(beg, end);
581 result = crc.checksum();
583 munmap(mm, info.st_size);
586 #else // no SUM_WITH_MMAP
587 result = checksum_ifstream_fallback(file);
588 #endif // SUM_WITH_MMAP
591 LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
592 << result << " lasted " << t.elapsed() << " ms.");
597 bool FileName::removeFile() const
599 bool const success = QFile::remove(d->fi.absoluteFilePath());
601 if (!success && exists())
602 LYXERR0("Could not delete file " << *this);
607 static bool rmdir(QFileInfo const & fi)
609 QDir dir(fi.absoluteFilePath());
610 QFileInfoList list = dir.entryInfoList();
612 for (int i = 0; i != list.size(); ++i) {
613 if (list.at(i).fileName() == ".")
615 if (list.at(i).fileName() == "..")
618 if (list.at(i).isDir()) {
619 LYXERR(Debug::FILES, "Removing dir "
620 << fromqstr(list.at(i).absoluteFilePath()));
621 removed = rmdir(list.at(i));
624 LYXERR(Debug::FILES, "Removing file "
625 << fromqstr(list.at(i).absoluteFilePath()));
626 removed = dir.remove(list.at(i).fileName());
630 LYXERR0("Could not delete "
631 << fromqstr(list.at(i).absoluteFilePath()));
634 QDir parent = fi.absolutePath();
635 success &= parent.rmdir(fi.fileName());
640 bool FileName::destroyDirectory() const
642 bool const success = rmdir(d->fi);
644 LYXERR0("Could not delete " << *this);
650 // Only used in non Win32 platforms
651 static int mymkdir(char const * pathname, unsigned long int mode)
653 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
655 # if MKDIR_TAKES_ONE_ARG
657 return ::mkdir(pathname);
658 // FIXME: "Permissions of created directories are ignored on this system."
661 return ::mkdir(pathname, mode_t(mode));
663 #elif defined(_WIN32)
665 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
666 // FIXME: "Permissions of created directories are ignored on this system."
668 return ::_mkdir(pathname);
669 // FIXME: "Permissions of created directories are ignored on this system."
671 # error "Don't know how to create a directory on this system."
677 bool FileName::createDirectory(int permission) const
679 LASSERT(!empty(), return false);
681 // FIXME: "Permissions of created directories are ignored on this system."
684 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
689 bool FileName::createPath() const
691 LASSERT(!empty(), return false);
692 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
697 bool success = dir.mkpath(d->fi.absoluteFilePath());
699 LYXERR0("Cannot create path '" << *this << "'!");
704 docstring const FileName::absoluteFilePath() const
706 return qstring_to_ucs4(d->fi.absoluteFilePath());
710 docstring FileName::displayName(int threshold) const
712 return makeDisplayPath(absFileName(), threshold);
716 docstring FileName::fileContents(string const & encoding) const
718 if (!isReadableFile()) {
719 LYXERR0("File '" << *this << "' is not redable!");
723 QFile file(d->fi.absoluteFilePath());
724 if (!file.open(QIODevice::ReadOnly)) {
725 LYXERR0("File '" << *this
726 << "' could not be opened in read only mode!");
729 QByteArray contents = file.readAll();
732 if (contents.isEmpty()) {
733 LYXERR(Debug::FILES, "File '" << *this
734 << "' is either empty or some error happened while reading it.");
739 if (encoding.empty() || encoding == "UTF-8")
740 s = QString::fromUtf8(contents.data());
741 else if (encoding == "ascii")
742 s = QString::fromAscii(contents.data());
743 else if (encoding == "local8bit")
744 s = QString::fromLocal8Bit(contents.data());
745 else if (encoding == "latin1")
746 s = QString::fromLatin1(contents.data());
748 return qstring_to_ucs4(s);
752 void FileName::changeExtension(string const & extension)
754 // FIXME: use Qt native methods...
755 string const oldname = absFileName();
756 string::size_type const last_slash = oldname.rfind('/');
757 string::size_type last_dot = oldname.rfind('.');
758 if (last_dot < last_slash && last_slash != string::npos)
759 last_dot = string::npos;
762 // Make sure the extension starts with a dot
763 if (!extension.empty() && extension[0] != '.')
764 ext= '.' + extension;
768 set(oldname.substr(0, last_dot) + ext);
772 string FileName::guessFormatFromContents() const
774 // the different filetypes and what they contain in one of the first lines
775 // (dots are any characters). (Herbert 20020131)
778 // EPS %!PS-Adobe-3.0 EPSF...
785 // PBM P1... or P4 (B/W)
786 // PGM P2... or P5 (Grayscale)
787 // PPM P3... or P6 (color)
788 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
789 // SGI \001\332... (decimal 474)
791 // TIFF II... or MM...
793 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
794 // ...static char *...
795 // XWD \000\000\000\151 (0x00006900) decimal 105
797 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
798 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
799 // Z \037\235 UNIX compress
802 if (empty() || !isReadableFile())
805 ifstream ifs(toFilesystemEncoding().c_str());
807 // Couldn't open file...
811 static string const gzipStamp = "\037\213";
814 static string const zipStamp = "PK";
817 static string const compressStamp = "\037\235";
819 // Maximum strings to read
820 int const max_count = 50;
825 bool firstLine = true;
826 while ((count++ < max_count) && format.empty()) {
828 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
829 << "\tFile type not recognised before EOF!");
834 string const stamp = str.substr(0, 2);
835 if (firstLine && str.size() >= 2) {
836 // at first we check for a zipped file, because this
837 // information is saved in the first bytes of the file!
838 // also some graphic formats which save the information
839 // in the first line, too.
840 if (prefixIs(str, gzipStamp)) {
843 } else if (stamp == zipStamp) {
846 } else if (stamp == compressStamp) {
850 } else if (stamp == "BM") {
853 } else if (stamp == "\001\332") {
857 // Don't need to use str.at(0), str.at(1) because
858 // we already know that str.size() >= 2
859 } else if (str[0] == 'P') {
875 } else if ((stamp == "II") || (stamp == "MM")) {
878 } else if (prefixIs(str,"%TGIF")) {
881 } else if (prefixIs(str,"#FIG")) {
884 } else if (prefixIs(str,"GIF")) {
887 } else if (str.size() > 3) {
888 int const c = ((str[0] << 24) & (str[1] << 16) &
889 (str[2] << 8) & str[3]);
900 else if (contains(str,"EPSF"))
901 // dummy, if we have wrong file description like
902 // %!PS-Adobe-2.0EPSF"
905 else if (contains(str, "Grace"))
908 else if (contains(str, "JFIF"))
911 else if (contains(str, "%PDF"))
914 else if (contains(str, "PNG"))
917 else if (contains(str, "%!PS-Adobe")) {
920 if (contains(str,"EPSF"))
926 else if (contains(str, "_bits[]"))
929 else if (contains(str, "XPM") || contains(str, "static char *"))
932 else if (contains(str, "BITPIX"))
936 // Dia knows also compressed form
937 if ((format == "gzip") && (!compare_ascii_no_case(extension(), "dia")))
940 if (!format.empty()) {
941 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
945 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
946 << "\tCouldn't find a known format!");
951 bool FileName::isZippedFile() const
953 string const type = guessFormatFromContents();
954 return contains("gzip zip compress", type) && !type.empty();
958 docstring const FileName::relPath(string const & path) const
961 return makeRelPath(absoluteFilePath(), from_utf8(path));
965 // Note: According to Qt, QFileInfo::operator== is undefined when
966 // both files do not exist (Qt4.5 gives true for all non-existent
967 // files, while Qt4.4 compares the filenames).
969 // http://www.qtsoftware.com/developer/task-tracker/
970 // index_html?id=248471&method=entry.
971 bool equivalent(FileName const & l, FileName const & r)
973 // FIXME: In future use Qt.
974 // Qt 4.4: We need to solve this warning from Qt documentation:
975 // * Long and short file names that refer to the same file on Windows are
976 // treated as if they referred to different files.
977 // This is supposed to be fixed for Qt5.
978 FileName const lhs(os::internal_path(l.absFileName()));
979 FileName const rhs(os::internal_path(r.absFileName()));
982 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
986 // Avoid unnecessary checks below.
992 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
993 // Qt already checks if the filesystem is case sensitive or not.
994 // see note above why the extra check with fileName is needed.
995 return lhs.d->fi == rhs.d->fi
996 && lhs.d->fi.fileName() == rhs.d->fi.fileName();
999 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
1000 QFileInfo fi1(lhs.d->fi);
1001 if (fi1.isSymLink())
1002 fi1 = QFileInfo(fi1.symLinkTarget());
1003 QFileInfo fi2(rhs.d->fi);
1004 if (fi2.isSymLink())
1005 fi2 = QFileInfo(fi2.symLinkTarget());
1006 // see note above why the extra check with fileName is needed.
1007 return fi1 == fi2 && fi1.fileName() == fi2.fileName();
1011 bool operator==(FileName const & lhs, FileName const & rhs)
1013 return os::isFilesystemCaseSensitive()
1014 ? lhs.absFileName() == rhs.absFileName()
1015 : !QString::compare(toqstr(lhs.absFileName()),
1016 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
1020 bool operator!=(FileName const & lhs, FileName const & rhs)
1022 return !(operator==(lhs, rhs));
1026 bool operator<(FileName const & lhs, FileName const & rhs)
1028 return lhs.absFileName() < rhs.absFileName();
1032 bool operator>(FileName const & lhs, FileName const & rhs)
1034 return lhs.absFileName() > rhs.absFileName();
1038 ostream & operator<<(ostream & os, FileName const & filename)
1040 return os << filename.absFileName();
1044 /////////////////////////////////////////////////////////////////////
1048 /////////////////////////////////////////////////////////////////////
1051 DocFileName::DocFileName()
1052 : save_abs_path_(true)
1056 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
1057 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
1061 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
1062 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
1066 void DocFileName::set(string const & name, string const & buffer_path)
1068 save_abs_path_ = isAbsolute(name);
1070 FileName::set(name);
1072 FileName::set(makeAbsPath(name, buffer_path).absFileName());
1073 zipped_valid_ = false;
1077 void DocFileName::erase()
1080 zipped_valid_ = false;
1084 string DocFileName::relFileName(string const & path) const
1087 return to_utf8(relPath(path));
1091 string DocFileName::outputFileName(string const & path) const
1093 return save_abs_path_ ? absFileName() : relFileName(path);
1097 string DocFileName::mangledFileName(string const & dir) const
1099 // We need to make sure that every DocFileName instance for a given
1100 // filename returns the same mangled name.
1101 typedef map<string, string> MangledMap;
1102 static MangledMap mangledNames;
1103 MangledMap::const_iterator const it = mangledNames.find(absFileName());
1104 if (it != mangledNames.end())
1105 return (*it).second;
1107 string const name = absFileName();
1108 // Now the real work
1109 string mname = os::internal_path(name);
1110 // Remove the extension.
1111 mname = support::changeExtension(name, string());
1112 // The mangled name must be a valid LaTeX name.
1113 // The list of characters to keep is probably over-restrictive,
1114 // but it is not really a problem.
1115 // Apart from non-ASCII characters, at least the following characters
1116 // are forbidden: '/', '.', ' ', and ':'.
1117 // On windows it is not possible to create files with '<', '>' or '?'
1119 static string const keep = "abcdefghijklmnopqrstuvwxyz"
1120 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1122 string::size_type pos = 0;
1123 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
1125 // Add the extension back on
1126 mname = support::changeExtension(mname, getExtension(name));
1128 // Prepend a counter to the filename. This is necessary to make
1129 // the mangled name unique.
1130 static int counter = 0;
1132 s << counter++ << mname;
1135 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
1136 // is longer than about 160 characters. MiKTeX's pdflatex
1137 // is even pickier. A maximum length of 100 has been proven to work.
1138 // If dir.size() > max length, all bets are off for YAP. We truncate
1139 // the filename nevertheless, keeping a minimum of 10 chars.
1141 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
1143 // If the mangled file name is too long, hack it to fit.
1144 // We know we're guaranteed to have a unique file name because
1146 if (mname.size() > max_length) {
1147 int const half = (int(max_length) / 2) - 2;
1149 mname = mname.substr(0, half) + "___" +
1150 mname.substr(mname.size() - half);
1154 mangledNames[absFileName()] = mname;
1159 bool DocFileName::isZipped() const
1161 if (!zipped_valid_) {
1162 zipped_ = isZippedFile();
1163 zipped_valid_ = true;
1169 string DocFileName::unzippedFileName() const
1171 return support::unzippedFileName(absFileName());
1175 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1177 return static_cast<FileName const &>(lhs)
1178 == static_cast<FileName const &>(rhs)
1179 && lhs.saveAbsPath() == rhs.saveAbsPath();
1183 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1185 return !(lhs == rhs);
1188 } // namespace support