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 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
312 FileName const tmpfl = FileName::tempName(absFilename() + "/lyxwritetest");
313 return !tmpfl.empty();
317 FileNameList FileName::dirList(string const & ext) const
319 FileNameList dirlist;
320 if (!isDirectory()) {
321 LYXERR0("Directory '" << *this << "' does not exist!");
325 QDir dir = d->fi.absoluteDir();
330 case '.': filter = "*" + toqstr(ext); break;
331 case '*': filter = toqstr(ext); break;
332 default: filter = "*." + toqstr(ext);
334 dir.setNameFilters(QStringList(filter));
335 LYXERR(Debug::FILES, "filtering on extension "
336 << fromqstr(filter) << " is requested.");
339 QFileInfoList list = dir.entryInfoList();
340 for (int i = 0; i != list.size(); ++i) {
341 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
342 dirlist.push_back(fi);
343 LYXERR(Debug::FILES, "found file " << fi);
350 FileName FileName::tempName(string const & mask)
352 FileName tmp_name(mask);
354 if (tmp_name.d->fi.isAbsolute())
357 tmpfl = package().temp_dir().absFilename() + "/" + mask;
359 QTemporaryFile qt_tmp(toqstr(tmpfl));
361 tmp_name.d->fi.setFile(qt_tmp.fileName());
362 LYXERR(Debug::FILES, "Temporary file `" << tmp_name << "' created.");
365 LYXERR(Debug::FILES, "LyX Error: Unable to create temporary file.");
370 FileName FileName::getcwd()
372 return FileName(".");
376 FileName FileName::tempPath()
378 return FileName(fromqstr(QDir::tempPath()));
382 time_t FileName::lastModified() const
384 // QFileInfo caches information about the file. So, in case this file has
385 // been touched between the object creation and now, we refresh the file
388 return d->fi.lastModified().toTime_t();
392 bool FileName::chdir() const
394 return QDir::setCurrent(d->fi.absoluteFilePath());
398 extern unsigned long sum(char const * file);
400 unsigned long FileName::checksum() const
403 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
406 // a directory may be passed here so we need to test it. (bug 3622)
408 LYXERR0('"' << absFilename() << "\" is a directory!");
411 if (!lyxerr.debugging(Debug::FILES))
412 return sum(absFilename().c_str());
416 unsigned long r = sum(absFilename().c_str());
417 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
418 << t.elapsed() << " ms." << endl;
423 bool FileName::removeFile() const
425 bool const success = QFile::remove(d->fi.absoluteFilePath());
426 if (!success && exists())
427 LYXERR0("Could not delete file " << *this);
432 static bool rmdir(QFileInfo const & fi)
434 QDir dir(fi.absoluteFilePath());
435 QFileInfoList list = dir.entryInfoList();
437 for (int i = 0; i != list.size(); ++i) {
438 if (list.at(i).fileName() == ".")
440 if (list.at(i).fileName() == "..")
443 if (list.at(i).isDir()) {
444 LYXERR(Debug::FILES, "Removing dir "
445 << fromqstr(list.at(i).absoluteFilePath()));
446 removed = rmdir(list.at(i));
449 LYXERR(Debug::FILES, "Removing file "
450 << fromqstr(list.at(i).absoluteFilePath()));
451 removed = dir.remove(list.at(i).fileName());
455 LYXERR0("Could not delete "
456 << fromqstr(list.at(i).absoluteFilePath()));
459 QDir parent = fi.absolutePath();
460 success &= parent.rmdir(fi.fileName());
465 bool FileName::destroyDirectory() const
467 bool const success = rmdir(d->fi);
469 LYXERR0("Could not delete " << *this);
475 static int mymkdir(char const * pathname, unsigned long int mode)
477 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
479 # if MKDIR_TAKES_ONE_ARG
481 return ::mkdir(pathname);
482 // FIXME: "Permissions of created directories are ignored on this system."
485 return ::mkdir(pathname, mode_t(mode));
487 #elif defined(_WIN32)
489 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
490 // FIXME: "Permissions of created directories are ignored on this system."
492 return ::_mkdir(pathname);
493 // FIXME: "Permissions of created directories are ignored on this system."
495 # error "Don't know how to create a directory on this system."
501 bool FileName::createDirectory(int permission) const
503 LASSERT(!empty(), /**/);
504 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
508 bool FileName::createPath() const
510 LASSERT(!empty(), /**/);
515 bool success = dir.mkpath(d->fi.absoluteFilePath());
517 LYXERR0("Cannot create path '" << *this << "'!");
522 docstring const FileName::absoluteFilePath() const
524 return qstring_to_ucs4(d->fi.absoluteFilePath());
528 docstring FileName::displayName(int threshold) const
530 return makeDisplayPath(absFilename(), threshold);
534 docstring FileName::fileContents(string const & encoding) const
536 if (!isReadableFile()) {
537 LYXERR0("File '" << *this << "' is not redable!");
541 QFile file(d->fi.absoluteFilePath());
542 if (!file.open(QIODevice::ReadOnly)) {
543 LYXERR0("File '" << *this
544 << "' could not be opened in read only mode!");
547 QByteArray contents = file.readAll();
550 if (contents.isEmpty()) {
551 LYXERR(Debug::FILES, "File '" << *this
552 << "' is either empty or some error happened while reading it.");
557 if (encoding.empty() || encoding == "UTF-8")
558 s = QString::fromUtf8(contents.data());
559 else if (encoding == "ascii")
560 s = QString::fromAscii(contents.data());
561 else if (encoding == "local8bit")
562 s = QString::fromLocal8Bit(contents.data());
563 else if (encoding == "latin1")
564 s = QString::fromLatin1(contents.data());
566 return qstring_to_ucs4(s);
570 void FileName::changeExtension(string const & extension)
572 // FIXME: use Qt native methods...
573 string const oldname = absFilename();
574 string::size_type const last_slash = oldname.rfind('/');
575 string::size_type last_dot = oldname.rfind('.');
576 if (last_dot < last_slash && last_slash != string::npos)
577 last_dot = string::npos;
580 // Make sure the extension starts with a dot
581 if (!extension.empty() && extension[0] != '.')
582 ext= '.' + extension;
586 set(oldname.substr(0, last_dot) + ext);
590 string FileName::guessFormatFromContents() const
592 // the different filetypes and what they contain in one of the first lines
593 // (dots are any characters). (Herbert 20020131)
596 // EPS %!PS-Adobe-3.0 EPSF...
603 // PBM P1... or P4 (B/W)
604 // PGM P2... or P5 (Grayscale)
605 // PPM P3... or P6 (color)
606 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
607 // SGI \001\332... (decimal 474)
609 // TIFF II... or MM...
611 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
612 // ...static char *...
613 // XWD \000\000\000\151 (0x00006900) decimal 105
615 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
616 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
617 // Z \037\235 UNIX compress
620 if (empty() || !isReadableFile())
623 ifstream ifs(toFilesystemEncoding().c_str());
625 // Couldn't open file...
629 static string const gzipStamp = "\037\213";
632 static string const zipStamp = "PK";
635 static string const compressStamp = "\037\235";
637 // Maximum strings to read
638 int const max_count = 50;
643 bool firstLine = true;
644 while ((count++ < max_count) && format.empty()) {
646 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
647 << "\tFile type not recognised before EOF!");
652 string const stamp = str.substr(0, 2);
653 if (firstLine && str.size() >= 2) {
654 // at first we check for a zipped file, because this
655 // information is saved in the first bytes of the file!
656 // also some graphic formats which save the information
657 // in the first line, too.
658 if (prefixIs(str, gzipStamp)) {
661 } else if (stamp == zipStamp) {
664 } else if (stamp == compressStamp) {
668 } else if (stamp == "BM") {
671 } else if (stamp == "\001\332") {
675 // Don't need to use str.at(0), str.at(1) because
676 // we already know that str.size() >= 2
677 } else if (str[0] == 'P') {
693 } else if ((stamp == "II") || (stamp == "MM")) {
696 } else if (prefixIs(str,"%TGIF")) {
699 } else if (prefixIs(str,"#FIG")) {
702 } else if (prefixIs(str,"GIF")) {
705 } else if (str.size() > 3) {
706 int const c = ((str[0] << 24) & (str[1] << 16) &
707 (str[2] << 8) & str[3]);
718 else if (contains(str,"EPSF"))
719 // dummy, if we have wrong file description like
720 // %!PS-Adobe-2.0EPSF"
723 else if (contains(str, "Grace"))
726 else if (contains(str, "JFIF"))
729 else if (contains(str, "%PDF"))
732 else if (contains(str, "PNG"))
735 else if (contains(str, "%!PS-Adobe")) {
738 if (contains(str,"EPSF"))
744 else if (contains(str, "_bits[]"))
747 else if (contains(str, "XPM") || contains(str, "static char *"))
750 else if (contains(str, "BITPIX"))
754 if (!format.empty()) {
755 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
759 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
760 << "\tCouldn't find a known format!");
765 bool FileName::isZippedFile() const
767 string const type = guessFormatFromContents();
768 return contains("gzip zip compress", type) && !type.empty();
772 docstring const FileName::relPath(string const & path) const
775 return makeRelPath(absoluteFilePath(), from_utf8(path));
779 bool operator==(FileName const & lhs, FileName const & rhs)
781 return lhs.absFilename() == rhs.absFilename();
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 ostream & operator<<(ostream & os, FileName const & filename)
805 return os << filename.absFilename();
809 /////////////////////////////////////////////////////////////////////
813 /////////////////////////////////////////////////////////////////////
816 DocFileName::DocFileName()
817 : save_abs_path_(true)
821 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
822 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
826 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
827 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
831 void DocFileName::set(string const & name, string const & buffer_path)
834 bool const nameIsAbsolute = isAbsolute();
835 save_abs_path_ = nameIsAbsolute;
837 FileName::set(makeAbsPath(name, buffer_path).absFilename());
838 zipped_valid_ = false;
842 void DocFileName::erase()
845 zipped_valid_ = false;
849 string DocFileName::relFilename(string const & path) const
852 return to_utf8(relPath(path));
856 string DocFileName::outputFilename(string const & path) const
858 return save_abs_path_ ? absFilename() : relFilename(path);
862 string DocFileName::mangledFilename(string const & dir) const
864 // We need to make sure that every DocFileName instance for a given
865 // filename returns the same mangled name.
866 typedef map<string, string> MangledMap;
867 static MangledMap mangledNames;
868 MangledMap::const_iterator const it = mangledNames.find(absFilename());
869 if (it != mangledNames.end())
872 string const name = absFilename();
874 string mname = os::internal_path(name);
875 // Remove the extension.
876 mname = support::changeExtension(name, string());
877 // The mangled name must be a valid LaTeX name.
878 // The list of characters to keep is probably over-restrictive,
879 // but it is not really a problem.
880 // Apart from non-ASCII characters, at least the following characters
881 // are forbidden: '/', '.', ' ', and ':'.
882 // On windows it is not possible to create files with '<', '>' or '?'
884 static string const keep = "abcdefghijklmnopqrstuvwxyz"
885 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
887 string::size_type pos = 0;
888 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
890 // Add the extension back on
891 mname = support::changeExtension(mname, getExtension(name));
893 // Prepend a counter to the filename. This is necessary to make
894 // the mangled name unique.
895 static int counter = 0;
897 s << counter++ << mname;
900 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
901 // is longer than about 160 characters. MiKTeX's pdflatex
902 // is even pickier. A maximum length of 100 has been proven to work.
903 // If dir.size() > max length, all bets are off for YAP. We truncate
904 // the filename nevertheless, keeping a minimum of 10 chars.
906 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
908 // If the mangled file name is too long, hack it to fit.
909 // We know we're guaranteed to have a unique file name because
911 if (mname.size() > max_length) {
912 int const half = (int(max_length) / 2) - 2;
914 mname = mname.substr(0, half) + "___" +
915 mname.substr(mname.size() - half);
919 mangledNames[absFilename()] = mname;
924 bool DocFileName::isZipped() const
926 if (!zipped_valid_) {
927 zipped_ = isZippedFile();
928 zipped_valid_ = true;
934 string DocFileName::unzippedFilename() const
936 return unzippedFileName(absFilename());
940 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
942 return lhs.absFilename() == rhs.absFilename()
943 && lhs.saveAbsPath() == rhs.saveAbsPath();
947 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
949 return !(lhs == rhs);
952 } // namespace support