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/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 "support/lassert.h"
34 #include <boost/scoped_array.hpp>
41 #ifdef HAVE_SYS_TYPES_H
42 # include <sys/types.h>
44 #ifdef HAVE_SYS_STAT_H
45 # include <sys/stat.h>
65 #if defined(HAVE_MKSTEMP) && ! defined(HAVE_DECL_MKSTEMP)
66 extern "C" int mkstemp(char *);
69 #if !defined(HAVE_MKSTEMP) && defined(HAVE_MKTEMP)
73 # ifdef HAVE_PROCESS_H
84 /////////////////////////////////////////////////////////////////////
88 /////////////////////////////////////////////////////////////////////
90 struct FileName::Private
94 Private(string const & abs_filename) : fi(toqstr(abs_filename))
96 fi.setCaching(fi.exists() ? true : false);
101 // There seems to be a bug in Qt >= 4.2.0, at least, that causes problems with
102 // QFileInfo::refresh() on *nix. So we recreate the object in that case.
103 // FIXME: When Trolltech fixes the bug, we will have to replace 0x999999 below
104 // with the actual working minimum version.
105 #if defined(_WIN32) || (QT_VERSION >= 0x999999)
108 fi = QFileInfo(fi.absoluteFilePath());
115 /////////////////////////////////////////////////////////////////////
119 /////////////////////////////////////////////////////////////////////
122 FileName::FileName() : d(new Private)
127 FileName::FileName(string const & abs_filename)
128 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
133 FileName::~FileName()
139 FileName::FileName(FileName const & rhs) : d(new Private)
145 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
147 if (!rhs.d->fi.isDir())
148 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
150 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
154 FileName & FileName::operator=(FileName const & rhs)
161 bool FileName::empty() const
163 return d->fi.absoluteFilePath().isEmpty();
167 bool FileName::isAbsolute() const
169 return d->fi.isAbsolute();
173 string FileName::absFilename() const
175 return fromqstr(d->fi.absoluteFilePath());
179 void FileName::set(string const & name)
181 d->fi.setFile(toqstr(name));
185 void FileName::erase()
191 bool FileName::copyTo(FileName const & name) const
193 LYXERR(Debug::FILES, "Copying " << name);
194 QFile::remove(name.d->fi.absoluteFilePath());
195 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
197 LYXERR0("FileName::copyTo(): Could not copy file "
198 << *this << " to " << name);
203 bool FileName::renameTo(FileName const & name) const
205 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
207 LYXERR0("Could not rename file " << *this << " to " << name);
212 bool FileName::moveTo(FileName const & name) const
214 QFile::remove(name.d->fi.absoluteFilePath());
216 bool success = QFile::rename(d->fi.absoluteFilePath(),
217 name.d->fi.absoluteFilePath());
219 LYXERR0("Could not move file " << *this << " to " << name);
224 bool FileName::changePermission(unsigned long int mode) const
226 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
227 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
228 LYXERR0("File " << *this << ": cannot change permission to "
237 string FileName::toFilesystemEncoding() const
239 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
240 return string(encoded.begin(), encoded.end());
244 FileName FileName::fromFilesystemEncoding(string const & name)
246 QByteArray const encoded(name.c_str(), name.length());
247 return FileName(fromqstr(QFile::decodeName(encoded)));
251 bool FileName::exists() const
253 return d->fi.exists();
257 bool FileName::isSymLink() const
259 return d->fi.isSymLink();
263 bool FileName::isFileEmpty() const
265 return d->fi.size() == 0;
269 bool FileName::isDirectory() const
271 return d->fi.isDir();
275 bool FileName::isReadOnly() const
277 return d->fi.isReadable() && !d->fi.isWritable();
281 bool FileName::isReadableDirectory() const
283 return d->fi.isDir() && d->fi.isReadable();
287 string FileName::onlyFileName() const
289 return fromqstr(d->fi.fileName());
293 string FileName::onlyFileNameWithoutExt() const
295 return fromqstr(d->fi.baseName());
299 FileName FileName::onlyPath() const
302 path.d->fi.setFile(d->fi.path());
307 bool FileName::isReadableFile() const
309 return d->fi.isFile() && d->fi.isReadable();
313 bool FileName::isWritable() const
315 return d->fi.isWritable();
319 bool FileName::isDirWritable() const
321 LASSERT(d->fi.isDir(), return false);
322 QFileInfo tmp(d->fi.absoluteDir(), "lyxwritetest");
323 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
325 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
328 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
333 FileNameList FileName::dirList(string const & ext) const
335 FileNameList dirlist;
336 if (!isDirectory()) {
337 LYXERR0("Directory '" << *this << "' does not exist!");
341 QDir dir = d->fi.absoluteDir();
346 case '.': filter = "*" + toqstr(ext); break;
347 case '*': filter = toqstr(ext); break;
348 default: filter = "*." + toqstr(ext);
350 dir.setNameFilters(QStringList(filter));
351 LYXERR(Debug::FILES, "filtering on extension "
352 << fromqstr(filter) << " is requested.");
355 QFileInfoList list = dir.entryInfoList();
356 for (int i = 0; i != list.size(); ++i) {
357 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
358 dirlist.push_back(fi);
359 LYXERR(Debug::FILES, "found file " << fi);
366 static string createTempFile(QString const & mask)
368 QTemporaryFile qt_tmp(mask);
370 string const temp_file = fromqstr(qt_tmp.fileName());
371 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
374 LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
375 << qt_tmp.fileTemplate());
380 FileName FileName::tempName(FileName const & temp_dir, string const & mask)
382 QFileInfo tmp_fi(QDir(temp_dir.d->fi.absoluteFilePath()), toqstr(mask));
383 LYXERR(Debug::FILES, "Temporary file in " << tmp_fi.absoluteFilePath());
384 return FileName(createTempFile(tmp_fi.absoluteFilePath()));
388 FileName FileName::tempName(string const & mask)
390 QFileInfo tmp_fi(toqstr(mask));
391 if (!tmp_fi.isAbsolute())
392 tmp_fi.setFile(package().temp_dir().d->fi.absoluteDir(), toqstr(mask));
393 return FileName(createTempFile(tmp_fi.absoluteFilePath()));
397 FileName FileName::getcwd()
399 return FileName(".");
403 FileName FileName::tempPath()
405 return FileName(fromqstr(QDir::tempPath()));
409 time_t FileName::lastModified() const
411 // QFileInfo caches information about the file. So, in case this file has
412 // been touched between the object creation and now, we refresh the file
415 return d->fi.lastModified().toTime_t();
419 bool FileName::chdir() const
421 return QDir::setCurrent(d->fi.absoluteFilePath());
425 extern unsigned long sum(char const * file);
427 unsigned long FileName::checksum() const
430 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
433 // a directory may be passed here so we need to test it. (bug 3622)
435 LYXERR0('"' << absFilename() << "\" is a directory!");
438 if (!lyxerr.debugging(Debug::FILES))
439 return sum(absFilename().c_str());
443 unsigned long r = sum(absFilename().c_str());
444 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
445 << t.elapsed() << " ms." << endl;
450 bool FileName::removeFile() const
452 bool const success = QFile::remove(d->fi.absoluteFilePath());
453 if (!success && exists())
454 LYXERR0("Could not delete file " << *this);
459 static bool rmdir(QFileInfo const & fi)
461 QDir dir(fi.absoluteFilePath());
462 QFileInfoList list = dir.entryInfoList();
464 for (int i = 0; i != list.size(); ++i) {
465 if (list.at(i).fileName() == ".")
467 if (list.at(i).fileName() == "..")
470 if (list.at(i).isDir()) {
471 LYXERR(Debug::FILES, "Removing dir "
472 << fromqstr(list.at(i).absoluteFilePath()));
473 removed = rmdir(list.at(i));
476 LYXERR(Debug::FILES, "Removing file "
477 << fromqstr(list.at(i).absoluteFilePath()));
478 removed = dir.remove(list.at(i).fileName());
482 LYXERR0("Could not delete "
483 << fromqstr(list.at(i).absoluteFilePath()));
486 QDir parent = fi.absolutePath();
487 success &= parent.rmdir(fi.fileName());
492 bool FileName::destroyDirectory() const
494 bool const success = rmdir(d->fi);
496 LYXERR0("Could not delete " << *this);
502 static int mymkdir(char const * pathname, unsigned long int mode)
504 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
506 # if MKDIR_TAKES_ONE_ARG
508 return ::mkdir(pathname);
509 // FIXME: "Permissions of created directories are ignored on this system."
512 return ::mkdir(pathname, mode_t(mode));
514 #elif defined(_WIN32)
516 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
517 // FIXME: "Permissions of created directories are ignored on this system."
519 return ::_mkdir(pathname);
520 // FIXME: "Permissions of created directories are ignored on this system."
522 # error "Don't know how to create a directory on this system."
528 bool FileName::createDirectory(int permission) const
530 LASSERT(!empty(), /**/);
531 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
535 bool FileName::createPath() const
537 LASSERT(!empty(), /**/);
542 bool success = dir.mkpath(d->fi.absoluteFilePath());
544 LYXERR0("Cannot create path '" << *this << "'!");
549 docstring const FileName::absoluteFilePath() const
551 return qstring_to_ucs4(d->fi.absoluteFilePath());
555 docstring FileName::displayName(int threshold) const
557 return makeDisplayPath(absFilename(), threshold);
561 docstring FileName::fileContents(string const & encoding) const
563 if (!isReadableFile()) {
564 LYXERR0("File '" << *this << "' is not redable!");
568 QFile file(d->fi.absoluteFilePath());
569 if (!file.open(QIODevice::ReadOnly)) {
570 LYXERR0("File '" << *this
571 << "' could not be opened in read only mode!");
574 QByteArray contents = file.readAll();
577 if (contents.isEmpty()) {
578 LYXERR(Debug::FILES, "File '" << *this
579 << "' is either empty or some error happened while reading it.");
584 if (encoding.empty() || encoding == "UTF-8")
585 s = QString::fromUtf8(contents.data());
586 else if (encoding == "ascii")
587 s = QString::fromAscii(contents.data());
588 else if (encoding == "local8bit")
589 s = QString::fromLocal8Bit(contents.data());
590 else if (encoding == "latin1")
591 s = QString::fromLatin1(contents.data());
593 return qstring_to_ucs4(s);
597 void FileName::changeExtension(string const & extension)
599 // FIXME: use Qt native methods...
600 string const oldname = absFilename();
601 string::size_type const last_slash = oldname.rfind('/');
602 string::size_type last_dot = oldname.rfind('.');
603 if (last_dot < last_slash && last_slash != string::npos)
604 last_dot = string::npos;
607 // Make sure the extension starts with a dot
608 if (!extension.empty() && extension[0] != '.')
609 ext= '.' + extension;
613 set(oldname.substr(0, last_dot) + ext);
617 string FileName::guessFormatFromContents() const
619 // the different filetypes and what they contain in one of the first lines
620 // (dots are any characters). (Herbert 20020131)
623 // EPS %!PS-Adobe-3.0 EPSF...
630 // PBM P1... or P4 (B/W)
631 // PGM P2... or P5 (Grayscale)
632 // PPM P3... or P6 (color)
633 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
634 // SGI \001\332... (decimal 474)
636 // TIFF II... or MM...
638 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
639 // ...static char *...
640 // XWD \000\000\000\151 (0x00006900) decimal 105
642 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
643 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
644 // Z \037\235 UNIX compress
647 if (empty() || !isReadableFile())
650 ifstream ifs(toFilesystemEncoding().c_str());
652 // Couldn't open file...
656 static string const gzipStamp = "\037\213";
659 static string const zipStamp = "PK";
662 static string const compressStamp = "\037\235";
664 // Maximum strings to read
665 int const max_count = 50;
670 bool firstLine = true;
671 while ((count++ < max_count) && format.empty()) {
673 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
674 << "\tFile type not recognised before EOF!");
679 string const stamp = str.substr(0, 2);
680 if (firstLine && str.size() >= 2) {
681 // at first we check for a zipped file, because this
682 // information is saved in the first bytes of the file!
683 // also some graphic formats which save the information
684 // in the first line, too.
685 if (prefixIs(str, gzipStamp)) {
688 } else if (stamp == zipStamp) {
691 } else if (stamp == compressStamp) {
695 } else if (stamp == "BM") {
698 } else if (stamp == "\001\332") {
702 // Don't need to use str.at(0), str.at(1) because
703 // we already know that str.size() >= 2
704 } else if (str[0] == 'P') {
720 } else if ((stamp == "II") || (stamp == "MM")) {
723 } else if (prefixIs(str,"%TGIF")) {
726 } else if (prefixIs(str,"#FIG")) {
729 } else if (prefixIs(str,"GIF")) {
732 } else if (str.size() > 3) {
733 int const c = ((str[0] << 24) & (str[1] << 16) &
734 (str[2] << 8) & str[3]);
745 else if (contains(str,"EPSF"))
746 // dummy, if we have wrong file description like
747 // %!PS-Adobe-2.0EPSF"
750 else if (contains(str, "Grace"))
753 else if (contains(str, "JFIF"))
756 else if (contains(str, "%PDF"))
759 else if (contains(str, "PNG"))
762 else if (contains(str, "%!PS-Adobe")) {
765 if (contains(str,"EPSF"))
771 else if (contains(str, "_bits[]"))
774 else if (contains(str, "XPM") || contains(str, "static char *"))
777 else if (contains(str, "BITPIX"))
781 if (!format.empty()) {
782 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
786 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
787 << "\tCouldn't find a known format!");
792 bool FileName::isZippedFile() const
794 string const type = guessFormatFromContents();
795 return contains("gzip zip compress", type) && !type.empty();
799 docstring const FileName::relPath(string const & path) const
802 return makeRelPath(absoluteFilePath(), from_utf8(path));
806 bool operator==(FileName const & lhs, FileName const & rhs)
808 return lhs.absFilename() == rhs.absFilename();
812 bool operator!=(FileName const & lhs, FileName const & rhs)
814 return lhs.absFilename() != rhs.absFilename();
818 bool operator<(FileName const & lhs, FileName const & rhs)
820 return lhs.absFilename() < rhs.absFilename();
824 bool operator>(FileName const & lhs, FileName const & rhs)
826 return lhs.absFilename() > rhs.absFilename();
830 ostream & operator<<(ostream & os, FileName const & filename)
832 return os << filename.absFilename();
836 /////////////////////////////////////////////////////////////////////
840 /////////////////////////////////////////////////////////////////////
843 DocFileName::DocFileName()
844 : save_abs_path_(true)
848 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
849 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
853 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
854 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
858 void DocFileName::set(string const & name, string const & buffer_path)
861 bool const nameIsAbsolute = isAbsolute();
862 save_abs_path_ = nameIsAbsolute;
864 FileName::set(makeAbsPath(name, buffer_path).absFilename());
865 zipped_valid_ = false;
869 void DocFileName::erase()
872 zipped_valid_ = false;
876 string DocFileName::relFilename(string const & path) const
879 return to_utf8(relPath(path));
883 string DocFileName::outputFilename(string const & path) const
885 return save_abs_path_ ? absFilename() : relFilename(path);
889 string DocFileName::mangledFilename(string const & dir) const
891 // We need to make sure that every DocFileName instance for a given
892 // filename returns the same mangled name.
893 typedef map<string, string> MangledMap;
894 static MangledMap mangledNames;
895 MangledMap::const_iterator const it = mangledNames.find(absFilename());
896 if (it != mangledNames.end())
899 string const name = absFilename();
901 string mname = os::internal_path(name);
902 // Remove the extension.
903 mname = support::changeExtension(name, string());
904 // The mangled name must be a valid LaTeX name.
905 // The list of characters to keep is probably over-restrictive,
906 // but it is not really a problem.
907 // Apart from non-ASCII characters, at least the following characters
908 // are forbidden: '/', '.', ' ', and ':'.
909 // On windows it is not possible to create files with '<', '>' or '?'
911 static string const keep = "abcdefghijklmnopqrstuvwxyz"
912 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
914 string::size_type pos = 0;
915 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
917 // Add the extension back on
918 mname = support::changeExtension(mname, getExtension(name));
920 // Prepend a counter to the filename. This is necessary to make
921 // the mangled name unique.
922 static int counter = 0;
924 s << counter++ << mname;
927 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
928 // is longer than about 160 characters. MiKTeX's pdflatex
929 // is even pickier. A maximum length of 100 has been proven to work.
930 // If dir.size() > max length, all bets are off for YAP. We truncate
931 // the filename nevertheless, keeping a minimum of 10 chars.
933 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
935 // If the mangled file name is too long, hack it to fit.
936 // We know we're guaranteed to have a unique file name because
938 if (mname.size() > max_length) {
939 int const half = (int(max_length) / 2) - 2;
941 mname = mname.substr(0, half) + "___" +
942 mname.substr(mname.size() - half);
946 mangledNames[absFilename()] = mname;
951 bool DocFileName::isZipped() const
953 if (!zipped_valid_) {
954 zipped_ = isZippedFile();
955 zipped_valid_ = true;
961 string DocFileName::unzippedFilename() const
963 return unzippedFileName(absFilename());
967 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
969 return lhs.absFilename() == rhs.absFilename()
970 && lhs.saveAbsPath() == rhs.saveAbsPath();
974 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
976 return !(lhs == rhs);
979 } // namespace support