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 std::string FileName::onlyFileName() const
121 return support::onlyFilename(absFilename());
125 std::string FileName::onlyPath() const
127 return support::onlyPath(absFilename());
131 bool FileName::isFileReadable() const
133 QFileInfo const fi(toqstr(name_));
134 return fi.isFile() && fi.isReadable();
138 bool FileName::isWritable() const
140 QFileInfo const fi(toqstr(name_));
141 return fi.isWritable();
145 bool FileName::isDirWritable() const
147 LYXERR(Debug::FILES) << "isDirWriteable: " << *this << std::endl;
149 FileName const tmpfl(tempName(*this, "lyxwritetest"));
159 FileName FileName::tempName(FileName const & dir, std::string const & mask)
161 return support::tempName(dir, mask);
165 std::time_t FileName::lastModified() const
167 return fs::last_write_time(toFilesystemEncoding());
171 bool FileName::destroyDirectory() const
174 return fs::remove_all(toFilesystemEncoding()) > 0;
175 } catch (fs::filesystem_error const & fe){
176 lyxerr << "Could not delete " << *this << ". (" << fe.what() << ")"
183 bool FileName::createDirectory(int permission) const
185 BOOST_ASSERT(!empty());
186 return mkdir(*this, permission) == 0;
190 docstring FileName::displayName(int threshold) const
192 return makeDisplayPath(absFilename(), threshold);
196 string FileName::fileContents() const
199 string const encodedname = toFilesystemEncoding();
200 ifstream ifs(encodedname.c_str());
208 lyxerr << "LyX was not able to read file '" << *this << '\'' << std::endl;
213 string FileName::guessFormatFromContents() const
215 // the different filetypes and what they contain in one of the first lines
216 // (dots are any characters). (Herbert 20020131)
219 // EPS %!PS-Adobe-3.0 EPSF...
226 // PBM P1... or P4 (B/W)
227 // PGM P2... or P5 (Grayscale)
228 // PPM P3... or P6 (color)
229 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
230 // SGI \001\332... (decimal 474)
232 // TIFF II... or MM...
234 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
235 // ...static char *...
236 // XWD \000\000\000\151 (0x00006900) decimal 105
238 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
239 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
240 // Z \037\235 UNIX compress
243 if (empty() || !isReadable())
246 ifstream ifs(toFilesystemEncoding().c_str());
248 // Couldn't open file...
252 static string const gzipStamp = "\037\213";
255 static string const zipStamp = "PK";
258 static string const compressStamp = "\037\235";
260 // Maximum strings to read
261 int const max_count = 50;
266 bool firstLine = true;
267 while ((count++ < max_count) && format.empty()) {
269 LYXERR(Debug::GRAPHICS)
270 << "filetools(getFormatFromContents)\n"
271 << "\tFile type not recognised before EOF!"
277 string const stamp = str.substr(0, 2);
278 if (firstLine && str.size() >= 2) {
279 // at first we check for a zipped file, because this
280 // information is saved in the first bytes of the file!
281 // also some graphic formats which save the information
282 // in the first line, too.
283 if (prefixIs(str, gzipStamp)) {
286 } else if (stamp == zipStamp) {
289 } else if (stamp == compressStamp) {
293 } else if (stamp == "BM") {
296 } else if (stamp == "\001\332") {
300 // Don't need to use str.at(0), str.at(1) because
301 // we already know that str.size() >= 2
302 } else if (str[0] == 'P') {
318 } else if ((stamp == "II") || (stamp == "MM")) {
321 } else if (prefixIs(str,"%TGIF")) {
324 } else if (prefixIs(str,"#FIG")) {
327 } else if (prefixIs(str,"GIF")) {
330 } else if (str.size() > 3) {
331 int const c = ((str[0] << 24) & (str[1] << 16) &
332 (str[2] << 8) & str[3]);
343 else if (contains(str,"EPSF"))
344 // dummy, if we have wrong file description like
345 // %!PS-Adobe-2.0EPSF"
348 else if (contains(str, "Grace"))
351 else if (contains(str, "JFIF"))
354 else if (contains(str, "%PDF"))
357 else if (contains(str, "PNG"))
360 else if (contains(str, "%!PS-Adobe")) {
363 if (contains(str,"EPSF"))
369 else if (contains(str, "_bits[]"))
372 else if (contains(str, "XPM") || contains(str, "static char *"))
375 else if (contains(str, "BITPIX"))
379 if (!format.empty()) {
380 LYXERR(Debug::GRAPHICS)
381 << "Recognised Fileformat: " << format << endl;
385 LYXERR(Debug::GRAPHICS)
386 << "filetools(getFormatFromContents)\n"
387 << "\tCouldn't find a known format!\n";
392 bool FileName::isZippedFile() const
394 string const type = guessFormatFromContents();
395 return contains("gzip zip compress", type) && !type.empty();
399 bool operator==(FileName const & lhs, FileName const & rhs)
401 return lhs.absFilename() == rhs.absFilename();
405 bool operator!=(FileName const & lhs, FileName const & rhs)
407 return lhs.absFilename() != rhs.absFilename();
411 bool operator<(FileName const & lhs, FileName const & rhs)
413 return lhs.absFilename() < rhs.absFilename();
417 bool operator>(FileName const & lhs, FileName const & rhs)
419 return lhs.absFilename() > rhs.absFilename();
423 std::ostream & operator<<(std::ostream & os, FileName const & filename)
425 return os << filename.absFilename();
429 /////////////////////////////////////////////////////////////////////
433 /////////////////////////////////////////////////////////////////////
436 DocFileName::DocFileName()
437 : save_abs_path_(true)
441 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
442 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
446 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
447 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
451 void DocFileName::set(string const & name, string const & buffer_path)
453 save_abs_path_ = absolutePath(name);
454 name_ = save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename();
455 zipped_valid_ = false;
459 void DocFileName::erase()
462 zipped_valid_ = false;
466 string const DocFileName::relFilename(string const & path) const
469 return to_utf8(makeRelPath(from_utf8(name_), from_utf8(path)));
473 string const DocFileName::outputFilename(string const & path) const
476 return save_abs_path_ ? name_ : to_utf8(makeRelPath(from_utf8(name_), from_utf8(path)));
480 string const DocFileName::mangledFilename(std::string const & dir) const
482 // We need to make sure that every DocFileName instance for a given
483 // filename returns the same mangled name.
484 typedef map<string, string> MangledMap;
485 static MangledMap mangledNames;
486 MangledMap::const_iterator const it = mangledNames.find(name_);
487 if (it != mangledNames.end())
491 string mname = os::internal_path(name_);
492 // Remove the extension.
493 mname = changeExtension(name_, string());
494 // The mangled name must be a valid LaTeX name.
495 // The list of characters to keep is probably over-restrictive,
496 // but it is not really a problem.
497 // Apart from non-ASCII characters, at least the following characters
498 // are forbidden: '/', '.', ' ', and ':'.
499 // On windows it is not possible to create files with '<', '>' or '?'
501 static string const keep = "abcdefghijklmnopqrstuvwxyz"
502 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
504 string::size_type pos = 0;
505 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
507 // Add the extension back on
508 mname = changeExtension(mname, getExtension(name_));
510 // Prepend a counter to the filename. This is necessary to make
511 // the mangled name unique.
512 static int counter = 0;
513 std::ostringstream s;
514 s << counter++ << mname;
517 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
518 // is longer than about 160 characters. MiKTeX's pdflatex
519 // is even pickier. A maximum length of 100 has been proven to work.
520 // If dir.size() > max length, all bets are off for YAP. We truncate
521 // the filename nevertheless, keeping a minimum of 10 chars.
523 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
525 // If the mangled file name is too long, hack it to fit.
526 // We know we're guaranteed to have a unique file name because
528 if (mname.size() > max_length) {
529 int const half = (int(max_length) / 2) - 2;
531 mname = mname.substr(0, half) + "___" +
532 mname.substr(mname.size() - half);
536 mangledNames[name_] = mname;
541 bool DocFileName::isZipped() const
543 if (!zipped_valid_) {
544 zipped_ = isZippedFile();
545 zipped_valid_ = true;
551 string const DocFileName::unzippedFilename() const
553 return unzippedFileName(name_);
557 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
559 return lhs.absFilename() == rhs.absFilename()
560 && lhs.saveAbsPath() == rhs.saveAbsPath();
564 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
566 return !(lhs == rhs);
569 } // namespace support