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"
25 #include <boost/filesystem/exception.hpp>
26 #include <boost/filesystem/operations.hpp>
37 using std::ostringstream;
40 namespace fs = boost::filesystem;
46 /////////////////////////////////////////////////////////////////////
50 /////////////////////////////////////////////////////////////////////
53 FileName::FileName(string const & abs_filename)
56 BOOST_ASSERT(empty() || absolutePath(name_));
58 BOOST_ASSERT(!contains(name_, '\\'));
63 void FileName::set(string const & name)
66 BOOST_ASSERT(absolutePath(name_));
68 BOOST_ASSERT(!contains(name_, '\\'));
73 void FileName::erase()
79 string FileName::toFilesystemEncoding() const
81 QByteArray const encoded = QFile::encodeName(toqstr(name_));
82 return string(encoded.begin(), encoded.end());
86 FileName FileName::fromFilesystemEncoding(string const & name)
88 QByteArray const encoded(name.c_str(), name.length());
89 return FileName(fromqstr(QFile::decodeName(encoded)));
93 bool FileName::exists() const
95 return QFileInfo(toqstr(name_)).exists();
99 bool FileName::isDirectory() const
101 return QFileInfo(toqstr(name_)).isDir();
105 bool FileName::isReadOnly() const
107 QFileInfo const fi(toqstr(name_));
108 return fi.isReadable() && !fi.isWritable();
112 bool FileName::isReadable() const
114 QFileInfo const fi(toqstr(name_));
115 return fi.isReadable();
119 bool FileName::isFileReadable() const
121 QFileInfo const fi(toqstr(name_));
122 return fi.isFile() && fi.isReadable();
126 bool FileName::isWritable() const
128 QFileInfo const fi(toqstr(name_));
129 return fi.isWritable();
133 bool FileName::isDirWritable() const
135 LYXERR(Debug::FILES) << "isDirWriteable: " << *this << std::endl;
137 FileName const tmpfl(tempName(*this, "lyxwritetest"));
147 FileName FileName::tempName(FileName const & dir, std::string const & mask)
149 return support::tempName(dir, mask);
153 std::time_t FileName::lastModified() const
155 return fs::last_write_time(toFilesystemEncoding());
159 bool FileName::destroyDirectory() const
162 return fs::remove_all(toFilesystemEncoding()) > 0;
163 } catch (fs::filesystem_error const & fe){
164 lyxerr << "Could not delete " << *this << ". (" << fe.what() << ")"
171 bool FileName::createDirectory(int permission) const
173 BOOST_ASSERT(!empty());
174 return mkdir(*this, permission) == 0;
178 string FileName::fileContents() const
181 string const encodedname = toFilesystemEncoding();
182 ifstream ifs(encodedname.c_str());
190 lyxerr << "LyX was not able to read file '" << *this << '\'' << std::endl;
195 string FileName::guessFormatFromContents() const
197 // the different filetypes and what they contain in one of the first lines
198 // (dots are any characters). (Herbert 20020131)
201 // EPS %!PS-Adobe-3.0 EPSF...
208 // PBM P1... or P4 (B/W)
209 // PGM P2... or P5 (Grayscale)
210 // PPM P3... or P6 (color)
211 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
212 // SGI \001\332... (decimal 474)
214 // TIFF II... or MM...
216 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
217 // ...static char *...
218 // XWD \000\000\000\151 (0x00006900) decimal 105
220 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
221 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
222 // Z \037\235 UNIX compress
225 if (empty() || !isReadable())
228 ifstream ifs(toFilesystemEncoding().c_str());
230 // Couldn't open file...
234 static string const gzipStamp = "\037\213";
237 static string const zipStamp = "PK";
240 static string const compressStamp = "\037\235";
242 // Maximum strings to read
243 int const max_count = 50;
248 bool firstLine = true;
249 while ((count++ < max_count) && format.empty()) {
251 LYXERR(Debug::GRAPHICS)
252 << "filetools(getFormatFromContents)\n"
253 << "\tFile type not recognised before EOF!"
259 string const stamp = str.substr(0, 2);
260 if (firstLine && str.size() >= 2) {
261 // at first we check for a zipped file, because this
262 // information is saved in the first bytes of the file!
263 // also some graphic formats which save the information
264 // in the first line, too.
265 if (prefixIs(str, gzipStamp)) {
268 } else if (stamp == zipStamp) {
271 } else if (stamp == compressStamp) {
275 } else if (stamp == "BM") {
278 } else if (stamp == "\001\332") {
282 // Don't need to use str.at(0), str.at(1) because
283 // we already know that str.size() >= 2
284 } else if (str[0] == 'P') {
300 } else if ((stamp == "II") || (stamp == "MM")) {
303 } else if (prefixIs(str,"%TGIF")) {
306 } else if (prefixIs(str,"#FIG")) {
309 } else if (prefixIs(str,"GIF")) {
312 } else if (str.size() > 3) {
313 int const c = ((str[0] << 24) & (str[1] << 16) &
314 (str[2] << 8) & str[3]);
325 else if (contains(str,"EPSF"))
326 // dummy, if we have wrong file description like
327 // %!PS-Adobe-2.0EPSF"
330 else if (contains(str, "Grace"))
333 else if (contains(str, "JFIF"))
336 else if (contains(str, "%PDF"))
339 else if (contains(str, "PNG"))
342 else if (contains(str, "%!PS-Adobe")) {
345 if (contains(str,"EPSF"))
351 else if (contains(str, "_bits[]"))
354 else if (contains(str, "XPM") || contains(str, "static char *"))
357 else if (contains(str, "BITPIX"))
361 if (!format.empty()) {
362 LYXERR(Debug::GRAPHICS)
363 << "Recognised Fileformat: " << format << endl;
367 LYXERR(Debug::GRAPHICS)
368 << "filetools(getFormatFromContents)\n"
369 << "\tCouldn't find a known format!\n";
374 bool FileName::isZippedFile() const
376 string const type = guessFormatFromContents();
377 return contains("gzip zip compress", type) && !type.empty();
381 bool operator==(FileName const & lhs, FileName const & rhs)
383 return lhs.absFilename() == rhs.absFilename();
387 bool operator!=(FileName const & lhs, FileName const & rhs)
389 return lhs.absFilename() != rhs.absFilename();
393 bool operator<(FileName const & lhs, FileName const & rhs)
395 return lhs.absFilename() < rhs.absFilename();
399 bool operator>(FileName const & lhs, FileName const & rhs)
401 return lhs.absFilename() > rhs.absFilename();
405 std::ostream & operator<<(std::ostream & os, FileName const & filename)
407 return os << filename.absFilename();
411 /////////////////////////////////////////////////////////////////////
415 /////////////////////////////////////////////////////////////////////
418 DocFileName::DocFileName()
419 : save_abs_path_(true)
423 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
424 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
428 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
429 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
433 void DocFileName::set(string const & name, string const & buffer_path)
435 save_abs_path_ = absolutePath(name);
436 name_ = save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename();
437 zipped_valid_ = false;
441 void DocFileName::erase()
444 zipped_valid_ = false;
448 string const DocFileName::relFilename(string const & path) const
451 return to_utf8(makeRelPath(from_utf8(name_), from_utf8(path)));
455 string const DocFileName::outputFilename(string const & path) const
458 return save_abs_path_ ? name_ : to_utf8(makeRelPath(from_utf8(name_), from_utf8(path)));
462 string const DocFileName::mangledFilename(std::string const & dir) const
464 // We need to make sure that every DocFileName instance for a given
465 // filename returns the same mangled name.
466 typedef map<string, string> MangledMap;
467 static MangledMap mangledNames;
468 MangledMap::const_iterator const it = mangledNames.find(name_);
469 if (it != mangledNames.end())
473 string mname = os::internal_path(name_);
474 // Remove the extension.
475 mname = changeExtension(name_, string());
476 // The mangled name must be a valid LaTeX name.
477 // The list of characters to keep is probably over-restrictive,
478 // but it is not really a problem.
479 // Apart from non-ASCII characters, at least the following characters
480 // are forbidden: '/', '.', ' ', and ':'.
481 // On windows it is not possible to create files with '<', '>' or '?'
483 static string const keep = "abcdefghijklmnopqrstuvwxyz"
484 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
486 string::size_type pos = 0;
487 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
489 // Add the extension back on
490 mname = changeExtension(mname, getExtension(name_));
492 // Prepend a counter to the filename. This is necessary to make
493 // the mangled name unique.
494 static int counter = 0;
495 std::ostringstream s;
496 s << counter++ << mname;
499 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
500 // is longer than about 160 characters. MiKTeX's pdflatex
501 // is even pickier. A maximum length of 100 has been proven to work.
502 // If dir.size() > max length, all bets are off for YAP. We truncate
503 // the filename nevertheless, keeping a minimum of 10 chars.
505 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
507 // If the mangled file name is too long, hack it to fit.
508 // We know we're guaranteed to have a unique file name because
510 if (mname.size() > max_length) {
511 int const half = (int(max_length) / 2) - 2;
513 mname = mname.substr(0, half) + "___" +
514 mname.substr(mname.size() - half);
518 mangledNames[name_] = mname;
523 bool DocFileName::isZipped() const
525 if (!zipped_valid_) {
526 zipped_ = isZippedFile();
527 zipped_valid_ = true;
533 string const DocFileName::unzippedFilename() const
535 return unzippedFileName(name_);
539 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
541 return lhs.absFilename() == rhs.absFilename()
542 && lhs.saveAbsPath() == rhs.saveAbsPath();
546 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
548 return !(lhs == rhs);
551 } // namespace support