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/os.h"
21 #include "support/Package.h"
22 #include "support/qstring_helpers.h"
29 #include <QTemporaryFile>
32 #include "support/lassert.h"
33 #include <boost/scoped_array.hpp>
40 #ifdef HAVE_SYS_TYPES_H
41 # include <sys/types.h>
43 #ifdef HAVE_SYS_STAT_H
44 # include <sys/stat.h>
64 #if defined(HAVE_MKSTEMP) && ! defined(HAVE_DECL_MKSTEMP)
65 extern "C" int mkstemp(char *);
68 #if !defined(HAVE_MKSTEMP) && defined(HAVE_MKTEMP)
72 # ifdef HAVE_PROCESS_H
83 /////////////////////////////////////////////////////////////////////
87 /////////////////////////////////////////////////////////////////////
89 struct FileName::Private
93 Private(string const & abs_filename) : fi(toqstr(abs_filename))
95 fi.setCaching(fi.exists() ? true : false);
100 // There seems to be a bug in Qt >= 4.2.0, at least, that causes problems with
101 // QFileInfo::refresh() on *nix. So we recreate the object in that case.
102 // FIXME: When Trolltech fixes the bug, we will have to replace 0x999999 below
103 // with the actual working minimum version.
104 #if defined(_WIN32) || (QT_VERSION >= 0x999999)
107 fi = QFileInfo(fi.absoluteFilePath());
114 /////////////////////////////////////////////////////////////////////
118 /////////////////////////////////////////////////////////////////////
121 FileName::FileName() : d(new Private)
126 FileName::FileName(string const & abs_filename)
127 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
132 FileName::~FileName()
138 FileName::FileName(FileName const & rhs) : d(new Private)
144 FileName & FileName::operator=(FileName const & rhs)
151 bool FileName::empty() const
153 return d->fi.absoluteFilePath().isEmpty();
157 bool FileName::isAbsolute() const
159 return d->fi.isAbsolute();
163 string FileName::absFilename() const
165 return fromqstr(d->fi.absoluteFilePath());
169 void FileName::set(string const & name)
171 d->fi.setFile(toqstr(name));
175 void FileName::erase()
181 bool FileName::copyTo(FileName const & name) const
183 LYXERR(Debug::FILES, "Copying " << name);
184 QFile::remove(name.d->fi.absoluteFilePath());
185 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
187 LYXERR0("FileName::copyTo(): Could not copy file "
188 << *this << " to " << name);
193 bool FileName::renameTo(FileName const & name) const
195 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
197 LYXERR0("Could not rename file " << *this << " to " << name);
202 bool FileName::moveTo(FileName const & name) const
204 QFile::remove(name.d->fi.absoluteFilePath());
206 bool success = QFile::rename(d->fi.absoluteFilePath(),
207 name.d->fi.absoluteFilePath());
209 LYXERR0("Could not move file " << *this << " to " << name);
214 bool FileName::changePermission(unsigned long int mode) const
216 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
217 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
218 LYXERR0("File " << *this << ": cannot change permission to "
227 string FileName::toFilesystemEncoding() const
229 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
230 return string(encoded.begin(), encoded.end());
234 FileName FileName::fromFilesystemEncoding(string const & name)
236 QByteArray const encoded(name.c_str(), name.length());
237 return FileName(fromqstr(QFile::decodeName(encoded)));
241 bool FileName::exists() const
243 return d->fi.exists();
247 bool FileName::isSymLink() const
249 return d->fi.isSymLink();
253 bool FileName::isFileEmpty() const
255 return d->fi.size() == 0;
259 bool FileName::isDirectory() const
261 return d->fi.isDir();
265 bool FileName::isReadOnly() const
267 return d->fi.isReadable() && !d->fi.isWritable();
271 bool FileName::isReadableDirectory() const
273 return d->fi.isDir() && d->fi.isReadable();
277 string FileName::onlyFileName() const
279 return fromqstr(d->fi.fileName());
283 string FileName::onlyFileNameWithoutExt() const
285 return fromqstr(d->fi.baseName());
289 FileName FileName::onlyPath() const
292 path.d->fi.setFile(d->fi.path());
297 bool FileName::isReadableFile() const
299 return d->fi.isFile() && d->fi.isReadable();
303 bool FileName::isWritable() const
305 return d->fi.isWritable();
309 bool FileName::isDirWritable() const
311 LASSERT(d->fi.isDir(), return false);
312 QFileInfo tmp(d->fi.absoluteDir(), "lyxwritetest");
313 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
315 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
318 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
323 FileNameList FileName::dirList(string const & ext) const
325 FileNameList dirlist;
326 if (!isDirectory()) {
327 LYXERR0("Directory '" << *this << "' does not exist!");
331 QDir dir = d->fi.absoluteDir();
336 case '.': filter = "*" + toqstr(ext); break;
337 case '*': filter = toqstr(ext); break;
338 default: filter = "*." + toqstr(ext);
340 dir.setNameFilters(QStringList(filter));
341 LYXERR(Debug::FILES, "filtering on extension "
342 << fromqstr(filter) << " is requested.");
345 QFileInfoList list = dir.entryInfoList();
346 for (int i = 0; i != list.size(); ++i) {
347 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
348 dirlist.push_back(fi);
349 LYXERR(Debug::FILES, "found file " << fi);
356 FileName FileName::tempName(string const & mask)
358 FileName tmp_name(mask);
360 if (tmp_name.d->fi.isAbsolute())
363 tmpfl = package().temp_dir().absFilename() + "/" + mask;
365 QTemporaryFile qt_tmp(toqstr(tmpfl));
367 tmp_name.d->fi.setFile(qt_tmp.fileName());
368 LYXERR(Debug::FILES, "Temporary file `" << tmp_name << "' created.");
371 LYXERR(Debug::FILES, "LyX Error: Unable to create temporary file.");
376 FileName FileName::getcwd()
378 return FileName(".");
382 FileName FileName::tempPath()
384 return FileName(fromqstr(QDir::tempPath()));
388 time_t FileName::lastModified() const
390 // QFileInfo caches information about the file. So, in case this file has
391 // been touched between the object creation and now, we refresh the file
394 return d->fi.lastModified().toTime_t();
398 bool FileName::chdir() const
400 return QDir::setCurrent(d->fi.absoluteFilePath());
404 extern unsigned long sum(char const * file);
406 unsigned long FileName::checksum() const
409 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
412 // a directory may be passed here so we need to test it. (bug 3622)
414 LYXERR0('"' << absFilename() << "\" is a directory!");
417 if (!lyxerr.debugging(Debug::FILES))
418 return sum(absFilename().c_str());
422 unsigned long r = sum(absFilename().c_str());
423 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
424 << t.elapsed() << " ms." << endl;
429 bool FileName::removeFile() const
431 bool const success = QFile::remove(d->fi.absoluteFilePath());
432 if (!success && exists())
433 LYXERR0("Could not delete file " << *this);
438 static bool rmdir(QFileInfo const & fi)
440 QDir dir(fi.absoluteFilePath());
441 QFileInfoList list = dir.entryInfoList();
443 for (int i = 0; i != list.size(); ++i) {
444 if (list.at(i).fileName() == ".")
446 if (list.at(i).fileName() == "..")
449 if (list.at(i).isDir()) {
450 LYXERR(Debug::FILES, "Removing dir "
451 << fromqstr(list.at(i).absoluteFilePath()));
452 removed = rmdir(list.at(i));
455 LYXERR(Debug::FILES, "Removing file "
456 << fromqstr(list.at(i).absoluteFilePath()));
457 removed = dir.remove(list.at(i).fileName());
461 LYXERR0("Could not delete "
462 << fromqstr(list.at(i).absoluteFilePath()));
465 QDir parent = fi.absolutePath();
466 success &= parent.rmdir(fi.fileName());
471 bool FileName::destroyDirectory() const
473 bool const success = rmdir(d->fi);
475 LYXERR0("Could not delete " << *this);
481 static int mymkdir(char const * pathname, unsigned long int mode)
483 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
485 # if MKDIR_TAKES_ONE_ARG
487 return ::mkdir(pathname);
488 // FIXME: "Permissions of created directories are ignored on this system."
491 return ::mkdir(pathname, mode_t(mode));
493 #elif defined(_WIN32)
495 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
496 // FIXME: "Permissions of created directories are ignored on this system."
498 return ::_mkdir(pathname);
499 // FIXME: "Permissions of created directories are ignored on this system."
501 # error "Don't know how to create a directory on this system."
507 bool FileName::createDirectory(int permission) const
509 LASSERT(!empty(), /**/);
510 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
514 bool FileName::createPath() const
516 LASSERT(!empty(), /**/);
521 bool success = dir.mkpath(d->fi.absoluteFilePath());
523 LYXERR0("Cannot create path '" << *this << "'!");
528 docstring const FileName::absoluteFilePath() const
530 return qstring_to_ucs4(d->fi.absoluteFilePath());
534 docstring FileName::displayName(int threshold) const
536 return makeDisplayPath(absFilename(), threshold);
540 docstring FileName::fileContents(string const & encoding) const
542 if (!isReadableFile()) {
543 LYXERR0("File '" << *this << "' is not redable!");
547 QFile file(d->fi.absoluteFilePath());
548 if (!file.open(QIODevice::ReadOnly)) {
549 LYXERR0("File '" << *this
550 << "' could not be opened in read only mode!");
553 QByteArray contents = file.readAll();
556 if (contents.isEmpty()) {
557 LYXERR(Debug::FILES, "File '" << *this
558 << "' is either empty or some error happened while reading it.");
563 if (encoding.empty() || encoding == "UTF-8")
564 s = QString::fromUtf8(contents.data());
565 else if (encoding == "ascii")
566 s = QString::fromAscii(contents.data());
567 else if (encoding == "local8bit")
568 s = QString::fromLocal8Bit(contents.data());
569 else if (encoding == "latin1")
570 s = QString::fromLatin1(contents.data());
572 return qstring_to_ucs4(s);
576 void FileName::changeExtension(string const & extension)
578 // FIXME: use Qt native methods...
579 string const oldname = absFilename();
580 string::size_type const last_slash = oldname.rfind('/');
581 string::size_type last_dot = oldname.rfind('.');
582 if (last_dot < last_slash && last_slash != string::npos)
583 last_dot = string::npos;
586 // Make sure the extension starts with a dot
587 if (!extension.empty() && extension[0] != '.')
588 ext= '.' + extension;
592 set(oldname.substr(0, last_dot) + ext);
596 string FileName::guessFormatFromContents() const
598 // the different filetypes and what they contain in one of the first lines
599 // (dots are any characters). (Herbert 20020131)
602 // EPS %!PS-Adobe-3.0 EPSF...
609 // PBM P1... or P4 (B/W)
610 // PGM P2... or P5 (Grayscale)
611 // PPM P3... or P6 (color)
612 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
613 // SGI \001\332... (decimal 474)
615 // TIFF II... or MM...
617 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
618 // ...static char *...
619 // XWD \000\000\000\151 (0x00006900) decimal 105
621 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
622 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
623 // Z \037\235 UNIX compress
626 if (empty() || !isReadableFile())
629 ifstream ifs(toFilesystemEncoding().c_str());
631 // Couldn't open file...
635 static string const gzipStamp = "\037\213";
638 static string const zipStamp = "PK";
641 static string const compressStamp = "\037\235";
643 // Maximum strings to read
644 int const max_count = 50;
649 bool firstLine = true;
650 while ((count++ < max_count) && format.empty()) {
652 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
653 << "\tFile type not recognised before EOF!");
658 string const stamp = str.substr(0, 2);
659 if (firstLine && str.size() >= 2) {
660 // at first we check for a zipped file, because this
661 // information is saved in the first bytes of the file!
662 // also some graphic formats which save the information
663 // in the first line, too.
664 if (prefixIs(str, gzipStamp)) {
667 } else if (stamp == zipStamp) {
670 } else if (stamp == compressStamp) {
674 } else if (stamp == "BM") {
677 } else if (stamp == "\001\332") {
681 // Don't need to use str.at(0), str.at(1) because
682 // we already know that str.size() >= 2
683 } else if (str[0] == 'P') {
699 } else if ((stamp == "II") || (stamp == "MM")) {
702 } else if (prefixIs(str,"%TGIF")) {
705 } else if (prefixIs(str,"#FIG")) {
708 } else if (prefixIs(str,"GIF")) {
711 } else if (str.size() > 3) {
712 int const c = ((str[0] << 24) & (str[1] << 16) &
713 (str[2] << 8) & str[3]);
724 else if (contains(str,"EPSF"))
725 // dummy, if we have wrong file description like
726 // %!PS-Adobe-2.0EPSF"
729 else if (contains(str, "Grace"))
732 else if (contains(str, "JFIF"))
735 else if (contains(str, "%PDF"))
738 else if (contains(str, "PNG"))
741 else if (contains(str, "%!PS-Adobe")) {
744 if (contains(str,"EPSF"))
750 else if (contains(str, "_bits[]"))
753 else if (contains(str, "XPM") || contains(str, "static char *"))
756 else if (contains(str, "BITPIX"))
760 if (!format.empty()) {
761 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
765 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
766 << "\tCouldn't find a known format!");
771 bool FileName::isZippedFile() const
773 string const type = guessFormatFromContents();
774 return contains("gzip zip compress", type) && !type.empty();
778 docstring const FileName::relPath(string const & path) const
781 return makeRelPath(absoluteFilePath(), from_utf8(path));
785 bool operator==(FileName const & lhs, FileName const & rhs)
787 return lhs.absFilename() == rhs.absFilename();
791 bool operator!=(FileName const & lhs, FileName const & rhs)
793 return lhs.absFilename() != rhs.absFilename();
797 bool operator<(FileName const & lhs, FileName const & rhs)
799 return lhs.absFilename() < rhs.absFilename();
803 bool operator>(FileName const & lhs, FileName const & rhs)
805 return lhs.absFilename() > rhs.absFilename();
809 ostream & operator<<(ostream & os, FileName const & filename)
811 return os << filename.absFilename();
815 /////////////////////////////////////////////////////////////////////
819 /////////////////////////////////////////////////////////////////////
822 DocFileName::DocFileName()
823 : save_abs_path_(true)
827 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
828 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
832 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
833 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
837 void DocFileName::set(string const & name, string const & buffer_path)
840 bool const nameIsAbsolute = isAbsolute();
841 save_abs_path_ = nameIsAbsolute;
843 FileName::set(makeAbsPath(name, buffer_path).absFilename());
844 zipped_valid_ = false;
848 void DocFileName::erase()
851 zipped_valid_ = false;
855 string DocFileName::relFilename(string const & path) const
858 return to_utf8(relPath(path));
862 string DocFileName::outputFilename(string const & path) const
864 return save_abs_path_ ? absFilename() : relFilename(path);
868 string DocFileName::mangledFilename(string const & dir) const
870 // We need to make sure that every DocFileName instance for a given
871 // filename returns the same mangled name.
872 typedef map<string, string> MangledMap;
873 static MangledMap mangledNames;
874 MangledMap::const_iterator const it = mangledNames.find(absFilename());
875 if (it != mangledNames.end())
878 string const name = absFilename();
880 string mname = os::internal_path(name);
881 // Remove the extension.
882 mname = support::changeExtension(name, string());
883 // The mangled name must be a valid LaTeX name.
884 // The list of characters to keep is probably over-restrictive,
885 // but it is not really a problem.
886 // Apart from non-ASCII characters, at least the following characters
887 // are forbidden: '/', '.', ' ', and ':'.
888 // On windows it is not possible to create files with '<', '>' or '?'
890 static string const keep = "abcdefghijklmnopqrstuvwxyz"
891 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
893 string::size_type pos = 0;
894 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
896 // Add the extension back on
897 mname = support::changeExtension(mname, getExtension(name));
899 // Prepend a counter to the filename. This is necessary to make
900 // the mangled name unique.
901 static int counter = 0;
903 s << counter++ << mname;
906 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
907 // is longer than about 160 characters. MiKTeX's pdflatex
908 // is even pickier. A maximum length of 100 has been proven to work.
909 // If dir.size() > max length, all bets are off for YAP. We truncate
910 // the filename nevertheless, keeping a minimum of 10 chars.
912 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
914 // If the mangled file name is too long, hack it to fit.
915 // We know we're guaranteed to have a unique file name because
917 if (mname.size() > max_length) {
918 int const half = (int(max_length) / 2) - 2;
920 mname = mname.substr(0, half) + "___" +
921 mname.substr(mname.size() - half);
925 mangledNames[absFilename()] = mname;
930 bool DocFileName::isZipped() const
932 if (!zipped_valid_) {
933 zipped_ = isZippedFile();
934 zipped_valid_ = true;
940 string DocFileName::unzippedFilename() const
942 return unzippedFileName(absFilename());
946 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
948 return lhs.absFilename() == rhs.absFilename()
949 && lhs.saveAbsPath() == rhs.saveAbsPath();
953 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
955 return !(lhs == rhs);
958 } // namespace support