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::moveTo(FileName const & name) const
155 if (name.exists() && !name.removeFile())
158 bool success = QFile::rename(d->fi.absoluteFilePath(),
159 name.d->fi.absoluteFilePath());
161 LYXERR0("Could not move file " << *this << " to " << name);
166 bool FileName::changePermission(unsigned long int mode) const
169 LYXERR0("File " << *this << " is not writable!");
173 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
174 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
175 LYXERR0("File " << *this << ": cannot change permission to "
184 string FileName::toFilesystemEncoding() const
186 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
187 return string(encoded.begin(), encoded.end());
191 FileName FileName::fromFilesystemEncoding(string const & name)
193 QByteArray const encoded(name.c_str(), name.length());
194 return FileName(fromqstr(QFile::decodeName(encoded)));
198 bool FileName::exists() const
200 return d->fi.exists();
204 bool FileName::isSymLink() const
206 return d->fi.isSymLink();
210 bool FileName::isFileEmpty() const
212 return d->fi.size() == 0;
216 bool FileName::isDirectory() const
218 return d->fi.isDir();
222 bool FileName::isReadOnly() const
224 return d->fi.isReadable() && !d->fi.isWritable();
228 bool FileName::isReadableDirectory() const
230 return d->fi.isDir() && d->fi.isReadable();
234 string FileName::onlyFileName() const
236 return support::onlyFilename(absFilename());
240 FileName FileName::onlyPath() const
242 return FileName(support::onlyPath(absFilename()));
246 bool FileName::isReadableFile() const
248 return d->fi.isFile() && d->fi.isReadable();
252 bool FileName::isWritable() const
254 return d->fi.isWritable();
258 bool FileName::isDirWritable() const
260 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
262 FileName const tmpfl(tempName(*this, "lyxwritetest"));
272 FileNameList FileName::dirList(string const & ext) const
274 FileNameList dirlist;
275 if (!isDirectory()) {
276 LYXERR0("Directory '" << *this << "' does not exist!");
280 QDir dir = d->fi.absoluteDir();
285 case '.': filter = "*" + toqstr(ext); break;
286 case '*': filter = toqstr(ext); break;
287 default: filter = "*." + toqstr(ext);
289 dir.setNameFilters(QStringList(filter));
290 LYXERR(Debug::FILES, "filtering on extension "
291 << fromqstr(filter) << " is requested.");
294 QFileInfoList list = dir.entryInfoList();
295 for (int i = 0; i != list.size(); ++i) {
296 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
297 dirlist.push_back(fi);
298 LYXERR(Debug::FILES, "found file " << fi);
305 FileName FileName::tempName(FileName const & dir, string const & mask)
307 return support::tempName(dir, mask);
311 time_t FileName::lastModified() const
313 return d->fi.lastModified().toTime_t();
317 bool FileName::chdir() const
319 return QDir::setCurrent(d->fi.absoluteFilePath());
323 extern unsigned long sum(char const * file);
325 unsigned long FileName::checksum() const
328 LYXERR0("File \"" << absFilename() << "\" does not exist!");
331 // a directory may be passed here so we need to test it. (bug 3622)
333 LYXERR0('"' << absFilename() << "\" is a directory!");
336 if (!lyxerr.debugging(Debug::FILES))
337 return sum(absFilename().c_str());
341 unsigned long r = sum(absFilename().c_str());
342 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
343 << t.elapsed() << " ms." << endl;
348 bool FileName::removeFile() const
350 bool const success = QFile::remove(d->fi.absoluteFilePath());
351 if (!success && exists())
352 LYXERR0("Could not delete file " << *this);
357 static bool rmdir(QFileInfo const & fi)
359 QDir dir(fi.absoluteFilePath());
360 QFileInfoList list = dir.entryInfoList();
362 for (int i = 0; i != list.size(); ++i) {
363 if (list.at(i).fileName() == ".")
365 if (list.at(i).fileName() == "..")
368 if (list.at(i).isDir()) {
369 LYXERR(Debug::FILES, "Removing dir "
370 << fromqstr(list.at(i).absoluteFilePath()));
371 removed = rmdir(list.at(i));
374 LYXERR(Debug::FILES, "Removing file "
375 << fromqstr(list.at(i).absoluteFilePath()));
376 removed = dir.remove(list.at(i).fileName());
380 LYXERR0("Could not delete "
381 << fromqstr(list.at(i).absoluteFilePath()));
384 QDir parent = fi.absolutePath();
385 success &= parent.rmdir(fi.fileName());
390 bool FileName::destroyDirectory() const
392 bool const success = rmdir(d->fi);
394 LYXERR0("Could not delete " << *this);
400 bool FileName::createDirectory(int permission) const
402 BOOST_ASSERT(!empty());
403 return mkdir(*this, permission) == 0;
407 docstring const FileName::absoluteFilePath() const
409 return qstring_to_ucs4(d->fi.absoluteFilePath());
413 docstring FileName::displayName(int threshold) const
415 return makeDisplayPath(absFilename(), threshold);
419 docstring FileName::fileContents(string const & encoding) const
421 if (!isReadableFile()) {
422 LYXERR0("File '" << *this << "' is not redable!");
426 QFile file(d->fi.absoluteFilePath());
427 if (!file.open(QIODevice::ReadOnly)) {
428 LYXERR0("File '" << *this
429 << "' could not be opened in read only mode!");
432 QByteArray contents = file.readAll();
435 if (contents.isEmpty()) {
436 LYXERR(Debug::FILES, "File '" << *this
437 << "' is either empty or some error happened while reading it.");
442 if (encoding.empty() || encoding == "UTF-8")
443 s = QString::fromUtf8(contents.data());
444 else if (encoding == "ascii")
445 s = QString::fromAscii(contents.data());
446 else if (encoding == "local8bit")
447 s = QString::fromLocal8Bit(contents.data());
448 else if (encoding == "latin1")
449 s = QString::fromLatin1(contents.data());
451 return qstring_to_ucs4(s);
455 void FileName::changeExtension(string const & extension)
457 // FIXME: use Qt native methods...
458 string const oldname = absFilename();
459 string::size_type const last_slash = oldname.rfind('/');
460 string::size_type last_dot = oldname.rfind('.');
461 if (last_dot < last_slash && last_slash != string::npos)
462 last_dot = string::npos;
465 // Make sure the extension starts with a dot
466 if (!extension.empty() && extension[0] != '.')
467 ext= '.' + extension;
471 set(oldname.substr(0, last_dot) + ext);
475 string FileName::guessFormatFromContents() const
477 // the different filetypes and what they contain in one of the first lines
478 // (dots are any characters). (Herbert 20020131)
481 // EPS %!PS-Adobe-3.0 EPSF...
488 // PBM P1... or P4 (B/W)
489 // PGM P2... or P5 (Grayscale)
490 // PPM P3... or P6 (color)
491 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
492 // SGI \001\332... (decimal 474)
494 // TIFF II... or MM...
496 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
497 // ...static char *...
498 // XWD \000\000\000\151 (0x00006900) decimal 105
500 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
501 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
502 // Z \037\235 UNIX compress
505 if (empty() || !isReadableFile())
508 ifstream ifs(toFilesystemEncoding().c_str());
510 // Couldn't open file...
514 static string const gzipStamp = "\037\213";
517 static string const zipStamp = "PK";
520 static string const compressStamp = "\037\235";
522 // Maximum strings to read
523 int const max_count = 50;
528 bool firstLine = true;
529 while ((count++ < max_count) && format.empty()) {
531 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
532 << "\tFile type not recognised before EOF!");
537 string const stamp = str.substr(0, 2);
538 if (firstLine && str.size() >= 2) {
539 // at first we check for a zipped file, because this
540 // information is saved in the first bytes of the file!
541 // also some graphic formats which save the information
542 // in the first line, too.
543 if (prefixIs(str, gzipStamp)) {
546 } else if (stamp == zipStamp) {
549 } else if (stamp == compressStamp) {
553 } else if (stamp == "BM") {
556 } else if (stamp == "\001\332") {
560 // Don't need to use str.at(0), str.at(1) because
561 // we already know that str.size() >= 2
562 } else if (str[0] == 'P') {
578 } else if ((stamp == "II") || (stamp == "MM")) {
581 } else if (prefixIs(str,"%TGIF")) {
584 } else if (prefixIs(str,"#FIG")) {
587 } else if (prefixIs(str,"GIF")) {
590 } else if (str.size() > 3) {
591 int const c = ((str[0] << 24) & (str[1] << 16) &
592 (str[2] << 8) & str[3]);
603 else if (contains(str,"EPSF"))
604 // dummy, if we have wrong file description like
605 // %!PS-Adobe-2.0EPSF"
608 else if (contains(str, "Grace"))
611 else if (contains(str, "JFIF"))
614 else if (contains(str, "%PDF"))
617 else if (contains(str, "PNG"))
620 else if (contains(str, "%!PS-Adobe")) {
623 if (contains(str,"EPSF"))
629 else if (contains(str, "_bits[]"))
632 else if (contains(str, "XPM") || contains(str, "static char *"))
635 else if (contains(str, "BITPIX"))
639 if (!format.empty()) {
640 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
644 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
645 << "\tCouldn't find a known format!");
650 bool FileName::isZippedFile() const
652 string const type = guessFormatFromContents();
653 return contains("gzip zip compress", type) && !type.empty();
657 docstring const FileName::relPath(string const & path) const
660 return makeRelPath(absoluteFilePath(), from_utf8(path));
664 bool operator==(FileName const & lhs, FileName const & rhs)
666 return lhs.absFilename() == rhs.absFilename();
670 bool operator!=(FileName const & lhs, FileName const & rhs)
672 return lhs.absFilename() != rhs.absFilename();
676 bool operator<(FileName const & lhs, FileName const & rhs)
678 return lhs.absFilename() < rhs.absFilename();
682 bool operator>(FileName const & lhs, FileName const & rhs)
684 return lhs.absFilename() > rhs.absFilename();
688 ostream & operator<<(ostream & os, FileName const & filename)
690 return os << filename.absFilename();
694 /////////////////////////////////////////////////////////////////////
698 /////////////////////////////////////////////////////////////////////
701 DocFileName::DocFileName()
702 : save_abs_path_(true)
706 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
707 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
711 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
712 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
716 void DocFileName::set(string const & name, string const & buffer_path)
718 save_abs_path_ = absolutePath(name);
719 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
720 zipped_valid_ = false;
724 void DocFileName::erase()
727 zipped_valid_ = false;
731 string DocFileName::relFilename(string const & path) const
734 return to_utf8(relPath(path));
738 string DocFileName::outputFilename(string const & path) const
740 return save_abs_path_ ? absFilename() : relFilename(path);
744 string DocFileName::mangledFilename(string const & dir) const
746 // We need to make sure that every DocFileName instance for a given
747 // filename returns the same mangled name.
748 typedef map<string, string> MangledMap;
749 static MangledMap mangledNames;
750 MangledMap::const_iterator const it = mangledNames.find(absFilename());
751 if (it != mangledNames.end())
754 string const name = absFilename();
756 string mname = os::internal_path(name);
757 // Remove the extension.
758 mname = support::changeExtension(name, string());
759 // The mangled name must be a valid LaTeX name.
760 // The list of characters to keep is probably over-restrictive,
761 // but it is not really a problem.
762 // Apart from non-ASCII characters, at least the following characters
763 // are forbidden: '/', '.', ' ', and ':'.
764 // On windows it is not possible to create files with '<', '>' or '?'
766 static string const keep = "abcdefghijklmnopqrstuvwxyz"
767 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
769 string::size_type pos = 0;
770 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
772 // Add the extension back on
773 mname = support::changeExtension(mname, getExtension(name));
775 // Prepend a counter to the filename. This is necessary to make
776 // the mangled name unique.
777 static int counter = 0;
779 s << counter++ << mname;
782 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
783 // is longer than about 160 characters. MiKTeX's pdflatex
784 // is even pickier. A maximum length of 100 has been proven to work.
785 // If dir.size() > max length, all bets are off for YAP. We truncate
786 // the filename nevertheless, keeping a minimum of 10 chars.
788 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
790 // If the mangled file name is too long, hack it to fit.
791 // We know we're guaranteed to have a unique file name because
793 if (mname.size() > max_length) {
794 int const half = (int(max_length) / 2) - 2;
796 mname = mname.substr(0, half) + "___" +
797 mname.substr(mname.size() - half);
801 mangledNames[absFilename()] = mname;
806 bool DocFileName::isZipped() const
808 if (!zipped_valid_) {
809 zipped_ = isZippedFile();
810 zipped_valid_ = true;
816 string DocFileName::unzippedFilename() const
818 return unzippedFileName(absFilename());
822 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
824 return lhs.absFilename() == rhs.absFilename()
825 && lhs.saveAbsPath() == rhs.saveAbsPath();
829 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
831 return !(lhs == rhs);
834 } // namespace support