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 "support/lassert.h"
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);
99 // There seems to be a bug in Qt 4.3.5, at least, that causes problems with
100 // QFileInfo::refresh() on Linux. So we recreate the object in that case.
101 #if defined(__linux__) && (QT_VERSION >= 0x040300)
102 fi = QFileInfo(fi.absoluteFilePath());
111 /////////////////////////////////////////////////////////////////////
115 /////////////////////////////////////////////////////////////////////
118 FileName::FileName() : d(new Private)
123 FileName::FileName(string const & abs_filename)
124 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
129 FileName::~FileName()
135 FileName::FileName(FileName const & rhs) : d(new Private)
141 FileName & FileName::operator=(FileName const & rhs)
148 bool FileName::empty() const
150 return d->fi.absoluteFilePath().isEmpty();
154 bool FileName::isAbsolute() const
156 return d->fi.isAbsolute();
160 string FileName::absFilename() const
162 return fromqstr(d->fi.absoluteFilePath());
166 void FileName::set(string const & name)
168 d->fi.setFile(toqstr(name));
172 void FileName::erase()
178 bool FileName::copyTo(FileName const & name) const
180 LYXERR(Debug::FILES, "Copying " << name);
181 QFile::remove(name.d->fi.absoluteFilePath());
182 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
184 LYXERR0("FileName::copyTo(): Could not copy file "
185 << *this << " to " << name);
190 bool FileName::renameTo(FileName const & name) const
192 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
194 LYXERR0("Could not rename file " << *this << " to " << name);
199 bool FileName::moveTo(FileName const & name) const
201 QFile::remove(name.d->fi.absoluteFilePath());
203 bool success = QFile::rename(d->fi.absoluteFilePath(),
204 name.d->fi.absoluteFilePath());
206 LYXERR0("Could not move file " << *this << " to " << name);
211 bool FileName::changePermission(unsigned long int mode) const
213 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
214 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
215 LYXERR0("File " << *this << ": cannot change permission to "
224 string FileName::toFilesystemEncoding() const
226 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
227 return string(encoded.begin(), encoded.end());
231 FileName FileName::fromFilesystemEncoding(string const & name)
233 QByteArray const encoded(name.c_str(), name.length());
234 return FileName(fromqstr(QFile::decodeName(encoded)));
238 bool FileName::exists() const
240 return d->fi.exists();
244 bool FileName::isSymLink() const
246 return d->fi.isSymLink();
250 bool FileName::isFileEmpty() const
252 return d->fi.size() == 0;
256 bool FileName::isDirectory() const
258 return d->fi.isDir();
262 bool FileName::isReadOnly() const
264 return d->fi.isReadable() && !d->fi.isWritable();
268 bool FileName::isReadableDirectory() const
270 return d->fi.isDir() && d->fi.isReadable();
274 string FileName::onlyFileName() const
276 return fromqstr(d->fi.fileName());
280 string FileName::onlyFileNameWithoutExt() const
282 return fromqstr(d->fi.baseName());
286 FileName FileName::onlyPath() const
289 path.d->fi.setFile(d->fi.path());
294 bool FileName::isReadableFile() const
296 return d->fi.isFile() && d->fi.isReadable();
300 bool FileName::isWritable() const
302 return d->fi.isWritable();
306 bool FileName::isDirWritable() const
308 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
310 FileName const tmpfl = FileName::tempName(absFilename() + "/lyxwritetest");
320 FileNameList FileName::dirList(string const & ext) const
322 FileNameList dirlist;
323 if (!isDirectory()) {
324 LYXERR0("Directory '" << *this << "' does not exist!");
328 QDir dir = d->fi.absoluteDir();
333 case '.': filter = "*" + toqstr(ext); break;
334 case '*': filter = toqstr(ext); break;
335 default: filter = "*." + toqstr(ext);
337 dir.setNameFilters(QStringList(filter));
338 LYXERR(Debug::FILES, "filtering on extension "
339 << fromqstr(filter) << " is requested.");
342 QFileInfoList list = dir.entryInfoList();
343 for (int i = 0; i != list.size(); ++i) {
344 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
345 dirlist.push_back(fi);
346 LYXERR(Debug::FILES, "found file " << fi);
353 static int make_tempfile(char * templ)
355 #if defined(HAVE_MKSTEMP)
356 return ::mkstemp(templ);
357 #elif defined(HAVE_MKTEMP)
358 // This probably just barely works...
360 # if defined (HAVE_OPEN)
361 # if (!defined S_IRUSR)
362 # define S_IRUSR S_IREAD
363 # define S_IWUSR S_IWRITE
365 return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
366 # elif defined (HAVE__OPEN)
367 return ::_open(templ,
368 _O_RDWR | _O_CREAT | _O_EXCL,
369 _S_IREAD | _S_IWRITE);
371 # error No open() function.
379 FileName FileName::tempName(string const & mask)
381 FileName tmp_name(mask);
383 if (tmp_name.d->fi.isAbsolute())
386 tmpfl = package().temp_dir().absFilename() + "/" + mask;
388 #if defined (HAVE_GETPID)
389 tmpfl += convert<string>(getpid());
390 #elif defined (HAVE__GETPID)
391 tmpfl += convert<string>(_getpid());
393 # error No getpid() function
397 // The supposedly safe mkstemp version
398 // FIXME: why not using std::string directly?
399 boost::scoped_array<char> tmpl(new char[tmpfl.length() + 1]); // + 1 for '\0'
400 tmpfl.copy(tmpl.get(), string::npos);
401 tmpl[tmpfl.length()] = '\0'; // terminator
403 int const tmpf = make_tempfile(tmpl.get());
405 string const t(to_utf8(from_filesystem8bit(tmpl.get())));
406 #if defined (HAVE_CLOSE)
408 #elif defined (HAVE__CLOSE)
411 # error No x() function.
413 LYXERR(Debug::FILES, "Temporary file `" << t << "' created.");
416 LYXERR(Debug::FILES, "LyX Error: Unable to create temporary file.");
421 FileName FileName::getcwd()
423 return FileName(".");
427 time_t FileName::lastModified() const
429 // QFileInfo caches information about the file. So, in case this file has
430 // been touched between the object creation and now, we refresh the file
433 return d->fi.lastModified().toTime_t();
437 bool FileName::chdir() const
439 return QDir::setCurrent(d->fi.absoluteFilePath());
443 extern unsigned long sum(char const * file);
445 unsigned long FileName::checksum() const
448 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
451 // a directory may be passed here so we need to test it. (bug 3622)
453 LYXERR0('"' << absFilename() << "\" is a directory!");
456 if (!lyxerr.debugging(Debug::FILES))
457 return sum(absFilename().c_str());
461 unsigned long r = sum(absFilename().c_str());
462 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
463 << t.elapsed() << " ms." << endl;
468 bool FileName::removeFile() const
470 bool const success = QFile::remove(d->fi.absoluteFilePath());
471 if (!success && exists())
472 LYXERR0("Could not delete file " << *this);
477 static bool rmdir(QFileInfo const & fi)
479 QDir dir(fi.absoluteFilePath());
480 QFileInfoList list = dir.entryInfoList();
482 for (int i = 0; i != list.size(); ++i) {
483 if (list.at(i).fileName() == ".")
485 if (list.at(i).fileName() == "..")
488 if (list.at(i).isDir()) {
489 LYXERR(Debug::FILES, "Removing dir "
490 << fromqstr(list.at(i).absoluteFilePath()));
491 removed = rmdir(list.at(i));
494 LYXERR(Debug::FILES, "Removing file "
495 << fromqstr(list.at(i).absoluteFilePath()));
496 removed = dir.remove(list.at(i).fileName());
500 LYXERR0("Could not delete "
501 << fromqstr(list.at(i).absoluteFilePath()));
504 QDir parent = fi.absolutePath();
505 success &= parent.rmdir(fi.fileName());
510 bool FileName::destroyDirectory() const
512 bool const success = rmdir(d->fi);
514 LYXERR0("Could not delete " << *this);
520 static int mymkdir(char const * pathname, unsigned long int mode)
522 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
524 # if MKDIR_TAKES_ONE_ARG
526 return ::mkdir(pathname);
527 // FIXME: "Permissions of created directories are ignored on this system."
530 return ::mkdir(pathname, mode_t(mode));
532 #elif defined(_WIN32)
534 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
535 // FIXME: "Permissions of created directories are ignored on this system."
537 return ::_mkdir(pathname);
538 // FIXME: "Permissions of created directories are ignored on this system."
540 # error "Don't know how to create a directory on this system."
546 bool FileName::createDirectory(int permission) const
548 LASSERT(!empty(), /**/);
549 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
553 bool FileName::createPath() const
555 LASSERT(!empty(), /**/);
560 bool success = dir.mkpath(d->fi.absoluteFilePath());
562 LYXERR0("Cannot create path '" << *this << "'!");
567 docstring const FileName::absoluteFilePath() const
569 return qstring_to_ucs4(d->fi.absoluteFilePath());
573 docstring FileName::displayName(int threshold) const
575 return makeDisplayPath(absFilename(), threshold);
579 docstring FileName::fileContents(string const & encoding) const
581 if (!isReadableFile()) {
582 LYXERR0("File '" << *this << "' is not redable!");
586 QFile file(d->fi.absoluteFilePath());
587 if (!file.open(QIODevice::ReadOnly)) {
588 LYXERR0("File '" << *this
589 << "' could not be opened in read only mode!");
592 QByteArray contents = file.readAll();
595 if (contents.isEmpty()) {
596 LYXERR(Debug::FILES, "File '" << *this
597 << "' is either empty or some error happened while reading it.");
602 if (encoding.empty() || encoding == "UTF-8")
603 s = QString::fromUtf8(contents.data());
604 else if (encoding == "ascii")
605 s = QString::fromAscii(contents.data());
606 else if (encoding == "local8bit")
607 s = QString::fromLocal8Bit(contents.data());
608 else if (encoding == "latin1")
609 s = QString::fromLatin1(contents.data());
611 return qstring_to_ucs4(s);
615 void FileName::changeExtension(string const & extension)
617 // FIXME: use Qt native methods...
618 string const oldname = absFilename();
619 string::size_type const last_slash = oldname.rfind('/');
620 string::size_type last_dot = oldname.rfind('.');
621 if (last_dot < last_slash && last_slash != string::npos)
622 last_dot = string::npos;
625 // Make sure the extension starts with a dot
626 if (!extension.empty() && extension[0] != '.')
627 ext= '.' + extension;
631 set(oldname.substr(0, last_dot) + ext);
635 string FileName::guessFormatFromContents() const
637 // the different filetypes and what they contain in one of the first lines
638 // (dots are any characters). (Herbert 20020131)
641 // EPS %!PS-Adobe-3.0 EPSF...
648 // PBM P1... or P4 (B/W)
649 // PGM P2... or P5 (Grayscale)
650 // PPM P3... or P6 (color)
651 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
652 // SGI \001\332... (decimal 474)
654 // TIFF II... or MM...
656 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
657 // ...static char *...
658 // XWD \000\000\000\151 (0x00006900) decimal 105
660 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
661 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
662 // Z \037\235 UNIX compress
665 if (empty() || !isReadableFile())
668 ifstream ifs(toFilesystemEncoding().c_str());
670 // Couldn't open file...
674 static string const gzipStamp = "\037\213";
677 static string const zipStamp = "PK";
680 static string const compressStamp = "\037\235";
682 // Maximum strings to read
683 int const max_count = 50;
688 bool firstLine = true;
689 while ((count++ < max_count) && format.empty()) {
691 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
692 << "\tFile type not recognised before EOF!");
697 string const stamp = str.substr(0, 2);
698 if (firstLine && str.size() >= 2) {
699 // at first we check for a zipped file, because this
700 // information is saved in the first bytes of the file!
701 // also some graphic formats which save the information
702 // in the first line, too.
703 if (prefixIs(str, gzipStamp)) {
706 } else if (stamp == zipStamp) {
709 } else if (stamp == compressStamp) {
713 } else if (stamp == "BM") {
716 } else if (stamp == "\001\332") {
720 // Don't need to use str.at(0), str.at(1) because
721 // we already know that str.size() >= 2
722 } else if (str[0] == 'P') {
738 } else if ((stamp == "II") || (stamp == "MM")) {
741 } else if (prefixIs(str,"%TGIF")) {
744 } else if (prefixIs(str,"#FIG")) {
747 } else if (prefixIs(str,"GIF")) {
750 } else if (str.size() > 3) {
751 int const c = ((str[0] << 24) & (str[1] << 16) &
752 (str[2] << 8) & str[3]);
763 else if (contains(str,"EPSF"))
764 // dummy, if we have wrong file description like
765 // %!PS-Adobe-2.0EPSF"
768 else if (contains(str, "Grace"))
771 else if (contains(str, "JFIF"))
774 else if (contains(str, "%PDF"))
777 else if (contains(str, "PNG"))
780 else if (contains(str, "%!PS-Adobe")) {
783 if (contains(str,"EPSF"))
789 else if (contains(str, "_bits[]"))
792 else if (contains(str, "XPM") || contains(str, "static char *"))
795 else if (contains(str, "BITPIX"))
799 if (!format.empty()) {
800 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
804 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
805 << "\tCouldn't find a known format!");
810 bool FileName::isZippedFile() const
812 string const type = guessFormatFromContents();
813 return contains("gzip zip compress", type) && !type.empty();
817 docstring const FileName::relPath(string const & path) const
820 return makeRelPath(absoluteFilePath(), from_utf8(path));
824 bool operator==(FileName const & lhs, FileName const & rhs)
826 return lhs.absFilename() == rhs.absFilename();
830 bool operator!=(FileName const & lhs, FileName const & rhs)
832 return lhs.absFilename() != rhs.absFilename();
836 bool operator<(FileName const & lhs, FileName const & rhs)
838 return lhs.absFilename() < rhs.absFilename();
842 bool operator>(FileName const & lhs, FileName const & rhs)
844 return lhs.absFilename() > rhs.absFilename();
848 ostream & operator<<(ostream & os, FileName const & filename)
850 return os << filename.absFilename();
854 /////////////////////////////////////////////////////////////////////
858 /////////////////////////////////////////////////////////////////////
861 DocFileName::DocFileName()
862 : save_abs_path_(true)
866 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
867 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
871 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
872 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
876 void DocFileName::set(string const & name, string const & buffer_path)
879 bool const nameIsAbsolute = isAbsolute();
880 save_abs_path_ = nameIsAbsolute;
882 FileName::set(makeAbsPath(name, buffer_path).absFilename());
883 zipped_valid_ = false;
887 void DocFileName::erase()
890 zipped_valid_ = false;
894 string DocFileName::relFilename(string const & path) const
897 return to_utf8(relPath(path));
901 string DocFileName::outputFilename(string const & path) const
903 return save_abs_path_ ? absFilename() : relFilename(path);
907 string DocFileName::mangledFilename(string const & dir) const
909 // We need to make sure that every DocFileName instance for a given
910 // filename returns the same mangled name.
911 typedef map<string, string> MangledMap;
912 static MangledMap mangledNames;
913 MangledMap::const_iterator const it = mangledNames.find(absFilename());
914 if (it != mangledNames.end())
917 string const name = absFilename();
919 string mname = os::internal_path(name);
920 // Remove the extension.
921 mname = support::changeExtension(name, string());
922 // The mangled name must be a valid LaTeX name.
923 // The list of characters to keep is probably over-restrictive,
924 // but it is not really a problem.
925 // Apart from non-ASCII characters, at least the following characters
926 // are forbidden: '/', '.', ' ', and ':'.
927 // On windows it is not possible to create files with '<', '>' or '?'
929 static string const keep = "abcdefghijklmnopqrstuvwxyz"
930 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
932 string::size_type pos = 0;
933 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
935 // Add the extension back on
936 mname = support::changeExtension(mname, getExtension(name));
938 // Prepend a counter to the filename. This is necessary to make
939 // the mangled name unique.
940 static int counter = 0;
942 s << counter++ << mname;
945 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
946 // is longer than about 160 characters. MiKTeX's pdflatex
947 // is even pickier. A maximum length of 100 has been proven to work.
948 // If dir.size() > max length, all bets are off for YAP. We truncate
949 // the filename nevertheless, keeping a minimum of 10 chars.
951 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
953 // If the mangled file name is too long, hack it to fit.
954 // We know we're guaranteed to have a unique file name because
956 if (mname.size() > max_length) {
957 int const half = (int(max_length) / 2) - 2;
959 mname = mname.substr(0, half) + "___" +
960 mname.substr(mname.size() - half);
964 mangledNames[absFilename()] = mname;
969 bool DocFileName::isZipped() const
971 if (!zipped_valid_) {
972 zipped_ = isZippedFile();
973 zipped_valid_ = true;
979 string DocFileName::unzippedFilename() const
981 return unzippedFileName(absFilename());
985 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
987 return lhs.absFilename() == rhs.absFilename()
988 && lhs.saveAbsPath() == rhs.saveAbsPath();
992 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
994 return !(lhs == rhs);
997 } // namespace support