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))
68 /////////////////////////////////////////////////////////////////////
72 /////////////////////////////////////////////////////////////////////
75 FileName::FileName() : d(new Private)
80 FileName::FileName(string const & abs_filename)
81 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
92 FileName::FileName(FileName const & rhs) : d(new Private)
98 FileName & FileName::operator=(FileName const & rhs)
105 bool FileName::empty() const
107 return d->fi.absoluteFilePath().isEmpty();
111 string FileName::absFilename() const
113 return fromqstr(d->fi.absoluteFilePath());
117 void FileName::set(string const & name)
119 d->fi.setFile(toqstr(name));
120 BOOST_ASSERT(d->fi.isAbsolute());
124 void FileName::erase()
130 bool FileName::copyTo(FileName const & name, bool overwrite) const
133 QFile::remove(name.d->fi.absoluteFilePath());
134 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
136 lyxerr << "FileName::copyTo(): Could not copy file "
137 << *this << " to " << name << endl;
142 string FileName::toFilesystemEncoding() const
144 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
145 return string(encoded.begin(), encoded.end());
149 FileName FileName::fromFilesystemEncoding(string const & name)
151 QByteArray const encoded(name.c_str(), name.length());
152 return FileName(fromqstr(QFile::decodeName(encoded)));
156 bool FileName::exists() const
158 return d->fi.exists();
162 bool FileName::isSymLink() const
164 return d->fi.isSymLink();
168 bool FileName::isFileEmpty() const
170 return d->fi.size() == 0;
174 bool FileName::isDirectory() const
176 return d->fi.isDir();
180 bool FileName::isReadOnly() const
182 return d->fi.isReadable() && !d->fi.isWritable();
186 bool FileName::isReadableDirectory() const
188 return d->fi.isDir() && d->fi.isReadable();
192 string FileName::onlyFileName() const
194 return support::onlyFilename(absFilename());
198 FileName FileName::onlyPath() const
200 return FileName(support::onlyPath(absFilename()));
204 bool FileName::isReadableFile() const
206 return d->fi.isFile() && d->fi.isReadable();
210 bool FileName::isWritable() const
212 return d->fi.isWritable();
216 bool FileName::isDirWritable() const
218 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
220 FileName const tmpfl(tempName(*this, "lyxwritetest"));
230 FileNameList FileName::dirList(string const & ext) const
232 FileNameList dirlist;
233 if (!isDirectory()) {
234 LYXERR0("Directory '" << *this << "' does not exist!");
238 QDir dir = d->fi.absoluteDir();
243 case '.': filter = "*" + toqstr(ext); break;
244 case '*': filter = toqstr(ext); break;
245 default: filter = "*." + toqstr(ext);
247 dir.setNameFilters(QStringList(filter));
248 LYXERR(Debug::FILES, "filtering on extension "
249 << fromqstr(filter) << " is requested.");
252 QFileInfoList list = dir.entryInfoList();
253 for (int i = 0; i != list.size(); ++i) {
254 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
255 dirlist.push_back(fi);
256 LYXERR(Debug::FILES, "found file " << fi);
263 FileName FileName::tempName(FileName const & dir, string const & mask)
265 return support::tempName(dir, mask);
269 time_t FileName::lastModified() const
271 return d->fi.lastModified().toTime_t();
275 bool FileName::chdir() const
277 return QDir::setCurrent(d->fi.absoluteFilePath());
281 extern unsigned long sum(char const * file);
283 unsigned long FileName::checksum() const
286 LYXERR0("File \"" << absFilename() << "\" does not exist!");
289 // a directory may be passed here so we need to test it. (bug 3622)
291 LYXERR0('"' << absFilename() << "\" is a directory!");
294 if (!lyxerr.debugging(Debug::FILES))
295 return sum(absFilename().c_str());
299 unsigned long r = sum(absFilename().c_str());
300 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
301 << t.elapsed() << " ms." << endl;
306 bool FileName::removeFile() const
308 bool const success = QFile::remove(d->fi.absoluteFilePath());
309 if (!success && exists())
310 LYXERR0("Could not delete file " << *this);
315 static bool rmdir(QFileInfo const & fi)
317 QDir dir(fi.absoluteFilePath());
318 QFileInfoList list = dir.entryInfoList();
320 for (int i = 0; i != list.size(); ++i) {
321 if (list.at(i).fileName() == ".")
323 if (list.at(i).fileName() == "..")
326 if (list.at(i).isDir()) {
327 LYXERR(Debug::FILES, "Removing dir "
328 << fromqstr(list.at(i).absoluteFilePath()));
329 removed = rmdir(list.at(i));
332 LYXERR(Debug::FILES, "Removing file "
333 << fromqstr(list.at(i).absoluteFilePath()));
334 removed = dir.remove(list.at(i).fileName());
338 LYXERR0("Could not delete "
339 << fromqstr(list.at(i).absoluteFilePath()));
342 QDir parent = fi.absolutePath();
343 success &= parent.rmdir(fi.fileName());
348 bool FileName::destroyDirectory() const
350 bool const success = rmdir(d->fi);
352 LYXERR0("Could not delete " << *this);
358 bool FileName::createDirectory(int permission) const
360 BOOST_ASSERT(!empty());
361 return mkdir(*this, permission) == 0;
365 docstring const FileName::absoluteFilePath() const
367 return qstring_to_ucs4(d->fi.absoluteFilePath());
371 docstring FileName::displayName(int threshold) const
373 return makeDisplayPath(absFilename(), threshold);
377 docstring FileName::fileContents(string const & encoding) const
379 if (!isReadableFile()) {
380 LYXERR0("File '" << *this << "' is not redable!");
384 QFile file(d->fi.absoluteFilePath());
385 if (!file.open(QIODevice::ReadOnly)) {
386 LYXERR0("File '" << *this
387 << "' could not be opened in read only mode!");
390 QByteArray contents = file.readAll();
393 if (contents.isEmpty()) {
394 LYXERR(Debug::FILES, "File '" << *this
395 << "' is either empty or some error happened while reading it.");
400 if (encoding.empty() || encoding == "UTF-8")
401 s = QString::fromUtf8(contents.data());
402 else if (encoding == "ascii")
403 s = QString::fromAscii(contents.data());
404 else if (encoding == "local8bit")
405 s = QString::fromLocal8Bit(contents.data());
406 else if (encoding == "latin1")
407 s = QString::fromLatin1(contents.data());
409 return qstring_to_ucs4(s);
413 void FileName::changeExtension(string const & extension)
415 // FIXME: use Qt native methods...
416 string const oldname = absFilename();
417 string::size_type const last_slash = oldname.rfind('/');
418 string::size_type last_dot = oldname.rfind('.');
419 if (last_dot < last_slash && last_slash != string::npos)
420 last_dot = string::npos;
423 // Make sure the extension starts with a dot
424 if (!extension.empty() && extension[0] != '.')
425 ext= '.' + extension;
429 set(oldname.substr(0, last_dot) + ext);
433 string FileName::guessFormatFromContents() const
435 // the different filetypes and what they contain in one of the first lines
436 // (dots are any characters). (Herbert 20020131)
439 // EPS %!PS-Adobe-3.0 EPSF...
446 // PBM P1... or P4 (B/W)
447 // PGM P2... or P5 (Grayscale)
448 // PPM P3... or P6 (color)
449 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
450 // SGI \001\332... (decimal 474)
452 // TIFF II... or MM...
454 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
455 // ...static char *...
456 // XWD \000\000\000\151 (0x00006900) decimal 105
458 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
459 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
460 // Z \037\235 UNIX compress
463 if (empty() || !isReadableFile())
466 ifstream ifs(toFilesystemEncoding().c_str());
468 // Couldn't open file...
472 static string const gzipStamp = "\037\213";
475 static string const zipStamp = "PK";
478 static string const compressStamp = "\037\235";
480 // Maximum strings to read
481 int const max_count = 50;
486 bool firstLine = true;
487 while ((count++ < max_count) && format.empty()) {
489 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
490 << "\tFile type not recognised before EOF!");
495 string const stamp = str.substr(0, 2);
496 if (firstLine && str.size() >= 2) {
497 // at first we check for a zipped file, because this
498 // information is saved in the first bytes of the file!
499 // also some graphic formats which save the information
500 // in the first line, too.
501 if (prefixIs(str, gzipStamp)) {
504 } else if (stamp == zipStamp) {
507 } else if (stamp == compressStamp) {
511 } else if (stamp == "BM") {
514 } else if (stamp == "\001\332") {
518 // Don't need to use str.at(0), str.at(1) because
519 // we already know that str.size() >= 2
520 } else if (str[0] == 'P') {
536 } else if ((stamp == "II") || (stamp == "MM")) {
539 } else if (prefixIs(str,"%TGIF")) {
542 } else if (prefixIs(str,"#FIG")) {
545 } else if (prefixIs(str,"GIF")) {
548 } else if (str.size() > 3) {
549 int const c = ((str[0] << 24) & (str[1] << 16) &
550 (str[2] << 8) & str[3]);
561 else if (contains(str,"EPSF"))
562 // dummy, if we have wrong file description like
563 // %!PS-Adobe-2.0EPSF"
566 else if (contains(str, "Grace"))
569 else if (contains(str, "JFIF"))
572 else if (contains(str, "%PDF"))
575 else if (contains(str, "PNG"))
578 else if (contains(str, "%!PS-Adobe")) {
581 if (contains(str,"EPSF"))
587 else if (contains(str, "_bits[]"))
590 else if (contains(str, "XPM") || contains(str, "static char *"))
593 else if (contains(str, "BITPIX"))
597 if (!format.empty()) {
598 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
602 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
603 << "\tCouldn't find a known format!");
608 bool FileName::isZippedFile() const
610 string const type = guessFormatFromContents();
611 return contains("gzip zip compress", type) && !type.empty();
615 docstring const FileName::relPath(string const & path) const
618 return makeRelPath(absoluteFilePath(), from_utf8(path));
622 bool operator==(FileName const & lhs, FileName const & rhs)
624 return lhs.absFilename() == rhs.absFilename();
628 bool operator!=(FileName const & lhs, FileName const & rhs)
630 return lhs.absFilename() != rhs.absFilename();
634 bool operator<(FileName const & lhs, FileName const & rhs)
636 return lhs.absFilename() < rhs.absFilename();
640 bool operator>(FileName const & lhs, FileName const & rhs)
642 return lhs.absFilename() > rhs.absFilename();
646 ostream & operator<<(ostream & os, FileName const & filename)
648 return os << filename.absFilename();
652 /////////////////////////////////////////////////////////////////////
656 /////////////////////////////////////////////////////////////////////
659 DocFileName::DocFileName()
660 : save_abs_path_(true)
664 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
665 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
669 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
670 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
674 void DocFileName::set(string const & name, string const & buffer_path)
676 save_abs_path_ = absolutePath(name);
677 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
678 zipped_valid_ = false;
682 void DocFileName::erase()
685 zipped_valid_ = false;
689 string DocFileName::relFilename(string const & path) const
692 return to_utf8(relPath(path));
696 string DocFileName::outputFilename(string const & path) const
698 return save_abs_path_ ? absFilename() : relFilename(path);
702 string DocFileName::mangledFilename(string const & dir) const
704 // We need to make sure that every DocFileName instance for a given
705 // filename returns the same mangled name.
706 typedef map<string, string> MangledMap;
707 static MangledMap mangledNames;
708 MangledMap::const_iterator const it = mangledNames.find(absFilename());
709 if (it != mangledNames.end())
712 string const name = absFilename();
714 string mname = os::internal_path(name);
715 // Remove the extension.
716 mname = support::changeExtension(name, string());
717 // The mangled name must be a valid LaTeX name.
718 // The list of characters to keep is probably over-restrictive,
719 // but it is not really a problem.
720 // Apart from non-ASCII characters, at least the following characters
721 // are forbidden: '/', '.', ' ', and ':'.
722 // On windows it is not possible to create files with '<', '>' or '?'
724 static string const keep = "abcdefghijklmnopqrstuvwxyz"
725 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
727 string::size_type pos = 0;
728 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
730 // Add the extension back on
731 mname = support::changeExtension(mname, getExtension(name));
733 // Prepend a counter to the filename. This is necessary to make
734 // the mangled name unique.
735 static int counter = 0;
737 s << counter++ << mname;
740 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
741 // is longer than about 160 characters. MiKTeX's pdflatex
742 // is even pickier. A maximum length of 100 has been proven to work.
743 // If dir.size() > max length, all bets are off for YAP. We truncate
744 // the filename nevertheless, keeping a minimum of 10 chars.
746 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
748 // If the mangled file name is too long, hack it to fit.
749 // We know we're guaranteed to have a unique file name because
751 if (mname.size() > max_length) {
752 int const half = (int(max_length) / 2) - 2;
754 mname = mname.substr(0, half) + "___" +
755 mname.substr(mname.size() - half);
759 mangledNames[absFilename()] = mname;
764 bool DocFileName::isZipped() const
766 if (!zipped_valid_) {
767 zipped_ = isZippedFile();
768 zipped_valid_ = true;
774 string DocFileName::unzippedFilename() const
776 return unzippedFileName(absFilename());
780 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
782 return lhs.absFilename() == rhs.absFilename()
783 && lhs.saveAbsPath() == rhs.saveAbsPath();
787 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
789 return !(lhs == rhs);
792 } // namespace support