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 bool global_success = true;
243 for (int i = 0; i < list.size(); ++i) {
244 if (list.at(i).fileName() == ".")
246 if (list.at(i).fileName() == "..")
249 if (list.at(i).isDir()) {
250 LYXERR(Debug::FILES, "Erasing dir "
251 << fromqstr(list.at(i).absoluteFilePath()) << endl);
252 success = rmdir(list.at(i));
255 LYXERR(Debug::FILES, "Erasing file "
256 << fromqstr(list.at(i).absoluteFilePath()) << endl);
257 success = dir.remove(list.at(i).fileName());
260 global_success = false;
261 lyxerr << "Could not delete "
262 << fromqstr(list.at(i).absoluteFilePath()) << "." << endl;
265 QDir parent = fi.absolutePath();
266 global_success |= parent.rmdir(fi.fileName());
267 return global_success;
271 bool FileName::destroyDirectory() const
273 bool const success = rmdir(d->fi);
275 lyxerr << "Could not delete " << *this << "." << endl;
281 bool FileName::createDirectory(int permission) const
283 BOOST_ASSERT(!empty());
284 return mkdir(*this, permission) == 0;
288 std::vector<FileName> FileName::dirList(std::string const & ext)
290 std::vector<FileName> dirlist;
291 if (!exists() || !isDirectory()) {
292 lyxerr << "FileName::dirList(): Directory \"" << absFilename()
293 << "\" does not exist!" << endl;
297 QDir dir(d->fi.absoluteFilePath());
302 case '.': filter = "*" + toqstr(ext); break;
303 case '*': filter = toqstr(ext); break;
304 default: filter = "*." + toqstr(ext);
306 dir.setNameFilters(QStringList(filter));
307 LYXERR(Debug::FILES, "FileName::dirList(): filtering on extension "
308 << fromqstr(filter) << " is requested." << endl);
311 QFileInfoList list = dir.entryInfoList();
312 for (int i = 0; i < list.size(); ++i) {
314 fi.d->fi = list.at(i);
315 dirlist.push_back(fi);
316 LYXERR(Debug::FILES, "FileName::dirList(): found file "
317 << fi.absFilename() << endl);
324 docstring FileName::displayName(int threshold) const
326 return makeDisplayPath(absFilename(), threshold);
330 string FileName::fileContents() const
333 string const encodedname = toFilesystemEncoding();
334 ifstream ifs(encodedname.c_str());
342 lyxerr << "LyX was not able to read file '" << *this << '\'' << std::endl;
347 string FileName::guessFormatFromContents() const
349 // the different filetypes and what they contain in one of the first lines
350 // (dots are any characters). (Herbert 20020131)
353 // EPS %!PS-Adobe-3.0 EPSF...
360 // PBM P1... or P4 (B/W)
361 // PGM P2... or P5 (Grayscale)
362 // PPM P3... or P6 (color)
363 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
364 // SGI \001\332... (decimal 474)
366 // TIFF II... or MM...
368 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
369 // ...static char *...
370 // XWD \000\000\000\151 (0x00006900) decimal 105
372 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
373 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
374 // Z \037\235 UNIX compress
377 if (empty() || !isReadableFile())
380 ifstream ifs(toFilesystemEncoding().c_str());
382 // Couldn't open file...
386 static string const gzipStamp = "\037\213";
389 static string const zipStamp = "PK";
392 static string const compressStamp = "\037\235";
394 // Maximum strings to read
395 int const max_count = 50;
400 bool firstLine = true;
401 while ((count++ < max_count) && format.empty()) {
403 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
404 << "\tFile type not recognised before EOF!");
409 string const stamp = str.substr(0, 2);
410 if (firstLine && str.size() >= 2) {
411 // at first we check for a zipped file, because this
412 // information is saved in the first bytes of the file!
413 // also some graphic formats which save the information
414 // in the first line, too.
415 if (prefixIs(str, gzipStamp)) {
418 } else if (stamp == zipStamp) {
421 } else if (stamp == compressStamp) {
425 } else if (stamp == "BM") {
428 } else if (stamp == "\001\332") {
432 // Don't need to use str.at(0), str.at(1) because
433 // we already know that str.size() >= 2
434 } else if (str[0] == 'P') {
450 } else if ((stamp == "II") || (stamp == "MM")) {
453 } else if (prefixIs(str,"%TGIF")) {
456 } else if (prefixIs(str,"#FIG")) {
459 } else if (prefixIs(str,"GIF")) {
462 } else if (str.size() > 3) {
463 int const c = ((str[0] << 24) & (str[1] << 16) &
464 (str[2] << 8) & str[3]);
475 else if (contains(str,"EPSF"))
476 // dummy, if we have wrong file description like
477 // %!PS-Adobe-2.0EPSF"
480 else if (contains(str, "Grace"))
483 else if (contains(str, "JFIF"))
486 else if (contains(str, "%PDF"))
489 else if (contains(str, "PNG"))
492 else if (contains(str, "%!PS-Adobe")) {
495 if (contains(str,"EPSF"))
501 else if (contains(str, "_bits[]"))
504 else if (contains(str, "XPM") || contains(str, "static char *"))
507 else if (contains(str, "BITPIX"))
511 if (!format.empty()) {
512 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
516 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
517 << "\tCouldn't find a known format!");
522 bool FileName::isZippedFile() const
524 string const type = guessFormatFromContents();
525 return contains("gzip zip compress", type) && !type.empty();
529 bool operator==(FileName const & lhs, FileName const & rhs)
531 return lhs.absFilename() == rhs.absFilename();
535 bool operator!=(FileName const & lhs, FileName const & rhs)
537 return lhs.absFilename() != rhs.absFilename();
541 bool operator<(FileName const & lhs, FileName const & rhs)
543 return lhs.absFilename() < rhs.absFilename();
547 bool operator>(FileName const & lhs, FileName const & rhs)
549 return lhs.absFilename() > rhs.absFilename();
553 std::ostream & operator<<(std::ostream & os, FileName const & filename)
555 return os << filename.absFilename();
559 /////////////////////////////////////////////////////////////////////
563 /////////////////////////////////////////////////////////////////////
566 DocFileName::DocFileName()
567 : save_abs_path_(true)
571 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
572 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
576 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
577 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
581 void DocFileName::set(string const & name, string const & buffer_path)
583 save_abs_path_ = absolutePath(name);
584 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
585 zipped_valid_ = false;
589 void DocFileName::erase()
592 zipped_valid_ = false;
596 string const DocFileName::relFilename(string const & path) const
599 return to_utf8(makeRelPath(qstring_to_ucs4(d->fi.absoluteFilePath()), from_utf8(path)));
603 string const DocFileName::outputFilename(string const & path) const
605 return save_abs_path_ ? absFilename() : relFilename(path);
609 string const DocFileName::mangledFilename(std::string const & dir) const
611 // We need to make sure that every DocFileName instance for a given
612 // filename returns the same mangled name.
613 typedef map<string, string> MangledMap;
614 static MangledMap mangledNames;
615 MangledMap::const_iterator const it = mangledNames.find(absFilename());
616 if (it != mangledNames.end())
619 string const name = absFilename();
621 string mname = os::internal_path(name);
622 // Remove the extension.
623 mname = changeExtension(name, string());
624 // The mangled name must be a valid LaTeX name.
625 // The list of characters to keep is probably over-restrictive,
626 // but it is not really a problem.
627 // Apart from non-ASCII characters, at least the following characters
628 // are forbidden: '/', '.', ' ', and ':'.
629 // On windows it is not possible to create files with '<', '>' or '?'
631 static string const keep = "abcdefghijklmnopqrstuvwxyz"
632 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
634 string::size_type pos = 0;
635 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
637 // Add the extension back on
638 mname = changeExtension(mname, getExtension(name));
640 // Prepend a counter to the filename. This is necessary to make
641 // the mangled name unique.
642 static int counter = 0;
643 std::ostringstream s;
644 s << counter++ << mname;
647 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
648 // is longer than about 160 characters. MiKTeX's pdflatex
649 // is even pickier. A maximum length of 100 has been proven to work.
650 // If dir.size() > max length, all bets are off for YAP. We truncate
651 // the filename nevertheless, keeping a minimum of 10 chars.
653 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
655 // If the mangled file name is too long, hack it to fit.
656 // We know we're guaranteed to have a unique file name because
658 if (mname.size() > max_length) {
659 int const half = (int(max_length) / 2) - 2;
661 mname = mname.substr(0, half) + "___" +
662 mname.substr(mname.size() - half);
666 mangledNames[absFilename()] = mname;
671 bool DocFileName::isZipped() const
673 if (!zipped_valid_) {
674 zipped_ = isZippedFile();
675 zipped_valid_ = true;
681 string const DocFileName::unzippedFilename() const
683 return unzippedFileName(absFilename());
687 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
689 return lhs.absFilename() == rhs.absFilename()
690 && lhs.saveAbsPath() == rhs.saveAbsPath();
694 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
696 return !(lhs == rhs);
699 } // namespace support