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 static QString longPathName(QString const & path)
129 if (path.isEmpty()) {
132 QString maybeShort = QDir::toNativeSeparators(path);
133 QByteArray shortName = maybeShort.toLocal8Bit();;
134 char longPath[MAX_PATH];
135 int err = GetLongPathName(shortName.constData(), longPath, MAX_PATH);
137 return QDir::fromNativeSeparators(QString::fromLocal8Bit(longPath));
145 /////////////////////////////////////////////////////////////////////
149 /////////////////////////////////////////////////////////////////////
152 FileName::FileName() : d(new Private)
157 FileName::FileName(string const & abs_filename)
158 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
163 FileName::~FileName()
169 FileName::FileName(FileName const & rhs) : d(new Private)
175 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
181 FileName & FileName::operator=(FileName const & rhs)
188 bool FileName::empty() const
190 return d->fi.absoluteFilePath().isEmpty();
194 bool FileName::isAbsolute() const
196 return d->fi.isAbsolute();
200 string FileName::absFilename() const
202 return fromqstr(d->fi.absoluteFilePath());
206 void FileName::set(string const & name)
208 d->fi.setFile(toqstr(name));
212 void FileName::set(FileName const & rhs, string const & suffix)
214 if (!rhs.d->fi.isDir())
215 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
217 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
221 void FileName::erase()
227 bool FileName::copyTo(FileName const & name) const
229 LYXERR(Debug::FILES, "Copying " << name);
230 QFile::remove(name.d->fi.absoluteFilePath());
231 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
233 LYXERR0("FileName::copyTo(): Could not copy file "
234 << *this << " to " << name);
239 bool FileName::renameTo(FileName const & name) const
241 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
243 LYXERR0("Could not rename file " << *this << " to " << name);
248 bool FileName::moveTo(FileName const & name) const
250 QFile::remove(name.d->fi.absoluteFilePath());
252 bool success = QFile::rename(d->fi.absoluteFilePath(),
253 name.d->fi.absoluteFilePath());
255 LYXERR0("Could not move file " << *this << " to " << name);
260 bool FileName::changePermission(unsigned long int mode) const
262 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
263 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
264 LYXERR0("File " << *this << ": cannot change permission to "
273 string FileName::toFilesystemEncoding() const
275 // FIXME: This doesn't work on Windows for non ascii file names with Qt < 4.4.
276 // Provided that Windows package uses Qt4.4, this isn't a problem.
277 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
278 return string(encoded.begin(), encoded.end());
282 FileName FileName::fromFilesystemEncoding(string const & name)
284 QByteArray const encoded(name.c_str(), name.length());
285 return FileName(fromqstr(QFile::decodeName(encoded)));
289 bool FileName::exists() const
291 return d->fi.exists();
295 bool FileName::isSymLink() const
297 return d->fi.isSymLink();
301 bool FileName::isFileEmpty() const
303 return d->fi.size() == 0;
307 bool FileName::isDirectory() const
309 return d->fi.isDir();
313 bool FileName::isReadOnly() const
315 return d->fi.isReadable() && !d->fi.isWritable();
319 bool FileName::isReadableDirectory() const
321 return d->fi.isDir() && d->fi.isReadable();
325 string FileName::onlyFileName() const
327 return fromqstr(d->fi.fileName());
331 string FileName::onlyFileNameWithoutExt() const
333 return fromqstr(d->fi.baseName());
337 string FileName::extension() const
339 return fromqstr(d->fi.suffix());
343 FileName FileName::onlyPath() const
346 path.d->fi.setFile(d->fi.path());
351 bool FileName::isReadableFile() const
353 return d->fi.isFile() && d->fi.isReadable();
357 bool FileName::isWritable() const
359 return d->fi.isWritable();
363 bool FileName::isDirWritable() const
365 LASSERT(d->fi.isDir(), return false);
366 QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
367 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
369 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
372 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
377 FileNameList FileName::dirList(string const & ext) const
379 FileNameList dirlist;
380 if (!isDirectory()) {
381 LYXERR0("Directory '" << *this << "' does not exist!");
385 QDir dir = d->fi.absoluteDir();
390 case '.': filter = "*" + toqstr(ext); break;
391 case '*': filter = toqstr(ext); break;
392 default: filter = "*." + toqstr(ext);
394 dir.setNameFilters(QStringList(filter));
395 LYXERR(Debug::FILES, "filtering on extension "
396 << fromqstr(filter) << " is requested.");
399 QFileInfoList list = dir.entryInfoList();
400 for (int i = 0; i != list.size(); ++i) {
401 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
402 dirlist.push_back(fi);
403 LYXERR(Debug::FILES, "found file " << fi);
410 static string createTempFile(QString const & mask)
412 QTemporaryFile qt_tmp(mask);
414 string const temp_file = fromqstr(qt_tmp.fileName());
415 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
418 LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
419 << qt_tmp.fileTemplate());
424 FileName FileName::tempName(FileName const & temp_dir, string const & mask)
426 QFileInfo tmp_fi(QDir(temp_dir.d->fi.absoluteFilePath()), toqstr(mask));
427 LYXERR(Debug::FILES, "Temporary file in " << tmp_fi.absoluteFilePath());
428 return FileName(createTempFile(tmp_fi.absoluteFilePath()));
432 FileName FileName::tempName(string const & mask)
434 return tempName(package().temp_dir(), mask);
438 FileName FileName::getcwd()
440 return FileName(".");
444 FileName FileName::tempPath()
446 return FileName(fromqstr(Private::longPathName(QDir::tempPath())));
450 time_t FileName::lastModified() const
452 // QFileInfo caches information about the file. So, in case this file has
453 // been touched between the object creation and now, we refresh the file
456 return d->fi.lastModified().toTime_t();
460 bool FileName::chdir() const
462 return QDir::setCurrent(d->fi.absoluteFilePath());
466 unsigned long FileName::checksum() const
468 unsigned long result = 0;
471 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
474 // a directory may be passed here so we need to test it. (bug 3622)
476 LYXERR0('"' << absFilename() << "\" is a directory!");
480 // This is used in the debug output at the end of the method.
482 if (lyxerr.debugging(Debug::FILES))
485 #if QT_VERSION >= 0x999999
486 // First version of checksum uses Qt4.4 mmap support.
487 // FIXME: This code is not ready with Qt4.4.2,
488 // see http://bugzilla.lyx.org/show_bug.cgi?id=5293
489 // FIXME: should we check if the MapExtension extension is supported?
490 // see QAbstractFileEngine::supportsExtension() and
491 // QAbstractFileEngine::MapExtension)
492 QFile qf(fi.filePath());
493 if (!qf.open(QIODevice::ReadOnly))
495 qint64 size = fi.size();
496 uchar * ubeg = qf.map(0, size);
497 uchar * uend = ubeg + size;
498 boost::crc_32_type ucrc;
499 ucrc.process_block(ubeg, uend);
502 result = ucrc.checksum();
506 string const encoded = toFilesystemEncoding();
507 char const * file = encoded.c_str();
510 //LYXERR(Debug::FILES, "using mmap (lightning fast)");
512 int fd = open(file, O_RDONLY);
519 void * mm = mmap(0, info.st_size, PROT_READ,
521 // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
522 if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
527 char * beg = static_cast<char*>(mm);
528 char * end = beg + info.st_size;
530 boost::crc_32_type crc;
531 crc.process_block(beg, end);
532 result = crc.checksum();
534 munmap(mm, info.st_size);
537 #else // no SUM_WITH_MMAP
539 //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
540 ifstream ifs(file, ios_base::in | ios_base::binary);
544 istreambuf_iterator<char> beg(ifs);
545 istreambuf_iterator<char> end;
546 boost::crc_32_type crc;
547 crc = for_each(beg, end, crc);
548 result = crc.checksum();
550 #endif // SUM_WITH_MMAP
553 LYXERR(Debug::FILES, "Checksumming \"" << absFilename() << "\" "
554 << result << " lasted " << t.elapsed() << " ms.");
559 bool FileName::removeFile() const
561 bool const success = QFile::remove(d->fi.absoluteFilePath());
562 if (!success && exists())
563 LYXERR0("Could not delete file " << *this);
568 static bool rmdir(QFileInfo const & fi)
570 QDir dir(fi.absoluteFilePath());
571 QFileInfoList list = dir.entryInfoList();
573 for (int i = 0; i != list.size(); ++i) {
574 if (list.at(i).fileName() == ".")
576 if (list.at(i).fileName() == "..")
579 if (list.at(i).isDir()) {
580 LYXERR(Debug::FILES, "Removing dir "
581 << fromqstr(list.at(i).absoluteFilePath()));
582 removed = rmdir(list.at(i));
585 LYXERR(Debug::FILES, "Removing file "
586 << fromqstr(list.at(i).absoluteFilePath()));
587 removed = dir.remove(list.at(i).fileName());
591 LYXERR0("Could not delete "
592 << fromqstr(list.at(i).absoluteFilePath()));
595 QDir parent = fi.absolutePath();
596 success &= parent.rmdir(fi.fileName());
601 bool FileName::destroyDirectory() const
603 bool const success = rmdir(d->fi);
605 LYXERR0("Could not delete " << *this);
611 // Only used in non Win32 platforms
612 static int mymkdir(char const * pathname, unsigned long int mode)
614 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
616 # if MKDIR_TAKES_ONE_ARG
618 return ::mkdir(pathname);
619 // FIXME: "Permissions of created directories are ignored on this system."
622 return ::mkdir(pathname, mode_t(mode));
624 #elif defined(_WIN32)
626 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
627 // FIXME: "Permissions of created directories are ignored on this system."
629 return ::_mkdir(pathname);
630 // FIXME: "Permissions of created directories are ignored on this system."
632 # error "Don't know how to create a directory on this system."
638 bool FileName::createDirectory(int permission) const
640 LASSERT(!empty(), return false);
642 // FIXME: "Permissions of created directories are ignored on this system."
645 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
650 bool FileName::createPath() const
652 LASSERT(!empty(), /**/);
653 LYXERR(Debug::FILES, "creating path '" << *this << "'.");
658 bool success = dir.mkpath(d->fi.absoluteFilePath());
660 LYXERR0("Cannot create path '" << *this << "'!");
665 docstring const FileName::absoluteFilePath() const
667 return qstring_to_ucs4(d->fi.absoluteFilePath());
671 docstring FileName::displayName(int threshold) const
673 return makeDisplayPath(absFilename(), threshold);
677 docstring FileName::fileContents(string const & encoding) const
679 if (!isReadableFile()) {
680 LYXERR0("File '" << *this << "' is not redable!");
684 QFile file(d->fi.absoluteFilePath());
685 if (!file.open(QIODevice::ReadOnly)) {
686 LYXERR0("File '" << *this
687 << "' could not be opened in read only mode!");
690 QByteArray contents = file.readAll();
693 if (contents.isEmpty()) {
694 LYXERR(Debug::FILES, "File '" << *this
695 << "' is either empty or some error happened while reading it.");
700 if (encoding.empty() || encoding == "UTF-8")
701 s = QString::fromUtf8(contents.data());
702 else if (encoding == "ascii")
703 s = QString::fromAscii(contents.data());
704 else if (encoding == "local8bit")
705 s = QString::fromLocal8Bit(contents.data());
706 else if (encoding == "latin1")
707 s = QString::fromLatin1(contents.data());
709 return qstring_to_ucs4(s);
713 void FileName::changeExtension(string const & extension)
715 // FIXME: use Qt native methods...
716 string const oldname = absFilename();
717 string::size_type const last_slash = oldname.rfind('/');
718 string::size_type last_dot = oldname.rfind('.');
719 if (last_dot < last_slash && last_slash != string::npos)
720 last_dot = string::npos;
723 // Make sure the extension starts with a dot
724 if (!extension.empty() && extension[0] != '.')
725 ext= '.' + extension;
729 set(oldname.substr(0, last_dot) + ext);
733 string FileName::guessFormatFromContents() const
735 // the different filetypes and what they contain in one of the first lines
736 // (dots are any characters). (Herbert 20020131)
739 // EPS %!PS-Adobe-3.0 EPSF...
746 // PBM P1... or P4 (B/W)
747 // PGM P2... or P5 (Grayscale)
748 // PPM P3... or P6 (color)
749 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
750 // SGI \001\332... (decimal 474)
752 // TIFF II... or MM...
754 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
755 // ...static char *...
756 // XWD \000\000\000\151 (0x00006900) decimal 105
758 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
759 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
760 // Z \037\235 UNIX compress
763 if (empty() || !isReadableFile())
766 ifstream ifs(toFilesystemEncoding().c_str());
768 // Couldn't open file...
772 static string const gzipStamp = "\037\213";
775 static string const zipStamp = "PK";
778 static string const compressStamp = "\037\235";
780 // Maximum strings to read
781 int const max_count = 50;
786 bool firstLine = true;
787 while ((count++ < max_count) && format.empty()) {
789 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
790 << "\tFile type not recognised before EOF!");
795 string const stamp = str.substr(0, 2);
796 if (firstLine && str.size() >= 2) {
797 // at first we check for a zipped file, because this
798 // information is saved in the first bytes of the file!
799 // also some graphic formats which save the information
800 // in the first line, too.
801 if (prefixIs(str, gzipStamp)) {
804 } else if (stamp == zipStamp) {
807 } else if (stamp == compressStamp) {
811 } else if (stamp == "BM") {
814 } else if (stamp == "\001\332") {
818 // Don't need to use str.at(0), str.at(1) because
819 // we already know that str.size() >= 2
820 } else if (str[0] == 'P') {
836 } else if ((stamp == "II") || (stamp == "MM")) {
839 } else if (prefixIs(str,"%TGIF")) {
842 } else if (prefixIs(str,"#FIG")) {
845 } else if (prefixIs(str,"GIF")) {
848 } else if (str.size() > 3) {
849 int const c = ((str[0] << 24) & (str[1] << 16) &
850 (str[2] << 8) & str[3]);
861 else if (contains(str,"EPSF"))
862 // dummy, if we have wrong file description like
863 // %!PS-Adobe-2.0EPSF"
866 else if (contains(str, "Grace"))
869 else if (contains(str, "JFIF"))
872 else if (contains(str, "%PDF"))
875 else if (contains(str, "PNG"))
878 else if (contains(str, "%!PS-Adobe")) {
881 if (contains(str,"EPSF"))
887 else if (contains(str, "_bits[]"))
890 else if (contains(str, "XPM") || contains(str, "static char *"))
893 else if (contains(str, "BITPIX"))
897 if (!format.empty()) {
898 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
902 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
903 << "\tCouldn't find a known format!");
908 bool FileName::isZippedFile() const
910 string const type = guessFormatFromContents();
911 return contains("gzip zip compress", type) && !type.empty();
915 docstring const FileName::relPath(string const & path) const
918 return makeRelPath(absoluteFilePath(), from_utf8(path));
922 bool operator==(FileName const & lhs, FileName const & rhs)
924 // FIXME: We need to solve this warning from Qt documentation:
925 // * Long and short file names that refer to the same file on Windows are
926 // treated as if they referred to different files.
927 // This is supposed to be fixed for Qt5.
930 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
934 // Avoid unnecessary checks below.
940 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink())
941 return lhs.d->fi == rhs.d->fi;
943 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
944 QFileInfo fi1(lhs.d->fi);
946 fi1 = QFileInfo(fi1.symLinkTarget());
947 QFileInfo fi2(rhs.d->fi);
949 fi2 = QFileInfo(fi2.symLinkTarget());
954 bool operator!=(FileName const & lhs, FileName const & rhs)
956 return !(operator==(lhs, rhs));
960 bool operator<(FileName const & lhs, FileName const & rhs)
962 return lhs.absFilename() < rhs.absFilename();
966 bool operator>(FileName const & lhs, FileName const & rhs)
968 return lhs.absFilename() > rhs.absFilename();
972 ostream & operator<<(ostream & os, FileName const & filename)
974 return os << filename.absFilename();
978 /////////////////////////////////////////////////////////////////////
982 /////////////////////////////////////////////////////////////////////
985 DocFileName::DocFileName()
986 : save_abs_path_(true)
990 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
991 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
995 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
996 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
1000 void DocFileName::set(string const & name, string const & buffer_path)
1002 FileName::set(name);
1003 bool const nameIsAbsolute = isAbsolute();
1004 save_abs_path_ = nameIsAbsolute;
1005 if (!nameIsAbsolute)
1006 FileName::set(makeAbsPath(name, buffer_path).absFilename());
1007 zipped_valid_ = false;
1011 void DocFileName::erase()
1014 zipped_valid_ = false;
1018 string DocFileName::relFilename(string const & path) const
1021 return to_utf8(relPath(path));
1025 string DocFileName::outputFilename(string const & path) const
1027 return save_abs_path_ ? absFilename() : relFilename(path);
1031 string DocFileName::mangledFilename(string const & dir) const
1033 // We need to make sure that every DocFileName instance for a given
1034 // filename returns the same mangled name.
1035 typedef map<string, string> MangledMap;
1036 static MangledMap mangledNames;
1037 MangledMap::const_iterator const it = mangledNames.find(absFilename());
1038 if (it != mangledNames.end())
1039 return (*it).second;
1041 string const name = absFilename();
1042 // Now the real work
1043 string mname = os::internal_path(name);
1044 // Remove the extension.
1045 mname = support::changeExtension(name, string());
1046 // The mangled name must be a valid LaTeX name.
1047 // The list of characters to keep is probably over-restrictive,
1048 // but it is not really a problem.
1049 // Apart from non-ASCII characters, at least the following characters
1050 // are forbidden: '/', '.', ' ', and ':'.
1051 // On windows it is not possible to create files with '<', '>' or '?'
1053 static string const keep = "abcdefghijklmnopqrstuvwxyz"
1054 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1056 string::size_type pos = 0;
1057 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
1059 // Add the extension back on
1060 mname = support::changeExtension(mname, getExtension(name));
1062 // Prepend a counter to the filename. This is necessary to make
1063 // the mangled name unique.
1064 static int counter = 0;
1066 s << counter++ << mname;
1069 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
1070 // is longer than about 160 characters. MiKTeX's pdflatex
1071 // is even pickier. A maximum length of 100 has been proven to work.
1072 // If dir.size() > max length, all bets are off for YAP. We truncate
1073 // the filename nevertheless, keeping a minimum of 10 chars.
1075 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
1077 // If the mangled file name is too long, hack it to fit.
1078 // We know we're guaranteed to have a unique file name because
1080 if (mname.size() > max_length) {
1081 int const half = (int(max_length) / 2) - 2;
1083 mname = mname.substr(0, half) + "___" +
1084 mname.substr(mname.size() - half);
1088 mangledNames[absFilename()] = mname;
1093 bool DocFileName::isZipped() const
1095 if (!zipped_valid_) {
1096 zipped_ = isZippedFile();
1097 zipped_valid_ = true;
1103 string DocFileName::unzippedFilename() const
1105 return unzippedFileName(absFilename());
1109 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1111 return static_cast<FileName const &>(lhs)
1112 == static_cast<FileName const &>(rhs)
1113 && lhs.saveAbsPath() == rhs.saveAbsPath();
1117 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1119 return !(lhs == rhs);
1122 } // namespace support