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 lyxerr << "FileName::removeFile(): Could not delete file "
308 << *this << "." << endl;
313 static bool rmdir(QFileInfo const & fi)
315 QDir dir(fi.absoluteFilePath());
316 QFileInfoList list = dir.entryInfoList();
317 bool global_success = true;
318 for (int i = 0; i != list.size(); ++i) {
319 if (list.at(i).fileName() == ".")
321 if (list.at(i).fileName() == "..")
324 if (list.at(i).isDir()) {
325 LYXERR(Debug::FILES, "Erasing dir "
326 << fromqstr(list.at(i).absoluteFilePath()));
327 success = rmdir(list.at(i));
330 LYXERR(Debug::FILES, "Erasing file "
331 << fromqstr(list.at(i).absoluteFilePath()));
332 success = dir.remove(list.at(i).fileName());
335 global_success = false;
336 lyxerr << "Could not delete "
337 << fromqstr(list.at(i).absoluteFilePath()) << "." << endl;
340 QDir parent = fi.absolutePath();
341 global_success |= parent.rmdir(fi.fileName());
342 return global_success;
346 bool FileName::destroyDirectory() const
348 bool const success = rmdir(d->fi);
350 lyxerr << "Could not delete " << *this << "." << endl;
356 bool FileName::createDirectory(int permission) const
358 BOOST_ASSERT(!empty());
359 return mkdir(*this, permission) == 0;
363 docstring const FileName::absoluteFilePath() const
365 return qstring_to_ucs4(d->fi.absoluteFilePath());
369 docstring FileName::displayName(int threshold) const
371 return makeDisplayPath(absFilename(), threshold);
375 docstring FileName::fileContents(string const & encoding) const
377 if (!isReadableFile()) {
378 LYXERR0("File '" << *this
379 << "' is not redable!");
383 QFile file(d->fi.absoluteFilePath());
384 if (!file.open(QIODevice::ReadOnly)) {
385 LYXERR0("File '" << *this
386 << "' could not be opened in read only mode!");
389 QByteArray contents = file.readAll();
392 if (contents.isEmpty()) {
393 LYXERR(Debug::FILES, "File '" << *this
394 << "' is either empty or some error happened while reading it.");
399 if (encoding.empty() || encoding == "UTF-8")
400 s = QString::fromUtf8(contents.data());
401 else if (encoding == "ascii")
402 s = QString::fromAscii(contents.data());
403 else if (encoding == "local8bit")
404 s = QString::fromLocal8Bit(contents.data());
405 else if (encoding == "latin1")
406 s = QString::fromLatin1(contents.data());
408 return qstring_to_ucs4(s);
412 void FileName::changeExtension(std::string const & extension)
414 // FIXME: use Qt native methods...
415 string const oldname = absFilename();
416 string::size_type const last_slash = oldname.rfind('/');
417 string::size_type last_dot = oldname.rfind('.');
418 if (last_dot < last_slash && last_slash != string::npos)
419 last_dot = string::npos;
422 // Make sure the extension starts with a dot
423 if (!extension.empty() && extension[0] != '.')
424 ext= '.' + extension;
428 set(oldname.substr(0, last_dot) + ext);
432 string FileName::guessFormatFromContents() const
434 // the different filetypes and what they contain in one of the first lines
435 // (dots are any characters). (Herbert 20020131)
438 // EPS %!PS-Adobe-3.0 EPSF...
445 // PBM P1... or P4 (B/W)
446 // PGM P2... or P5 (Grayscale)
447 // PPM P3... or P6 (color)
448 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
449 // SGI \001\332... (decimal 474)
451 // TIFF II... or MM...
453 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
454 // ...static char *...
455 // XWD \000\000\000\151 (0x00006900) decimal 105
457 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
458 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
459 // Z \037\235 UNIX compress
462 if (empty() || !isReadableFile())
465 ifstream ifs(toFilesystemEncoding().c_str());
467 // Couldn't open file...
471 static string const gzipStamp = "\037\213";
474 static string const zipStamp = "PK";
477 static string const compressStamp = "\037\235";
479 // Maximum strings to read
480 int const max_count = 50;
485 bool firstLine = true;
486 while ((count++ < max_count) && format.empty()) {
488 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
489 << "\tFile type not recognised before EOF!");
494 string const stamp = str.substr(0, 2);
495 if (firstLine && str.size() >= 2) {
496 // at first we check for a zipped file, because this
497 // information is saved in the first bytes of the file!
498 // also some graphic formats which save the information
499 // in the first line, too.
500 if (prefixIs(str, gzipStamp)) {
503 } else if (stamp == zipStamp) {
506 } else if (stamp == compressStamp) {
510 } else if (stamp == "BM") {
513 } else if (stamp == "\001\332") {
517 // Don't need to use str.at(0), str.at(1) because
518 // we already know that str.size() >= 2
519 } else if (str[0] == 'P') {
535 } else if ((stamp == "II") || (stamp == "MM")) {
538 } else if (prefixIs(str,"%TGIF")) {
541 } else if (prefixIs(str,"#FIG")) {
544 } else if (prefixIs(str,"GIF")) {
547 } else if (str.size() > 3) {
548 int const c = ((str[0] << 24) & (str[1] << 16) &
549 (str[2] << 8) & str[3]);
560 else if (contains(str,"EPSF"))
561 // dummy, if we have wrong file description like
562 // %!PS-Adobe-2.0EPSF"
565 else if (contains(str, "Grace"))
568 else if (contains(str, "JFIF"))
571 else if (contains(str, "%PDF"))
574 else if (contains(str, "PNG"))
577 else if (contains(str, "%!PS-Adobe")) {
580 if (contains(str,"EPSF"))
586 else if (contains(str, "_bits[]"))
589 else if (contains(str, "XPM") || contains(str, "static char *"))
592 else if (contains(str, "BITPIX"))
596 if (!format.empty()) {
597 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
601 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
602 << "\tCouldn't find a known format!");
607 bool FileName::isZippedFile() const
609 string const type = guessFormatFromContents();
610 return contains("gzip zip compress", type) && !type.empty();
614 docstring const FileName::relPath(string const & path) const
617 return makeRelPath(absoluteFilePath(), from_utf8(path));
621 bool operator==(FileName const & lhs, FileName const & rhs)
623 return lhs.absFilename() == rhs.absFilename();
627 bool operator!=(FileName const & lhs, FileName const & rhs)
629 return lhs.absFilename() != rhs.absFilename();
633 bool operator<(FileName const & lhs, FileName const & rhs)
635 return lhs.absFilename() < rhs.absFilename();
639 bool operator>(FileName const & lhs, FileName const & rhs)
641 return lhs.absFilename() > rhs.absFilename();
645 std::ostream & operator<<(std::ostream & os, FileName const & filename)
647 return os << filename.absFilename();
651 /////////////////////////////////////////////////////////////////////
655 /////////////////////////////////////////////////////////////////////
658 DocFileName::DocFileName()
659 : save_abs_path_(true)
663 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
664 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
668 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
669 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
673 void DocFileName::set(string const & name, string const & buffer_path)
675 save_abs_path_ = absolutePath(name);
676 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
677 zipped_valid_ = false;
681 void DocFileName::erase()
684 zipped_valid_ = false;
688 string DocFileName::relFilename(string const & path) const
691 return to_utf8(relPath(path));
695 string DocFileName::outputFilename(string const & path) const
697 return save_abs_path_ ? absFilename() : relFilename(path);
701 string DocFileName::mangledFilename(std::string const & dir) const
703 // We need to make sure that every DocFileName instance for a given
704 // filename returns the same mangled name.
705 typedef map<string, string> MangledMap;
706 static MangledMap mangledNames;
707 MangledMap::const_iterator const it = mangledNames.find(absFilename());
708 if (it != mangledNames.end())
711 string const name = absFilename();
713 string mname = os::internal_path(name);
714 // Remove the extension.
715 mname = support::changeExtension(name, string());
716 // The mangled name must be a valid LaTeX name.
717 // The list of characters to keep is probably over-restrictive,
718 // but it is not really a problem.
719 // Apart from non-ASCII characters, at least the following characters
720 // are forbidden: '/', '.', ' ', and ':'.
721 // On windows it is not possible to create files with '<', '>' or '?'
723 static string const keep = "abcdefghijklmnopqrstuvwxyz"
724 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
726 string::size_type pos = 0;
727 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
729 // Add the extension back on
730 mname = support::changeExtension(mname, getExtension(name));
732 // Prepend a counter to the filename. This is necessary to make
733 // the mangled name unique.
734 static int counter = 0;
735 std::ostringstream s;
736 s << counter++ << mname;
739 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
740 // is longer than about 160 characters. MiKTeX's pdflatex
741 // is even pickier. A maximum length of 100 has been proven to work.
742 // If dir.size() > max length, all bets are off for YAP. We truncate
743 // the filename nevertheless, keeping a minimum of 10 chars.
745 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
747 // If the mangled file name is too long, hack it to fit.
748 // We know we're guaranteed to have a unique file name because
750 if (mname.size() > max_length) {
751 int const half = (int(max_length) / 2) - 2;
753 mname = mname.substr(0, half) + "___" +
754 mname.substr(mname.size() - half);
758 mangledNames[absFilename()] = mname;
763 bool DocFileName::isZipped() const
765 if (!zipped_valid_) {
766 zipped_ = isZippedFile();
767 zipped_valid_ = true;
773 string DocFileName::unzippedFilename() const
775 return unzippedFileName(absFilename());
779 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
781 return lhs.absFilename() == rhs.absFilename()
782 && lhs.saveAbsPath() == rhs.saveAbsPath();
786 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
788 return !(lhs == rhs);
791 } // namespace support