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/filetools.h"
15 #include "support/lstrings.h"
16 #include "support/os.h"
17 #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)
81 FileName::FileName(string const & abs_filename)
82 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
84 BOOST_ASSERT(empty() || d->fi.isAbsolute());
86 BOOST_ASSERT(!contains(abs_filename, '\\'));
91 FileName::FileName(FileName const & rhs) : d(new Private)
97 FileName & FileName::operator=(FileName const & rhs)
104 bool FileName::empty() const
106 return d->fi.absoluteFilePath().isEmpty();
110 string FileName::absFilename() const
112 return fromqstr(d->fi.absoluteFilePath());
116 void FileName::set(string const & name)
118 d->fi.setFile(toqstr(name));
119 BOOST_ASSERT(d->fi.isAbsolute());
121 BOOST_ASSERT(!contains(name, '\\'));
126 void FileName::erase()
132 bool FileName::copyTo(FileName const & name) const
134 return QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
138 string FileName::toFilesystemEncoding() const
140 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
141 return string(encoded.begin(), encoded.end());
145 FileName FileName::fromFilesystemEncoding(string const & name)
147 QByteArray const encoded(name.c_str(), name.length());
148 return FileName(fromqstr(QFile::decodeName(encoded)));
152 bool FileName::exists() const
154 return d->fi.exists();
158 bool FileName::isSymLink() const
160 return d->fi.isSymLink();
164 bool FileName::isFileEmpty() const
166 return d->fi.size() == 0;
170 bool FileName::isDirectory() const
172 return d->fi.isDir();
176 bool FileName::isReadOnly() const
178 return d->fi.isReadable() && !d->fi.isWritable();
182 bool FileName::isReadableDirectory() const
184 return d->fi.isDir() && d->fi.isReadable();
188 std::string FileName::onlyFileName() const
190 return support::onlyFilename(absFilename());
194 FileName FileName::onlyPath() const
196 return FileName(support::onlyPath(absFilename()));
200 bool FileName::isReadableFile() const
202 return d->fi.isFile() && d->fi.isReadable();
206 bool FileName::isWritable() const
208 return d->fi.isWritable();
212 bool FileName::isDirWritable() const
214 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
216 FileName const tmpfl(tempName(*this, "lyxwritetest"));
226 FileName FileName::tempName(FileName const & dir, std::string const & mask)
228 return support::tempName(dir, mask);
232 std::time_t FileName::lastModified() const
234 return d->fi.lastModified().toTime_t();
238 static bool rmdir(QFileInfo const & fi)
240 QDir dir(fi.absoluteFilePath());
241 QFileInfoList list = dir.entryInfoList();
242 for (int i = 0; i < list.size(); ++i) {
243 if (list.at(i).fileName() == ".")
245 if (list.at(i).fileName() == "..")
247 if (list.at(i).isDir()) {
248 LYXERR(Debug::FILES, "Erasing dir "
249 << fromqstr(list.at(i).absoluteFilePath()) << endl);
250 if (!rmdir(list.at(i)))
254 LYXERR(Debug::FILES, "Erasing file "
255 << fromqstr(list.at(i).absoluteFilePath()) << endl);
256 dir.remove(list.at(i).fileName());
259 QDir parent = fi.absolutePath();
260 return parent.rmdir(fi.fileName());
264 bool FileName::destroyDirectory() const
266 bool const success = rmdir(d->fi);
268 lyxerr << "Could not delete " << *this << "." << endl;
274 bool FileName::createDirectory(int permission) const
276 BOOST_ASSERT(!empty());
277 return mkdir(*this, permission) == 0;
281 docstring FileName::displayName(int threshold) const
283 return makeDisplayPath(absFilename(), threshold);
287 string FileName::fileContents() const
290 string const encodedname = toFilesystemEncoding();
291 ifstream ifs(encodedname.c_str());
299 lyxerr << "LyX was not able to read file '" << *this << '\'' << std::endl;
304 string FileName::guessFormatFromContents() const
306 // the different filetypes and what they contain in one of the first lines
307 // (dots are any characters). (Herbert 20020131)
310 // EPS %!PS-Adobe-3.0 EPSF...
317 // PBM P1... or P4 (B/W)
318 // PGM P2... or P5 (Grayscale)
319 // PPM P3... or P6 (color)
320 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
321 // SGI \001\332... (decimal 474)
323 // TIFF II... or MM...
325 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
326 // ...static char *...
327 // XWD \000\000\000\151 (0x00006900) decimal 105
329 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
330 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
331 // Z \037\235 UNIX compress
334 if (empty() || !isReadableFile())
337 ifstream ifs(toFilesystemEncoding().c_str());
339 // Couldn't open file...
343 static string const gzipStamp = "\037\213";
346 static string const zipStamp = "PK";
349 static string const compressStamp = "\037\235";
351 // Maximum strings to read
352 int const max_count = 50;
357 bool firstLine = true;
358 while ((count++ < max_count) && format.empty()) {
360 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
361 << "\tFile type not recognised before EOF!");
366 string const stamp = str.substr(0, 2);
367 if (firstLine && str.size() >= 2) {
368 // at first we check for a zipped file, because this
369 // information is saved in the first bytes of the file!
370 // also some graphic formats which save the information
371 // in the first line, too.
372 if (prefixIs(str, gzipStamp)) {
375 } else if (stamp == zipStamp) {
378 } else if (stamp == compressStamp) {
382 } else if (stamp == "BM") {
385 } else if (stamp == "\001\332") {
389 // Don't need to use str.at(0), str.at(1) because
390 // we already know that str.size() >= 2
391 } else if (str[0] == 'P') {
407 } else if ((stamp == "II") || (stamp == "MM")) {
410 } else if (prefixIs(str,"%TGIF")) {
413 } else if (prefixIs(str,"#FIG")) {
416 } else if (prefixIs(str,"GIF")) {
419 } else if (str.size() > 3) {
420 int const c = ((str[0] << 24) & (str[1] << 16) &
421 (str[2] << 8) & str[3]);
432 else if (contains(str,"EPSF"))
433 // dummy, if we have wrong file description like
434 // %!PS-Adobe-2.0EPSF"
437 else if (contains(str, "Grace"))
440 else if (contains(str, "JFIF"))
443 else if (contains(str, "%PDF"))
446 else if (contains(str, "PNG"))
449 else if (contains(str, "%!PS-Adobe")) {
452 if (contains(str,"EPSF"))
458 else if (contains(str, "_bits[]"))
461 else if (contains(str, "XPM") || contains(str, "static char *"))
464 else if (contains(str, "BITPIX"))
468 if (!format.empty()) {
469 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
473 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
474 << "\tCouldn't find a known format!");
479 bool FileName::isZippedFile() const
481 string const type = guessFormatFromContents();
482 return contains("gzip zip compress", type) && !type.empty();
486 bool operator==(FileName const & lhs, FileName const & rhs)
488 return lhs.absFilename() == rhs.absFilename();
492 bool operator!=(FileName const & lhs, FileName const & rhs)
494 return lhs.absFilename() != rhs.absFilename();
498 bool operator<(FileName const & lhs, FileName const & rhs)
500 return lhs.absFilename() < rhs.absFilename();
504 bool operator>(FileName const & lhs, FileName const & rhs)
506 return lhs.absFilename() > rhs.absFilename();
510 std::ostream & operator<<(std::ostream & os, FileName const & filename)
512 return os << filename.absFilename();
516 /////////////////////////////////////////////////////////////////////
520 /////////////////////////////////////////////////////////////////////
523 DocFileName::DocFileName()
524 : save_abs_path_(true)
528 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
529 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
533 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
534 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
538 void DocFileName::set(string const & name, string const & buffer_path)
540 save_abs_path_ = absolutePath(name);
541 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
542 zipped_valid_ = false;
546 void DocFileName::erase()
549 zipped_valid_ = false;
553 string const DocFileName::relFilename(string const & path) const
556 return to_utf8(makeRelPath(qstring_to_ucs4(d->fi.absoluteFilePath()), from_utf8(path)));
560 string const DocFileName::outputFilename(string const & path) const
562 return save_abs_path_ ? absFilename() : relFilename(path);
566 string const DocFileName::mangledFilename(std::string const & dir) const
568 // We need to make sure that every DocFileName instance for a given
569 // filename returns the same mangled name.
570 typedef map<string, string> MangledMap;
571 static MangledMap mangledNames;
572 MangledMap::const_iterator const it = mangledNames.find(absFilename());
573 if (it != mangledNames.end())
576 string const name = absFilename();
578 string mname = os::internal_path(name);
579 // Remove the extension.
580 mname = changeExtension(name, string());
581 // The mangled name must be a valid LaTeX name.
582 // The list of characters to keep is probably over-restrictive,
583 // but it is not really a problem.
584 // Apart from non-ASCII characters, at least the following characters
585 // are forbidden: '/', '.', ' ', and ':'.
586 // On windows it is not possible to create files with '<', '>' or '?'
588 static string const keep = "abcdefghijklmnopqrstuvwxyz"
589 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
591 string::size_type pos = 0;
592 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
594 // Add the extension back on
595 mname = changeExtension(mname, getExtension(name));
597 // Prepend a counter to the filename. This is necessary to make
598 // the mangled name unique.
599 static int counter = 0;
600 std::ostringstream s;
601 s << counter++ << mname;
604 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
605 // is longer than about 160 characters. MiKTeX's pdflatex
606 // is even pickier. A maximum length of 100 has been proven to work.
607 // If dir.size() > max length, all bets are off for YAP. We truncate
608 // the filename nevertheless, keeping a minimum of 10 chars.
610 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
612 // If the mangled file name is too long, hack it to fit.
613 // We know we're guaranteed to have a unique file name because
615 if (mname.size() > max_length) {
616 int const half = (int(max_length) / 2) - 2;
618 mname = mname.substr(0, half) + "___" +
619 mname.substr(mname.size() - half);
623 mangledNames[absFilename()] = mname;
628 bool DocFileName::isZipped() const
630 if (!zipped_valid_) {
631 zipped_ = isZippedFile();
632 zipped_valid_ = true;
638 string const DocFileName::unzippedFilename() const
640 return unzippedFileName(absFilename());
644 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
646 return lhs.absFilename() == rhs.absFilename()
647 && lhs.saveAbsPath() == rhs.saveAbsPath();
651 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
653 return !(lhs == rhs);
656 } // namespace support