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/lyxlib.h"
21 #include "support/os.h"
22 #include "support/Package.h"
23 #include "support/qstring_helpers.h"
32 #include <boost/assert.hpp>
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);
101 /////////////////////////////////////////////////////////////////////
105 /////////////////////////////////////////////////////////////////////
108 FileName::FileName() : d(new Private)
113 FileName::FileName(string const & abs_filename)
114 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
119 FileName::~FileName()
125 FileName::FileName(FileName const & rhs) : d(new Private)
131 FileName & FileName::operator=(FileName const & rhs)
138 bool FileName::empty() const
140 return d->fi.absoluteFilePath().isEmpty();
144 string FileName::absFilename() const
146 return fromqstr(d->fi.absoluteFilePath());
150 void FileName::set(string const & name)
152 d->fi.setFile(toqstr(name));
153 BOOST_ASSERT(d->fi.isAbsolute());
157 void FileName::erase()
163 bool FileName::copyTo(FileName const & name) const
165 QFile::remove(name.d->fi.absoluteFilePath());
166 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
168 lyxerr << "FileName::copyTo(): Could not copy file "
169 << *this << " to " << name << endl;
174 bool FileName::renameTo(FileName const & name) const
176 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
178 LYXERR0("Could not rename file " << *this << " to " << name);
183 bool FileName::moveTo(FileName const & name) const
185 QFile::remove(name.d->fi.absoluteFilePath());
187 bool success = QFile::rename(d->fi.absoluteFilePath(),
188 name.d->fi.absoluteFilePath());
190 LYXERR0("Could not move file " << *this << " to " << name);
195 bool FileName::changePermission(unsigned long int mode) const
198 LYXERR0("File " << *this << " is not writable!");
202 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
203 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
204 LYXERR0("File " << *this << ": cannot change permission to "
213 string FileName::toFilesystemEncoding() const
215 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
216 return string(encoded.begin(), encoded.end());
220 FileName FileName::fromFilesystemEncoding(string const & name)
222 QByteArray const encoded(name.c_str(), name.length());
223 return FileName(fromqstr(QFile::decodeName(encoded)));
227 bool FileName::exists() const
229 return d->fi.exists();
233 bool FileName::isSymLink() const
235 return d->fi.isSymLink();
239 bool FileName::isFileEmpty() const
241 return d->fi.size() == 0;
245 bool FileName::isDirectory() const
247 return d->fi.isDir();
251 bool FileName::isReadOnly() const
253 return d->fi.isReadable() && !d->fi.isWritable();
257 bool FileName::isReadableDirectory() const
259 return d->fi.isDir() && d->fi.isReadable();
263 string FileName::onlyFileName() const
265 return support::onlyFilename(absFilename());
269 FileName FileName::onlyPath() const
271 return FileName(support::onlyPath(absFilename()));
275 bool FileName::isReadableFile() const
277 return d->fi.isFile() && d->fi.isReadable();
281 bool FileName::isWritable() const
283 return d->fi.isWritable();
287 bool FileName::isDirWritable() const
289 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
291 FileName const tmpfl = FileName::tempName(absFilename() + "/lyxwritetest");
301 FileNameList FileName::dirList(string const & ext) const
303 FileNameList dirlist;
304 if (!isDirectory()) {
305 LYXERR0("Directory '" << *this << "' does not exist!");
309 QDir dir = d->fi.absoluteDir();
314 case '.': filter = "*" + toqstr(ext); break;
315 case '*': filter = toqstr(ext); break;
316 default: filter = "*." + toqstr(ext);
318 dir.setNameFilters(QStringList(filter));
319 LYXERR(Debug::FILES, "filtering on extension "
320 << fromqstr(filter) << " is requested.");
323 QFileInfoList list = dir.entryInfoList();
324 for (int i = 0; i != list.size(); ++i) {
325 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
326 dirlist.push_back(fi);
327 LYXERR(Debug::FILES, "found file " << fi);
334 static int make_tempfile(char * templ)
336 #if defined(HAVE_MKSTEMP)
337 return ::mkstemp(templ);
338 #elif defined(HAVE_MKTEMP)
339 // This probably just barely works...
341 # if defined (HAVE_OPEN)
342 # if (!defined S_IRUSR)
343 # define S_IRUSR S_IREAD
344 # define S_IWUSR S_IWRITE
346 return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
347 # elif defined (HAVE__OPEN)
348 return ::_open(templ,
349 _O_RDWR | _O_CREAT | _O_EXCL,
350 _S_IREAD | _S_IWRITE);
352 # error No open() function.
360 FileName FileName::tempName(string const & mask)
362 FileName tmp_name(mask);
364 if (tmp_name.d->fi.isAbsolute())
367 tmpfl = package().temp_dir().absFilename() + "/" + mask;
369 #if defined (HAVE_GETPID)
370 tmpfl += convert<string>(getpid());
371 #elif defined (HAVE__GETPID)
372 tmpfl += convert<string>(_getpid());
374 # error No getpid() function
378 // The supposedly safe mkstemp version
379 // FIXME: why not using std::string directly?
380 boost::scoped_array<char> tmpl(new char[tmpfl.length() + 1]); // + 1 for '\0'
381 tmpfl.copy(tmpl.get(), string::npos);
382 tmpl[tmpfl.length()] = '\0'; // terminator
384 int const tmpf = make_tempfile(tmpl.get());
386 string const t(to_utf8(from_filesystem8bit(tmpl.get())));
387 #if defined (HAVE_CLOSE)
389 #elif defined (HAVE__CLOSE)
392 # error No x() function.
394 LYXERR(Debug::FILES, "Temporary file `" << t << "' created.");
397 LYXERR(Debug::FILES, "LyX Error: Unable to create temporary file.");
402 time_t FileName::lastModified() const
404 return d->fi.lastModified().toTime_t();
408 bool FileName::chdir() const
410 return QDir::setCurrent(d->fi.absoluteFilePath());
414 extern unsigned long sum(char const * file);
416 unsigned long FileName::checksum() const
419 LYXERR0("File \"" << absFilename() << "\" does not exist!");
422 // a directory may be passed here so we need to test it. (bug 3622)
424 LYXERR0('"' << absFilename() << "\" is a directory!");
427 if (!lyxerr.debugging(Debug::FILES))
428 return sum(absFilename().c_str());
432 unsigned long r = sum(absFilename().c_str());
433 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
434 << t.elapsed() << " ms." << endl;
439 bool FileName::removeFile() const
441 bool const success = QFile::remove(d->fi.absoluteFilePath());
442 if (!success && exists())
443 LYXERR0("Could not delete file " << *this);
448 static bool rmdir(QFileInfo const & fi)
450 QDir dir(fi.absoluteFilePath());
451 QFileInfoList list = dir.entryInfoList();
453 for (int i = 0; i != list.size(); ++i) {
454 if (list.at(i).fileName() == ".")
456 if (list.at(i).fileName() == "..")
459 if (list.at(i).isDir()) {
460 LYXERR(Debug::FILES, "Removing dir "
461 << fromqstr(list.at(i).absoluteFilePath()));
462 removed = rmdir(list.at(i));
465 LYXERR(Debug::FILES, "Removing file "
466 << fromqstr(list.at(i).absoluteFilePath()));
467 removed = dir.remove(list.at(i).fileName());
471 LYXERR0("Could not delete "
472 << fromqstr(list.at(i).absoluteFilePath()));
475 QDir parent = fi.absolutePath();
476 success &= parent.rmdir(fi.fileName());
481 bool FileName::destroyDirectory() const
483 bool const success = rmdir(d->fi);
485 LYXERR0("Could not delete " << *this);
491 static int mymkdir(char const * pathname, unsigned long int mode)
493 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
495 # if MKDIR_TAKES_ONE_ARG
497 return ::mkdir(pathname);
498 // FIXME: "Permissions of created directories are ignored on this system."
501 return ::mkdir(pathname, mode_t(mode));
503 #elif defined(_WIN32)
505 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
506 // FIXME: "Permissions of created directories are ignored on this system."
508 return ::_mkdir(pathname);
509 // FIXME: "Permissions of created directories are ignored on this system."
511 # error "Don't know how to create a directory on this system."
517 bool FileName::createDirectory(int permission) const
519 BOOST_ASSERT(!empty());
520 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
524 bool FileName::createPath() const
526 BOOST_ASSERT(!empty());
531 bool success = dir.mkpath(d->fi.absoluteFilePath());
533 LYXERR0("Cannot create path '" << *this << "'!");
538 docstring const FileName::absoluteFilePath() const
540 return qstring_to_ucs4(d->fi.absoluteFilePath());
544 docstring FileName::displayName(int threshold) const
546 return makeDisplayPath(absFilename(), threshold);
550 docstring FileName::fileContents(string const & encoding) const
552 if (!isReadableFile()) {
553 LYXERR0("File '" << *this << "' is not redable!");
557 QFile file(d->fi.absoluteFilePath());
558 if (!file.open(QIODevice::ReadOnly)) {
559 LYXERR0("File '" << *this
560 << "' could not be opened in read only mode!");
563 QByteArray contents = file.readAll();
566 if (contents.isEmpty()) {
567 LYXERR(Debug::FILES, "File '" << *this
568 << "' is either empty or some error happened while reading it.");
573 if (encoding.empty() || encoding == "UTF-8")
574 s = QString::fromUtf8(contents.data());
575 else if (encoding == "ascii")
576 s = QString::fromAscii(contents.data());
577 else if (encoding == "local8bit")
578 s = QString::fromLocal8Bit(contents.data());
579 else if (encoding == "latin1")
580 s = QString::fromLatin1(contents.data());
582 return qstring_to_ucs4(s);
586 void FileName::changeExtension(string const & extension)
588 // FIXME: use Qt native methods...
589 string const oldname = absFilename();
590 string::size_type const last_slash = oldname.rfind('/');
591 string::size_type last_dot = oldname.rfind('.');
592 if (last_dot < last_slash && last_slash != string::npos)
593 last_dot = string::npos;
596 // Make sure the extension starts with a dot
597 if (!extension.empty() && extension[0] != '.')
598 ext= '.' + extension;
602 set(oldname.substr(0, last_dot) + ext);
606 string FileName::guessFormatFromContents() const
608 // the different filetypes and what they contain in one of the first lines
609 // (dots are any characters). (Herbert 20020131)
612 // EPS %!PS-Adobe-3.0 EPSF...
619 // PBM P1... or P4 (B/W)
620 // PGM P2... or P5 (Grayscale)
621 // PPM P3... or P6 (color)
622 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
623 // SGI \001\332... (decimal 474)
625 // TIFF II... or MM...
627 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
628 // ...static char *...
629 // XWD \000\000\000\151 (0x00006900) decimal 105
631 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
632 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
633 // Z \037\235 UNIX compress
636 if (empty() || !isReadableFile())
639 ifstream ifs(toFilesystemEncoding().c_str());
641 // Couldn't open file...
645 static string const gzipStamp = "\037\213";
648 static string const zipStamp = "PK";
651 static string const compressStamp = "\037\235";
653 // Maximum strings to read
654 int const max_count = 50;
659 bool firstLine = true;
660 while ((count++ < max_count) && format.empty()) {
662 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
663 << "\tFile type not recognised before EOF!");
668 string const stamp = str.substr(0, 2);
669 if (firstLine && str.size() >= 2) {
670 // at first we check for a zipped file, because this
671 // information is saved in the first bytes of the file!
672 // also some graphic formats which save the information
673 // in the first line, too.
674 if (prefixIs(str, gzipStamp)) {
677 } else if (stamp == zipStamp) {
680 } else if (stamp == compressStamp) {
684 } else if (stamp == "BM") {
687 } else if (stamp == "\001\332") {
691 // Don't need to use str.at(0), str.at(1) because
692 // we already know that str.size() >= 2
693 } else if (str[0] == 'P') {
709 } else if ((stamp == "II") || (stamp == "MM")) {
712 } else if (prefixIs(str,"%TGIF")) {
715 } else if (prefixIs(str,"#FIG")) {
718 } else if (prefixIs(str,"GIF")) {
721 } else if (str.size() > 3) {
722 int const c = ((str[0] << 24) & (str[1] << 16) &
723 (str[2] << 8) & str[3]);
734 else if (contains(str,"EPSF"))
735 // dummy, if we have wrong file description like
736 // %!PS-Adobe-2.0EPSF"
739 else if (contains(str, "Grace"))
742 else if (contains(str, "JFIF"))
745 else if (contains(str, "%PDF"))
748 else if (contains(str, "PNG"))
751 else if (contains(str, "%!PS-Adobe")) {
754 if (contains(str,"EPSF"))
760 else if (contains(str, "_bits[]"))
763 else if (contains(str, "XPM") || contains(str, "static char *"))
766 else if (contains(str, "BITPIX"))
770 if (!format.empty()) {
771 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
775 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
776 << "\tCouldn't find a known format!");
781 bool FileName::isZippedFile() const
783 string const type = guessFormatFromContents();
784 return contains("gzip zip compress", type) && !type.empty();
788 docstring const FileName::relPath(string const & path) const
791 return makeRelPath(absoluteFilePath(), from_utf8(path));
795 bool operator==(FileName const & lhs, FileName const & rhs)
797 return lhs.absFilename() == rhs.absFilename();
801 bool operator!=(FileName const & lhs, FileName const & rhs)
803 return lhs.absFilename() != rhs.absFilename();
807 bool operator<(FileName const & lhs, FileName const & rhs)
809 return lhs.absFilename() < rhs.absFilename();
813 bool operator>(FileName const & lhs, FileName const & rhs)
815 return lhs.absFilename() > rhs.absFilename();
819 ostream & operator<<(ostream & os, FileName const & filename)
821 return os << filename.absFilename();
825 /////////////////////////////////////////////////////////////////////
829 /////////////////////////////////////////////////////////////////////
832 DocFileName::DocFileName()
833 : save_abs_path_(true)
837 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
838 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
842 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
843 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
847 void DocFileName::set(string const & name, string const & buffer_path)
849 save_abs_path_ = absolutePath(name);
850 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
851 zipped_valid_ = false;
855 void DocFileName::erase()
858 zipped_valid_ = false;
862 string DocFileName::relFilename(string const & path) const
865 return to_utf8(relPath(path));
869 string DocFileName::outputFilename(string const & path) const
871 return save_abs_path_ ? absFilename() : relFilename(path);
875 string DocFileName::mangledFilename(string const & dir) const
877 // We need to make sure that every DocFileName instance for a given
878 // filename returns the same mangled name.
879 typedef map<string, string> MangledMap;
880 static MangledMap mangledNames;
881 MangledMap::const_iterator const it = mangledNames.find(absFilename());
882 if (it != mangledNames.end())
885 string const name = absFilename();
887 string mname = os::internal_path(name);
888 // Remove the extension.
889 mname = support::changeExtension(name, string());
890 // The mangled name must be a valid LaTeX name.
891 // The list of characters to keep is probably over-restrictive,
892 // but it is not really a problem.
893 // Apart from non-ASCII characters, at least the following characters
894 // are forbidden: '/', '.', ' ', and ':'.
895 // On windows it is not possible to create files with '<', '>' or '?'
897 static string const keep = "abcdefghijklmnopqrstuvwxyz"
898 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
900 string::size_type pos = 0;
901 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
903 // Add the extension back on
904 mname = support::changeExtension(mname, getExtension(name));
906 // Prepend a counter to the filename. This is necessary to make
907 // the mangled name unique.
908 static int counter = 0;
910 s << counter++ << mname;
913 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
914 // is longer than about 160 characters. MiKTeX's pdflatex
915 // is even pickier. A maximum length of 100 has been proven to work.
916 // If dir.size() > max length, all bets are off for YAP. We truncate
917 // the filename nevertheless, keeping a minimum of 10 chars.
919 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
921 // If the mangled file name is too long, hack it to fit.
922 // We know we're guaranteed to have a unique file name because
924 if (mname.size() > max_length) {
925 int const half = (int(max_length) / 2) - 2;
927 mname = mname.substr(0, half) + "___" +
928 mname.substr(mname.size() - half);
932 mangledNames[absFilename()] = mname;
937 bool DocFileName::isZipped() const
939 if (!zipped_valid_) {
940 zipped_ = isZippedFile();
941 zipped_valid_ = true;
947 string DocFileName::unzippedFilename() const
949 return unzippedFileName(absFilename());
953 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
955 return lhs.absFilename() == rhs.absFilename()
956 && lhs.saveAbsPath() == rhs.saveAbsPath();
960 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
962 return !(lhs == rhs);
965 } // namespace support