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/debug.h"
17 #include "support/filetools.h"
18 #include "support/lstrings.h"
19 #include "support/lyxlib.h"
20 #include "support/os.h"
21 #include "support/qstring_helpers.h"
30 #include <boost/assert.hpp>
37 #ifdef HAVE_SYS_TYPES_H
38 # include <sys/types.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
52 /////////////////////////////////////////////////////////////////////
56 /////////////////////////////////////////////////////////////////////
58 struct FileName::Private
62 Private(string const & abs_filename) : fi(toqstr(abs_filename))
64 fi.setCaching(fi.exists() ? true : false);
70 /////////////////////////////////////////////////////////////////////
74 /////////////////////////////////////////////////////////////////////
77 FileName::FileName() : d(new Private)
82 FileName::FileName(string const & abs_filename)
83 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
94 FileName::FileName(FileName const & rhs) : d(new Private)
100 FileName & FileName::operator=(FileName const & rhs)
107 bool FileName::empty() const
109 return d->fi.absoluteFilePath().isEmpty();
113 string FileName::absFilename() const
115 return fromqstr(d->fi.absoluteFilePath());
119 void FileName::set(string const & name)
121 d->fi.setFile(toqstr(name));
122 BOOST_ASSERT(d->fi.isAbsolute());
126 void FileName::erase()
132 bool FileName::copyTo(FileName const & name, bool overwrite) const
135 QFile::remove(name.d->fi.absoluteFilePath());
136 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
138 lyxerr << "FileName::copyTo(): Could not copy file "
139 << *this << " to " << name << endl;
144 bool FileName::renameTo(FileName const & name) const
146 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
148 LYXERR0("Could not rename file " << *this << " to " << name);
153 bool FileName::changePermission(unsigned long int mode) const
156 LYXERR0("File " << *this << " is not writable!");
160 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
161 if (::chmod(file.toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
162 LYXERR0("File " << *this << ": cannot change permission to "
171 string FileName::toFilesystemEncoding() const
173 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
174 return string(encoded.begin(), encoded.end());
178 FileName FileName::fromFilesystemEncoding(string const & name)
180 QByteArray const encoded(name.c_str(), name.length());
181 return FileName(fromqstr(QFile::decodeName(encoded)));
185 bool FileName::exists() const
187 return d->fi.exists();
191 bool FileName::isSymLink() const
193 return d->fi.isSymLink();
197 bool FileName::isFileEmpty() const
199 return d->fi.size() == 0;
203 bool FileName::isDirectory() const
205 return d->fi.isDir();
209 bool FileName::isReadOnly() const
211 return d->fi.isReadable() && !d->fi.isWritable();
215 bool FileName::isReadableDirectory() const
217 return d->fi.isDir() && d->fi.isReadable();
221 string FileName::onlyFileName() const
223 return support::onlyFilename(absFilename());
227 FileName FileName::onlyPath() const
229 return FileName(support::onlyPath(absFilename()));
233 bool FileName::isReadableFile() const
235 return d->fi.isFile() && d->fi.isReadable();
239 bool FileName::isWritable() const
241 return d->fi.isWritable();
245 bool FileName::isDirWritable() const
247 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
249 FileName const tmpfl(tempName(*this, "lyxwritetest"));
259 FileNameList FileName::dirList(string const & ext) const
261 FileNameList dirlist;
262 if (!isDirectory()) {
263 LYXERR0("Directory '" << *this << "' does not exist!");
267 QDir dir = d->fi.absoluteDir();
272 case '.': filter = "*" + toqstr(ext); break;
273 case '*': filter = toqstr(ext); break;
274 default: filter = "*." + toqstr(ext);
276 dir.setNameFilters(QStringList(filter));
277 LYXERR(Debug::FILES, "filtering on extension "
278 << fromqstr(filter) << " is requested.");
281 QFileInfoList list = dir.entryInfoList();
282 for (int i = 0; i != list.size(); ++i) {
283 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
284 dirlist.push_back(fi);
285 LYXERR(Debug::FILES, "found file " << fi);
292 FileName FileName::tempName(FileName const & dir, string const & mask)
294 return support::tempName(dir, mask);
298 time_t FileName::lastModified() const
300 return d->fi.lastModified().toTime_t();
304 bool FileName::chdir() const
306 return QDir::setCurrent(d->fi.absoluteFilePath());
310 extern unsigned long sum(char const * file);
312 unsigned long FileName::checksum() const
315 LYXERR0("File \"" << absFilename() << "\" does not exist!");
318 // a directory may be passed here so we need to test it. (bug 3622)
320 LYXERR0('"' << absFilename() << "\" is a directory!");
323 if (!lyxerr.debugging(Debug::FILES))
324 return sum(absFilename().c_str());
328 unsigned long r = sum(absFilename().c_str());
329 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
330 << t.elapsed() << " ms." << endl;
335 bool FileName::removeFile() const
337 bool const success = QFile::remove(d->fi.absoluteFilePath());
338 if (!success && exists())
339 LYXERR0("Could not delete file " << *this);
344 static bool rmdir(QFileInfo const & fi)
346 QDir dir(fi.absoluteFilePath());
347 QFileInfoList list = dir.entryInfoList();
349 for (int i = 0; i != list.size(); ++i) {
350 if (list.at(i).fileName() == ".")
352 if (list.at(i).fileName() == "..")
355 if (list.at(i).isDir()) {
356 LYXERR(Debug::FILES, "Removing dir "
357 << fromqstr(list.at(i).absoluteFilePath()));
358 removed = rmdir(list.at(i));
361 LYXERR(Debug::FILES, "Removing file "
362 << fromqstr(list.at(i).absoluteFilePath()));
363 removed = dir.remove(list.at(i).fileName());
367 LYXERR0("Could not delete "
368 << fromqstr(list.at(i).absoluteFilePath()));
371 QDir parent = fi.absolutePath();
372 success &= parent.rmdir(fi.fileName());
377 bool FileName::destroyDirectory() const
379 bool const success = rmdir(d->fi);
381 LYXERR0("Could not delete " << *this);
387 bool FileName::createDirectory(int permission) const
389 BOOST_ASSERT(!empty());
390 return mkdir(*this, permission) == 0;
394 docstring const FileName::absoluteFilePath() const
396 return qstring_to_ucs4(d->fi.absoluteFilePath());
400 docstring FileName::displayName(int threshold) const
402 return makeDisplayPath(absFilename(), threshold);
406 docstring FileName::fileContents(string const & encoding) const
408 if (!isReadableFile()) {
409 LYXERR0("File '" << *this << "' is not redable!");
413 QFile file(d->fi.absoluteFilePath());
414 if (!file.open(QIODevice::ReadOnly)) {
415 LYXERR0("File '" << *this
416 << "' could not be opened in read only mode!");
419 QByteArray contents = file.readAll();
422 if (contents.isEmpty()) {
423 LYXERR(Debug::FILES, "File '" << *this
424 << "' is either empty or some error happened while reading it.");
429 if (encoding.empty() || encoding == "UTF-8")
430 s = QString::fromUtf8(contents.data());
431 else if (encoding == "ascii")
432 s = QString::fromAscii(contents.data());
433 else if (encoding == "local8bit")
434 s = QString::fromLocal8Bit(contents.data());
435 else if (encoding == "latin1")
436 s = QString::fromLatin1(contents.data());
438 return qstring_to_ucs4(s);
442 void FileName::changeExtension(string const & extension)
444 // FIXME: use Qt native methods...
445 string const oldname = absFilename();
446 string::size_type const last_slash = oldname.rfind('/');
447 string::size_type last_dot = oldname.rfind('.');
448 if (last_dot < last_slash && last_slash != string::npos)
449 last_dot = string::npos;
452 // Make sure the extension starts with a dot
453 if (!extension.empty() && extension[0] != '.')
454 ext= '.' + extension;
458 set(oldname.substr(0, last_dot) + ext);
462 string FileName::guessFormatFromContents() const
464 // the different filetypes and what they contain in one of the first lines
465 // (dots are any characters). (Herbert 20020131)
468 // EPS %!PS-Adobe-3.0 EPSF...
475 // PBM P1... or P4 (B/W)
476 // PGM P2... or P5 (Grayscale)
477 // PPM P3... or P6 (color)
478 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
479 // SGI \001\332... (decimal 474)
481 // TIFF II... or MM...
483 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
484 // ...static char *...
485 // XWD \000\000\000\151 (0x00006900) decimal 105
487 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
488 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
489 // Z \037\235 UNIX compress
492 if (empty() || !isReadableFile())
495 ifstream ifs(toFilesystemEncoding().c_str());
497 // Couldn't open file...
501 static string const gzipStamp = "\037\213";
504 static string const zipStamp = "PK";
507 static string const compressStamp = "\037\235";
509 // Maximum strings to read
510 int const max_count = 50;
515 bool firstLine = true;
516 while ((count++ < max_count) && format.empty()) {
518 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
519 << "\tFile type not recognised before EOF!");
524 string const stamp = str.substr(0, 2);
525 if (firstLine && str.size() >= 2) {
526 // at first we check for a zipped file, because this
527 // information is saved in the first bytes of the file!
528 // also some graphic formats which save the information
529 // in the first line, too.
530 if (prefixIs(str, gzipStamp)) {
533 } else if (stamp == zipStamp) {
536 } else if (stamp == compressStamp) {
540 } else if (stamp == "BM") {
543 } else if (stamp == "\001\332") {
547 // Don't need to use str.at(0), str.at(1) because
548 // we already know that str.size() >= 2
549 } else if (str[0] == 'P') {
565 } else if ((stamp == "II") || (stamp == "MM")) {
568 } else if (prefixIs(str,"%TGIF")) {
571 } else if (prefixIs(str,"#FIG")) {
574 } else if (prefixIs(str,"GIF")) {
577 } else if (str.size() > 3) {
578 int const c = ((str[0] << 24) & (str[1] << 16) &
579 (str[2] << 8) & str[3]);
590 else if (contains(str,"EPSF"))
591 // dummy, if we have wrong file description like
592 // %!PS-Adobe-2.0EPSF"
595 else if (contains(str, "Grace"))
598 else if (contains(str, "JFIF"))
601 else if (contains(str, "%PDF"))
604 else if (contains(str, "PNG"))
607 else if (contains(str, "%!PS-Adobe")) {
610 if (contains(str,"EPSF"))
616 else if (contains(str, "_bits[]"))
619 else if (contains(str, "XPM") || contains(str, "static char *"))
622 else if (contains(str, "BITPIX"))
626 if (!format.empty()) {
627 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
631 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
632 << "\tCouldn't find a known format!");
637 bool FileName::isZippedFile() const
639 string const type = guessFormatFromContents();
640 return contains("gzip zip compress", type) && !type.empty();
644 docstring const FileName::relPath(string const & path) const
647 return makeRelPath(absoluteFilePath(), from_utf8(path));
651 bool operator==(FileName const & lhs, FileName const & rhs)
653 return lhs.absFilename() == rhs.absFilename();
657 bool operator!=(FileName const & lhs, FileName const & rhs)
659 return lhs.absFilename() != rhs.absFilename();
663 bool operator<(FileName const & lhs, FileName const & rhs)
665 return lhs.absFilename() < rhs.absFilename();
669 bool operator>(FileName const & lhs, FileName const & rhs)
671 return lhs.absFilename() > rhs.absFilename();
675 ostream & operator<<(ostream & os, FileName const & filename)
677 return os << filename.absFilename();
681 /////////////////////////////////////////////////////////////////////
685 /////////////////////////////////////////////////////////////////////
688 DocFileName::DocFileName()
689 : save_abs_path_(true)
693 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
694 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
698 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
699 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
703 void DocFileName::set(string const & name, string const & buffer_path)
705 save_abs_path_ = absolutePath(name);
706 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
707 zipped_valid_ = false;
711 void DocFileName::erase()
714 zipped_valid_ = false;
718 string DocFileName::relFilename(string const & path) const
721 return to_utf8(relPath(path));
725 string DocFileName::outputFilename(string const & path) const
727 return save_abs_path_ ? absFilename() : relFilename(path);
731 string DocFileName::mangledFilename(string const & dir) const
733 // We need to make sure that every DocFileName instance for a given
734 // filename returns the same mangled name.
735 typedef map<string, string> MangledMap;
736 static MangledMap mangledNames;
737 MangledMap::const_iterator const it = mangledNames.find(absFilename());
738 if (it != mangledNames.end())
741 string const name = absFilename();
743 string mname = os::internal_path(name);
744 // Remove the extension.
745 mname = support::changeExtension(name, string());
746 // The mangled name must be a valid LaTeX name.
747 // The list of characters to keep is probably over-restrictive,
748 // but it is not really a problem.
749 // Apart from non-ASCII characters, at least the following characters
750 // are forbidden: '/', '.', ' ', and ':'.
751 // On windows it is not possible to create files with '<', '>' or '?'
753 static string const keep = "abcdefghijklmnopqrstuvwxyz"
754 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
756 string::size_type pos = 0;
757 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
759 // Add the extension back on
760 mname = support::changeExtension(mname, getExtension(name));
762 // Prepend a counter to the filename. This is necessary to make
763 // the mangled name unique.
764 static int counter = 0;
766 s << counter++ << mname;
769 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
770 // is longer than about 160 characters. MiKTeX's pdflatex
771 // is even pickier. A maximum length of 100 has been proven to work.
772 // If dir.size() > max length, all bets are off for YAP. We truncate
773 // the filename nevertheless, keeping a minimum of 10 chars.
775 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
777 // If the mangled file name is too long, hack it to fit.
778 // We know we're guaranteed to have a unique file name because
780 if (mname.size() > max_length) {
781 int const half = (int(max_length) / 2) - 2;
783 mname = mname.substr(0, half) + "___" +
784 mname.substr(mname.size() - half);
788 mangledNames[absFilename()] = mname;
793 bool DocFileName::isZipped() const
795 if (!zipped_valid_) {
796 zipped_ = isZippedFile();
797 zipped_valid_ = true;
803 string DocFileName::unzippedFilename() const
805 return unzippedFileName(absFilename());
809 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
811 return lhs.absFilename() == rhs.absFilename()
812 && lhs.saveAbsPath() == rhs.saveAbsPath();
816 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
818 return !(lhs == rhs);
821 } // namespace support