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/FileNameList.h"
16 #include "support/debug.h"
17 #include "support/filetools.h"
18 #include "support/lstrings.h"
19 #include "support/lyxlib.h"
20 #include "support/os.h"
21 #include "support/qstring_helpers.h"
30 #include <boost/assert.hpp>
37 #ifdef HAVE_SYS_TYPES_H
38 # include <sys/types.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
52 /////////////////////////////////////////////////////////////////////
56 /////////////////////////////////////////////////////////////////////
58 struct FileName::Private
62 Private(string const & abs_filename) : fi(toqstr(abs_filename))
64 fi.setCaching(fi.exists() ? true : false);
70 /////////////////////////////////////////////////////////////////////
74 /////////////////////////////////////////////////////////////////////
77 FileName::FileName() : d(new Private)
82 FileName::FileName(string const & abs_filename)
83 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
94 FileName::FileName(FileName const & rhs) : d(new Private)
100 FileName & FileName::operator=(FileName const & rhs)
107 bool FileName::empty() const
109 return d->fi.absoluteFilePath().isEmpty();
113 string FileName::absFilename() const
115 return fromqstr(d->fi.absoluteFilePath());
119 void FileName::set(string const & name)
121 d->fi.setFile(toqstr(name));
122 BOOST_ASSERT(d->fi.isAbsolute());
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 bool FileName::renameTo(FileName const & name) const
146 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
148 LYXERR0("Could not rename file " << *this << " to " << name);
153 bool FileName::changePermission(unsigned long int mode) const
155 if (!fname.isWritable()) {
156 LYXERR0("File " << *this << " is not writable!");
160 if (!chmod(fname, mode)) {
161 LYXERR0("File " << *this << " cannot be changed to " << mode << " mode!");
168 string FileName::toFilesystemEncoding() const
170 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
171 return string(encoded.begin(), encoded.end());
175 FileName FileName::fromFilesystemEncoding(string const & name)
177 QByteArray const encoded(name.c_str(), name.length());
178 return FileName(fromqstr(QFile::decodeName(encoded)));
182 bool FileName::exists() const
184 return d->fi.exists();
188 bool FileName::isSymLink() const
190 return d->fi.isSymLink();
194 bool FileName::isFileEmpty() const
196 return d->fi.size() == 0;
200 bool FileName::isDirectory() const
202 return d->fi.isDir();
206 bool FileName::isReadOnly() const
208 return d->fi.isReadable() && !d->fi.isWritable();
212 bool FileName::isReadableDirectory() const
214 return d->fi.isDir() && d->fi.isReadable();
218 string FileName::onlyFileName() const
220 return support::onlyFilename(absFilename());
224 FileName FileName::onlyPath() const
226 return FileName(support::onlyPath(absFilename()));
230 bool FileName::isReadableFile() const
232 return d->fi.isFile() && d->fi.isReadable();
236 bool FileName::isWritable() const
238 return d->fi.isWritable();
242 bool FileName::isDirWritable() const
244 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
246 FileName const tmpfl(tempName(*this, "lyxwritetest"));
256 FileNameList FileName::dirList(string const & ext) const
258 FileNameList dirlist;
259 if (!isDirectory()) {
260 LYXERR0("Directory '" << *this << "' does not exist!");
264 QDir dir = d->fi.absoluteDir();
269 case '.': filter = "*" + toqstr(ext); break;
270 case '*': filter = toqstr(ext); break;
271 default: filter = "*." + toqstr(ext);
273 dir.setNameFilters(QStringList(filter));
274 LYXERR(Debug::FILES, "filtering on extension "
275 << fromqstr(filter) << " is requested.");
278 QFileInfoList list = dir.entryInfoList();
279 for (int i = 0; i != list.size(); ++i) {
280 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
281 dirlist.push_back(fi);
282 LYXERR(Debug::FILES, "found file " << fi);
289 FileName FileName::tempName(FileName const & dir, string const & mask)
291 return support::tempName(dir, mask);
295 time_t FileName::lastModified() const
297 return d->fi.lastModified().toTime_t();
301 bool FileName::chdir() const
303 return QDir::setCurrent(d->fi.absoluteFilePath());
307 extern unsigned long sum(char const * file);
309 unsigned long FileName::checksum() const
312 LYXERR0("File \"" << absFilename() << "\" does not exist!");
315 // a directory may be passed here so we need to test it. (bug 3622)
317 LYXERR0('"' << absFilename() << "\" is a directory!");
320 if (!lyxerr.debugging(Debug::FILES))
321 return sum(absFilename().c_str());
325 unsigned long r = sum(absFilename().c_str());
326 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
327 << t.elapsed() << " ms." << endl;
332 bool FileName::removeFile() const
334 bool const success = QFile::remove(d->fi.absoluteFilePath());
335 if (!success && exists())
336 LYXERR0("Could not delete file " << *this);
341 static bool rmdir(QFileInfo const & fi)
343 QDir dir(fi.absoluteFilePath());
344 QFileInfoList list = dir.entryInfoList();
346 for (int i = 0; i != list.size(); ++i) {
347 if (list.at(i).fileName() == ".")
349 if (list.at(i).fileName() == "..")
352 if (list.at(i).isDir()) {
353 LYXERR(Debug::FILES, "Removing dir "
354 << fromqstr(list.at(i).absoluteFilePath()));
355 removed = rmdir(list.at(i));
358 LYXERR(Debug::FILES, "Removing file "
359 << fromqstr(list.at(i).absoluteFilePath()));
360 removed = dir.remove(list.at(i).fileName());
364 LYXERR0("Could not delete "
365 << fromqstr(list.at(i).absoluteFilePath()));
368 QDir parent = fi.absolutePath();
369 success &= parent.rmdir(fi.fileName());
374 bool FileName::destroyDirectory() const
376 bool const success = rmdir(d->fi);
378 LYXERR0("Could not delete " << *this);
384 bool FileName::createDirectory(int permission) const
386 BOOST_ASSERT(!empty());
387 return mkdir(*this, permission) == 0;
391 docstring const FileName::absoluteFilePath() const
393 return qstring_to_ucs4(d->fi.absoluteFilePath());
397 docstring FileName::displayName(int threshold) const
399 return makeDisplayPath(absFilename(), threshold);
403 docstring FileName::fileContents(string const & encoding) const
405 if (!isReadableFile()) {
406 LYXERR0("File '" << *this << "' is not redable!");
410 QFile file(d->fi.absoluteFilePath());
411 if (!file.open(QIODevice::ReadOnly)) {
412 LYXERR0("File '" << *this
413 << "' could not be opened in read only mode!");
416 QByteArray contents = file.readAll();
419 if (contents.isEmpty()) {
420 LYXERR(Debug::FILES, "File '" << *this
421 << "' is either empty or some error happened while reading it.");
426 if (encoding.empty() || encoding == "UTF-8")
427 s = QString::fromUtf8(contents.data());
428 else if (encoding == "ascii")
429 s = QString::fromAscii(contents.data());
430 else if (encoding == "local8bit")
431 s = QString::fromLocal8Bit(contents.data());
432 else if (encoding == "latin1")
433 s = QString::fromLatin1(contents.data());
435 return qstring_to_ucs4(s);
439 void FileName::changeExtension(string const & extension)
441 // FIXME: use Qt native methods...
442 string const oldname = absFilename();
443 string::size_type const last_slash = oldname.rfind('/');
444 string::size_type last_dot = oldname.rfind('.');
445 if (last_dot < last_slash && last_slash != string::npos)
446 last_dot = string::npos;
449 // Make sure the extension starts with a dot
450 if (!extension.empty() && extension[0] != '.')
451 ext= '.' + extension;
455 set(oldname.substr(0, last_dot) + ext);
459 string FileName::guessFormatFromContents() const
461 // the different filetypes and what they contain in one of the first lines
462 // (dots are any characters). (Herbert 20020131)
465 // EPS %!PS-Adobe-3.0 EPSF...
472 // PBM P1... or P4 (B/W)
473 // PGM P2... or P5 (Grayscale)
474 // PPM P3... or P6 (color)
475 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
476 // SGI \001\332... (decimal 474)
478 // TIFF II... or MM...
480 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
481 // ...static char *...
482 // XWD \000\000\000\151 (0x00006900) decimal 105
484 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
485 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
486 // Z \037\235 UNIX compress
489 if (empty() || !isReadableFile())
492 ifstream ifs(toFilesystemEncoding().c_str());
494 // Couldn't open file...
498 static string const gzipStamp = "\037\213";
501 static string const zipStamp = "PK";
504 static string const compressStamp = "\037\235";
506 // Maximum strings to read
507 int const max_count = 50;
512 bool firstLine = true;
513 while ((count++ < max_count) && format.empty()) {
515 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
516 << "\tFile type not recognised before EOF!");
521 string const stamp = str.substr(0, 2);
522 if (firstLine && str.size() >= 2) {
523 // at first we check for a zipped file, because this
524 // information is saved in the first bytes of the file!
525 // also some graphic formats which save the information
526 // in the first line, too.
527 if (prefixIs(str, gzipStamp)) {
530 } else if (stamp == zipStamp) {
533 } else if (stamp == compressStamp) {
537 } else if (stamp == "BM") {
540 } else if (stamp == "\001\332") {
544 // Don't need to use str.at(0), str.at(1) because
545 // we already know that str.size() >= 2
546 } else if (str[0] == 'P') {
562 } else if ((stamp == "II") || (stamp == "MM")) {
565 } else if (prefixIs(str,"%TGIF")) {
568 } else if (prefixIs(str,"#FIG")) {
571 } else if (prefixIs(str,"GIF")) {
574 } else if (str.size() > 3) {
575 int const c = ((str[0] << 24) & (str[1] << 16) &
576 (str[2] << 8) & str[3]);
587 else if (contains(str,"EPSF"))
588 // dummy, if we have wrong file description like
589 // %!PS-Adobe-2.0EPSF"
592 else if (contains(str, "Grace"))
595 else if (contains(str, "JFIF"))
598 else if (contains(str, "%PDF"))
601 else if (contains(str, "PNG"))
604 else if (contains(str, "%!PS-Adobe")) {
607 if (contains(str,"EPSF"))
613 else if (contains(str, "_bits[]"))
616 else if (contains(str, "XPM") || contains(str, "static char *"))
619 else if (contains(str, "BITPIX"))
623 if (!format.empty()) {
624 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
628 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
629 << "\tCouldn't find a known format!");
634 bool FileName::isZippedFile() const
636 string const type = guessFormatFromContents();
637 return contains("gzip zip compress", type) && !type.empty();
641 docstring const FileName::relPath(string const & path) const
644 return makeRelPath(absoluteFilePath(), from_utf8(path));
648 bool operator==(FileName const & lhs, FileName const & rhs)
650 return lhs.absFilename() == rhs.absFilename();
654 bool operator!=(FileName const & lhs, FileName const & rhs)
656 return lhs.absFilename() != rhs.absFilename();
660 bool operator<(FileName const & lhs, FileName const & rhs)
662 return lhs.absFilename() < rhs.absFilename();
666 bool operator>(FileName const & lhs, FileName const & rhs)
668 return lhs.absFilename() > rhs.absFilename();
672 ostream & operator<<(ostream & os, FileName const & filename)
674 return os << filename.absFilename();
678 /////////////////////////////////////////////////////////////////////
682 /////////////////////////////////////////////////////////////////////
685 DocFileName::DocFileName()
686 : save_abs_path_(true)
690 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
691 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
695 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
696 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
700 void DocFileName::set(string const & name, string const & buffer_path)
702 save_abs_path_ = absolutePath(name);
703 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
704 zipped_valid_ = false;
708 void DocFileName::erase()
711 zipped_valid_ = false;
715 string DocFileName::relFilename(string const & path) const
718 return to_utf8(relPath(path));
722 string DocFileName::outputFilename(string const & path) const
724 return save_abs_path_ ? absFilename() : relFilename(path);
728 string DocFileName::mangledFilename(string const & dir) const
730 // We need to make sure that every DocFileName instance for a given
731 // filename returns the same mangled name.
732 typedef map<string, string> MangledMap;
733 static MangledMap mangledNames;
734 MangledMap::const_iterator const it = mangledNames.find(absFilename());
735 if (it != mangledNames.end())
738 string const name = absFilename();
740 string mname = os::internal_path(name);
741 // Remove the extension.
742 mname = support::changeExtension(name, string());
743 // The mangled name must be a valid LaTeX name.
744 // The list of characters to keep is probably over-restrictive,
745 // but it is not really a problem.
746 // Apart from non-ASCII characters, at least the following characters
747 // are forbidden: '/', '.', ' ', and ':'.
748 // On windows it is not possible to create files with '<', '>' or '?'
750 static string const keep = "abcdefghijklmnopqrstuvwxyz"
751 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
753 string::size_type pos = 0;
754 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
756 // Add the extension back on
757 mname = support::changeExtension(mname, getExtension(name));
759 // Prepend a counter to the filename. This is necessary to make
760 // the mangled name unique.
761 static int counter = 0;
763 s << counter++ << mname;
766 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
767 // is longer than about 160 characters. MiKTeX's pdflatex
768 // is even pickier. A maximum length of 100 has been proven to work.
769 // If dir.size() > max length, all bets are off for YAP. We truncate
770 // the filename nevertheless, keeping a minimum of 10 chars.
772 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
774 // If the mangled file name is too long, hack it to fit.
775 // We know we're guaranteed to have a unique file name because
777 if (mname.size() > max_length) {
778 int const half = (int(max_length) / 2) - 2;
780 mname = mname.substr(0, half) + "___" +
781 mname.substr(mname.size() - half);
785 mangledNames[absFilename()] = mname;
790 bool DocFileName::isZipped() const
792 if (!zipped_valid_) {
793 zipped_ = isZippedFile();
794 zipped_valid_ = true;
800 string DocFileName::unzippedFilename() const
802 return unzippedFileName(absFilename());
806 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
808 return lhs.absFilename() == rhs.absFilename()
809 && lhs.saveAbsPath() == rhs.saveAbsPath();
813 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
815 return !(lhs == rhs);
818 } // namespace support