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 bool FileName::renameTo(FileName const & name) const
144 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
146 LYXERR0("Could not rename file " << *this << " to " << name);
151 string FileName::toFilesystemEncoding() const
153 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
154 return string(encoded.begin(), encoded.end());
158 FileName FileName::fromFilesystemEncoding(string const & name)
160 QByteArray const encoded(name.c_str(), name.length());
161 return FileName(fromqstr(QFile::decodeName(encoded)));
165 bool FileName::exists() const
167 return d->fi.exists();
171 bool FileName::isSymLink() const
173 return d->fi.isSymLink();
177 bool FileName::isFileEmpty() const
179 return d->fi.size() == 0;
183 bool FileName::isDirectory() const
185 return d->fi.isDir();
189 bool FileName::isReadOnly() const
191 return d->fi.isReadable() && !d->fi.isWritable();
195 bool FileName::isReadableDirectory() const
197 return d->fi.isDir() && d->fi.isReadable();
201 string FileName::onlyFileName() const
203 return support::onlyFilename(absFilename());
207 FileName FileName::onlyPath() const
209 return FileName(support::onlyPath(absFilename()));
213 bool FileName::isReadableFile() const
215 return d->fi.isFile() && d->fi.isReadable();
219 bool FileName::isWritable() const
221 return d->fi.isWritable();
225 bool FileName::isDirWritable() const
227 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
229 FileName const tmpfl(tempName(*this, "lyxwritetest"));
239 FileNameList FileName::dirList(string const & ext) const
241 FileNameList dirlist;
242 if (!isDirectory()) {
243 LYXERR0("Directory '" << *this << "' does not exist!");
247 QDir dir = d->fi.absoluteDir();
252 case '.': filter = "*" + toqstr(ext); break;
253 case '*': filter = toqstr(ext); break;
254 default: filter = "*." + toqstr(ext);
256 dir.setNameFilters(QStringList(filter));
257 LYXERR(Debug::FILES, "filtering on extension "
258 << fromqstr(filter) << " is requested.");
261 QFileInfoList list = dir.entryInfoList();
262 for (int i = 0; i != list.size(); ++i) {
263 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
264 dirlist.push_back(fi);
265 LYXERR(Debug::FILES, "found file " << fi);
272 FileName FileName::tempName(FileName const & dir, string const & mask)
274 return support::tempName(dir, mask);
278 time_t FileName::lastModified() const
280 return d->fi.lastModified().toTime_t();
284 bool FileName::chdir() const
286 return QDir::setCurrent(d->fi.absoluteFilePath());
290 extern unsigned long sum(char const * file);
292 unsigned long FileName::checksum() const
295 LYXERR0("File \"" << absFilename() << "\" does not exist!");
298 // a directory may be passed here so we need to test it. (bug 3622)
300 LYXERR0('"' << absFilename() << "\" is a directory!");
303 if (!lyxerr.debugging(Debug::FILES))
304 return sum(absFilename().c_str());
308 unsigned long r = sum(absFilename().c_str());
309 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
310 << t.elapsed() << " ms." << endl;
315 bool FileName::removeFile() const
317 bool const success = QFile::remove(d->fi.absoluteFilePath());
318 if (!success && exists())
319 LYXERR0("Could not delete file " << *this);
324 static bool rmdir(QFileInfo const & fi)
326 QDir dir(fi.absoluteFilePath());
327 QFileInfoList list = dir.entryInfoList();
329 for (int i = 0; i != list.size(); ++i) {
330 if (list.at(i).fileName() == ".")
332 if (list.at(i).fileName() == "..")
335 if (list.at(i).isDir()) {
336 LYXERR(Debug::FILES, "Removing dir "
337 << fromqstr(list.at(i).absoluteFilePath()));
338 removed = rmdir(list.at(i));
341 LYXERR(Debug::FILES, "Removing file "
342 << fromqstr(list.at(i).absoluteFilePath()));
343 removed = dir.remove(list.at(i).fileName());
347 LYXERR0("Could not delete "
348 << fromqstr(list.at(i).absoluteFilePath()));
351 QDir parent = fi.absolutePath();
352 success &= parent.rmdir(fi.fileName());
357 bool FileName::destroyDirectory() const
359 bool const success = rmdir(d->fi);
361 LYXERR0("Could not delete " << *this);
367 bool FileName::createDirectory(int permission) const
369 BOOST_ASSERT(!empty());
370 return mkdir(*this, permission) == 0;
374 docstring const FileName::absoluteFilePath() const
376 return qstring_to_ucs4(d->fi.absoluteFilePath());
380 docstring FileName::displayName(int threshold) const
382 return makeDisplayPath(absFilename(), threshold);
386 docstring FileName::fileContents(string const & encoding) const
388 if (!isReadableFile()) {
389 LYXERR0("File '" << *this << "' is not redable!");
393 QFile file(d->fi.absoluteFilePath());
394 if (!file.open(QIODevice::ReadOnly)) {
395 LYXERR0("File '" << *this
396 << "' could not be opened in read only mode!");
399 QByteArray contents = file.readAll();
402 if (contents.isEmpty()) {
403 LYXERR(Debug::FILES, "File '" << *this
404 << "' is either empty or some error happened while reading it.");
409 if (encoding.empty() || encoding == "UTF-8")
410 s = QString::fromUtf8(contents.data());
411 else if (encoding == "ascii")
412 s = QString::fromAscii(contents.data());
413 else if (encoding == "local8bit")
414 s = QString::fromLocal8Bit(contents.data());
415 else if (encoding == "latin1")
416 s = QString::fromLatin1(contents.data());
418 return qstring_to_ucs4(s);
422 void FileName::changeExtension(string const & extension)
424 // FIXME: use Qt native methods...
425 string const oldname = absFilename();
426 string::size_type const last_slash = oldname.rfind('/');
427 string::size_type last_dot = oldname.rfind('.');
428 if (last_dot < last_slash && last_slash != string::npos)
429 last_dot = string::npos;
432 // Make sure the extension starts with a dot
433 if (!extension.empty() && extension[0] != '.')
434 ext= '.' + extension;
438 set(oldname.substr(0, last_dot) + ext);
442 string FileName::guessFormatFromContents() const
444 // the different filetypes and what they contain in one of the first lines
445 // (dots are any characters). (Herbert 20020131)
448 // EPS %!PS-Adobe-3.0 EPSF...
455 // PBM P1... or P4 (B/W)
456 // PGM P2... or P5 (Grayscale)
457 // PPM P3... or P6 (color)
458 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
459 // SGI \001\332... (decimal 474)
461 // TIFF II... or MM...
463 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
464 // ...static char *...
465 // XWD \000\000\000\151 (0x00006900) decimal 105
467 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
468 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
469 // Z \037\235 UNIX compress
472 if (empty() || !isReadableFile())
475 ifstream ifs(toFilesystemEncoding().c_str());
477 // Couldn't open file...
481 static string const gzipStamp = "\037\213";
484 static string const zipStamp = "PK";
487 static string const compressStamp = "\037\235";
489 // Maximum strings to read
490 int const max_count = 50;
495 bool firstLine = true;
496 while ((count++ < max_count) && format.empty()) {
498 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
499 << "\tFile type not recognised before EOF!");
504 string const stamp = str.substr(0, 2);
505 if (firstLine && str.size() >= 2) {
506 // at first we check for a zipped file, because this
507 // information is saved in the first bytes of the file!
508 // also some graphic formats which save the information
509 // in the first line, too.
510 if (prefixIs(str, gzipStamp)) {
513 } else if (stamp == zipStamp) {
516 } else if (stamp == compressStamp) {
520 } else if (stamp == "BM") {
523 } else if (stamp == "\001\332") {
527 // Don't need to use str.at(0), str.at(1) because
528 // we already know that str.size() >= 2
529 } else if (str[0] == 'P') {
545 } else if ((stamp == "II") || (stamp == "MM")) {
548 } else if (prefixIs(str,"%TGIF")) {
551 } else if (prefixIs(str,"#FIG")) {
554 } else if (prefixIs(str,"GIF")) {
557 } else if (str.size() > 3) {
558 int const c = ((str[0] << 24) & (str[1] << 16) &
559 (str[2] << 8) & str[3]);
570 else if (contains(str,"EPSF"))
571 // dummy, if we have wrong file description like
572 // %!PS-Adobe-2.0EPSF"
575 else if (contains(str, "Grace"))
578 else if (contains(str, "JFIF"))
581 else if (contains(str, "%PDF"))
584 else if (contains(str, "PNG"))
587 else if (contains(str, "%!PS-Adobe")) {
590 if (contains(str,"EPSF"))
596 else if (contains(str, "_bits[]"))
599 else if (contains(str, "XPM") || contains(str, "static char *"))
602 else if (contains(str, "BITPIX"))
606 if (!format.empty()) {
607 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
611 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
612 << "\tCouldn't find a known format!");
617 bool FileName::isZippedFile() const
619 string const type = guessFormatFromContents();
620 return contains("gzip zip compress", type) && !type.empty();
624 docstring const FileName::relPath(string const & path) const
627 return makeRelPath(absoluteFilePath(), from_utf8(path));
631 bool operator==(FileName const & lhs, FileName const & rhs)
633 return lhs.absFilename() == rhs.absFilename();
637 bool operator!=(FileName const & lhs, FileName const & rhs)
639 return lhs.absFilename() != rhs.absFilename();
643 bool operator<(FileName const & lhs, FileName const & rhs)
645 return lhs.absFilename() < rhs.absFilename();
649 bool operator>(FileName const & lhs, FileName const & rhs)
651 return lhs.absFilename() > rhs.absFilename();
655 ostream & operator<<(ostream & os, FileName const & filename)
657 return os << filename.absFilename();
661 /////////////////////////////////////////////////////////////////////
665 /////////////////////////////////////////////////////////////////////
668 DocFileName::DocFileName()
669 : save_abs_path_(true)
673 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
674 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
678 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
679 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
683 void DocFileName::set(string const & name, string const & buffer_path)
685 save_abs_path_ = absolutePath(name);
686 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
687 zipped_valid_ = false;
691 void DocFileName::erase()
694 zipped_valid_ = false;
698 string DocFileName::relFilename(string const & path) const
701 return to_utf8(relPath(path));
705 string DocFileName::outputFilename(string const & path) const
707 return save_abs_path_ ? absFilename() : relFilename(path);
711 string DocFileName::mangledFilename(string const & dir) const
713 // We need to make sure that every DocFileName instance for a given
714 // filename returns the same mangled name.
715 typedef map<string, string> MangledMap;
716 static MangledMap mangledNames;
717 MangledMap::const_iterator const it = mangledNames.find(absFilename());
718 if (it != mangledNames.end())
721 string const name = absFilename();
723 string mname = os::internal_path(name);
724 // Remove the extension.
725 mname = support::changeExtension(name, string());
726 // The mangled name must be a valid LaTeX name.
727 // The list of characters to keep is probably over-restrictive,
728 // but it is not really a problem.
729 // Apart from non-ASCII characters, at least the following characters
730 // are forbidden: '/', '.', ' ', and ':'.
731 // On windows it is not possible to create files with '<', '>' or '?'
733 static string const keep = "abcdefghijklmnopqrstuvwxyz"
734 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
736 string::size_type pos = 0;
737 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
739 // Add the extension back on
740 mname = support::changeExtension(mname, getExtension(name));
742 // Prepend a counter to the filename. This is necessary to make
743 // the mangled name unique.
744 static int counter = 0;
746 s << counter++ << mname;
749 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
750 // is longer than about 160 characters. MiKTeX's pdflatex
751 // is even pickier. A maximum length of 100 has been proven to work.
752 // If dir.size() > max length, all bets are off for YAP. We truncate
753 // the filename nevertheless, keeping a minimum of 10 chars.
755 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
757 // If the mangled file name is too long, hack it to fit.
758 // We know we're guaranteed to have a unique file name because
760 if (mname.size() > max_length) {
761 int const half = (int(max_length) / 2) - 2;
763 mname = mname.substr(0, half) + "___" +
764 mname.substr(mname.size() - half);
768 mangledNames[absFilename()] = mname;
773 bool DocFileName::isZipped() const
775 if (!zipped_valid_) {
776 zipped_ = isZippedFile();
777 zipped_valid_ = true;
783 string DocFileName::unzippedFilename() const
785 return unzippedFileName(absFilename());
789 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
791 return lhs.absFilename() == rhs.absFilename()
792 && lhs.saveAbsPath() == rhs.saveAbsPath();
796 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
798 return !(lhs == rhs);
801 } // namespace support