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>
62 /////////////////////////////////////////////////////////////////////
66 /////////////////////////////////////////////////////////////////////
68 struct FileName::Private
72 Private(string const & abs_filename) : fi(toqstr(abs_filename))
74 fi.setCaching(fi.exists() ? true : false);
80 /////////////////////////////////////////////////////////////////////
84 /////////////////////////////////////////////////////////////////////
87 FileName::FileName() : d(new Private)
92 FileName::FileName(string const & abs_filename)
93 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
104 FileName::FileName(FileName const & rhs) : d(new Private)
110 FileName & FileName::operator=(FileName const & rhs)
117 bool FileName::empty() const
119 return d->fi.absoluteFilePath().isEmpty();
123 string FileName::absFilename() const
125 return fromqstr(d->fi.absoluteFilePath());
129 void FileName::set(string const & name)
131 d->fi.setFile(toqstr(name));
132 BOOST_ASSERT(d->fi.isAbsolute());
136 void FileName::erase()
142 bool FileName::copyTo(FileName const & name, bool overwrite) const
145 QFile::remove(name.d->fi.absoluteFilePath());
146 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
148 lyxerr << "FileName::copyTo(): Could not copy file "
149 << *this << " to " << name << endl;
154 bool FileName::renameTo(FileName const & name) const
156 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
158 LYXERR0("Could not rename file " << *this << " to " << name);
163 bool FileName::moveTo(FileName const & name) const
165 QFile::remove(name.d->fi.absoluteFilePath());
167 bool success = QFile::rename(d->fi.absoluteFilePath(),
168 name.d->fi.absoluteFilePath());
170 LYXERR0("Could not move file " << *this << " to " << name);
175 bool FileName::changePermission(unsigned long int mode) const
178 LYXERR0("File " << *this << " is not writable!");
182 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
183 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
184 LYXERR0("File " << *this << ": cannot change permission to "
193 string FileName::toFilesystemEncoding() const
195 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
196 return string(encoded.begin(), encoded.end());
200 FileName FileName::fromFilesystemEncoding(string const & name)
202 QByteArray const encoded(name.c_str(), name.length());
203 return FileName(fromqstr(QFile::decodeName(encoded)));
207 bool FileName::exists() const
209 return d->fi.exists();
213 bool FileName::isSymLink() const
215 return d->fi.isSymLink();
219 bool FileName::isFileEmpty() const
221 return d->fi.size() == 0;
225 bool FileName::isDirectory() const
227 return d->fi.isDir();
231 bool FileName::isReadOnly() const
233 return d->fi.isReadable() && !d->fi.isWritable();
237 bool FileName::isReadableDirectory() const
239 return d->fi.isDir() && d->fi.isReadable();
243 string FileName::onlyFileName() const
245 return support::onlyFilename(absFilename());
249 FileName FileName::onlyPath() const
251 return FileName(support::onlyPath(absFilename()));
255 bool FileName::isReadableFile() const
257 return d->fi.isFile() && d->fi.isReadable();
261 bool FileName::isWritable() const
263 return d->fi.isWritable();
267 bool FileName::isDirWritable() const
269 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
271 FileName const tmpfl(tempName(*this, "lyxwritetest"));
281 FileNameList FileName::dirList(string const & ext) const
283 FileNameList dirlist;
284 if (!isDirectory()) {
285 LYXERR0("Directory '" << *this << "' does not exist!");
289 QDir dir = d->fi.absoluteDir();
294 case '.': filter = "*" + toqstr(ext); break;
295 case '*': filter = toqstr(ext); break;
296 default: filter = "*." + toqstr(ext);
298 dir.setNameFilters(QStringList(filter));
299 LYXERR(Debug::FILES, "filtering on extension "
300 << fromqstr(filter) << " is requested.");
303 QFileInfoList list = dir.entryInfoList();
304 for (int i = 0; i != list.size(); ++i) {
305 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
306 dirlist.push_back(fi);
307 LYXERR(Debug::FILES, "found file " << fi);
314 FileName FileName::tempName(FileName const & dir, string const & mask)
316 return support::tempName(dir, mask);
320 time_t FileName::lastModified() const
322 return d->fi.lastModified().toTime_t();
326 bool FileName::chdir() const
328 return QDir::setCurrent(d->fi.absoluteFilePath());
332 extern unsigned long sum(char const * file);
334 unsigned long FileName::checksum() const
337 LYXERR0("File \"" << absFilename() << "\" does not exist!");
340 // a directory may be passed here so we need to test it. (bug 3622)
342 LYXERR0('"' << absFilename() << "\" is a directory!");
345 if (!lyxerr.debugging(Debug::FILES))
346 return sum(absFilename().c_str());
350 unsigned long r = sum(absFilename().c_str());
351 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
352 << t.elapsed() << " ms." << endl;
357 bool FileName::removeFile() const
359 bool const success = QFile::remove(d->fi.absoluteFilePath());
360 if (!success && exists())
361 LYXERR0("Could not delete file " << *this);
366 static bool rmdir(QFileInfo const & fi)
368 QDir dir(fi.absoluteFilePath());
369 QFileInfoList list = dir.entryInfoList();
371 for (int i = 0; i != list.size(); ++i) {
372 if (list.at(i).fileName() == ".")
374 if (list.at(i).fileName() == "..")
377 if (list.at(i).isDir()) {
378 LYXERR(Debug::FILES, "Removing dir "
379 << fromqstr(list.at(i).absoluteFilePath()));
380 removed = rmdir(list.at(i));
383 LYXERR(Debug::FILES, "Removing file "
384 << fromqstr(list.at(i).absoluteFilePath()));
385 removed = dir.remove(list.at(i).fileName());
389 LYXERR0("Could not delete "
390 << fromqstr(list.at(i).absoluteFilePath()));
393 QDir parent = fi.absolutePath();
394 success &= parent.rmdir(fi.fileName());
399 bool FileName::destroyDirectory() const
401 bool const success = rmdir(d->fi);
403 LYXERR0("Could not delete " << *this);
409 static int mymkdir(char const * pathname, unsigned long int mode)
411 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
413 # if MKDIR_TAKES_ONE_ARG
415 return ::mkdir(pathname);
416 // FIXME: "Permissions of created directories are ignored on this system."
419 return ::mkdir(pathname, mode_t(mode));
421 #elif defined(_WIN32)
423 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
424 // FIXME: "Permissions of created directories are ignored on this system."
426 return ::_mkdir(pathname);
427 // FIXME: "Permissions of created directories are ignored on this system."
429 # error "Don't know how to create a directory on this system."
435 bool FileName::createDirectory(int permission) const
437 BOOST_ASSERT(!empty());
438 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
442 bool FileName::createPath() const
444 BOOST_ASSERT(!empty());
449 bool success = dir.mkpath(d->fi.absoluteFilePath());
451 LYXERR0("Cannot create path '" << *this << "'!");
456 docstring const FileName::absoluteFilePath() const
458 return qstring_to_ucs4(d->fi.absoluteFilePath());
462 docstring FileName::displayName(int threshold) const
464 return makeDisplayPath(absFilename(), threshold);
468 docstring FileName::fileContents(string const & encoding) const
470 if (!isReadableFile()) {
471 LYXERR0("File '" << *this << "' is not redable!");
475 QFile file(d->fi.absoluteFilePath());
476 if (!file.open(QIODevice::ReadOnly)) {
477 LYXERR0("File '" << *this
478 << "' could not be opened in read only mode!");
481 QByteArray contents = file.readAll();
484 if (contents.isEmpty()) {
485 LYXERR(Debug::FILES, "File '" << *this
486 << "' is either empty or some error happened while reading it.");
491 if (encoding.empty() || encoding == "UTF-8")
492 s = QString::fromUtf8(contents.data());
493 else if (encoding == "ascii")
494 s = QString::fromAscii(contents.data());
495 else if (encoding == "local8bit")
496 s = QString::fromLocal8Bit(contents.data());
497 else if (encoding == "latin1")
498 s = QString::fromLatin1(contents.data());
500 return qstring_to_ucs4(s);
504 void FileName::changeExtension(string const & extension)
506 // FIXME: use Qt native methods...
507 string const oldname = absFilename();
508 string::size_type const last_slash = oldname.rfind('/');
509 string::size_type last_dot = oldname.rfind('.');
510 if (last_dot < last_slash && last_slash != string::npos)
511 last_dot = string::npos;
514 // Make sure the extension starts with a dot
515 if (!extension.empty() && extension[0] != '.')
516 ext= '.' + extension;
520 set(oldname.substr(0, last_dot) + ext);
524 string FileName::guessFormatFromContents() const
526 // the different filetypes and what they contain in one of the first lines
527 // (dots are any characters). (Herbert 20020131)
530 // EPS %!PS-Adobe-3.0 EPSF...
537 // PBM P1... or P4 (B/W)
538 // PGM P2... or P5 (Grayscale)
539 // PPM P3... or P6 (color)
540 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
541 // SGI \001\332... (decimal 474)
543 // TIFF II... or MM...
545 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
546 // ...static char *...
547 // XWD \000\000\000\151 (0x00006900) decimal 105
549 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
550 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
551 // Z \037\235 UNIX compress
554 if (empty() || !isReadableFile())
557 ifstream ifs(toFilesystemEncoding().c_str());
559 // Couldn't open file...
563 static string const gzipStamp = "\037\213";
566 static string const zipStamp = "PK";
569 static string const compressStamp = "\037\235";
571 // Maximum strings to read
572 int const max_count = 50;
577 bool firstLine = true;
578 while ((count++ < max_count) && format.empty()) {
580 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
581 << "\tFile type not recognised before EOF!");
586 string const stamp = str.substr(0, 2);
587 if (firstLine && str.size() >= 2) {
588 // at first we check for a zipped file, because this
589 // information is saved in the first bytes of the file!
590 // also some graphic formats which save the information
591 // in the first line, too.
592 if (prefixIs(str, gzipStamp)) {
595 } else if (stamp == zipStamp) {
598 } else if (stamp == compressStamp) {
602 } else if (stamp == "BM") {
605 } else if (stamp == "\001\332") {
609 // Don't need to use str.at(0), str.at(1) because
610 // we already know that str.size() >= 2
611 } else if (str[0] == 'P') {
627 } else if ((stamp == "II") || (stamp == "MM")) {
630 } else if (prefixIs(str,"%TGIF")) {
633 } else if (prefixIs(str,"#FIG")) {
636 } else if (prefixIs(str,"GIF")) {
639 } else if (str.size() > 3) {
640 int const c = ((str[0] << 24) & (str[1] << 16) &
641 (str[2] << 8) & str[3]);
652 else if (contains(str,"EPSF"))
653 // dummy, if we have wrong file description like
654 // %!PS-Adobe-2.0EPSF"
657 else if (contains(str, "Grace"))
660 else if (contains(str, "JFIF"))
663 else if (contains(str, "%PDF"))
666 else if (contains(str, "PNG"))
669 else if (contains(str, "%!PS-Adobe")) {
672 if (contains(str,"EPSF"))
678 else if (contains(str, "_bits[]"))
681 else if (contains(str, "XPM") || contains(str, "static char *"))
684 else if (contains(str, "BITPIX"))
688 if (!format.empty()) {
689 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
693 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
694 << "\tCouldn't find a known format!");
699 bool FileName::isZippedFile() const
701 string const type = guessFormatFromContents();
702 return contains("gzip zip compress", type) && !type.empty();
706 docstring const FileName::relPath(string const & path) const
709 return makeRelPath(absoluteFilePath(), from_utf8(path));
713 bool operator==(FileName const & lhs, FileName const & rhs)
715 return lhs.absFilename() == rhs.absFilename();
719 bool operator!=(FileName const & lhs, FileName const & rhs)
721 return lhs.absFilename() != rhs.absFilename();
725 bool operator<(FileName const & lhs, FileName const & rhs)
727 return lhs.absFilename() < rhs.absFilename();
731 bool operator>(FileName const & lhs, FileName const & rhs)
733 return lhs.absFilename() > rhs.absFilename();
737 ostream & operator<<(ostream & os, FileName const & filename)
739 return os << filename.absFilename();
743 /////////////////////////////////////////////////////////////////////
747 /////////////////////////////////////////////////////////////////////
750 DocFileName::DocFileName()
751 : save_abs_path_(true)
755 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
756 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
760 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
761 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
765 void DocFileName::set(string const & name, string const & buffer_path)
767 save_abs_path_ = absolutePath(name);
768 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
769 zipped_valid_ = false;
773 void DocFileName::erase()
776 zipped_valid_ = false;
780 string DocFileName::relFilename(string const & path) const
783 return to_utf8(relPath(path));
787 string DocFileName::outputFilename(string const & path) const
789 return save_abs_path_ ? absFilename() : relFilename(path);
793 string DocFileName::mangledFilename(string const & dir) const
795 // We need to make sure that every DocFileName instance for a given
796 // filename returns the same mangled name.
797 typedef map<string, string> MangledMap;
798 static MangledMap mangledNames;
799 MangledMap::const_iterator const it = mangledNames.find(absFilename());
800 if (it != mangledNames.end())
803 string const name = absFilename();
805 string mname = os::internal_path(name);
806 // Remove the extension.
807 mname = support::changeExtension(name, string());
808 // The mangled name must be a valid LaTeX name.
809 // The list of characters to keep is probably over-restrictive,
810 // but it is not really a problem.
811 // Apart from non-ASCII characters, at least the following characters
812 // are forbidden: '/', '.', ' ', and ':'.
813 // On windows it is not possible to create files with '<', '>' or '?'
815 static string const keep = "abcdefghijklmnopqrstuvwxyz"
816 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
818 string::size_type pos = 0;
819 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
821 // Add the extension back on
822 mname = support::changeExtension(mname, getExtension(name));
824 // Prepend a counter to the filename. This is necessary to make
825 // the mangled name unique.
826 static int counter = 0;
828 s << counter++ << mname;
831 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
832 // is longer than about 160 characters. MiKTeX's pdflatex
833 // is even pickier. A maximum length of 100 has been proven to work.
834 // If dir.size() > max length, all bets are off for YAP. We truncate
835 // the filename nevertheless, keeping a minimum of 10 chars.
837 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
839 // If the mangled file name is too long, hack it to fit.
840 // We know we're guaranteed to have a unique file name because
842 if (mname.size() > max_length) {
843 int const half = (int(max_length) / 2) - 2;
845 mname = mname.substr(0, half) + "___" +
846 mname.substr(mname.size() - half);
850 mangledNames[absFilename()] = mname;
855 bool DocFileName::isZipped() const
857 if (!zipped_valid_) {
858 zipped_ = isZippedFile();
859 zipped_valid_ = true;
865 string DocFileName::unzippedFilename() const
867 return unzippedFileName(absFilename());
871 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
873 return lhs.absFilename() == rhs.absFilename()
874 && lhs.saveAbsPath() == rhs.saveAbsPath();
878 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
880 return !(lhs == rhs);
883 } // namespace support