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 FileName FileName::getcwd()
404 return FileName(".");
408 time_t FileName::lastModified() const
410 return d->fi.lastModified().toTime_t();
414 bool FileName::chdir() const
416 return QDir::setCurrent(d->fi.absoluteFilePath());
420 extern unsigned long sum(char const * file);
422 unsigned long FileName::checksum() const
425 LYXERR0("File \"" << absFilename() << "\" does not exist!");
428 // a directory may be passed here so we need to test it. (bug 3622)
430 LYXERR0('"' << absFilename() << "\" is a directory!");
433 if (!lyxerr.debugging(Debug::FILES))
434 return sum(absFilename().c_str());
438 unsigned long r = sum(absFilename().c_str());
439 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
440 << t.elapsed() << " ms." << endl;
445 bool FileName::removeFile() const
447 bool const success = QFile::remove(d->fi.absoluteFilePath());
448 if (!success && exists())
449 LYXERR0("Could not delete file " << *this);
454 static bool rmdir(QFileInfo const & fi)
456 QDir dir(fi.absoluteFilePath());
457 QFileInfoList list = dir.entryInfoList();
459 for (int i = 0; i != list.size(); ++i) {
460 if (list.at(i).fileName() == ".")
462 if (list.at(i).fileName() == "..")
465 if (list.at(i).isDir()) {
466 LYXERR(Debug::FILES, "Removing dir "
467 << fromqstr(list.at(i).absoluteFilePath()));
468 removed = rmdir(list.at(i));
471 LYXERR(Debug::FILES, "Removing file "
472 << fromqstr(list.at(i).absoluteFilePath()));
473 removed = dir.remove(list.at(i).fileName());
477 LYXERR0("Could not delete "
478 << fromqstr(list.at(i).absoluteFilePath()));
481 QDir parent = fi.absolutePath();
482 success &= parent.rmdir(fi.fileName());
487 bool FileName::destroyDirectory() const
489 bool const success = rmdir(d->fi);
491 LYXERR0("Could not delete " << *this);
497 static int mymkdir(char const * pathname, unsigned long int mode)
499 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
501 # if MKDIR_TAKES_ONE_ARG
503 return ::mkdir(pathname);
504 // FIXME: "Permissions of created directories are ignored on this system."
507 return ::mkdir(pathname, mode_t(mode));
509 #elif defined(_WIN32)
511 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
512 // FIXME: "Permissions of created directories are ignored on this system."
514 return ::_mkdir(pathname);
515 // FIXME: "Permissions of created directories are ignored on this system."
517 # error "Don't know how to create a directory on this system."
523 bool FileName::createDirectory(int permission) const
525 BOOST_ASSERT(!empty());
526 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
530 bool FileName::createPath() const
532 BOOST_ASSERT(!empty());
537 bool success = dir.mkpath(d->fi.absoluteFilePath());
539 LYXERR0("Cannot create path '" << *this << "'!");
544 docstring const FileName::absoluteFilePath() const
546 return qstring_to_ucs4(d->fi.absoluteFilePath());
550 docstring FileName::displayName(int threshold) const
552 return makeDisplayPath(absFilename(), threshold);
556 docstring FileName::fileContents(string const & encoding) const
558 if (!isReadableFile()) {
559 LYXERR0("File '" << *this << "' is not redable!");
563 QFile file(d->fi.absoluteFilePath());
564 if (!file.open(QIODevice::ReadOnly)) {
565 LYXERR0("File '" << *this
566 << "' could not be opened in read only mode!");
569 QByteArray contents = file.readAll();
572 if (contents.isEmpty()) {
573 LYXERR(Debug::FILES, "File '" << *this
574 << "' is either empty or some error happened while reading it.");
579 if (encoding.empty() || encoding == "UTF-8")
580 s = QString::fromUtf8(contents.data());
581 else if (encoding == "ascii")
582 s = QString::fromAscii(contents.data());
583 else if (encoding == "local8bit")
584 s = QString::fromLocal8Bit(contents.data());
585 else if (encoding == "latin1")
586 s = QString::fromLatin1(contents.data());
588 return qstring_to_ucs4(s);
592 void FileName::changeExtension(string const & extension)
594 // FIXME: use Qt native methods...
595 string const oldname = absFilename();
596 string::size_type const last_slash = oldname.rfind('/');
597 string::size_type last_dot = oldname.rfind('.');
598 if (last_dot < last_slash && last_slash != string::npos)
599 last_dot = string::npos;
602 // Make sure the extension starts with a dot
603 if (!extension.empty() && extension[0] != '.')
604 ext= '.' + extension;
608 set(oldname.substr(0, last_dot) + ext);
612 string FileName::guessFormatFromContents() const
614 // the different filetypes and what they contain in one of the first lines
615 // (dots are any characters). (Herbert 20020131)
618 // EPS %!PS-Adobe-3.0 EPSF...
625 // PBM P1... or P4 (B/W)
626 // PGM P2... or P5 (Grayscale)
627 // PPM P3... or P6 (color)
628 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
629 // SGI \001\332... (decimal 474)
631 // TIFF II... or MM...
633 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
634 // ...static char *...
635 // XWD \000\000\000\151 (0x00006900) decimal 105
637 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
638 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
639 // Z \037\235 UNIX compress
642 if (empty() || !isReadableFile())
645 ifstream ifs(toFilesystemEncoding().c_str());
647 // Couldn't open file...
651 static string const gzipStamp = "\037\213";
654 static string const zipStamp = "PK";
657 static string const compressStamp = "\037\235";
659 // Maximum strings to read
660 int const max_count = 50;
665 bool firstLine = true;
666 while ((count++ < max_count) && format.empty()) {
668 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
669 << "\tFile type not recognised before EOF!");
674 string const stamp = str.substr(0, 2);
675 if (firstLine && str.size() >= 2) {
676 // at first we check for a zipped file, because this
677 // information is saved in the first bytes of the file!
678 // also some graphic formats which save the information
679 // in the first line, too.
680 if (prefixIs(str, gzipStamp)) {
683 } else if (stamp == zipStamp) {
686 } else if (stamp == compressStamp) {
690 } else if (stamp == "BM") {
693 } else if (stamp == "\001\332") {
697 // Don't need to use str.at(0), str.at(1) because
698 // we already know that str.size() >= 2
699 } else if (str[0] == 'P') {
715 } else if ((stamp == "II") || (stamp == "MM")) {
718 } else if (prefixIs(str,"%TGIF")) {
721 } else if (prefixIs(str,"#FIG")) {
724 } else if (prefixIs(str,"GIF")) {
727 } else if (str.size() > 3) {
728 int const c = ((str[0] << 24) & (str[1] << 16) &
729 (str[2] << 8) & str[3]);
740 else if (contains(str,"EPSF"))
741 // dummy, if we have wrong file description like
742 // %!PS-Adobe-2.0EPSF"
745 else if (contains(str, "Grace"))
748 else if (contains(str, "JFIF"))
751 else if (contains(str, "%PDF"))
754 else if (contains(str, "PNG"))
757 else if (contains(str, "%!PS-Adobe")) {
760 if (contains(str,"EPSF"))
766 else if (contains(str, "_bits[]"))
769 else if (contains(str, "XPM") || contains(str, "static char *"))
772 else if (contains(str, "BITPIX"))
776 if (!format.empty()) {
777 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
781 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
782 << "\tCouldn't find a known format!");
787 bool FileName::isZippedFile() const
789 string const type = guessFormatFromContents();
790 return contains("gzip zip compress", type) && !type.empty();
794 docstring const FileName::relPath(string const & path) const
797 return makeRelPath(absoluteFilePath(), from_utf8(path));
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 bool operator>(FileName const & lhs, FileName const & rhs)
821 return lhs.absFilename() > rhs.absFilename();
825 ostream & operator<<(ostream & os, FileName const & filename)
827 return os << filename.absFilename();
831 /////////////////////////////////////////////////////////////////////
835 /////////////////////////////////////////////////////////////////////
838 DocFileName::DocFileName()
839 : save_abs_path_(true)
843 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
844 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
848 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
849 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
853 void DocFileName::set(string const & name, string const & buffer_path)
855 save_abs_path_ = absolutePath(name);
856 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
857 zipped_valid_ = false;
861 void DocFileName::erase()
864 zipped_valid_ = false;
868 string DocFileName::relFilename(string const & path) const
871 return to_utf8(relPath(path));
875 string DocFileName::outputFilename(string const & path) const
877 return save_abs_path_ ? absFilename() : relFilename(path);
881 string DocFileName::mangledFilename(string const & dir) const
883 // We need to make sure that every DocFileName instance for a given
884 // filename returns the same mangled name.
885 typedef map<string, string> MangledMap;
886 static MangledMap mangledNames;
887 MangledMap::const_iterator const it = mangledNames.find(absFilename());
888 if (it != mangledNames.end())
891 string const name = absFilename();
893 string mname = os::internal_path(name);
894 // Remove the extension.
895 mname = support::changeExtension(name, string());
896 // The mangled name must be a valid LaTeX name.
897 // The list of characters to keep is probably over-restrictive,
898 // but it is not really a problem.
899 // Apart from non-ASCII characters, at least the following characters
900 // are forbidden: '/', '.', ' ', and ':'.
901 // On windows it is not possible to create files with '<', '>' or '?'
903 static string const keep = "abcdefghijklmnopqrstuvwxyz"
904 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
906 string::size_type pos = 0;
907 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
909 // Add the extension back on
910 mname = support::changeExtension(mname, getExtension(name));
912 // Prepend a counter to the filename. This is necessary to make
913 // the mangled name unique.
914 static int counter = 0;
916 s << counter++ << mname;
919 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
920 // is longer than about 160 characters. MiKTeX's pdflatex
921 // is even pickier. A maximum length of 100 has been proven to work.
922 // If dir.size() > max length, all bets are off for YAP. We truncate
923 // the filename nevertheless, keeping a minimum of 10 chars.
925 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
927 // If the mangled file name is too long, hack it to fit.
928 // We know we're guaranteed to have a unique file name because
930 if (mname.size() > max_length) {
931 int const half = (int(max_length) / 2) - 2;
933 mname = mname.substr(0, half) + "___" +
934 mname.substr(mname.size() - half);
938 mangledNames[absFilename()] = mname;
943 bool DocFileName::isZipped() const
945 if (!zipped_valid_) {
946 zipped_ = isZippedFile();
947 zipped_valid_ = true;
953 string DocFileName::unzippedFilename() const
955 return unzippedFileName(absFilename());
959 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
961 return lhs.absFilename() == rhs.absFilename()
962 && lhs.saveAbsPath() == rhs.saveAbsPath();
966 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
968 return !(lhs == rhs);
971 } // namespace support