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(rhs.d->fi.absoluteDir(), 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(temp_dir.d->fi.absoluteDir(), toqstr(mask));
383 return FileName(createTempFile(tmp_fi.absoluteFilePath()));
387 FileName FileName::tempName(string const & mask)
389 QFileInfo tmp_fi(toqstr(mask));
390 if (!tmp_fi.isAbsolute())
391 tmp_fi.setFile(package().temp_dir().d->fi.absoluteDir(), toqstr(mask));
392 return FileName(createTempFile(tmp_fi.absoluteFilePath()));
396 FileName FileName::getcwd()
398 return FileName(".");
402 FileName FileName::tempPath()
404 return FileName(fromqstr(QDir::tempPath()));
408 time_t FileName::lastModified() const
410 // QFileInfo caches information about the file. So, in case this file has
411 // been touched between the object creation and now, we refresh the file
414 return d->fi.lastModified().toTime_t();
418 bool FileName::chdir() const
420 return QDir::setCurrent(d->fi.absoluteFilePath());
424 extern unsigned long sum(char const * file);
426 unsigned long FileName::checksum() const
429 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
432 // a directory may be passed here so we need to test it. (bug 3622)
434 LYXERR0('"' << absFilename() << "\" is a directory!");
437 if (!lyxerr.debugging(Debug::FILES))
438 return sum(absFilename().c_str());
442 unsigned long r = sum(absFilename().c_str());
443 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
444 << t.elapsed() << " ms." << endl;
449 bool FileName::removeFile() const
451 bool const success = QFile::remove(d->fi.absoluteFilePath());
452 if (!success && exists())
453 LYXERR0("Could not delete file " << *this);
458 static bool rmdir(QFileInfo const & fi)
460 QDir dir(fi.absoluteFilePath());
461 QFileInfoList list = dir.entryInfoList();
463 for (int i = 0; i != list.size(); ++i) {
464 if (list.at(i).fileName() == ".")
466 if (list.at(i).fileName() == "..")
469 if (list.at(i).isDir()) {
470 LYXERR(Debug::FILES, "Removing dir "
471 << fromqstr(list.at(i).absoluteFilePath()));
472 removed = rmdir(list.at(i));
475 LYXERR(Debug::FILES, "Removing file "
476 << fromqstr(list.at(i).absoluteFilePath()));
477 removed = dir.remove(list.at(i).fileName());
481 LYXERR0("Could not delete "
482 << fromqstr(list.at(i).absoluteFilePath()));
485 QDir parent = fi.absolutePath();
486 success &= parent.rmdir(fi.fileName());
491 bool FileName::destroyDirectory() const
493 bool const success = rmdir(d->fi);
495 LYXERR0("Could not delete " << *this);
501 static int mymkdir(char const * pathname, unsigned long int mode)
503 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
505 # if MKDIR_TAKES_ONE_ARG
507 return ::mkdir(pathname);
508 // FIXME: "Permissions of created directories are ignored on this system."
511 return ::mkdir(pathname, mode_t(mode));
513 #elif defined(_WIN32)
515 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
516 // FIXME: "Permissions of created directories are ignored on this system."
518 return ::_mkdir(pathname);
519 // FIXME: "Permissions of created directories are ignored on this system."
521 # error "Don't know how to create a directory on this system."
527 bool FileName::createDirectory(int permission) const
529 LASSERT(!empty(), /**/);
530 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
534 bool FileName::createPath() const
536 LASSERT(!empty(), /**/);
541 bool success = dir.mkpath(d->fi.absoluteFilePath());
543 LYXERR0("Cannot create path '" << *this << "'!");
548 docstring const FileName::absoluteFilePath() const
550 return qstring_to_ucs4(d->fi.absoluteFilePath());
554 docstring FileName::displayName(int threshold) const
556 return makeDisplayPath(absFilename(), threshold);
560 docstring FileName::fileContents(string const & encoding) const
562 if (!isReadableFile()) {
563 LYXERR0("File '" << *this << "' is not redable!");
567 QFile file(d->fi.absoluteFilePath());
568 if (!file.open(QIODevice::ReadOnly)) {
569 LYXERR0("File '" << *this
570 << "' could not be opened in read only mode!");
573 QByteArray contents = file.readAll();
576 if (contents.isEmpty()) {
577 LYXERR(Debug::FILES, "File '" << *this
578 << "' is either empty or some error happened while reading it.");
583 if (encoding.empty() || encoding == "UTF-8")
584 s = QString::fromUtf8(contents.data());
585 else if (encoding == "ascii")
586 s = QString::fromAscii(contents.data());
587 else if (encoding == "local8bit")
588 s = QString::fromLocal8Bit(contents.data());
589 else if (encoding == "latin1")
590 s = QString::fromLatin1(contents.data());
592 return qstring_to_ucs4(s);
596 void FileName::changeExtension(string const & extension)
598 // FIXME: use Qt native methods...
599 string const oldname = absFilename();
600 string::size_type const last_slash = oldname.rfind('/');
601 string::size_type last_dot = oldname.rfind('.');
602 if (last_dot < last_slash && last_slash != string::npos)
603 last_dot = string::npos;
606 // Make sure the extension starts with a dot
607 if (!extension.empty() && extension[0] != '.')
608 ext= '.' + extension;
612 set(oldname.substr(0, last_dot) + ext);
616 string FileName::guessFormatFromContents() const
618 // the different filetypes and what they contain in one of the first lines
619 // (dots are any characters). (Herbert 20020131)
622 // EPS %!PS-Adobe-3.0 EPSF...
629 // PBM P1... or P4 (B/W)
630 // PGM P2... or P5 (Grayscale)
631 // PPM P3... or P6 (color)
632 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
633 // SGI \001\332... (decimal 474)
635 // TIFF II... or MM...
637 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
638 // ...static char *...
639 // XWD \000\000\000\151 (0x00006900) decimal 105
641 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
642 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
643 // Z \037\235 UNIX compress
646 if (empty() || !isReadableFile())
649 ifstream ifs(toFilesystemEncoding().c_str());
651 // Couldn't open file...
655 static string const gzipStamp = "\037\213";
658 static string const zipStamp = "PK";
661 static string const compressStamp = "\037\235";
663 // Maximum strings to read
664 int const max_count = 50;
669 bool firstLine = true;
670 while ((count++ < max_count) && format.empty()) {
672 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
673 << "\tFile type not recognised before EOF!");
678 string const stamp = str.substr(0, 2);
679 if (firstLine && str.size() >= 2) {
680 // at first we check for a zipped file, because this
681 // information is saved in the first bytes of the file!
682 // also some graphic formats which save the information
683 // in the first line, too.
684 if (prefixIs(str, gzipStamp)) {
687 } else if (stamp == zipStamp) {
690 } else if (stamp == compressStamp) {
694 } else if (stamp == "BM") {
697 } else if (stamp == "\001\332") {
701 // Don't need to use str.at(0), str.at(1) because
702 // we already know that str.size() >= 2
703 } else if (str[0] == 'P') {
719 } else if ((stamp == "II") || (stamp == "MM")) {
722 } else if (prefixIs(str,"%TGIF")) {
725 } else if (prefixIs(str,"#FIG")) {
728 } else if (prefixIs(str,"GIF")) {
731 } else if (str.size() > 3) {
732 int const c = ((str[0] << 24) & (str[1] << 16) &
733 (str[2] << 8) & str[3]);
744 else if (contains(str,"EPSF"))
745 // dummy, if we have wrong file description like
746 // %!PS-Adobe-2.0EPSF"
749 else if (contains(str, "Grace"))
752 else if (contains(str, "JFIF"))
755 else if (contains(str, "%PDF"))
758 else if (contains(str, "PNG"))
761 else if (contains(str, "%!PS-Adobe")) {
764 if (contains(str,"EPSF"))
770 else if (contains(str, "_bits[]"))
773 else if (contains(str, "XPM") || contains(str, "static char *"))
776 else if (contains(str, "BITPIX"))
780 if (!format.empty()) {
781 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
785 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
786 << "\tCouldn't find a known format!");
791 bool FileName::isZippedFile() const
793 string const type = guessFormatFromContents();
794 return contains("gzip zip compress", type) && !type.empty();
798 docstring const FileName::relPath(string const & path) const
801 return makeRelPath(absoluteFilePath(), from_utf8(path));
805 bool operator==(FileName const & lhs, FileName const & rhs)
807 return lhs.absFilename() == rhs.absFilename();
811 bool operator!=(FileName const & lhs, FileName const & rhs)
813 return lhs.absFilename() != rhs.absFilename();
817 bool operator<(FileName const & lhs, FileName const & rhs)
819 return lhs.absFilename() < rhs.absFilename();
823 bool operator>(FileName const & lhs, FileName const & rhs)
825 return lhs.absFilename() > rhs.absFilename();
829 ostream & operator<<(ostream & os, FileName const & filename)
831 return os << filename.absFilename();
835 /////////////////////////////////////////////////////////////////////
839 /////////////////////////////////////////////////////////////////////
842 DocFileName::DocFileName()
843 : save_abs_path_(true)
847 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
848 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
852 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
853 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
857 void DocFileName::set(string const & name, string const & buffer_path)
860 bool const nameIsAbsolute = isAbsolute();
861 save_abs_path_ = nameIsAbsolute;
863 FileName::set(makeAbsPath(name, buffer_path).absFilename());
864 zipped_valid_ = false;
868 void DocFileName::erase()
871 zipped_valid_ = false;
875 string DocFileName::relFilename(string const & path) const
878 return to_utf8(relPath(path));
882 string DocFileName::outputFilename(string const & path) const
884 return save_abs_path_ ? absFilename() : relFilename(path);
888 string DocFileName::mangledFilename(string const & dir) const
890 // We need to make sure that every DocFileName instance for a given
891 // filename returns the same mangled name.
892 typedef map<string, string> MangledMap;
893 static MangledMap mangledNames;
894 MangledMap::const_iterator const it = mangledNames.find(absFilename());
895 if (it != mangledNames.end())
898 string const name = absFilename();
900 string mname = os::internal_path(name);
901 // Remove the extension.
902 mname = support::changeExtension(name, string());
903 // The mangled name must be a valid LaTeX name.
904 // The list of characters to keep is probably over-restrictive,
905 // but it is not really a problem.
906 // Apart from non-ASCII characters, at least the following characters
907 // are forbidden: '/', '.', ' ', and ':'.
908 // On windows it is not possible to create files with '<', '>' or '?'
910 static string const keep = "abcdefghijklmnopqrstuvwxyz"
911 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
913 string::size_type pos = 0;
914 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
916 // Add the extension back on
917 mname = support::changeExtension(mname, getExtension(name));
919 // Prepend a counter to the filename. This is necessary to make
920 // the mangled name unique.
921 static int counter = 0;
923 s << counter++ << mname;
926 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
927 // is longer than about 160 characters. MiKTeX's pdflatex
928 // is even pickier. A maximum length of 100 has been proven to work.
929 // If dir.size() > max length, all bets are off for YAP. We truncate
930 // the filename nevertheless, keeping a minimum of 10 chars.
932 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
934 // If the mangled file name is too long, hack it to fit.
935 // We know we're guaranteed to have a unique file name because
937 if (mname.size() > max_length) {
938 int const half = (int(max_length) / 2) - 2;
940 mname = mname.substr(0, half) + "___" +
941 mname.substr(mname.size() - half);
945 mangledNames[absFilename()] = mname;
950 bool DocFileName::isZipped() const
952 if (!zipped_valid_) {
953 zipped_ = isZippedFile();
954 zipped_valid_ = true;
960 string DocFileName::unzippedFilename() const
962 return unzippedFileName(absFilename());
966 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
968 return lhs.absFilename() == rhs.absFilename()
969 && lhs.saveAbsPath() == rhs.saveAbsPath();
973 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
975 return !(lhs == rhs);
978 } // namespace support