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"
31 #include <boost/assert.hpp>
32 #include <boost/scoped_array.hpp>
39 #ifdef HAVE_SYS_TYPES_H
40 # include <sys/types.h>
42 #ifdef HAVE_SYS_STAT_H
43 # include <sys/stat.h>
63 #if defined(HAVE_MKSTEMP) && ! defined(HAVE_DECL_MKSTEMP)
64 extern "C" int mkstemp(char *);
67 #if !defined(HAVE_MKSTEMP) && defined(HAVE_MKTEMP)
71 # ifdef HAVE_PROCESS_H
82 /////////////////////////////////////////////////////////////////////
86 /////////////////////////////////////////////////////////////////////
88 struct FileName::Private
92 Private(string const & abs_filename) : fi(toqstr(abs_filename))
94 fi.setCaching(fi.exists() ? true : false);
100 /////////////////////////////////////////////////////////////////////
104 /////////////////////////////////////////////////////////////////////
107 FileName::FileName() : d(new Private)
112 FileName::FileName(string const & abs_filename)
113 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
118 FileName::~FileName()
124 FileName::FileName(FileName const & rhs) : d(new Private)
130 FileName & FileName::operator=(FileName const & rhs)
137 bool FileName::empty() const
139 return d->fi.absoluteFilePath().isEmpty();
143 bool FileName::isAbsolute() const
145 return d->fi.isAbsolute();
149 string FileName::absFilename() const
151 return fromqstr(d->fi.absoluteFilePath());
155 void FileName::set(string const & name)
157 d->fi.setFile(toqstr(name));
158 BOOST_ASSERT(d->fi.isAbsolute());
162 void FileName::erase()
168 bool FileName::copyTo(FileName const & name) const
170 QFile::remove(name.d->fi.absoluteFilePath());
171 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
173 lyxerr << "FileName::copyTo(): Could not copy file "
174 << *this << " to " << name << endl;
179 bool FileName::renameTo(FileName const & name) const
181 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
183 LYXERR0("Could not rename file " << *this << " to " << name);
188 bool FileName::moveTo(FileName const & name) const
190 QFile::remove(name.d->fi.absoluteFilePath());
192 bool success = QFile::rename(d->fi.absoluteFilePath(),
193 name.d->fi.absoluteFilePath());
195 LYXERR0("Could not move file " << *this << " to " << name);
200 bool FileName::changePermission(unsigned long int mode) const
203 LYXERR0("File " << *this << " is not writable!");
207 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
208 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
209 LYXERR0("File " << *this << ": cannot change permission to "
218 string FileName::toFilesystemEncoding() const
220 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
221 return string(encoded.begin(), encoded.end());
225 FileName FileName::fromFilesystemEncoding(string const & name)
227 QByteArray const encoded(name.c_str(), name.length());
228 return FileName(fromqstr(QFile::decodeName(encoded)));
232 bool FileName::exists() const
234 return d->fi.exists();
238 bool FileName::isSymLink() const
240 return d->fi.isSymLink();
244 bool FileName::isFileEmpty() const
246 return d->fi.size() == 0;
250 bool FileName::isDirectory() const
252 return d->fi.isDir();
256 bool FileName::isReadOnly() const
258 return d->fi.isReadable() && !d->fi.isWritable();
262 bool FileName::isReadableDirectory() const
264 return d->fi.isDir() && d->fi.isReadable();
268 string FileName::onlyFileName() const
270 return support::onlyFilename(absFilename());
274 FileName FileName::onlyPath() const
276 return FileName(support::onlyPath(absFilename()));
280 bool FileName::isReadableFile() const
282 return d->fi.isFile() && d->fi.isReadable();
286 bool FileName::isWritable() const
288 return d->fi.isWritable();
292 bool FileName::isDirWritable() const
294 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
296 FileName const tmpfl = FileName::tempName(absFilename() + "/lyxwritetest");
306 FileNameList FileName::dirList(string const & ext) const
308 FileNameList dirlist;
309 if (!isDirectory()) {
310 LYXERR0("Directory '" << *this << "' does not exist!");
314 QDir dir = d->fi.absoluteDir();
319 case '.': filter = "*" + toqstr(ext); break;
320 case '*': filter = toqstr(ext); break;
321 default: filter = "*." + toqstr(ext);
323 dir.setNameFilters(QStringList(filter));
324 LYXERR(Debug::FILES, "filtering on extension "
325 << fromqstr(filter) << " is requested.");
328 QFileInfoList list = dir.entryInfoList();
329 for (int i = 0; i != list.size(); ++i) {
330 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
331 dirlist.push_back(fi);
332 LYXERR(Debug::FILES, "found file " << fi);
339 static int make_tempfile(char * templ)
341 #if defined(HAVE_MKSTEMP)
342 return ::mkstemp(templ);
343 #elif defined(HAVE_MKTEMP)
344 // This probably just barely works...
346 # if defined (HAVE_OPEN)
347 # if (!defined S_IRUSR)
348 # define S_IRUSR S_IREAD
349 # define S_IWUSR S_IWRITE
351 return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
352 # elif defined (HAVE__OPEN)
353 return ::_open(templ,
354 _O_RDWR | _O_CREAT | _O_EXCL,
355 _S_IREAD | _S_IWRITE);
357 # error No open() function.
365 FileName FileName::tempName(string const & mask)
367 FileName tmp_name(mask);
369 if (tmp_name.d->fi.isAbsolute())
372 tmpfl = package().temp_dir().absFilename() + "/" + mask;
374 #if defined (HAVE_GETPID)
375 tmpfl += convert<string>(getpid());
376 #elif defined (HAVE__GETPID)
377 tmpfl += convert<string>(_getpid());
379 # error No getpid() function
383 // The supposedly safe mkstemp version
384 // FIXME: why not using std::string directly?
385 boost::scoped_array<char> tmpl(new char[tmpfl.length() + 1]); // + 1 for '\0'
386 tmpfl.copy(tmpl.get(), string::npos);
387 tmpl[tmpfl.length()] = '\0'; // terminator
389 int const tmpf = make_tempfile(tmpl.get());
391 string const t(to_utf8(from_filesystem8bit(tmpl.get())));
392 #if defined (HAVE_CLOSE)
394 #elif defined (HAVE__CLOSE)
397 # error No x() function.
399 LYXERR(Debug::FILES, "Temporary file `" << t << "' created.");
402 LYXERR(Debug::FILES, "LyX Error: Unable to create temporary file.");
407 FileName FileName::getcwd()
409 return FileName(".");
413 time_t FileName::lastModified() const
415 return d->fi.lastModified().toTime_t();
419 bool FileName::chdir() const
421 return QDir::setCurrent(d->fi.absoluteFilePath());
425 extern unsigned long sum(char const * file);
427 unsigned long FileName::checksum() const
430 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
433 // a directory may be passed here so we need to test it. (bug 3622)
435 LYXERR0('"' << absFilename() << "\" is a directory!");
438 if (!lyxerr.debugging(Debug::FILES))
439 return sum(absFilename().c_str());
443 unsigned long r = sum(absFilename().c_str());
444 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
445 << t.elapsed() << " ms." << endl;
450 bool FileName::removeFile() const
452 bool const success = QFile::remove(d->fi.absoluteFilePath());
453 if (!success && exists())
454 LYXERR0("Could not delete file " << *this);
459 static bool rmdir(QFileInfo const & fi)
461 QDir dir(fi.absoluteFilePath());
462 QFileInfoList list = dir.entryInfoList();
464 for (int i = 0; i != list.size(); ++i) {
465 if (list.at(i).fileName() == ".")
467 if (list.at(i).fileName() == "..")
470 if (list.at(i).isDir()) {
471 LYXERR(Debug::FILES, "Removing dir "
472 << fromqstr(list.at(i).absoluteFilePath()));
473 removed = rmdir(list.at(i));
476 LYXERR(Debug::FILES, "Removing file "
477 << fromqstr(list.at(i).absoluteFilePath()));
478 removed = dir.remove(list.at(i).fileName());
482 LYXERR0("Could not delete "
483 << fromqstr(list.at(i).absoluteFilePath()));
486 QDir parent = fi.absolutePath();
487 success &= parent.rmdir(fi.fileName());
492 bool FileName::destroyDirectory() const
494 bool const success = rmdir(d->fi);
496 LYXERR0("Could not delete " << *this);
502 static int mymkdir(char const * pathname, unsigned long int mode)
504 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
506 # if MKDIR_TAKES_ONE_ARG
508 return ::mkdir(pathname);
509 // FIXME: "Permissions of created directories are ignored on this system."
512 return ::mkdir(pathname, mode_t(mode));
514 #elif defined(_WIN32)
516 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
517 // FIXME: "Permissions of created directories are ignored on this system."
519 return ::_mkdir(pathname);
520 // FIXME: "Permissions of created directories are ignored on this system."
522 # error "Don't know how to create a directory on this system."
528 bool FileName::createDirectory(int permission) const
530 BOOST_ASSERT(!empty());
531 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
535 bool FileName::createPath() const
537 BOOST_ASSERT(!empty());
542 bool success = dir.mkpath(d->fi.absoluteFilePath());
544 LYXERR0("Cannot create path '" << *this << "'!");
549 docstring const FileName::absoluteFilePath() const
551 return qstring_to_ucs4(d->fi.absoluteFilePath());
555 docstring FileName::displayName(int threshold) const
557 return makeDisplayPath(absFilename(), threshold);
561 docstring FileName::fileContents(string const & encoding) const
563 if (!isReadableFile()) {
564 LYXERR0("File '" << *this << "' is not redable!");
568 QFile file(d->fi.absoluteFilePath());
569 if (!file.open(QIODevice::ReadOnly)) {
570 LYXERR0("File '" << *this
571 << "' could not be opened in read only mode!");
574 QByteArray contents = file.readAll();
577 if (contents.isEmpty()) {
578 LYXERR(Debug::FILES, "File '" << *this
579 << "' is either empty or some error happened while reading it.");
584 if (encoding.empty() || encoding == "UTF-8")
585 s = QString::fromUtf8(contents.data());
586 else if (encoding == "ascii")
587 s = QString::fromAscii(contents.data());
588 else if (encoding == "local8bit")
589 s = QString::fromLocal8Bit(contents.data());
590 else if (encoding == "latin1")
591 s = QString::fromLatin1(contents.data());
593 return qstring_to_ucs4(s);
597 void FileName::changeExtension(string const & extension)
599 // FIXME: use Qt native methods...
600 string const oldname = absFilename();
601 string::size_type const last_slash = oldname.rfind('/');
602 string::size_type last_dot = oldname.rfind('.');
603 if (last_dot < last_slash && last_slash != string::npos)
604 last_dot = string::npos;
607 // Make sure the extension starts with a dot
608 if (!extension.empty() && extension[0] != '.')
609 ext= '.' + extension;
613 set(oldname.substr(0, last_dot) + ext);
617 string FileName::guessFormatFromContents() const
619 // the different filetypes and what they contain in one of the first lines
620 // (dots are any characters). (Herbert 20020131)
623 // EPS %!PS-Adobe-3.0 EPSF...
630 // PBM P1... or P4 (B/W)
631 // PGM P2... or P5 (Grayscale)
632 // PPM P3... or P6 (color)
633 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
634 // SGI \001\332... (decimal 474)
636 // TIFF II... or MM...
638 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
639 // ...static char *...
640 // XWD \000\000\000\151 (0x00006900) decimal 105
642 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
643 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
644 // Z \037\235 UNIX compress
647 if (empty() || !isReadableFile())
650 ifstream ifs(toFilesystemEncoding().c_str());
652 // Couldn't open file...
656 static string const gzipStamp = "\037\213";
659 static string const zipStamp = "PK";
662 static string const compressStamp = "\037\235";
664 // Maximum strings to read
665 int const max_count = 50;
670 bool firstLine = true;
671 while ((count++ < max_count) && format.empty()) {
673 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
674 << "\tFile type not recognised before EOF!");
679 string const stamp = str.substr(0, 2);
680 if (firstLine && str.size() >= 2) {
681 // at first we check for a zipped file, because this
682 // information is saved in the first bytes of the file!
683 // also some graphic formats which save the information
684 // in the first line, too.
685 if (prefixIs(str, gzipStamp)) {
688 } else if (stamp == zipStamp) {
691 } else if (stamp == compressStamp) {
695 } else if (stamp == "BM") {
698 } else if (stamp == "\001\332") {
702 // Don't need to use str.at(0), str.at(1) because
703 // we already know that str.size() >= 2
704 } else if (str[0] == 'P') {
720 } else if ((stamp == "II") || (stamp == "MM")) {
723 } else if (prefixIs(str,"%TGIF")) {
726 } else if (prefixIs(str,"#FIG")) {
729 } else if (prefixIs(str,"GIF")) {
732 } else if (str.size() > 3) {
733 int const c = ((str[0] << 24) & (str[1] << 16) &
734 (str[2] << 8) & str[3]);
745 else if (contains(str,"EPSF"))
746 // dummy, if we have wrong file description like
747 // %!PS-Adobe-2.0EPSF"
750 else if (contains(str, "Grace"))
753 else if (contains(str, "JFIF"))
756 else if (contains(str, "%PDF"))
759 else if (contains(str, "PNG"))
762 else if (contains(str, "%!PS-Adobe")) {
765 if (contains(str,"EPSF"))
771 else if (contains(str, "_bits[]"))
774 else if (contains(str, "XPM") || contains(str, "static char *"))
777 else if (contains(str, "BITPIX"))
781 if (!format.empty()) {
782 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
786 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
787 << "\tCouldn't find a known format!");
792 bool FileName::isZippedFile() const
794 string const type = guessFormatFromContents();
795 return contains("gzip zip compress", type) && !type.empty();
799 docstring const FileName::relPath(string const & path) const
802 return makeRelPath(absoluteFilePath(), from_utf8(path));
806 bool operator==(FileName const & lhs, FileName const & rhs)
808 return lhs.absFilename() == rhs.absFilename();
812 bool operator!=(FileName const & lhs, FileName const & rhs)
814 return lhs.absFilename() != rhs.absFilename();
818 bool operator<(FileName const & lhs, FileName const & rhs)
820 return lhs.absFilename() < rhs.absFilename();
824 bool operator>(FileName const & lhs, FileName const & rhs)
826 return lhs.absFilename() > rhs.absFilename();
830 ostream & operator<<(ostream & os, FileName const & filename)
832 return os << filename.absFilename();
836 /////////////////////////////////////////////////////////////////////
840 /////////////////////////////////////////////////////////////////////
843 DocFileName::DocFileName()
844 : save_abs_path_(true)
848 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
849 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
853 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
854 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
858 void DocFileName::set(string const & name, string const & buffer_path)
862 FileName::set(makeAbsPath(name, buffer_path).absFilename());
863 zipped_valid_ = false;
867 void DocFileName::erase()
870 zipped_valid_ = false;
874 string DocFileName::relFilename(string const & path) const
877 return to_utf8(relPath(path));
881 string DocFileName::outputFilename(string const & path) const
883 return save_abs_path_ ? absFilename() : relFilename(path);
887 string DocFileName::mangledFilename(string const & dir) const
889 // We need to make sure that every DocFileName instance for a given
890 // filename returns the same mangled name.
891 typedef map<string, string> MangledMap;
892 static MangledMap mangledNames;
893 MangledMap::const_iterator const it = mangledNames.find(absFilename());
894 if (it != mangledNames.end())
897 string const name = absFilename();
899 string mname = os::internal_path(name);
900 // Remove the extension.
901 mname = support::changeExtension(name, string());
902 // The mangled name must be a valid LaTeX name.
903 // The list of characters to keep is probably over-restrictive,
904 // but it is not really a problem.
905 // Apart from non-ASCII characters, at least the following characters
906 // are forbidden: '/', '.', ' ', and ':'.
907 // On windows it is not possible to create files with '<', '>' or '?'
909 static string const keep = "abcdefghijklmnopqrstuvwxyz"
910 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
912 string::size_type pos = 0;
913 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
915 // Add the extension back on
916 mname = support::changeExtension(mname, getExtension(name));
918 // Prepend a counter to the filename. This is necessary to make
919 // the mangled name unique.
920 static int counter = 0;
922 s << counter++ << mname;
925 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
926 // is longer than about 160 characters. MiKTeX's pdflatex
927 // is even pickier. A maximum length of 100 has been proven to work.
928 // If dir.size() > max length, all bets are off for YAP. We truncate
929 // the filename nevertheless, keeping a minimum of 10 chars.
931 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
933 // If the mangled file name is too long, hack it to fit.
934 // We know we're guaranteed to have a unique file name because
936 if (mname.size() > max_length) {
937 int const half = (int(max_length) / 2) - 2;
939 mname = mname.substr(0, half) + "___" +
940 mname.substr(mname.size() - half);
944 mangledNames[absFilename()] = mname;
949 bool DocFileName::isZipped() const
951 if (!zipped_valid_) {
952 zipped_ = isZippedFile();
953 zipped_valid_ = true;
959 string DocFileName::unzippedFilename() const
961 return unzippedFileName(absFilename());
965 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
967 return lhs.absFilename() == rhs.absFilename()
968 && lhs.saveAbsPath() == rhs.saveAbsPath();
972 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
974 return !(lhs == rhs);
977 } // namespace support