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"
15 #include "support/debug.h"
16 #include "support/filetools.h"
17 #include "support/lstrings.h"
18 #include "support/lyxlib.h"
19 #include "support/os.h"
20 #include "support/qstring_helpers.h"
28 #include <boost/assert.hpp>
35 #ifdef HAVE_SYS_TYPES_H
36 # include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
48 using std::ostringstream;
55 /////////////////////////////////////////////////////////////////////
59 /////////////////////////////////////////////////////////////////////
61 struct FileName::Private
65 Private(string const & abs_filename) : fi(toqstr(abs_filename))
71 /////////////////////////////////////////////////////////////////////
75 /////////////////////////////////////////////////////////////////////
78 FileName::FileName() : d(new Private)
83 FileName::FileName(string const & abs_filename)
84 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
95 FileName::FileName(FileName const & rhs) : d(new Private)
101 FileName & FileName::operator=(FileName const & rhs)
108 bool FileName::empty() const
110 return d->fi.absoluteFilePath().isEmpty();
114 string FileName::absFilename() const
116 return fromqstr(d->fi.absoluteFilePath());
120 void FileName::set(string const & name)
122 d->fi.setFile(toqstr(name));
123 BOOST_ASSERT(d->fi.isAbsolute());
127 void FileName::erase()
133 bool FileName::copyTo(FileName const & name, bool overwrite) const
136 QFile::remove(name.d->fi.absoluteFilePath());
137 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
139 lyxerr << "FileName::copyTo(): Could not copy file "
140 << *this << " to " << name << endl;
145 string FileName::toFilesystemEncoding() const
147 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
148 return string(encoded.begin(), encoded.end());
152 FileName FileName::fromFilesystemEncoding(string const & name)
154 QByteArray const encoded(name.c_str(), name.length());
155 return FileName(fromqstr(QFile::decodeName(encoded)));
159 bool FileName::exists() const
161 return d->fi.exists();
165 bool FileName::isSymLink() const
167 return d->fi.isSymLink();
171 bool FileName::isFileEmpty() const
173 return d->fi.size() == 0;
177 bool FileName::isDirectory() const
179 return d->fi.isDir();
183 bool FileName::isReadOnly() const
185 return d->fi.isReadable() && !d->fi.isWritable();
189 bool FileName::isReadableDirectory() const
191 return d->fi.isDir() && d->fi.isReadable();
195 std::string FileName::onlyFileName() const
197 return support::onlyFilename(absFilename());
201 FileName FileName::onlyPath() const
203 return FileName(support::onlyPath(absFilename()));
207 bool FileName::isReadableFile() const
209 return d->fi.isFile() && d->fi.isReadable();
213 bool FileName::isWritable() const
215 return d->fi.isWritable();
219 bool FileName::isDirWritable() const
221 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
223 FileName const tmpfl(tempName(*this, "lyxwritetest"));
233 FileName FileName::tempName(FileName const & dir, std::string const & mask)
235 return support::tempName(dir, mask);
239 std::time_t FileName::lastModified() const
241 return d->fi.lastModified().toTime_t();
245 bool FileName::chdir() const
247 return QDir::setCurrent(d->fi.absoluteFilePath());
251 extern unsigned long sum(char const * file);
253 unsigned long FileName::checksum() const
256 LYXERR0("File \"" << absFilename() << "\" does not exist!");
259 // a directory may be passed here so we need to test it. (bug 3622)
261 LYXERR0('\\' << absFilename() << "\" is a directory!");
264 LYXERR0("Checksumming \"" << absFilename() << "\".");
265 return sum(absFilename().c_str());
269 bool FileName::removeFile() const
271 bool const success = QFile::remove(d->fi.absoluteFilePath());
272 if (!success && exists())
273 lyxerr << "FileName::removeFile(): Could not delete file "
274 << *this << "." << endl;
279 static bool rmdir(QFileInfo const & fi)
281 QDir dir(fi.absoluteFilePath());
282 QFileInfoList list = dir.entryInfoList();
283 bool global_success = true;
284 for (int i = 0; i != list.size(); ++i) {
285 if (list.at(i).fileName() == ".")
287 if (list.at(i).fileName() == "..")
290 if (list.at(i).isDir()) {
291 LYXERR(Debug::FILES, "Erasing dir "
292 << fromqstr(list.at(i).absoluteFilePath()));
293 success = rmdir(list.at(i));
296 LYXERR(Debug::FILES, "Erasing file "
297 << fromqstr(list.at(i).absoluteFilePath()));
298 success = dir.remove(list.at(i).fileName());
301 global_success = false;
302 lyxerr << "Could not delete "
303 << fromqstr(list.at(i).absoluteFilePath()) << "." << endl;
306 QDir parent = fi.absolutePath();
307 global_success |= parent.rmdir(fi.fileName());
308 return global_success;
312 bool FileName::destroyDirectory() const
314 bool const success = rmdir(d->fi);
316 lyxerr << "Could not delete " << *this << "." << endl;
322 bool FileName::createDirectory(int permission) const
324 BOOST_ASSERT(!empty());
325 return mkdir(*this, permission) == 0;
329 docstring const FileName::absoluteFilePath() const
331 return qstring_to_ucs4(d->fi.absoluteFilePath());
335 docstring FileName::displayName(int threshold) const
337 return makeDisplayPath(absFilename(), threshold);
341 docstring FileName::fileContents(string const & encoding) const
343 if (!isReadableFile()) {
344 LYXERR0("File '" << *this
345 << "' is not redable!");
349 QFile file(d->fi.absoluteFilePath());
350 if (!file.open(QIODevice::ReadOnly)) {
351 LYXERR0("File '" << *this
352 << "' could not be opened in read only mode!");
355 QByteArray contents = file.readAll();
358 if (contents.isEmpty()) {
359 LYXERR(Debug::FILES, "File '" << *this
360 << "' is either empty or some error happened while reading it.");
365 if (encoding.empty() || encoding == "UTF-8")
366 s = QString::fromUtf8(contents.data());
367 else if (encoding == "ascii")
368 s = QString::fromAscii(contents.data());
369 else if (encoding == "local8bit")
370 s = QString::fromLocal8Bit(contents.data());
371 else if (encoding == "latin1")
372 s = QString::fromLatin1(contents.data());
374 return qstring_to_ucs4(s);
378 void FileName::changeExtension(std::string const & extension)
380 // FIXME: use Qt native methods...
381 string const oldname = absFilename();
382 string::size_type const last_slash = oldname.rfind('/');
383 string::size_type last_dot = oldname.rfind('.');
384 if (last_dot < last_slash && last_slash != string::npos)
385 last_dot = string::npos;
388 // Make sure the extension starts with a dot
389 if (!extension.empty() && extension[0] != '.')
390 ext= '.' + extension;
394 set(oldname.substr(0, last_dot) + ext);
398 string FileName::guessFormatFromContents() const
400 // the different filetypes and what they contain in one of the first lines
401 // (dots are any characters). (Herbert 20020131)
404 // EPS %!PS-Adobe-3.0 EPSF...
411 // PBM P1... or P4 (B/W)
412 // PGM P2... or P5 (Grayscale)
413 // PPM P3... or P6 (color)
414 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
415 // SGI \001\332... (decimal 474)
417 // TIFF II... or MM...
419 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
420 // ...static char *...
421 // XWD \000\000\000\151 (0x00006900) decimal 105
423 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
424 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
425 // Z \037\235 UNIX compress
428 if (empty() || !isReadableFile())
431 ifstream ifs(toFilesystemEncoding().c_str());
433 // Couldn't open file...
437 static string const gzipStamp = "\037\213";
440 static string const zipStamp = "PK";
443 static string const compressStamp = "\037\235";
445 // Maximum strings to read
446 int const max_count = 50;
451 bool firstLine = true;
452 while ((count++ < max_count) && format.empty()) {
454 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
455 << "\tFile type not recognised before EOF!");
460 string const stamp = str.substr(0, 2);
461 if (firstLine && str.size() >= 2) {
462 // at first we check for a zipped file, because this
463 // information is saved in the first bytes of the file!
464 // also some graphic formats which save the information
465 // in the first line, too.
466 if (prefixIs(str, gzipStamp)) {
469 } else if (stamp == zipStamp) {
472 } else if (stamp == compressStamp) {
476 } else if (stamp == "BM") {
479 } else if (stamp == "\001\332") {
483 // Don't need to use str.at(0), str.at(1) because
484 // we already know that str.size() >= 2
485 } else if (str[0] == 'P') {
501 } else if ((stamp == "II") || (stamp == "MM")) {
504 } else if (prefixIs(str,"%TGIF")) {
507 } else if (prefixIs(str,"#FIG")) {
510 } else if (prefixIs(str,"GIF")) {
513 } else if (str.size() > 3) {
514 int const c = ((str[0] << 24) & (str[1] << 16) &
515 (str[2] << 8) & str[3]);
526 else if (contains(str,"EPSF"))
527 // dummy, if we have wrong file description like
528 // %!PS-Adobe-2.0EPSF"
531 else if (contains(str, "Grace"))
534 else if (contains(str, "JFIF"))
537 else if (contains(str, "%PDF"))
540 else if (contains(str, "PNG"))
543 else if (contains(str, "%!PS-Adobe")) {
546 if (contains(str,"EPSF"))
552 else if (contains(str, "_bits[]"))
555 else if (contains(str, "XPM") || contains(str, "static char *"))
558 else if (contains(str, "BITPIX"))
562 if (!format.empty()) {
563 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
567 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
568 << "\tCouldn't find a known format!");
573 bool FileName::isZippedFile() const
575 string const type = guessFormatFromContents();
576 return contains("gzip zip compress", type) && !type.empty();
580 docstring const FileName::relPath(string const & path) const
583 return makeRelPath(absoluteFilePath(), from_utf8(path));
587 bool operator==(FileName const & lhs, FileName const & rhs)
589 return lhs.absFilename() == rhs.absFilename();
593 bool operator!=(FileName const & lhs, FileName const & rhs)
595 return lhs.absFilename() != rhs.absFilename();
599 bool operator<(FileName const & lhs, FileName const & rhs)
601 return lhs.absFilename() < rhs.absFilename();
605 bool operator>(FileName const & lhs, FileName const & rhs)
607 return lhs.absFilename() > rhs.absFilename();
611 std::ostream & operator<<(std::ostream & os, FileName const & filename)
613 return os << filename.absFilename();
617 /////////////////////////////////////////////////////////////////////
621 /////////////////////////////////////////////////////////////////////
624 DocFileName::DocFileName()
625 : save_abs_path_(true)
629 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
630 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
634 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
635 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
639 void DocFileName::set(string const & name, string const & buffer_path)
641 save_abs_path_ = absolutePath(name);
642 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
643 zipped_valid_ = false;
647 void DocFileName::erase()
650 zipped_valid_ = false;
654 string DocFileName::relFilename(string const & path) const
657 return to_utf8(relPath(path));
661 string DocFileName::outputFilename(string const & path) const
663 return save_abs_path_ ? absFilename() : relFilename(path);
667 string DocFileName::mangledFilename(std::string const & dir) const
669 // We need to make sure that every DocFileName instance for a given
670 // filename returns the same mangled name.
671 typedef map<string, string> MangledMap;
672 static MangledMap mangledNames;
673 MangledMap::const_iterator const it = mangledNames.find(absFilename());
674 if (it != mangledNames.end())
677 string const name = absFilename();
679 string mname = os::internal_path(name);
680 // Remove the extension.
681 mname = support::changeExtension(name, string());
682 // The mangled name must be a valid LaTeX name.
683 // The list of characters to keep is probably over-restrictive,
684 // but it is not really a problem.
685 // Apart from non-ASCII characters, at least the following characters
686 // are forbidden: '/', '.', ' ', and ':'.
687 // On windows it is not possible to create files with '<', '>' or '?'
689 static string const keep = "abcdefghijklmnopqrstuvwxyz"
690 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
692 string::size_type pos = 0;
693 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
695 // Add the extension back on
696 mname = support::changeExtension(mname, getExtension(name));
698 // Prepend a counter to the filename. This is necessary to make
699 // the mangled name unique.
700 static int counter = 0;
701 std::ostringstream s;
702 s << counter++ << mname;
705 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
706 // is longer than about 160 characters. MiKTeX's pdflatex
707 // is even pickier. A maximum length of 100 has been proven to work.
708 // If dir.size() > max length, all bets are off for YAP. We truncate
709 // the filename nevertheless, keeping a minimum of 10 chars.
711 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
713 // If the mangled file name is too long, hack it to fit.
714 // We know we're guaranteed to have a unique file name because
716 if (mname.size() > max_length) {
717 int const half = (int(max_length) / 2) - 2;
719 mname = mname.substr(0, half) + "___" +
720 mname.substr(mname.size() - half);
724 mangledNames[absFilename()] = mname;
729 bool DocFileName::isZipped() const
731 if (!zipped_valid_) {
732 zipped_ = isZippedFile();
733 zipped_valid_ = true;
739 string DocFileName::unzippedFilename() const
741 return unzippedFileName(absFilename());
745 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
747 return lhs.absFilename() == rhs.absFilename()
748 && lhs.saveAbsPath() == rhs.saveAbsPath();
752 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
754 return !(lhs == rhs);
757 } // namespace support