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"
15 #include "support/debug.h"
16 #include "support/filetools.h"
17 #include "support/lstrings.h"
18 #include "support/lyxlib.h"
19 #include "support/os.h"
20 #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)
83 FileName::FileName(string const & abs_filename)
84 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
89 FileName::FileName(FileName const & rhs) : d(new Private)
95 FileName & FileName::operator=(FileName const & rhs)
102 bool FileName::empty() const
104 return d->fi.absoluteFilePath().isEmpty();
108 string FileName::absFilename() const
110 return fromqstr(d->fi.absoluteFilePath());
114 void FileName::set(string const & name)
116 d->fi.setFile(toqstr(name));
117 BOOST_ASSERT(d->fi.isAbsolute());
121 void FileName::erase()
127 bool FileName::copyTo(FileName const & name, bool overwrite) const
130 QFile::remove(name.d->fi.absoluteFilePath());
131 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
133 lyxerr << "FileName::copyTo(): Could not copy file "
134 << *this << " to " << name << endl;
139 string FileName::toFilesystemEncoding() const
141 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
142 return string(encoded.begin(), encoded.end());
146 FileName FileName::fromFilesystemEncoding(string const & name)
148 QByteArray const encoded(name.c_str(), name.length());
149 return FileName(fromqstr(QFile::decodeName(encoded)));
153 bool FileName::exists() const
155 return d->fi.exists();
159 bool FileName::isSymLink() const
161 return d->fi.isSymLink();
165 bool FileName::isFileEmpty() const
167 return d->fi.size() == 0;
171 bool FileName::isDirectory() const
173 return d->fi.isDir();
177 bool FileName::isReadOnly() const
179 return d->fi.isReadable() && !d->fi.isWritable();
183 bool FileName::isReadableDirectory() const
185 return d->fi.isDir() && d->fi.isReadable();
189 std::string FileName::onlyFileName() const
191 return support::onlyFilename(absFilename());
195 FileName FileName::onlyPath() const
197 return FileName(support::onlyPath(absFilename()));
201 bool FileName::isReadableFile() const
203 return d->fi.isFile() && d->fi.isReadable();
207 bool FileName::isWritable() const
209 return d->fi.isWritable();
213 bool FileName::isDirWritable() const
215 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
217 FileName const tmpfl(tempName(*this, "lyxwritetest"));
227 FileName FileName::tempName(FileName const & dir, std::string const & mask)
229 return support::tempName(dir, mask);
233 std::time_t FileName::lastModified() const
235 return d->fi.lastModified().toTime_t();
239 extern unsigned long sum(char const * file);
241 unsigned long FileName::checksum() const
244 LYXERR0("File \"" << absFilename() << "\" does not exist!");
247 // a directory may be passed here so we need to test it. (bug 3622)
249 LYXERR0('\\' << absFilename() << "\" is a directory!");
252 return sum(absFilename().c_str());
256 bool FileName::removeFile() const
258 bool const success = QFile::remove(d->fi.absoluteFilePath());
260 lyxerr << "FileName::removeFile(): Could not delete file "
261 << *this << "." << endl;
266 static bool rmdir(QFileInfo const & fi)
268 QDir dir(fi.absoluteFilePath());
269 QFileInfoList list = dir.entryInfoList();
270 bool global_success = true;
271 for (int i = 0; i != list.size(); ++i) {
272 if (list.at(i).fileName() == ".")
274 if (list.at(i).fileName() == "..")
277 if (list.at(i).isDir()) {
278 LYXERR(Debug::FILES, "Erasing dir "
279 << fromqstr(list.at(i).absoluteFilePath()));
280 success = rmdir(list.at(i));
283 LYXERR(Debug::FILES, "Erasing file "
284 << fromqstr(list.at(i).absoluteFilePath()));
285 success = dir.remove(list.at(i).fileName());
288 global_success = false;
289 lyxerr << "Could not delete "
290 << fromqstr(list.at(i).absoluteFilePath()) << "." << endl;
293 QDir parent = fi.absolutePath();
294 global_success |= parent.rmdir(fi.fileName());
295 return global_success;
299 bool FileName::destroyDirectory() const
301 bool const success = rmdir(d->fi);
303 lyxerr << "Could not delete " << *this << "." << endl;
309 bool FileName::createDirectory(int permission) const
311 BOOST_ASSERT(!empty());
312 return mkdir(*this, permission) == 0;
316 std::vector<FileName> dirList(FileName const & dirname, std::string const & ext)
318 std::vector<FileName> dirlist;
319 if (!dirname.isDirectory()) {
320 LYXERR0("Directory '" << dirname << "' does not exist!");
324 QDir dir(dirname.d->fi.absoluteFilePath());
329 case '.': filter = "*" + toqstr(ext); break;
330 case '*': filter = toqstr(ext); break;
331 default: filter = "*." + toqstr(ext);
333 dir.setNameFilters(QStringList(filter));
334 LYXERR(Debug::FILES, "filtering on extension "
335 << fromqstr(filter) << " is requested.");
338 QFileInfoList list = dir.entryInfoList();
339 for (int i = 0; i != list.size(); ++i) {
341 fi.d->fi = list.at(i);
342 dirlist.push_back(fi);
343 LYXERR(Debug::FILES, "found file " << fi);
350 docstring FileName::displayName(int threshold) const
352 return makeDisplayPath(absFilename(), threshold);
356 string FileName::fileContents() const
359 string const encodedname = toFilesystemEncoding();
360 ifstream ifs(encodedname.c_str());
368 lyxerr << "LyX was not able to read file '" << *this << '\'' << std::endl;
373 void FileName::changeExtension(std::string const & extension)
375 // FIXME: use Qt native methods...
376 string const oldname = absFilename();
377 string::size_type const last_slash = oldname.rfind('/');
378 string::size_type last_dot = oldname.rfind('.');
379 if (last_dot < last_slash && last_slash != string::npos)
380 last_dot = string::npos;
383 // Make sure the extension starts with a dot
384 if (!extension.empty() && extension[0] != '.')
385 ext= '.' + extension;
389 set(oldname.substr(0, last_dot) + ext);
393 string FileName::guessFormatFromContents() const
395 // the different filetypes and what they contain in one of the first lines
396 // (dots are any characters). (Herbert 20020131)
399 // EPS %!PS-Adobe-3.0 EPSF...
406 // PBM P1... or P4 (B/W)
407 // PGM P2... or P5 (Grayscale)
408 // PPM P3... or P6 (color)
409 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
410 // SGI \001\332... (decimal 474)
412 // TIFF II... or MM...
414 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
415 // ...static char *...
416 // XWD \000\000\000\151 (0x00006900) decimal 105
418 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
419 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
420 // Z \037\235 UNIX compress
423 if (empty() || !isReadableFile())
426 ifstream ifs(toFilesystemEncoding().c_str());
428 // Couldn't open file...
432 static string const gzipStamp = "\037\213";
435 static string const zipStamp = "PK";
438 static string const compressStamp = "\037\235";
440 // Maximum strings to read
441 int const max_count = 50;
446 bool firstLine = true;
447 while ((count++ < max_count) && format.empty()) {
449 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
450 << "\tFile type not recognised before EOF!");
455 string const stamp = str.substr(0, 2);
456 if (firstLine && str.size() >= 2) {
457 // at first we check for a zipped file, because this
458 // information is saved in the first bytes of the file!
459 // also some graphic formats which save the information
460 // in the first line, too.
461 if (prefixIs(str, gzipStamp)) {
464 } else if (stamp == zipStamp) {
467 } else if (stamp == compressStamp) {
471 } else if (stamp == "BM") {
474 } else if (stamp == "\001\332") {
478 // Don't need to use str.at(0), str.at(1) because
479 // we already know that str.size() >= 2
480 } else if (str[0] == 'P') {
496 } else if ((stamp == "II") || (stamp == "MM")) {
499 } else if (prefixIs(str,"%TGIF")) {
502 } else if (prefixIs(str,"#FIG")) {
505 } else if (prefixIs(str,"GIF")) {
508 } else if (str.size() > 3) {
509 int const c = ((str[0] << 24) & (str[1] << 16) &
510 (str[2] << 8) & str[3]);
521 else if (contains(str,"EPSF"))
522 // dummy, if we have wrong file description like
523 // %!PS-Adobe-2.0EPSF"
526 else if (contains(str, "Grace"))
529 else if (contains(str, "JFIF"))
532 else if (contains(str, "%PDF"))
535 else if (contains(str, "PNG"))
538 else if (contains(str, "%!PS-Adobe")) {
541 if (contains(str,"EPSF"))
547 else if (contains(str, "_bits[]"))
550 else if (contains(str, "XPM") || contains(str, "static char *"))
553 else if (contains(str, "BITPIX"))
557 if (!format.empty()) {
558 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
562 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
563 << "\tCouldn't find a known format!");
568 bool FileName::isZippedFile() const
570 string const type = guessFormatFromContents();
571 return contains("gzip zip compress", type) && !type.empty();
575 bool operator==(FileName const & lhs, FileName const & rhs)
577 return lhs.absFilename() == rhs.absFilename();
581 bool operator!=(FileName const & lhs, FileName const & rhs)
583 return lhs.absFilename() != rhs.absFilename();
587 bool operator<(FileName const & lhs, FileName const & rhs)
589 return lhs.absFilename() < rhs.absFilename();
593 bool operator>(FileName const & lhs, FileName const & rhs)
595 return lhs.absFilename() > rhs.absFilename();
599 std::ostream & operator<<(std::ostream & os, FileName const & filename)
601 return os << filename.absFilename();
605 /////////////////////////////////////////////////////////////////////
609 /////////////////////////////////////////////////////////////////////
612 DocFileName::DocFileName()
613 : save_abs_path_(true)
617 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
618 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
622 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
623 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
627 void DocFileName::set(string const & name, string const & buffer_path)
629 save_abs_path_ = absolutePath(name);
630 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
631 zipped_valid_ = false;
635 void DocFileName::erase()
638 zipped_valid_ = false;
642 string DocFileName::relFilename(string const & path) const
645 return to_utf8(makeRelPath(qstring_to_ucs4(d->fi.absoluteFilePath()), from_utf8(path)));
649 string DocFileName::outputFilename(string const & path) const
651 return save_abs_path_ ? absFilename() : relFilename(path);
655 string DocFileName::mangledFilename(std::string const & dir) const
657 // We need to make sure that every DocFileName instance for a given
658 // filename returns the same mangled name.
659 typedef map<string, string> MangledMap;
660 static MangledMap mangledNames;
661 MangledMap::const_iterator const it = mangledNames.find(absFilename());
662 if (it != mangledNames.end())
665 string const name = absFilename();
667 string mname = os::internal_path(name);
668 // Remove the extension.
669 mname = support::changeExtension(name, string());
670 // The mangled name must be a valid LaTeX name.
671 // The list of characters to keep is probably over-restrictive,
672 // but it is not really a problem.
673 // Apart from non-ASCII characters, at least the following characters
674 // are forbidden: '/', '.', ' ', and ':'.
675 // On windows it is not possible to create files with '<', '>' or '?'
677 static string const keep = "abcdefghijklmnopqrstuvwxyz"
678 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
680 string::size_type pos = 0;
681 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
683 // Add the extension back on
684 mname = support::changeExtension(mname, getExtension(name));
686 // Prepend a counter to the filename. This is necessary to make
687 // the mangled name unique.
688 static int counter = 0;
689 std::ostringstream s;
690 s << counter++ << mname;
693 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
694 // is longer than about 160 characters. MiKTeX's pdflatex
695 // is even pickier. A maximum length of 100 has been proven to work.
696 // If dir.size() > max length, all bets are off for YAP. We truncate
697 // the filename nevertheless, keeping a minimum of 10 chars.
699 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
701 // If the mangled file name is too long, hack it to fit.
702 // We know we're guaranteed to have a unique file name because
704 if (mname.size() > max_length) {
705 int const half = (int(max_length) / 2) - 2;
707 mname = mname.substr(0, half) + "___" +
708 mname.substr(mname.size() - half);
712 mangledNames[absFilename()] = mname;
717 bool DocFileName::isZipped() const
719 if (!zipped_valid_) {
720 zipped_ = isZippedFile();
721 zipped_valid_ = true;
727 string DocFileName::unzippedFilename() const
729 return unzippedFileName(absFilename());
733 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
735 return lhs.absFilename() == rhs.absFilename()
736 && lhs.saveAbsPath() == rhs.saveAbsPath();
740 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
742 return !(lhs == rhs);
745 } // namespace support