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 bool FileName::chdir() const
241 return QDir::setCurrent(d->fi.absoluteFilePath());
245 extern unsigned long sum(char const * file);
247 unsigned long FileName::checksum() const
250 LYXERR0("File \"" << absFilename() << "\" does not exist!");
253 // a directory may be passed here so we need to test it. (bug 3622)
255 LYXERR0('\\' << absFilename() << "\" is a directory!");
258 return sum(absFilename().c_str());
262 bool FileName::removeFile() const
264 bool const success = QFile::remove(d->fi.absoluteFilePath());
265 if (!success && exists())
266 lyxerr << "FileName::removeFile(): Could not delete file "
267 << *this << "." << endl;
272 static bool rmdir(QFileInfo const & fi)
274 QDir dir(fi.absoluteFilePath());
275 QFileInfoList list = dir.entryInfoList();
276 bool global_success = true;
277 for (int i = 0; i != list.size(); ++i) {
278 if (list.at(i).fileName() == ".")
280 if (list.at(i).fileName() == "..")
283 if (list.at(i).isDir()) {
284 LYXERR(Debug::FILES, "Erasing dir "
285 << fromqstr(list.at(i).absoluteFilePath()));
286 success = rmdir(list.at(i));
289 LYXERR(Debug::FILES, "Erasing file "
290 << fromqstr(list.at(i).absoluteFilePath()));
291 success = dir.remove(list.at(i).fileName());
294 global_success = false;
295 lyxerr << "Could not delete "
296 << fromqstr(list.at(i).absoluteFilePath()) << "." << endl;
299 QDir parent = fi.absolutePath();
300 global_success |= parent.rmdir(fi.fileName());
301 return global_success;
305 bool FileName::destroyDirectory() const
307 bool const success = rmdir(d->fi);
309 lyxerr << "Could not delete " << *this << "." << endl;
315 bool FileName::createDirectory(int permission) const
317 BOOST_ASSERT(!empty());
318 return mkdir(*this, permission) == 0;
322 std::vector<FileName> dirList(FileName const & dirname, std::string const & ext)
324 std::vector<FileName> dirlist;
325 if (!dirname.isDirectory()) {
326 LYXERR0("Directory '" << dirname << "' does not exist!");
330 QDir dir(dirname.d->fi.absoluteFilePath());
335 case '.': filter = "*" + toqstr(ext); break;
336 case '*': filter = toqstr(ext); break;
337 default: filter = "*." + toqstr(ext);
339 dir.setNameFilters(QStringList(filter));
340 LYXERR(Debug::FILES, "filtering on extension "
341 << fromqstr(filter) << " is requested.");
344 QFileInfoList list = dir.entryInfoList();
345 for (int i = 0; i != list.size(); ++i) {
347 fi.d->fi = list.at(i);
348 dirlist.push_back(fi);
349 LYXERR(Debug::FILES, "found file " << fi);
356 docstring FileName::displayName(int threshold) const
358 return makeDisplayPath(absFilename(), threshold);
362 string FileName::fileContents() const
365 string const encodedname = toFilesystemEncoding();
366 ifstream ifs(encodedname.c_str());
374 lyxerr << "LyX was not able to read file '" << *this << '\'' << std::endl;
379 void FileName::changeExtension(std::string const & extension)
381 // FIXME: use Qt native methods...
382 string const oldname = absFilename();
383 string::size_type const last_slash = oldname.rfind('/');
384 string::size_type last_dot = oldname.rfind('.');
385 if (last_dot < last_slash && last_slash != string::npos)
386 last_dot = string::npos;
389 // Make sure the extension starts with a dot
390 if (!extension.empty() && extension[0] != '.')
391 ext= '.' + extension;
395 set(oldname.substr(0, last_dot) + ext);
399 string FileName::guessFormatFromContents() const
401 // the different filetypes and what they contain in one of the first lines
402 // (dots are any characters). (Herbert 20020131)
405 // EPS %!PS-Adobe-3.0 EPSF...
412 // PBM P1... or P4 (B/W)
413 // PGM P2... or P5 (Grayscale)
414 // PPM P3... or P6 (color)
415 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
416 // SGI \001\332... (decimal 474)
418 // TIFF II... or MM...
420 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
421 // ...static char *...
422 // XWD \000\000\000\151 (0x00006900) decimal 105
424 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
425 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
426 // Z \037\235 UNIX compress
429 if (empty() || !isReadableFile())
432 ifstream ifs(toFilesystemEncoding().c_str());
434 // Couldn't open file...
438 static string const gzipStamp = "\037\213";
441 static string const zipStamp = "PK";
444 static string const compressStamp = "\037\235";
446 // Maximum strings to read
447 int const max_count = 50;
452 bool firstLine = true;
453 while ((count++ < max_count) && format.empty()) {
455 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
456 << "\tFile type not recognised before EOF!");
461 string const stamp = str.substr(0, 2);
462 if (firstLine && str.size() >= 2) {
463 // at first we check for a zipped file, because this
464 // information is saved in the first bytes of the file!
465 // also some graphic formats which save the information
466 // in the first line, too.
467 if (prefixIs(str, gzipStamp)) {
470 } else if (stamp == zipStamp) {
473 } else if (stamp == compressStamp) {
477 } else if (stamp == "BM") {
480 } else if (stamp == "\001\332") {
484 // Don't need to use str.at(0), str.at(1) because
485 // we already know that str.size() >= 2
486 } else if (str[0] == 'P') {
502 } else if ((stamp == "II") || (stamp == "MM")) {
505 } else if (prefixIs(str,"%TGIF")) {
508 } else if (prefixIs(str,"#FIG")) {
511 } else if (prefixIs(str,"GIF")) {
514 } else if (str.size() > 3) {
515 int const c = ((str[0] << 24) & (str[1] << 16) &
516 (str[2] << 8) & str[3]);
527 else if (contains(str,"EPSF"))
528 // dummy, if we have wrong file description like
529 // %!PS-Adobe-2.0EPSF"
532 else if (contains(str, "Grace"))
535 else if (contains(str, "JFIF"))
538 else if (contains(str, "%PDF"))
541 else if (contains(str, "PNG"))
544 else if (contains(str, "%!PS-Adobe")) {
547 if (contains(str,"EPSF"))
553 else if (contains(str, "_bits[]"))
556 else if (contains(str, "XPM") || contains(str, "static char *"))
559 else if (contains(str, "BITPIX"))
563 if (!format.empty()) {
564 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
568 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
569 << "\tCouldn't find a known format!");
574 bool FileName::isZippedFile() const
576 string const type = guessFormatFromContents();
577 return contains("gzip zip compress", type) && !type.empty();
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 bool operator>(FileName const & lhs, FileName const & rhs)
601 return lhs.absFilename() > rhs.absFilename();
605 std::ostream & operator<<(std::ostream & os, FileName const & filename)
607 return os << filename.absFilename();
611 /////////////////////////////////////////////////////////////////////
615 /////////////////////////////////////////////////////////////////////
618 DocFileName::DocFileName()
619 : save_abs_path_(true)
623 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
624 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
628 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
629 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
633 void DocFileName::set(string const & name, string const & buffer_path)
635 save_abs_path_ = absolutePath(name);
636 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
637 zipped_valid_ = false;
641 void DocFileName::erase()
644 zipped_valid_ = false;
648 string DocFileName::relFilename(string const & path) const
651 return to_utf8(makeRelPath(qstring_to_ucs4(d->fi.absoluteFilePath()), from_utf8(path)));
655 string DocFileName::outputFilename(string const & path) const
657 return save_abs_path_ ? absFilename() : relFilename(path);
661 string DocFileName::mangledFilename(std::string const & dir) const
663 // We need to make sure that every DocFileName instance for a given
664 // filename returns the same mangled name.
665 typedef map<string, string> MangledMap;
666 static MangledMap mangledNames;
667 MangledMap::const_iterator const it = mangledNames.find(absFilename());
668 if (it != mangledNames.end())
671 string const name = absFilename();
673 string mname = os::internal_path(name);
674 // Remove the extension.
675 mname = support::changeExtension(name, string());
676 // The mangled name must be a valid LaTeX name.
677 // The list of characters to keep is probably over-restrictive,
678 // but it is not really a problem.
679 // Apart from non-ASCII characters, at least the following characters
680 // are forbidden: '/', '.', ' ', and ':'.
681 // On windows it is not possible to create files with '<', '>' or '?'
683 static string const keep = "abcdefghijklmnopqrstuvwxyz"
684 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
686 string::size_type pos = 0;
687 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
689 // Add the extension back on
690 mname = support::changeExtension(mname, getExtension(name));
692 // Prepend a counter to the filename. This is necessary to make
693 // the mangled name unique.
694 static int counter = 0;
695 std::ostringstream s;
696 s << counter++ << mname;
699 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
700 // is longer than about 160 characters. MiKTeX's pdflatex
701 // is even pickier. A maximum length of 100 has been proven to work.
702 // If dir.size() > max length, all bets are off for YAP. We truncate
703 // the filename nevertheless, keeping a minimum of 10 chars.
705 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
707 // If the mangled file name is too long, hack it to fit.
708 // We know we're guaranteed to have a unique file name because
710 if (mname.size() > max_length) {
711 int const half = (int(max_length) / 2) - 2;
713 mname = mname.substr(0, half) + "___" +
714 mname.substr(mname.size() - half);
718 mangledNames[absFilename()] = mname;
723 bool DocFileName::isZipped() const
725 if (!zipped_valid_) {
726 zipped_ = isZippedFile();
727 zipped_valid_ = true;
733 string DocFileName::unzippedFilename() const
735 return unzippedFileName(absFilename());
739 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
741 return lhs.absFilename() == rhs.absFilename()
742 && lhs.saveAbsPath() == rhs.saveAbsPath();
746 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
748 return !(lhs == rhs);
751 } // namespace support