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)
151 FileName & FileName::operator=(FileName const & rhs)
158 bool FileName::empty() const
160 return d->fi.absoluteFilePath().isEmpty();
164 bool FileName::isAbsolute() const
166 return d->fi.isAbsolute();
170 string FileName::absFilename() const
172 return fromqstr(d->fi.absoluteFilePath());
176 void FileName::set(string const & name)
178 d->fi.setFile(toqstr(name));
182 void FileName::set(FileName const & rhs, string const & suffix)
184 if (!rhs.d->fi.isDir())
185 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
187 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
191 void FileName::erase()
197 bool FileName::copyTo(FileName const & name) const
199 LYXERR(Debug::FILES, "Copying " << name);
200 QFile::remove(name.d->fi.absoluteFilePath());
201 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
203 LYXERR0("FileName::copyTo(): Could not copy file "
204 << *this << " to " << name);
209 bool FileName::renameTo(FileName const & name) const
211 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
213 LYXERR0("Could not rename file " << *this << " to " << name);
218 bool FileName::moveTo(FileName const & name) const
220 QFile::remove(name.d->fi.absoluteFilePath());
222 bool success = QFile::rename(d->fi.absoluteFilePath(),
223 name.d->fi.absoluteFilePath());
225 LYXERR0("Could not move file " << *this << " to " << name);
230 bool FileName::changePermission(unsigned long int mode) const
232 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
233 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
234 LYXERR0("File " << *this << ": cannot change permission to "
243 string FileName::toFilesystemEncoding() const
245 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
246 return string(encoded.begin(), encoded.end());
250 FileName FileName::fromFilesystemEncoding(string const & name)
252 QByteArray const encoded(name.c_str(), name.length());
253 return FileName(fromqstr(QFile::decodeName(encoded)));
257 bool FileName::exists() const
259 return d->fi.exists();
263 bool FileName::isSymLink() const
265 return d->fi.isSymLink();
269 bool FileName::isFileEmpty() const
271 return d->fi.size() == 0;
275 bool FileName::isDirectory() const
277 return d->fi.isDir();
281 bool FileName::isReadOnly() const
283 return d->fi.isReadable() && !d->fi.isWritable();
287 bool FileName::isReadableDirectory() const
289 return d->fi.isDir() && d->fi.isReadable();
293 string FileName::onlyFileName() const
295 return fromqstr(d->fi.fileName());
299 string FileName::onlyFileNameWithoutExt() const
301 return fromqstr(d->fi.baseName());
305 FileName FileName::onlyPath() const
308 path.d->fi.setFile(d->fi.path());
313 bool FileName::isReadableFile() const
315 return d->fi.isFile() && d->fi.isReadable();
319 bool FileName::isWritable() const
321 return d->fi.isWritable();
325 bool FileName::isDirWritable() const
327 LASSERT(d->fi.isDir(), return false);
328 QFileInfo tmp(d->fi.absoluteDir(), "lyxwritetest");
329 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
331 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
334 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
339 FileNameList FileName::dirList(string const & ext) const
341 FileNameList dirlist;
342 if (!isDirectory()) {
343 LYXERR0("Directory '" << *this << "' does not exist!");
347 QDir dir = d->fi.absoluteDir();
352 case '.': filter = "*" + toqstr(ext); break;
353 case '*': filter = toqstr(ext); break;
354 default: filter = "*." + toqstr(ext);
356 dir.setNameFilters(QStringList(filter));
357 LYXERR(Debug::FILES, "filtering on extension "
358 << fromqstr(filter) << " is requested.");
361 QFileInfoList list = dir.entryInfoList();
362 for (int i = 0; i != list.size(); ++i) {
363 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
364 dirlist.push_back(fi);
365 LYXERR(Debug::FILES, "found file " << fi);
372 static string createTempFile(QString const & mask)
374 QTemporaryFile qt_tmp(mask);
376 string const temp_file = fromqstr(qt_tmp.fileName());
377 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
380 LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
381 << qt_tmp.fileTemplate());
386 FileName FileName::tempName(FileName const & temp_dir, string const & mask)
388 QFileInfo tmp_fi(QDir(temp_dir.d->fi.absoluteFilePath()), toqstr(mask));
389 LYXERR(Debug::FILES, "Temporary file in " << tmp_fi.absoluteFilePath());
390 return FileName(createTempFile(tmp_fi.absoluteFilePath()));
394 FileName FileName::tempName(string const & mask)
396 return tempName(package().temp_dir(), mask);
400 FileName FileName::getcwd()
402 return FileName(".");
406 FileName FileName::tempPath()
408 return FileName(fromqstr(QDir::tempPath()));
412 time_t FileName::lastModified() const
414 // QFileInfo caches information about the file. So, in case this file has
415 // been touched between the object creation and now, we refresh the file
418 return d->fi.lastModified().toTime_t();
422 bool FileName::chdir() const
424 return QDir::setCurrent(d->fi.absoluteFilePath());
428 extern unsigned long sum(char const * file);
430 unsigned long FileName::checksum() const
433 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
436 // a directory may be passed here so we need to test it. (bug 3622)
438 LYXERR0('"' << absFilename() << "\" is a directory!");
441 if (!lyxerr.debugging(Debug::FILES))
442 return sum(absFilename().c_str());
446 unsigned long r = sum(absFilename().c_str());
447 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
448 << t.elapsed() << " ms." << endl;
453 bool FileName::removeFile() const
455 bool const success = QFile::remove(d->fi.absoluteFilePath());
456 if (!success && exists())
457 LYXERR0("Could not delete file " << *this);
462 static bool rmdir(QFileInfo const & fi)
464 QDir dir(fi.absoluteFilePath());
465 QFileInfoList list = dir.entryInfoList();
467 for (int i = 0; i != list.size(); ++i) {
468 if (list.at(i).fileName() == ".")
470 if (list.at(i).fileName() == "..")
473 if (list.at(i).isDir()) {
474 LYXERR(Debug::FILES, "Removing dir "
475 << fromqstr(list.at(i).absoluteFilePath()));
476 removed = rmdir(list.at(i));
479 LYXERR(Debug::FILES, "Removing file "
480 << fromqstr(list.at(i).absoluteFilePath()));
481 removed = dir.remove(list.at(i).fileName());
485 LYXERR0("Could not delete "
486 << fromqstr(list.at(i).absoluteFilePath()));
489 QDir parent = fi.absolutePath();
490 success &= parent.rmdir(fi.fileName());
495 bool FileName::destroyDirectory() const
497 bool const success = rmdir(d->fi);
499 LYXERR0("Could not delete " << *this);
505 static int mymkdir(char const * pathname, unsigned long int mode)
507 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
509 # if MKDIR_TAKES_ONE_ARG
511 return ::mkdir(pathname);
512 // FIXME: "Permissions of created directories are ignored on this system."
515 return ::mkdir(pathname, mode_t(mode));
517 #elif defined(_WIN32)
519 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
520 // FIXME: "Permissions of created directories are ignored on this system."
522 return ::_mkdir(pathname);
523 // FIXME: "Permissions of created directories are ignored on this system."
525 # error "Don't know how to create a directory on this system."
531 bool FileName::createDirectory(int permission) const
533 LASSERT(!empty(), /**/);
534 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
538 bool FileName::createPath() const
540 LASSERT(!empty(), /**/);
545 bool success = dir.mkpath(d->fi.absoluteFilePath());
547 LYXERR0("Cannot create path '" << *this << "'!");
552 docstring const FileName::absoluteFilePath() const
554 return qstring_to_ucs4(d->fi.absoluteFilePath());
558 docstring FileName::displayName(int threshold) const
560 return makeDisplayPath(absFilename(), threshold);
564 docstring FileName::fileContents(string const & encoding) const
566 if (!isReadableFile()) {
567 LYXERR0("File '" << *this << "' is not redable!");
571 QFile file(d->fi.absoluteFilePath());
572 if (!file.open(QIODevice::ReadOnly)) {
573 LYXERR0("File '" << *this
574 << "' could not be opened in read only mode!");
577 QByteArray contents = file.readAll();
580 if (contents.isEmpty()) {
581 LYXERR(Debug::FILES, "File '" << *this
582 << "' is either empty or some error happened while reading it.");
587 if (encoding.empty() || encoding == "UTF-8")
588 s = QString::fromUtf8(contents.data());
589 else if (encoding == "ascii")
590 s = QString::fromAscii(contents.data());
591 else if (encoding == "local8bit")
592 s = QString::fromLocal8Bit(contents.data());
593 else if (encoding == "latin1")
594 s = QString::fromLatin1(contents.data());
596 return qstring_to_ucs4(s);
600 void FileName::changeExtension(string const & extension)
602 // FIXME: use Qt native methods...
603 string const oldname = absFilename();
604 string::size_type const last_slash = oldname.rfind('/');
605 string::size_type last_dot = oldname.rfind('.');
606 if (last_dot < last_slash && last_slash != string::npos)
607 last_dot = string::npos;
610 // Make sure the extension starts with a dot
611 if (!extension.empty() && extension[0] != '.')
612 ext= '.' + extension;
616 set(oldname.substr(0, last_dot) + ext);
620 string FileName::guessFormatFromContents() const
622 // the different filetypes and what they contain in one of the first lines
623 // (dots are any characters). (Herbert 20020131)
626 // EPS %!PS-Adobe-3.0 EPSF...
633 // PBM P1... or P4 (B/W)
634 // PGM P2... or P5 (Grayscale)
635 // PPM P3... or P6 (color)
636 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
637 // SGI \001\332... (decimal 474)
639 // TIFF II... or MM...
641 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
642 // ...static char *...
643 // XWD \000\000\000\151 (0x00006900) decimal 105
645 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
646 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
647 // Z \037\235 UNIX compress
650 if (empty() || !isReadableFile())
653 ifstream ifs(toFilesystemEncoding().c_str());
655 // Couldn't open file...
659 static string const gzipStamp = "\037\213";
662 static string const zipStamp = "PK";
665 static string const compressStamp = "\037\235";
667 // Maximum strings to read
668 int const max_count = 50;
673 bool firstLine = true;
674 while ((count++ < max_count) && format.empty()) {
676 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
677 << "\tFile type not recognised before EOF!");
682 string const stamp = str.substr(0, 2);
683 if (firstLine && str.size() >= 2) {
684 // at first we check for a zipped file, because this
685 // information is saved in the first bytes of the file!
686 // also some graphic formats which save the information
687 // in the first line, too.
688 if (prefixIs(str, gzipStamp)) {
691 } else if (stamp == zipStamp) {
694 } else if (stamp == compressStamp) {
698 } else if (stamp == "BM") {
701 } else if (stamp == "\001\332") {
705 // Don't need to use str.at(0), str.at(1) because
706 // we already know that str.size() >= 2
707 } else if (str[0] == 'P') {
723 } else if ((stamp == "II") || (stamp == "MM")) {
726 } else if (prefixIs(str,"%TGIF")) {
729 } else if (prefixIs(str,"#FIG")) {
732 } else if (prefixIs(str,"GIF")) {
735 } else if (str.size() > 3) {
736 int const c = ((str[0] << 24) & (str[1] << 16) &
737 (str[2] << 8) & str[3]);
748 else if (contains(str,"EPSF"))
749 // dummy, if we have wrong file description like
750 // %!PS-Adobe-2.0EPSF"
753 else if (contains(str, "Grace"))
756 else if (contains(str, "JFIF"))
759 else if (contains(str, "%PDF"))
762 else if (contains(str, "PNG"))
765 else if (contains(str, "%!PS-Adobe")) {
768 if (contains(str,"EPSF"))
774 else if (contains(str, "_bits[]"))
777 else if (contains(str, "XPM") || contains(str, "static char *"))
780 else if (contains(str, "BITPIX"))
784 if (!format.empty()) {
785 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
789 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
790 << "\tCouldn't find a known format!");
795 bool FileName::isZippedFile() const
797 string const type = guessFormatFromContents();
798 return contains("gzip zip compress", type) && !type.empty();
802 docstring const FileName::relPath(string const & path) const
805 return makeRelPath(absoluteFilePath(), from_utf8(path));
809 bool operator==(FileName const & lhs, FileName const & rhs)
811 // FIXME: We need to solve this warning from Qt documentation:
812 // * Long and short file names that refer to the same file on Windows are
813 // treated as if they referred to different files.
814 // This is supposed to be fixed for Qt5.
817 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
821 // Avoid unnecessary checks below.
827 if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink())
828 return lhs.d->fi == rhs.d->fi;
830 // FIXME: When/if QFileInfo support symlink comparison, remove this code.
831 QFileInfo fi1(lhs.d->fi);
833 fi1 = QFileInfo(fi1.symLinkTarget());
834 QFileInfo fi2(rhs.d->fi);
836 fi2 = QFileInfo(fi2.symLinkTarget());
841 bool operator!=(FileName const & lhs, FileName const & rhs)
843 return !(operator==(lhs, rhs));
847 bool operator<(FileName const & lhs, FileName const & rhs)
849 return lhs.absFilename() < rhs.absFilename();
853 bool operator>(FileName const & lhs, FileName const & rhs)
855 return lhs.absFilename() > rhs.absFilename();
859 ostream & operator<<(ostream & os, FileName const & filename)
861 return os << filename.absFilename();
865 /////////////////////////////////////////////////////////////////////
869 /////////////////////////////////////////////////////////////////////
872 DocFileName::DocFileName()
873 : save_abs_path_(true)
877 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
878 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
882 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
883 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
887 void DocFileName::set(string const & name, string const & buffer_path)
890 bool const nameIsAbsolute = isAbsolute();
891 save_abs_path_ = nameIsAbsolute;
893 FileName::set(makeAbsPath(name, buffer_path).absFilename());
894 zipped_valid_ = false;
898 void DocFileName::erase()
901 zipped_valid_ = false;
905 string DocFileName::relFilename(string const & path) const
908 return to_utf8(relPath(path));
912 string DocFileName::outputFilename(string const & path) const
914 return save_abs_path_ ? absFilename() : relFilename(path);
918 string DocFileName::mangledFilename(string const & dir) const
920 // We need to make sure that every DocFileName instance for a given
921 // filename returns the same mangled name.
922 typedef map<string, string> MangledMap;
923 static MangledMap mangledNames;
924 MangledMap::const_iterator const it = mangledNames.find(absFilename());
925 if (it != mangledNames.end())
928 string const name = absFilename();
930 string mname = os::internal_path(name);
931 // Remove the extension.
932 mname = support::changeExtension(name, string());
933 // The mangled name must be a valid LaTeX name.
934 // The list of characters to keep is probably over-restrictive,
935 // but it is not really a problem.
936 // Apart from non-ASCII characters, at least the following characters
937 // are forbidden: '/', '.', ' ', and ':'.
938 // On windows it is not possible to create files with '<', '>' or '?'
940 static string const keep = "abcdefghijklmnopqrstuvwxyz"
941 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
943 string::size_type pos = 0;
944 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
946 // Add the extension back on
947 mname = support::changeExtension(mname, getExtension(name));
949 // Prepend a counter to the filename. This is necessary to make
950 // the mangled name unique.
951 static int counter = 0;
953 s << counter++ << mname;
956 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
957 // is longer than about 160 characters. MiKTeX's pdflatex
958 // is even pickier. A maximum length of 100 has been proven to work.
959 // If dir.size() > max length, all bets are off for YAP. We truncate
960 // the filename nevertheless, keeping a minimum of 10 chars.
962 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
964 // If the mangled file name is too long, hack it to fit.
965 // We know we're guaranteed to have a unique file name because
967 if (mname.size() > max_length) {
968 int const half = (int(max_length) / 2) - 2;
970 mname = mname.substr(0, half) + "___" +
971 mname.substr(mname.size() - half);
975 mangledNames[absFilename()] = mname;
980 bool DocFileName::isZipped() const
982 if (!zipped_valid_) {
983 zipped_ = isZippedFile();
984 zipped_valid_ = true;
990 string DocFileName::unzippedFilename() const
992 return unzippedFileName(absFilename());
996 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
998 return static_cast<FileName const &>(lhs)
999 == static_cast<FileName const &>(rhs)
1000 && lhs.saveAbsPath() == rhs.saveAbsPath();
1004 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1006 return !(lhs == rhs);
1009 } // namespace support