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"
29 #include <boost/assert.hpp>
36 #ifdef HAVE_SYS_TYPES_H
37 # include <sys/types.h>
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
49 using std::ostringstream;
56 /////////////////////////////////////////////////////////////////////
60 /////////////////////////////////////////////////////////////////////
62 struct FileName::Private
66 Private(string const & abs_filename) : fi(toqstr(abs_filename))
72 /////////////////////////////////////////////////////////////////////
76 /////////////////////////////////////////////////////////////////////
79 FileName::FileName() : d(new Private)
84 FileName::FileName(string const & abs_filename)
85 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
96 FileName::FileName(FileName const & rhs) : d(new Private)
102 FileName & FileName::operator=(FileName const & rhs)
109 bool FileName::empty() const
111 return d->fi.absoluteFilePath().isEmpty();
115 string FileName::absFilename() const
117 return fromqstr(d->fi.absoluteFilePath());
121 void FileName::set(string const & name)
123 d->fi.setFile(toqstr(name));
124 BOOST_ASSERT(d->fi.isAbsolute());
128 void FileName::erase()
134 bool FileName::copyTo(FileName const & name, bool overwrite) const
137 QFile::remove(name.d->fi.absoluteFilePath());
138 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
140 lyxerr << "FileName::copyTo(): Could not copy file "
141 << *this << " to " << name << endl;
146 string FileName::toFilesystemEncoding() const
148 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
149 return string(encoded.begin(), encoded.end());
153 FileName FileName::fromFilesystemEncoding(string const & name)
155 QByteArray const encoded(name.c_str(), name.length());
156 return FileName(fromqstr(QFile::decodeName(encoded)));
160 bool FileName::exists() const
162 return d->fi.exists();
166 bool FileName::isSymLink() const
168 return d->fi.isSymLink();
172 bool FileName::isFileEmpty() const
174 return d->fi.size() == 0;
178 bool FileName::isDirectory() const
180 return d->fi.isDir();
184 bool FileName::isReadOnly() const
186 return d->fi.isReadable() && !d->fi.isWritable();
190 bool FileName::isReadableDirectory() const
192 return d->fi.isDir() && d->fi.isReadable();
196 std::string FileName::onlyFileName() const
198 return support::onlyFilename(absFilename());
202 FileName FileName::onlyPath() const
204 return FileName(support::onlyPath(absFilename()));
208 bool FileName::isReadableFile() const
210 return d->fi.isFile() && d->fi.isReadable();
214 bool FileName::isWritable() const
216 return d->fi.isWritable();
220 bool FileName::isDirWritable() const
222 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
224 FileName const tmpfl(tempName(*this, "lyxwritetest"));
234 FileNameList FileName::dirList(std::string const & ext) const
236 FileNameList dirlist;
237 if (!isDirectory()) {
238 LYXERR0("Directory '" << *this << "' does not exist!");
242 QDir dir = d->fi.absoluteDir();
247 case '.': filter = "*" + toqstr(ext); break;
248 case '*': filter = toqstr(ext); break;
249 default: filter = "*." + toqstr(ext);
251 dir.setNameFilters(QStringList(filter));
252 LYXERR(Debug::FILES, "filtering on extension "
253 << fromqstr(filter) << " is requested.");
256 QFileInfoList list = dir.entryInfoList();
257 for (int i = 0; i != list.size(); ++i) {
258 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
259 dirlist.push_back(fi);
260 LYXERR(Debug::FILES, "found file " << fi);
267 FileName FileName::tempName(FileName const & dir, std::string const & mask)
269 return support::tempName(dir, mask);
273 std::time_t FileName::lastModified() const
275 return d->fi.lastModified().toTime_t();
279 bool FileName::chdir() const
281 return QDir::setCurrent(d->fi.absoluteFilePath());
285 extern unsigned long sum(char const * file);
287 unsigned long FileName::checksum() const
290 LYXERR0("File \"" << absFilename() << "\" does not exist!");
293 // a directory may be passed here so we need to test it. (bug 3622)
295 LYXERR0('"' << absFilename() << "\" is a directory!");
298 LYXERR0("Checksumming \"" << absFilename() << "\".");
299 return sum(absFilename().c_str());
303 bool FileName::removeFile() const
305 bool const success = QFile::remove(d->fi.absoluteFilePath());
306 if (!success && exists())
307 LYXERR0("Could not delete file " << *this);
312 static bool rmdir(QFileInfo const & fi)
314 QDir dir(fi.absoluteFilePath());
315 QFileInfoList list = dir.entryInfoList();
317 for (int i = 0; i != list.size(); ++i) {
318 if (list.at(i).fileName() == ".")
320 if (list.at(i).fileName() == "..")
323 if (list.at(i).isDir()) {
324 LYXERR(Debug::FILES, "Removing dir "
325 << fromqstr(list.at(i).absoluteFilePath()));
326 removed = rmdir(list.at(i));
329 LYXERR(Debug::FILES, "Removing file "
330 << fromqstr(list.at(i).absoluteFilePath()));
331 removed = dir.remove(list.at(i).fileName());
335 LYXERR0("Could not delete "
336 << fromqstr(list.at(i).absoluteFilePath()));
339 QDir parent = fi.absolutePath();
340 success &= parent.rmdir(fi.fileName());
345 bool FileName::destroyDirectory() const
347 bool const success = rmdir(d->fi);
349 LYXERR0("Could not delete " << *this);
355 bool FileName::createDirectory(int permission) const
357 BOOST_ASSERT(!empty());
358 return mkdir(*this, permission) == 0;
362 docstring const FileName::absoluteFilePath() const
364 return qstring_to_ucs4(d->fi.absoluteFilePath());
368 docstring FileName::displayName(int threshold) const
370 return makeDisplayPath(absFilename(), threshold);
374 docstring FileName::fileContents(string const & encoding) const
376 if (!isReadableFile()) {
377 LYXERR0("File '" << *this << "' is not redable!");
381 QFile file(d->fi.absoluteFilePath());
382 if (!file.open(QIODevice::ReadOnly)) {
383 LYXERR0("File '" << *this
384 << "' could not be opened in read only mode!");
387 QByteArray contents = file.readAll();
390 if (contents.isEmpty()) {
391 LYXERR(Debug::FILES, "File '" << *this
392 << "' is either empty or some error happened while reading it.");
397 if (encoding.empty() || encoding == "UTF-8")
398 s = QString::fromUtf8(contents.data());
399 else if (encoding == "ascii")
400 s = QString::fromAscii(contents.data());
401 else if (encoding == "local8bit")
402 s = QString::fromLocal8Bit(contents.data());
403 else if (encoding == "latin1")
404 s = QString::fromLatin1(contents.data());
406 return qstring_to_ucs4(s);
410 void FileName::changeExtension(std::string const & extension)
412 // FIXME: use Qt native methods...
413 string const oldname = absFilename();
414 string::size_type const last_slash = oldname.rfind('/');
415 string::size_type last_dot = oldname.rfind('.');
416 if (last_dot < last_slash && last_slash != string::npos)
417 last_dot = string::npos;
420 // Make sure the extension starts with a dot
421 if (!extension.empty() && extension[0] != '.')
422 ext= '.' + extension;
426 set(oldname.substr(0, last_dot) + ext);
430 string FileName::guessFormatFromContents() const
432 // the different filetypes and what they contain in one of the first lines
433 // (dots are any characters). (Herbert 20020131)
436 // EPS %!PS-Adobe-3.0 EPSF...
443 // PBM P1... or P4 (B/W)
444 // PGM P2... or P5 (Grayscale)
445 // PPM P3... or P6 (color)
446 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
447 // SGI \001\332... (decimal 474)
449 // TIFF II... or MM...
451 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
452 // ...static char *...
453 // XWD \000\000\000\151 (0x00006900) decimal 105
455 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
456 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
457 // Z \037\235 UNIX compress
460 if (empty() || !isReadableFile())
463 ifstream ifs(toFilesystemEncoding().c_str());
465 // Couldn't open file...
469 static string const gzipStamp = "\037\213";
472 static string const zipStamp = "PK";
475 static string const compressStamp = "\037\235";
477 // Maximum strings to read
478 int const max_count = 50;
483 bool firstLine = true;
484 while ((count++ < max_count) && format.empty()) {
486 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
487 << "\tFile type not recognised before EOF!");
492 string const stamp = str.substr(0, 2);
493 if (firstLine && str.size() >= 2) {
494 // at first we check for a zipped file, because this
495 // information is saved in the first bytes of the file!
496 // also some graphic formats which save the information
497 // in the first line, too.
498 if (prefixIs(str, gzipStamp)) {
501 } else if (stamp == zipStamp) {
504 } else if (stamp == compressStamp) {
508 } else if (stamp == "BM") {
511 } else if (stamp == "\001\332") {
515 // Don't need to use str.at(0), str.at(1) because
516 // we already know that str.size() >= 2
517 } else if (str[0] == 'P') {
533 } else if ((stamp == "II") || (stamp == "MM")) {
536 } else if (prefixIs(str,"%TGIF")) {
539 } else if (prefixIs(str,"#FIG")) {
542 } else if (prefixIs(str,"GIF")) {
545 } else if (str.size() > 3) {
546 int const c = ((str[0] << 24) & (str[1] << 16) &
547 (str[2] << 8) & str[3]);
558 else if (contains(str,"EPSF"))
559 // dummy, if we have wrong file description like
560 // %!PS-Adobe-2.0EPSF"
563 else if (contains(str, "Grace"))
566 else if (contains(str, "JFIF"))
569 else if (contains(str, "%PDF"))
572 else if (contains(str, "PNG"))
575 else if (contains(str, "%!PS-Adobe")) {
578 if (contains(str,"EPSF"))
584 else if (contains(str, "_bits[]"))
587 else if (contains(str, "XPM") || contains(str, "static char *"))
590 else if (contains(str, "BITPIX"))
594 if (!format.empty()) {
595 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
599 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
600 << "\tCouldn't find a known format!");
605 bool FileName::isZippedFile() const
607 string const type = guessFormatFromContents();
608 return contains("gzip zip compress", type) && !type.empty();
612 docstring const FileName::relPath(string const & path) const
615 return makeRelPath(absoluteFilePath(), from_utf8(path));
619 bool operator==(FileName const & lhs, FileName const & rhs)
621 return lhs.absFilename() == rhs.absFilename();
625 bool operator!=(FileName const & lhs, FileName const & rhs)
627 return lhs.absFilename() != rhs.absFilename();
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 std::ostream & operator<<(std::ostream & os, FileName const & filename)
645 return os << filename.absFilename();
649 /////////////////////////////////////////////////////////////////////
653 /////////////////////////////////////////////////////////////////////
656 DocFileName::DocFileName()
657 : save_abs_path_(true)
661 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
662 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
666 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
667 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
671 void DocFileName::set(string const & name, string const & buffer_path)
673 save_abs_path_ = absolutePath(name);
674 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
675 zipped_valid_ = false;
679 void DocFileName::erase()
682 zipped_valid_ = false;
686 string DocFileName::relFilename(string const & path) const
689 return to_utf8(relPath(path));
693 string DocFileName::outputFilename(string const & path) const
695 return save_abs_path_ ? absFilename() : relFilename(path);
699 string DocFileName::mangledFilename(std::string const & dir) const
701 // We need to make sure that every DocFileName instance for a given
702 // filename returns the same mangled name.
703 typedef map<string, string> MangledMap;
704 static MangledMap mangledNames;
705 MangledMap::const_iterator const it = mangledNames.find(absFilename());
706 if (it != mangledNames.end())
709 string const name = absFilename();
711 string mname = os::internal_path(name);
712 // Remove the extension.
713 mname = support::changeExtension(name, string());
714 // The mangled name must be a valid LaTeX name.
715 // The list of characters to keep is probably over-restrictive,
716 // but it is not really a problem.
717 // Apart from non-ASCII characters, at least the following characters
718 // are forbidden: '/', '.', ' ', and ':'.
719 // On windows it is not possible to create files with '<', '>' or '?'
721 static string const keep = "abcdefghijklmnopqrstuvwxyz"
722 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
724 string::size_type pos = 0;
725 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
727 // Add the extension back on
728 mname = support::changeExtension(mname, getExtension(name));
730 // Prepend a counter to the filename. This is necessary to make
731 // the mangled name unique.
732 static int counter = 0;
733 std::ostringstream s;
734 s << counter++ << mname;
737 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
738 // is longer than about 160 characters. MiKTeX's pdflatex
739 // is even pickier. A maximum length of 100 has been proven to work.
740 // If dir.size() > max length, all bets are off for YAP. We truncate
741 // the filename nevertheless, keeping a minimum of 10 chars.
743 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
745 // If the mangled file name is too long, hack it to fit.
746 // We know we're guaranteed to have a unique file name because
748 if (mname.size() > max_length) {
749 int const half = (int(max_length) / 2) - 2;
751 mname = mname.substr(0, half) + "___" +
752 mname.substr(mname.size() - half);
756 mangledNames[absFilename()] = mname;
761 bool DocFileName::isZipped() const
763 if (!zipped_valid_) {
764 zipped_ = isZippedFile();
765 zipped_valid_ = true;
771 string DocFileName::unzippedFilename() const
773 return unzippedFileName(absFilename());
777 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
779 return lhs.absFilename() == rhs.absFilename()
780 && lhs.saveAbsPath() == rhs.saveAbsPath();
784 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
786 return !(lhs == rhs);
789 } // namespace support