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)
82 FileName::FileName(string const & abs_filename)
83 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
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, bool overwrite) const
135 QFile::remove(name.d->fi.absoluteFilePath());
136 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
138 lyxerr << "FileName::copyTo(): Could not copy file "
139 << *this << " to " << name << endl;
144 string FileName::toFilesystemEncoding() const
146 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
147 return string(encoded.begin(), encoded.end());
151 FileName FileName::fromFilesystemEncoding(string const & name)
153 QByteArray const encoded(name.c_str(), name.length());
154 return FileName(fromqstr(QFile::decodeName(encoded)));
158 bool FileName::exists() const
160 return d->fi.exists();
164 bool FileName::isSymLink() const
166 return d->fi.isSymLink();
170 bool FileName::isFileEmpty() const
172 return d->fi.size() == 0;
176 bool FileName::isDirectory() const
178 return d->fi.isDir();
182 bool FileName::isReadOnly() const
184 return d->fi.isReadable() && !d->fi.isWritable();
188 bool FileName::isReadableDirectory() const
190 return d->fi.isDir() && d->fi.isReadable();
194 std::string FileName::onlyFileName() const
196 return support::onlyFilename(absFilename());
200 FileName FileName::onlyPath() const
202 return FileName(support::onlyPath(absFilename()));
206 bool FileName::isReadableFile() const
208 return d->fi.isFile() && d->fi.isReadable();
212 bool FileName::isWritable() const
214 return d->fi.isWritable();
218 bool FileName::isDirWritable() const
220 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
222 FileName const tmpfl(tempName(*this, "lyxwritetest"));
232 FileName FileName::tempName(FileName const & dir, std::string const & mask)
234 return support::tempName(dir, mask);
238 std::time_t FileName::lastModified() const
240 return d->fi.lastModified().toTime_t();
244 bool FileName::removeFile() const
246 bool const success = QFile::remove(d->fi.absoluteFilePath());
248 lyxerr << "FileName::removeFile(): Could not delete file "
249 << *this << "." << endl;
254 static bool rmdir(QFileInfo const & fi)
256 QDir dir(fi.absoluteFilePath());
257 QFileInfoList list = dir.entryInfoList();
258 bool global_success = true;
259 for (int i = 0; i < list.size(); ++i) {
260 if (list.at(i).fileName() == ".")
262 if (list.at(i).fileName() == "..")
265 if (list.at(i).isDir()) {
266 LYXERR(Debug::FILES, "Erasing dir "
267 << fromqstr(list.at(i).absoluteFilePath()));
268 success = rmdir(list.at(i));
271 LYXERR(Debug::FILES, "Erasing file "
272 << fromqstr(list.at(i).absoluteFilePath()));
273 success = dir.remove(list.at(i).fileName());
276 global_success = false;
277 lyxerr << "Could not delete "
278 << fromqstr(list.at(i).absoluteFilePath()) << "." << endl;
281 QDir parent = fi.absolutePath();
282 global_success |= parent.rmdir(fi.fileName());
283 return global_success;
287 bool FileName::destroyDirectory() const
289 bool const success = rmdir(d->fi);
291 lyxerr << "Could not delete " << *this << "." << endl;
297 bool FileName::createDirectory(int permission) const
299 BOOST_ASSERT(!empty());
300 return mkdir(*this, permission) == 0;
304 std::vector<FileName> FileName::dirList(std::string const & ext)
306 std::vector<FileName> dirlist;
307 if (!exists() || !isDirectory()) {
308 lyxerr << "FileName::dirList(): Directory \"" << absFilename()
309 << "\" does not exist!" << endl;
313 QDir dir(d->fi.absoluteFilePath());
318 case '.': filter = "*" + toqstr(ext); break;
319 case '*': filter = toqstr(ext); break;
320 default: filter = "*." + toqstr(ext);
322 dir.setNameFilters(QStringList(filter));
323 LYXERR(Debug::FILES, "FileName::dirList(): filtering on extension "
324 << fromqstr(filter) << " is requested." << endl);
327 QFileInfoList list = dir.entryInfoList();
328 for (int i = 0; i < list.size(); ++i) {
330 fi.d->fi = list.at(i);
331 dirlist.push_back(fi);
332 LYXERR(Debug::FILES, "FileName::dirList(): found file "
333 << fi.absFilename() << endl);
340 docstring FileName::displayName(int threshold) const
342 return makeDisplayPath(absFilename(), threshold);
346 string FileName::fileContents() const
349 string const encodedname = toFilesystemEncoding();
350 ifstream ifs(encodedname.c_str());
358 lyxerr << "LyX was not able to read file '" << *this << '\'' << std::endl;
363 string FileName::guessFormatFromContents() const
365 // the different filetypes and what they contain in one of the first lines
366 // (dots are any characters). (Herbert 20020131)
369 // EPS %!PS-Adobe-3.0 EPSF...
376 // PBM P1... or P4 (B/W)
377 // PGM P2... or P5 (Grayscale)
378 // PPM P3... or P6 (color)
379 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
380 // SGI \001\332... (decimal 474)
382 // TIFF II... or MM...
384 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
385 // ...static char *...
386 // XWD \000\000\000\151 (0x00006900) decimal 105
388 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
389 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
390 // Z \037\235 UNIX compress
393 if (empty() || !isReadableFile())
396 ifstream ifs(toFilesystemEncoding().c_str());
398 // Couldn't open file...
402 static string const gzipStamp = "\037\213";
405 static string const zipStamp = "PK";
408 static string const compressStamp = "\037\235";
410 // Maximum strings to read
411 int const max_count = 50;
416 bool firstLine = true;
417 while ((count++ < max_count) && format.empty()) {
419 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
420 << "\tFile type not recognised before EOF!");
425 string const stamp = str.substr(0, 2);
426 if (firstLine && str.size() >= 2) {
427 // at first we check for a zipped file, because this
428 // information is saved in the first bytes of the file!
429 // also some graphic formats which save the information
430 // in the first line, too.
431 if (prefixIs(str, gzipStamp)) {
434 } else if (stamp == zipStamp) {
437 } else if (stamp == compressStamp) {
441 } else if (stamp == "BM") {
444 } else if (stamp == "\001\332") {
448 // Don't need to use str.at(0), str.at(1) because
449 // we already know that str.size() >= 2
450 } else if (str[0] == 'P') {
466 } else if ((stamp == "II") || (stamp == "MM")) {
469 } else if (prefixIs(str,"%TGIF")) {
472 } else if (prefixIs(str,"#FIG")) {
475 } else if (prefixIs(str,"GIF")) {
478 } else if (str.size() > 3) {
479 int const c = ((str[0] << 24) & (str[1] << 16) &
480 (str[2] << 8) & str[3]);
491 else if (contains(str,"EPSF"))
492 // dummy, if we have wrong file description like
493 // %!PS-Adobe-2.0EPSF"
496 else if (contains(str, "Grace"))
499 else if (contains(str, "JFIF"))
502 else if (contains(str, "%PDF"))
505 else if (contains(str, "PNG"))
508 else if (contains(str, "%!PS-Adobe")) {
511 if (contains(str,"EPSF"))
517 else if (contains(str, "_bits[]"))
520 else if (contains(str, "XPM") || contains(str, "static char *"))
523 else if (contains(str, "BITPIX"))
527 if (!format.empty()) {
528 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
532 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
533 << "\tCouldn't find a known format!");
538 bool FileName::isZippedFile() const
540 string const type = guessFormatFromContents();
541 return contains("gzip zip compress", type) && !type.empty();
545 bool operator==(FileName const & lhs, FileName const & rhs)
547 return lhs.absFilename() == rhs.absFilename();
551 bool operator!=(FileName const & lhs, FileName const & rhs)
553 return lhs.absFilename() != rhs.absFilename();
557 bool operator<(FileName const & lhs, FileName const & rhs)
559 return lhs.absFilename() < rhs.absFilename();
563 bool operator>(FileName const & lhs, FileName const & rhs)
565 return lhs.absFilename() > rhs.absFilename();
569 std::ostream & operator<<(std::ostream & os, FileName const & filename)
571 return os << filename.absFilename();
575 /////////////////////////////////////////////////////////////////////
579 /////////////////////////////////////////////////////////////////////
582 DocFileName::DocFileName()
583 : save_abs_path_(true)
587 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
588 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
592 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
593 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
597 void DocFileName::set(string const & name, string const & buffer_path)
599 save_abs_path_ = absolutePath(name);
600 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
601 zipped_valid_ = false;
605 void DocFileName::erase()
608 zipped_valid_ = false;
612 string const DocFileName::relFilename(string const & path) const
615 return to_utf8(makeRelPath(qstring_to_ucs4(d->fi.absoluteFilePath()), from_utf8(path)));
619 string const DocFileName::outputFilename(string const & path) const
621 return save_abs_path_ ? absFilename() : relFilename(path);
625 string const DocFileName::mangledFilename(std::string const & dir) const
627 // We need to make sure that every DocFileName instance for a given
628 // filename returns the same mangled name.
629 typedef map<string, string> MangledMap;
630 static MangledMap mangledNames;
631 MangledMap::const_iterator const it = mangledNames.find(absFilename());
632 if (it != mangledNames.end())
635 string const name = absFilename();
637 string mname = os::internal_path(name);
638 // Remove the extension.
639 mname = changeExtension(name, string());
640 // The mangled name must be a valid LaTeX name.
641 // The list of characters to keep is probably over-restrictive,
642 // but it is not really a problem.
643 // Apart from non-ASCII characters, at least the following characters
644 // are forbidden: '/', '.', ' ', and ':'.
645 // On windows it is not possible to create files with '<', '>' or '?'
647 static string const keep = "abcdefghijklmnopqrstuvwxyz"
648 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
650 string::size_type pos = 0;
651 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
653 // Add the extension back on
654 mname = changeExtension(mname, getExtension(name));
656 // Prepend a counter to the filename. This is necessary to make
657 // the mangled name unique.
658 static int counter = 0;
659 std::ostringstream s;
660 s << counter++ << mname;
663 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
664 // is longer than about 160 characters. MiKTeX's pdflatex
665 // is even pickier. A maximum length of 100 has been proven to work.
666 // If dir.size() > max length, all bets are off for YAP. We truncate
667 // the filename nevertheless, keeping a minimum of 10 chars.
669 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
671 // If the mangled file name is too long, hack it to fit.
672 // We know we're guaranteed to have a unique file name because
674 if (mname.size() > max_length) {
675 int const half = (int(max_length) / 2) - 2;
677 mname = mname.substr(0, half) + "___" +
678 mname.substr(mname.size() - half);
682 mangledNames[absFilename()] = mname;
687 bool DocFileName::isZipped() const
689 if (!zipped_valid_) {
690 zipped_ = isZippedFile();
691 zipped_valid_ = true;
697 string const DocFileName::unzippedFilename() const
699 return unzippedFileName(absFilename());
703 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
705 return lhs.absFilename() == rhs.absFilename()
706 && lhs.saveAbsPath() == rhs.saveAbsPath();
710 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
712 return !(lhs == rhs);
715 } // namespace support