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>
62 /////////////////////////////////////////////////////////////////////
66 /////////////////////////////////////////////////////////////////////
68 struct FileName::Private
72 Private(string const & abs_filename) : fi(toqstr(abs_filename))
74 fi.setCaching(fi.exists() ? true : false);
80 /////////////////////////////////////////////////////////////////////
84 /////////////////////////////////////////////////////////////////////
87 FileName::FileName() : d(new Private)
92 FileName::FileName(string const & abs_filename)
93 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
104 FileName::FileName(FileName const & rhs) : d(new Private)
110 FileName & FileName::operator=(FileName const & rhs)
117 bool FileName::empty() const
119 return d->fi.absoluteFilePath().isEmpty();
123 string FileName::absFilename() const
125 return fromqstr(d->fi.absoluteFilePath());
129 void FileName::set(string const & name)
131 d->fi.setFile(toqstr(name));
132 BOOST_ASSERT(d->fi.isAbsolute());
136 void FileName::erase()
142 bool FileName::copyTo(FileName const & name) const
144 QFile::remove(name.d->fi.absoluteFilePath());
145 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
147 lyxerr << "FileName::copyTo(): Could not copy file "
148 << *this << " to " << name << endl;
153 bool FileName::renameTo(FileName const & name) const
155 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
157 LYXERR0("Could not rename file " << *this << " to " << name);
162 bool FileName::moveTo(FileName const & name) const
164 QFile::remove(name.d->fi.absoluteFilePath());
166 bool success = QFile::rename(d->fi.absoluteFilePath(),
167 name.d->fi.absoluteFilePath());
169 LYXERR0("Could not move file " << *this << " to " << name);
174 bool FileName::changePermission(unsigned long int mode) const
177 LYXERR0("File " << *this << " is not writable!");
181 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
182 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
183 LYXERR0("File " << *this << ": cannot change permission to "
192 string FileName::toFilesystemEncoding() const
194 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
195 return string(encoded.begin(), encoded.end());
199 FileName FileName::fromFilesystemEncoding(string const & name)
201 QByteArray const encoded(name.c_str(), name.length());
202 return FileName(fromqstr(QFile::decodeName(encoded)));
206 bool FileName::exists() const
208 return d->fi.exists();
212 bool FileName::isSymLink() const
214 return d->fi.isSymLink();
218 bool FileName::isFileEmpty() const
220 return d->fi.size() == 0;
224 bool FileName::isDirectory() const
226 return d->fi.isDir();
230 bool FileName::isReadOnly() const
232 return d->fi.isReadable() && !d->fi.isWritable();
236 bool FileName::isReadableDirectory() const
238 return d->fi.isDir() && d->fi.isReadable();
242 string FileName::onlyFileName() const
244 return support::onlyFilename(absFilename());
248 FileName FileName::onlyPath() const
250 return FileName(support::onlyPath(absFilename()));
254 bool FileName::isReadableFile() const
256 return d->fi.isFile() && d->fi.isReadable();
260 bool FileName::isWritable() const
262 return d->fi.isWritable();
266 bool FileName::isDirWritable() const
268 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
270 FileName const tmpfl(tempName(*this, "lyxwritetest"));
280 FileNameList FileName::dirList(string const & ext) const
282 FileNameList dirlist;
283 if (!isDirectory()) {
284 LYXERR0("Directory '" << *this << "' does not exist!");
288 QDir dir = d->fi.absoluteDir();
293 case '.': filter = "*" + toqstr(ext); break;
294 case '*': filter = toqstr(ext); break;
295 default: filter = "*." + toqstr(ext);
297 dir.setNameFilters(QStringList(filter));
298 LYXERR(Debug::FILES, "filtering on extension "
299 << fromqstr(filter) << " is requested.");
302 QFileInfoList list = dir.entryInfoList();
303 for (int i = 0; i != list.size(); ++i) {
304 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
305 dirlist.push_back(fi);
306 LYXERR(Debug::FILES, "found file " << fi);
313 FileName FileName::tempName(FileName const & dir, string const & mask)
315 return support::tempName(dir, mask);
319 time_t FileName::lastModified() const
321 return d->fi.lastModified().toTime_t();
325 bool FileName::chdir() const
327 return QDir::setCurrent(d->fi.absoluteFilePath());
331 extern unsigned long sum(char const * file);
333 unsigned long FileName::checksum() const
336 LYXERR0("File \"" << absFilename() << "\" does not exist!");
339 // a directory may be passed here so we need to test it. (bug 3622)
341 LYXERR0('"' << absFilename() << "\" is a directory!");
344 if (!lyxerr.debugging(Debug::FILES))
345 return sum(absFilename().c_str());
349 unsigned long r = sum(absFilename().c_str());
350 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
351 << t.elapsed() << " ms." << endl;
356 bool FileName::removeFile() const
358 bool const success = QFile::remove(d->fi.absoluteFilePath());
359 if (!success && exists())
360 LYXERR0("Could not delete file " << *this);
365 static bool rmdir(QFileInfo const & fi)
367 QDir dir(fi.absoluteFilePath());
368 QFileInfoList list = dir.entryInfoList();
370 for (int i = 0; i != list.size(); ++i) {
371 if (list.at(i).fileName() == ".")
373 if (list.at(i).fileName() == "..")
376 if (list.at(i).isDir()) {
377 LYXERR(Debug::FILES, "Removing dir "
378 << fromqstr(list.at(i).absoluteFilePath()));
379 removed = rmdir(list.at(i));
382 LYXERR(Debug::FILES, "Removing file "
383 << fromqstr(list.at(i).absoluteFilePath()));
384 removed = dir.remove(list.at(i).fileName());
388 LYXERR0("Could not delete "
389 << fromqstr(list.at(i).absoluteFilePath()));
392 QDir parent = fi.absolutePath();
393 success &= parent.rmdir(fi.fileName());
398 bool FileName::destroyDirectory() const
400 bool const success = rmdir(d->fi);
402 LYXERR0("Could not delete " << *this);
408 static int mymkdir(char const * pathname, unsigned long int mode)
410 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
412 # if MKDIR_TAKES_ONE_ARG
414 return ::mkdir(pathname);
415 // FIXME: "Permissions of created directories are ignored on this system."
418 return ::mkdir(pathname, mode_t(mode));
420 #elif defined(_WIN32)
422 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
423 // FIXME: "Permissions of created directories are ignored on this system."
425 return ::_mkdir(pathname);
426 // FIXME: "Permissions of created directories are ignored on this system."
428 # error "Don't know how to create a directory on this system."
434 bool FileName::createDirectory(int permission) const
436 BOOST_ASSERT(!empty());
437 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
441 bool FileName::createPath() const
443 BOOST_ASSERT(!empty());
448 bool success = dir.mkpath(d->fi.absoluteFilePath());
450 LYXERR0("Cannot create path '" << *this << "'!");
455 docstring const FileName::absoluteFilePath() const
457 return qstring_to_ucs4(d->fi.absoluteFilePath());
461 docstring FileName::displayName(int threshold) const
463 return makeDisplayPath(absFilename(), threshold);
467 docstring FileName::fileContents(string const & encoding) const
469 if (!isReadableFile()) {
470 LYXERR0("File '" << *this << "' is not redable!");
474 QFile file(d->fi.absoluteFilePath());
475 if (!file.open(QIODevice::ReadOnly)) {
476 LYXERR0("File '" << *this
477 << "' could not be opened in read only mode!");
480 QByteArray contents = file.readAll();
483 if (contents.isEmpty()) {
484 LYXERR(Debug::FILES, "File '" << *this
485 << "' is either empty or some error happened while reading it.");
490 if (encoding.empty() || encoding == "UTF-8")
491 s = QString::fromUtf8(contents.data());
492 else if (encoding == "ascii")
493 s = QString::fromAscii(contents.data());
494 else if (encoding == "local8bit")
495 s = QString::fromLocal8Bit(contents.data());
496 else if (encoding == "latin1")
497 s = QString::fromLatin1(contents.data());
499 return qstring_to_ucs4(s);
503 void FileName::changeExtension(string const & extension)
505 // FIXME: use Qt native methods...
506 string const oldname = absFilename();
507 string::size_type const last_slash = oldname.rfind('/');
508 string::size_type last_dot = oldname.rfind('.');
509 if (last_dot < last_slash && last_slash != string::npos)
510 last_dot = string::npos;
513 // Make sure the extension starts with a dot
514 if (!extension.empty() && extension[0] != '.')
515 ext= '.' + extension;
519 set(oldname.substr(0, last_dot) + ext);
523 string FileName::guessFormatFromContents() const
525 // the different filetypes and what they contain in one of the first lines
526 // (dots are any characters). (Herbert 20020131)
529 // EPS %!PS-Adobe-3.0 EPSF...
536 // PBM P1... or P4 (B/W)
537 // PGM P2... or P5 (Grayscale)
538 // PPM P3... or P6 (color)
539 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
540 // SGI \001\332... (decimal 474)
542 // TIFF II... or MM...
544 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
545 // ...static char *...
546 // XWD \000\000\000\151 (0x00006900) decimal 105
548 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
549 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
550 // Z \037\235 UNIX compress
553 if (empty() || !isReadableFile())
556 ifstream ifs(toFilesystemEncoding().c_str());
558 // Couldn't open file...
562 static string const gzipStamp = "\037\213";
565 static string const zipStamp = "PK";
568 static string const compressStamp = "\037\235";
570 // Maximum strings to read
571 int const max_count = 50;
576 bool firstLine = true;
577 while ((count++ < max_count) && format.empty()) {
579 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
580 << "\tFile type not recognised before EOF!");
585 string const stamp = str.substr(0, 2);
586 if (firstLine && str.size() >= 2) {
587 // at first we check for a zipped file, because this
588 // information is saved in the first bytes of the file!
589 // also some graphic formats which save the information
590 // in the first line, too.
591 if (prefixIs(str, gzipStamp)) {
594 } else if (stamp == zipStamp) {
597 } else if (stamp == compressStamp) {
601 } else if (stamp == "BM") {
604 } else if (stamp == "\001\332") {
608 // Don't need to use str.at(0), str.at(1) because
609 // we already know that str.size() >= 2
610 } else if (str[0] == 'P') {
626 } else if ((stamp == "II") || (stamp == "MM")) {
629 } else if (prefixIs(str,"%TGIF")) {
632 } else if (prefixIs(str,"#FIG")) {
635 } else if (prefixIs(str,"GIF")) {
638 } else if (str.size() > 3) {
639 int const c = ((str[0] << 24) & (str[1] << 16) &
640 (str[2] << 8) & str[3]);
651 else if (contains(str,"EPSF"))
652 // dummy, if we have wrong file description like
653 // %!PS-Adobe-2.0EPSF"
656 else if (contains(str, "Grace"))
659 else if (contains(str, "JFIF"))
662 else if (contains(str, "%PDF"))
665 else if (contains(str, "PNG"))
668 else if (contains(str, "%!PS-Adobe")) {
671 if (contains(str,"EPSF"))
677 else if (contains(str, "_bits[]"))
680 else if (contains(str, "XPM") || contains(str, "static char *"))
683 else if (contains(str, "BITPIX"))
687 if (!format.empty()) {
688 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
692 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
693 << "\tCouldn't find a known format!");
698 bool FileName::isZippedFile() const
700 string const type = guessFormatFromContents();
701 return contains("gzip zip compress", type) && !type.empty();
705 docstring const FileName::relPath(string const & path) const
708 return makeRelPath(absoluteFilePath(), from_utf8(path));
712 bool operator==(FileName const & lhs, FileName const & rhs)
714 return lhs.absFilename() == rhs.absFilename();
718 bool operator!=(FileName const & lhs, FileName const & rhs)
720 return lhs.absFilename() != rhs.absFilename();
724 bool operator<(FileName const & lhs, FileName const & rhs)
726 return lhs.absFilename() < rhs.absFilename();
730 bool operator>(FileName const & lhs, FileName const & rhs)
732 return lhs.absFilename() > rhs.absFilename();
736 ostream & operator<<(ostream & os, FileName const & filename)
738 return os << filename.absFilename();
742 /////////////////////////////////////////////////////////////////////
746 /////////////////////////////////////////////////////////////////////
749 DocFileName::DocFileName()
750 : save_abs_path_(true)
754 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
755 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
759 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
760 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
764 void DocFileName::set(string const & name, string const & buffer_path)
766 save_abs_path_ = absolutePath(name);
767 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
768 zipped_valid_ = false;
772 void DocFileName::erase()
775 zipped_valid_ = false;
779 string DocFileName::relFilename(string const & path) const
782 return to_utf8(relPath(path));
786 string DocFileName::outputFilename(string const & path) const
788 return save_abs_path_ ? absFilename() : relFilename(path);
792 string DocFileName::mangledFilename(string const & dir) const
794 // We need to make sure that every DocFileName instance for a given
795 // filename returns the same mangled name.
796 typedef map<string, string> MangledMap;
797 static MangledMap mangledNames;
798 MangledMap::const_iterator const it = mangledNames.find(absFilename());
799 if (it != mangledNames.end())
802 string const name = absFilename();
804 string mname = os::internal_path(name);
805 // Remove the extension.
806 mname = support::changeExtension(name, string());
807 // The mangled name must be a valid LaTeX name.
808 // The list of characters to keep is probably over-restrictive,
809 // but it is not really a problem.
810 // Apart from non-ASCII characters, at least the following characters
811 // are forbidden: '/', '.', ' ', and ':'.
812 // On windows it is not possible to create files with '<', '>' or '?'
814 static string const keep = "abcdefghijklmnopqrstuvwxyz"
815 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
817 string::size_type pos = 0;
818 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
820 // Add the extension back on
821 mname = support::changeExtension(mname, getExtension(name));
823 // Prepend a counter to the filename. This is necessary to make
824 // the mangled name unique.
825 static int counter = 0;
827 s << counter++ << mname;
830 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
831 // is longer than about 160 characters. MiKTeX's pdflatex
832 // is even pickier. A maximum length of 100 has been proven to work.
833 // If dir.size() > max length, all bets are off for YAP. We truncate
834 // the filename nevertheless, keeping a minimum of 10 chars.
836 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
838 // If the mangled file name is too long, hack it to fit.
839 // We know we're guaranteed to have a unique file name because
841 if (mname.size() > max_length) {
842 int const half = (int(max_length) / 2) - 2;
844 mname = mname.substr(0, half) + "___" +
845 mname.substr(mname.size() - half);
849 mangledNames[absFilename()] = mname;
854 bool DocFileName::isZipped() const
856 if (!zipped_valid_) {
857 zipped_ = isZippedFile();
858 zipped_valid_ = true;
864 string DocFileName::unzippedFilename() const
866 return unzippedFileName(absFilename());
870 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
872 return lhs.absFilename() == rhs.absFilename()
873 && lhs.saveAbsPath() == rhs.saveAbsPath();
877 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
879 return !(lhs == rhs);
882 } // namespace support