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/convert.h"
17 #include "support/debug.h"
18 #include "support/filetools.h"
19 #include "support/lstrings.h"
20 #include "support/os.h"
21 #include "support/Package.h"
22 #include "support/qstring_helpers.h"
29 #include <QTemporaryFile>
32 #include "support/lassert.h"
33 #include <boost/scoped_array.hpp>
40 #ifdef HAVE_SYS_TYPES_H
41 # include <sys/types.h>
43 #ifdef HAVE_SYS_STAT_H
44 # include <sys/stat.h>
64 #if defined(HAVE_MKSTEMP) && ! defined(HAVE_DECL_MKSTEMP)
65 extern "C" int mkstemp(char *);
68 #if !defined(HAVE_MKSTEMP) && defined(HAVE_MKTEMP)
72 # ifdef HAVE_PROCESS_H
83 /////////////////////////////////////////////////////////////////////
87 /////////////////////////////////////////////////////////////////////
89 struct FileName::Private
93 Private(string const & abs_filename) : fi(toqstr(abs_filename))
95 fi.setCaching(fi.exists() ? true : false);
100 // There seems to be a bug in Qt >= 4.2.0, at least, that causes problems with
101 // QFileInfo::refresh() on *nix. So we recreate the object in that case.
102 // FIXME: When Trolltech fixes the bug, we will have to replace 0x999999 below
103 // with the actual working minimum version.
104 #if defined(_WIN32) || (QT_VERSION >= 0x999999)
107 fi = QFileInfo(fi.absoluteFilePath());
114 /////////////////////////////////////////////////////////////////////
118 /////////////////////////////////////////////////////////////////////
121 FileName::FileName() : d(new Private)
126 FileName::FileName(string const & abs_filename)
127 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
132 FileName::~FileName()
138 FileName::FileName(FileName const & rhs) : d(new Private)
144 FileName & FileName::operator=(FileName const & rhs)
151 bool FileName::empty() const
153 return d->fi.absoluteFilePath().isEmpty();
157 bool FileName::isAbsolute() const
159 return d->fi.isAbsolute();
163 string FileName::absFilename() const
165 return fromqstr(d->fi.absoluteFilePath());
169 void FileName::set(string const & name)
171 d->fi.setFile(toqstr(name));
175 void FileName::erase()
181 bool FileName::copyTo(FileName const & name) const
183 LYXERR(Debug::FILES, "Copying " << name);
184 QFile::remove(name.d->fi.absoluteFilePath());
185 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
187 LYXERR0("FileName::copyTo(): Could not copy file "
188 << *this << " to " << name);
193 bool FileName::renameTo(FileName const & name) const
195 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
197 LYXERR0("Could not rename file " << *this << " to " << name);
202 bool FileName::moveTo(FileName const & name) const
204 QFile::remove(name.d->fi.absoluteFilePath());
206 bool success = QFile::rename(d->fi.absoluteFilePath(),
207 name.d->fi.absoluteFilePath());
209 LYXERR0("Could not move file " << *this << " to " << name);
214 bool FileName::changePermission(unsigned long int mode) const
216 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
217 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
218 LYXERR0("File " << *this << ": cannot change permission to "
227 string FileName::toFilesystemEncoding() const
229 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
230 return string(encoded.begin(), encoded.end());
234 FileName FileName::fromFilesystemEncoding(string const & name)
236 QByteArray const encoded(name.c_str(), name.length());
237 return FileName(fromqstr(QFile::decodeName(encoded)));
241 bool FileName::exists() const
243 return d->fi.exists();
247 bool FileName::isSymLink() const
249 return d->fi.isSymLink();
253 bool FileName::isFileEmpty() const
255 return d->fi.size() == 0;
259 bool FileName::isDirectory() const
261 return d->fi.isDir();
265 bool FileName::isReadOnly() const
267 return d->fi.isReadable() && !d->fi.isWritable();
271 bool FileName::isReadableDirectory() const
273 return d->fi.isDir() && d->fi.isReadable();
277 string FileName::onlyFileName() const
279 return fromqstr(d->fi.fileName());
283 string FileName::onlyFileNameWithoutExt() const
285 return fromqstr(d->fi.baseName());
289 FileName FileName::onlyPath() const
292 path.d->fi.setFile(d->fi.path());
297 bool FileName::isReadableFile() const
299 return d->fi.isFile() && d->fi.isReadable();
303 bool FileName::isWritable() const
305 return d->fi.isWritable();
309 bool FileName::isDirWritable() const
311 LASSERT(d->fi.isDir(), return false);
312 QFileInfo tmp(d->fi.absoluteDir(), "lyxwritetest");
313 QTemporaryFile qt_tmp(tmp.absoluteFilePath());
315 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
318 LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
323 FileNameList FileName::dirList(string const & ext) const
325 FileNameList dirlist;
326 if (!isDirectory()) {
327 LYXERR0("Directory '" << *this << "' does not exist!");
331 QDir dir = d->fi.absoluteDir();
336 case '.': filter = "*" + toqstr(ext); break;
337 case '*': filter = toqstr(ext); break;
338 default: filter = "*." + toqstr(ext);
340 dir.setNameFilters(QStringList(filter));
341 LYXERR(Debug::FILES, "filtering on extension "
342 << fromqstr(filter) << " is requested.");
345 QFileInfoList list = dir.entryInfoList();
346 for (int i = 0; i != list.size(); ++i) {
347 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
348 dirlist.push_back(fi);
349 LYXERR(Debug::FILES, "found file " << fi);
356 FileName FileName::tempName(string const & mask)
358 QFileInfo tmp_fi(toqstr(mask));
359 if (!tmp_fi.isAbsolute())
360 tmp_fi.setFile(package().temp_dir().d->fi.absoluteDir(), toqstr(mask));
362 QTemporaryFile qt_tmp(tmp_fi.absoluteFilePath());
364 FileName tmp_name(fromqstr(qt_tmp.fileName()));
365 LYXERR(Debug::FILES, "Temporary file `" << tmp_name << "' created.");
368 LYXERR(Debug::FILES, "LyX Error: Unable to create temporary file.");
373 FileName FileName::getcwd()
375 return FileName(".");
379 FileName FileName::tempPath()
381 return FileName(fromqstr(QDir::tempPath()));
385 time_t FileName::lastModified() const
387 // QFileInfo caches information about the file. So, in case this file has
388 // been touched between the object creation and now, we refresh the file
391 return d->fi.lastModified().toTime_t();
395 bool FileName::chdir() const
397 return QDir::setCurrent(d->fi.absoluteFilePath());
401 extern unsigned long sum(char const * file);
403 unsigned long FileName::checksum() const
406 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
409 // a directory may be passed here so we need to test it. (bug 3622)
411 LYXERR0('"' << absFilename() << "\" is a directory!");
414 if (!lyxerr.debugging(Debug::FILES))
415 return sum(absFilename().c_str());
419 unsigned long r = sum(absFilename().c_str());
420 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
421 << t.elapsed() << " ms." << endl;
426 bool FileName::removeFile() const
428 bool const success = QFile::remove(d->fi.absoluteFilePath());
429 if (!success && exists())
430 LYXERR0("Could not delete file " << *this);
435 static bool rmdir(QFileInfo const & fi)
437 QDir dir(fi.absoluteFilePath());
438 QFileInfoList list = dir.entryInfoList();
440 for (int i = 0; i != list.size(); ++i) {
441 if (list.at(i).fileName() == ".")
443 if (list.at(i).fileName() == "..")
446 if (list.at(i).isDir()) {
447 LYXERR(Debug::FILES, "Removing dir "
448 << fromqstr(list.at(i).absoluteFilePath()));
449 removed = rmdir(list.at(i));
452 LYXERR(Debug::FILES, "Removing file "
453 << fromqstr(list.at(i).absoluteFilePath()));
454 removed = dir.remove(list.at(i).fileName());
458 LYXERR0("Could not delete "
459 << fromqstr(list.at(i).absoluteFilePath()));
462 QDir parent = fi.absolutePath();
463 success &= parent.rmdir(fi.fileName());
468 bool FileName::destroyDirectory() const
470 bool const success = rmdir(d->fi);
472 LYXERR0("Could not delete " << *this);
478 static int mymkdir(char const * pathname, unsigned long int mode)
480 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
482 # if MKDIR_TAKES_ONE_ARG
484 return ::mkdir(pathname);
485 // FIXME: "Permissions of created directories are ignored on this system."
488 return ::mkdir(pathname, mode_t(mode));
490 #elif defined(_WIN32)
492 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
493 // FIXME: "Permissions of created directories are ignored on this system."
495 return ::_mkdir(pathname);
496 // FIXME: "Permissions of created directories are ignored on this system."
498 # error "Don't know how to create a directory on this system."
504 bool FileName::createDirectory(int permission) const
506 LASSERT(!empty(), /**/);
507 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
511 bool FileName::createPath() const
513 LASSERT(!empty(), /**/);
518 bool success = dir.mkpath(d->fi.absoluteFilePath());
520 LYXERR0("Cannot create path '" << *this << "'!");
525 docstring const FileName::absoluteFilePath() const
527 return qstring_to_ucs4(d->fi.absoluteFilePath());
531 docstring FileName::displayName(int threshold) const
533 return makeDisplayPath(absFilename(), threshold);
537 docstring FileName::fileContents(string const & encoding) const
539 if (!isReadableFile()) {
540 LYXERR0("File '" << *this << "' is not redable!");
544 QFile file(d->fi.absoluteFilePath());
545 if (!file.open(QIODevice::ReadOnly)) {
546 LYXERR0("File '" << *this
547 << "' could not be opened in read only mode!");
550 QByteArray contents = file.readAll();
553 if (contents.isEmpty()) {
554 LYXERR(Debug::FILES, "File '" << *this
555 << "' is either empty or some error happened while reading it.");
560 if (encoding.empty() || encoding == "UTF-8")
561 s = QString::fromUtf8(contents.data());
562 else if (encoding == "ascii")
563 s = QString::fromAscii(contents.data());
564 else if (encoding == "local8bit")
565 s = QString::fromLocal8Bit(contents.data());
566 else if (encoding == "latin1")
567 s = QString::fromLatin1(contents.data());
569 return qstring_to_ucs4(s);
573 void FileName::changeExtension(string const & extension)
575 // FIXME: use Qt native methods...
576 string const oldname = absFilename();
577 string::size_type const last_slash = oldname.rfind('/');
578 string::size_type last_dot = oldname.rfind('.');
579 if (last_dot < last_slash && last_slash != string::npos)
580 last_dot = string::npos;
583 // Make sure the extension starts with a dot
584 if (!extension.empty() && extension[0] != '.')
585 ext= '.' + extension;
589 set(oldname.substr(0, last_dot) + ext);
593 string FileName::guessFormatFromContents() const
595 // the different filetypes and what they contain in one of the first lines
596 // (dots are any characters). (Herbert 20020131)
599 // EPS %!PS-Adobe-3.0 EPSF...
606 // PBM P1... or P4 (B/W)
607 // PGM P2... or P5 (Grayscale)
608 // PPM P3... or P6 (color)
609 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
610 // SGI \001\332... (decimal 474)
612 // TIFF II... or MM...
614 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
615 // ...static char *...
616 // XWD \000\000\000\151 (0x00006900) decimal 105
618 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
619 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
620 // Z \037\235 UNIX compress
623 if (empty() || !isReadableFile())
626 ifstream ifs(toFilesystemEncoding().c_str());
628 // Couldn't open file...
632 static string const gzipStamp = "\037\213";
635 static string const zipStamp = "PK";
638 static string const compressStamp = "\037\235";
640 // Maximum strings to read
641 int const max_count = 50;
646 bool firstLine = true;
647 while ((count++ < max_count) && format.empty()) {
649 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
650 << "\tFile type not recognised before EOF!");
655 string const stamp = str.substr(0, 2);
656 if (firstLine && str.size() >= 2) {
657 // at first we check for a zipped file, because this
658 // information is saved in the first bytes of the file!
659 // also some graphic formats which save the information
660 // in the first line, too.
661 if (prefixIs(str, gzipStamp)) {
664 } else if (stamp == zipStamp) {
667 } else if (stamp == compressStamp) {
671 } else if (stamp == "BM") {
674 } else if (stamp == "\001\332") {
678 // Don't need to use str.at(0), str.at(1) because
679 // we already know that str.size() >= 2
680 } else if (str[0] == 'P') {
696 } else if ((stamp == "II") || (stamp == "MM")) {
699 } else if (prefixIs(str,"%TGIF")) {
702 } else if (prefixIs(str,"#FIG")) {
705 } else if (prefixIs(str,"GIF")) {
708 } else if (str.size() > 3) {
709 int const c = ((str[0] << 24) & (str[1] << 16) &
710 (str[2] << 8) & str[3]);
721 else if (contains(str,"EPSF"))
722 // dummy, if we have wrong file description like
723 // %!PS-Adobe-2.0EPSF"
726 else if (contains(str, "Grace"))
729 else if (contains(str, "JFIF"))
732 else if (contains(str, "%PDF"))
735 else if (contains(str, "PNG"))
738 else if (contains(str, "%!PS-Adobe")) {
741 if (contains(str,"EPSF"))
747 else if (contains(str, "_bits[]"))
750 else if (contains(str, "XPM") || contains(str, "static char *"))
753 else if (contains(str, "BITPIX"))
757 if (!format.empty()) {
758 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
762 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
763 << "\tCouldn't find a known format!");
768 bool FileName::isZippedFile() const
770 string const type = guessFormatFromContents();
771 return contains("gzip zip compress", type) && !type.empty();
775 docstring const FileName::relPath(string const & path) const
778 return makeRelPath(absoluteFilePath(), from_utf8(path));
782 bool operator==(FileName const & lhs, FileName const & rhs)
784 return lhs.absFilename() == rhs.absFilename();
788 bool operator!=(FileName const & lhs, FileName const & rhs)
790 return lhs.absFilename() != rhs.absFilename();
794 bool operator<(FileName const & lhs, FileName const & rhs)
796 return lhs.absFilename() < rhs.absFilename();
800 bool operator>(FileName const & lhs, FileName const & rhs)
802 return lhs.absFilename() > rhs.absFilename();
806 ostream & operator<<(ostream & os, FileName const & filename)
808 return os << filename.absFilename();
812 /////////////////////////////////////////////////////////////////////
816 /////////////////////////////////////////////////////////////////////
819 DocFileName::DocFileName()
820 : save_abs_path_(true)
824 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
825 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
829 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
830 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
834 void DocFileName::set(string const & name, string const & buffer_path)
837 bool const nameIsAbsolute = isAbsolute();
838 save_abs_path_ = nameIsAbsolute;
840 FileName::set(makeAbsPath(name, buffer_path).absFilename());
841 zipped_valid_ = false;
845 void DocFileName::erase()
848 zipped_valid_ = false;
852 string DocFileName::relFilename(string const & path) const
855 return to_utf8(relPath(path));
859 string DocFileName::outputFilename(string const & path) const
861 return save_abs_path_ ? absFilename() : relFilename(path);
865 string DocFileName::mangledFilename(string const & dir) const
867 // We need to make sure that every DocFileName instance for a given
868 // filename returns the same mangled name.
869 typedef map<string, string> MangledMap;
870 static MangledMap mangledNames;
871 MangledMap::const_iterator const it = mangledNames.find(absFilename());
872 if (it != mangledNames.end())
875 string const name = absFilename();
877 string mname = os::internal_path(name);
878 // Remove the extension.
879 mname = support::changeExtension(name, string());
880 // The mangled name must be a valid LaTeX name.
881 // The list of characters to keep is probably over-restrictive,
882 // but it is not really a problem.
883 // Apart from non-ASCII characters, at least the following characters
884 // are forbidden: '/', '.', ' ', and ':'.
885 // On windows it is not possible to create files with '<', '>' or '?'
887 static string const keep = "abcdefghijklmnopqrstuvwxyz"
888 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
890 string::size_type pos = 0;
891 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
893 // Add the extension back on
894 mname = support::changeExtension(mname, getExtension(name));
896 // Prepend a counter to the filename. This is necessary to make
897 // the mangled name unique.
898 static int counter = 0;
900 s << counter++ << mname;
903 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
904 // is longer than about 160 characters. MiKTeX's pdflatex
905 // is even pickier. A maximum length of 100 has been proven to work.
906 // If dir.size() > max length, all bets are off for YAP. We truncate
907 // the filename nevertheless, keeping a minimum of 10 chars.
909 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
911 // If the mangled file name is too long, hack it to fit.
912 // We know we're guaranteed to have a unique file name because
914 if (mname.size() > max_length) {
915 int const half = (int(max_length) / 2) - 2;
917 mname = mname.substr(0, half) + "___" +
918 mname.substr(mname.size() - half);
922 mangledNames[absFilename()] = mname;
927 bool DocFileName::isZipped() const
929 if (!zipped_valid_) {
930 zipped_ = isZippedFile();
931 zipped_valid_ = true;
937 string DocFileName::unzippedFilename() const
939 return unzippedFileName(absFilename());
943 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
945 return lhs.absFilename() == rhs.absFilename()
946 && lhs.saveAbsPath() == rhs.saveAbsPath();
950 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
952 return !(lhs == rhs);
955 } // namespace support