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.2.0, at least, that causes problems with
100 // QFileInfo::refresh() on *nix. So we recreate the object in that case.
101 // FIXME: When Trolltech fixes the bug, we will have to replace 0x999999 below
102 // with the actual working minimum version.
103 #if defined(_WIN32) || (QT_VERSION >= 0x999999)
106 fi = QFileInfo(fi.absoluteFilePath());
113 /////////////////////////////////////////////////////////////////////
117 /////////////////////////////////////////////////////////////////////
120 FileName::FileName() : d(new Private)
125 FileName::FileName(string const & abs_filename)
126 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
131 FileName::~FileName()
137 FileName::FileName(FileName const & rhs) : d(new Private)
143 FileName & FileName::operator=(FileName const & rhs)
150 bool FileName::empty() const
152 return d->fi.absoluteFilePath().isEmpty();
156 bool FileName::isAbsolute() const
158 return d->fi.isAbsolute();
162 string FileName::absFilename() const
164 return fromqstr(d->fi.absoluteFilePath());
168 void FileName::set(string const & name)
170 d->fi.setFile(toqstr(name));
174 void FileName::erase()
180 bool FileName::copyTo(FileName const & name) const
182 LYXERR(Debug::FILES, "Copying " << name);
183 QFile::remove(name.d->fi.absoluteFilePath());
184 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
186 LYXERR0("FileName::copyTo(): Could not copy file "
187 << *this << " to " << name);
192 bool FileName::renameTo(FileName const & name) const
194 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
196 LYXERR0("Could not rename file " << *this << " to " << name);
201 bool FileName::moveTo(FileName const & name) const
203 QFile::remove(name.d->fi.absoluteFilePath());
205 bool success = QFile::rename(d->fi.absoluteFilePath(),
206 name.d->fi.absoluteFilePath());
208 LYXERR0("Could not move file " << *this << " to " << name);
213 bool FileName::changePermission(unsigned long int mode) const
215 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
216 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
217 LYXERR0("File " << *this << ": cannot change permission to "
226 string FileName::toFilesystemEncoding() const
228 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
229 return string(encoded.begin(), encoded.end());
233 FileName FileName::fromFilesystemEncoding(string const & name)
235 QByteArray const encoded(name.c_str(), name.length());
236 return FileName(fromqstr(QFile::decodeName(encoded)));
240 bool FileName::exists() const
242 return d->fi.exists();
246 bool FileName::isSymLink() const
248 return d->fi.isSymLink();
252 bool FileName::isFileEmpty() const
254 return d->fi.size() == 0;
258 bool FileName::isDirectory() const
260 return d->fi.isDir();
264 bool FileName::isReadOnly() const
266 return d->fi.isReadable() && !d->fi.isWritable();
270 bool FileName::isReadableDirectory() const
272 return d->fi.isDir() && d->fi.isReadable();
276 string FileName::onlyFileName() const
278 return fromqstr(d->fi.fileName());
282 string FileName::onlyFileNameWithoutExt() const
284 return fromqstr(d->fi.baseName());
288 FileName FileName::onlyPath() const
291 path.d->fi.setFile(d->fi.path());
296 bool FileName::isReadableFile() const
298 return d->fi.isFile() && d->fi.isReadable();
302 bool FileName::isWritable() const
304 return d->fi.isWritable();
308 bool FileName::isDirWritable() const
310 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
312 FileName const tmpfl = FileName::tempName(absFilename() + "/lyxwritetest");
322 FileNameList FileName::dirList(string const & ext) const
324 FileNameList dirlist;
325 if (!isDirectory()) {
326 LYXERR0("Directory '" << *this << "' does not exist!");
330 QDir dir = d->fi.absoluteDir();
335 case '.': filter = "*" + toqstr(ext); break;
336 case '*': filter = toqstr(ext); break;
337 default: filter = "*." + toqstr(ext);
339 dir.setNameFilters(QStringList(filter));
340 LYXERR(Debug::FILES, "filtering on extension "
341 << fromqstr(filter) << " is requested.");
344 QFileInfoList list = dir.entryInfoList();
345 for (int i = 0; i != list.size(); ++i) {
346 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
347 dirlist.push_back(fi);
348 LYXERR(Debug::FILES, "found file " << fi);
355 static int make_tempfile(char * templ)
357 #if defined(HAVE_MKSTEMP)
358 return ::mkstemp(templ);
359 #elif defined(HAVE_MKTEMP)
360 // This probably just barely works...
362 # if defined (HAVE_OPEN)
363 # if (!defined S_IRUSR)
364 # define S_IRUSR S_IREAD
365 # define S_IWUSR S_IWRITE
367 return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
368 # elif defined (HAVE__OPEN)
369 return ::_open(templ,
370 _O_RDWR | _O_CREAT | _O_EXCL,
371 _S_IREAD | _S_IWRITE);
373 # error No open() function.
381 FileName FileName::tempName(string const & mask)
383 FileName tmp_name(mask);
385 if (tmp_name.d->fi.isAbsolute())
388 tmpfl = package().temp_dir().absFilename() + "/" + mask;
390 #if defined (HAVE_GETPID)
391 tmpfl += convert<string>(getpid());
392 #elif defined (HAVE__GETPID)
393 tmpfl += convert<string>(_getpid());
395 # error No getpid() function
399 // The supposedly safe mkstemp version
400 // FIXME: why not using std::string directly?
401 boost::scoped_array<char> tmpl(new char[tmpfl.length() + 1]); // + 1 for '\0'
402 tmpfl.copy(tmpl.get(), string::npos);
403 tmpl[tmpfl.length()] = '\0'; // terminator
405 int const tmpf = make_tempfile(tmpl.get());
407 string const t(to_utf8(from_filesystem8bit(tmpl.get())));
408 #if defined (HAVE_CLOSE)
410 #elif defined (HAVE__CLOSE)
413 # error No x() function.
415 LYXERR(Debug::FILES, "Temporary file `" << t << "' created.");
418 LYXERR(Debug::FILES, "LyX Error: Unable to create temporary file.");
423 FileName FileName::getcwd()
425 return FileName(".");
429 time_t FileName::lastModified() const
431 // QFileInfo caches information about the file. So, in case this file has
432 // been touched between the object creation and now, we refresh the file
435 return d->fi.lastModified().toTime_t();
439 bool FileName::chdir() const
441 return QDir::setCurrent(d->fi.absoluteFilePath());
445 extern unsigned long sum(char const * file);
447 unsigned long FileName::checksum() const
450 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
453 // a directory may be passed here so we need to test it. (bug 3622)
455 LYXERR0('"' << absFilename() << "\" is a directory!");
458 if (!lyxerr.debugging(Debug::FILES))
459 return sum(absFilename().c_str());
463 unsigned long r = sum(absFilename().c_str());
464 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
465 << t.elapsed() << " ms." << endl;
470 bool FileName::removeFile() const
472 bool const success = QFile::remove(d->fi.absoluteFilePath());
473 if (!success && exists())
474 LYXERR0("Could not delete file " << *this);
479 static bool rmdir(QFileInfo const & fi)
481 QDir dir(fi.absoluteFilePath());
482 QFileInfoList list = dir.entryInfoList();
484 for (int i = 0; i != list.size(); ++i) {
485 if (list.at(i).fileName() == ".")
487 if (list.at(i).fileName() == "..")
490 if (list.at(i).isDir()) {
491 LYXERR(Debug::FILES, "Removing dir "
492 << fromqstr(list.at(i).absoluteFilePath()));
493 removed = rmdir(list.at(i));
496 LYXERR(Debug::FILES, "Removing file "
497 << fromqstr(list.at(i).absoluteFilePath()));
498 removed = dir.remove(list.at(i).fileName());
502 LYXERR0("Could not delete "
503 << fromqstr(list.at(i).absoluteFilePath()));
506 QDir parent = fi.absolutePath();
507 success &= parent.rmdir(fi.fileName());
512 bool FileName::destroyDirectory() const
514 bool const success = rmdir(d->fi);
516 LYXERR0("Could not delete " << *this);
522 static int mymkdir(char const * pathname, unsigned long int mode)
524 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
526 # if MKDIR_TAKES_ONE_ARG
528 return ::mkdir(pathname);
529 // FIXME: "Permissions of created directories are ignored on this system."
532 return ::mkdir(pathname, mode_t(mode));
534 #elif defined(_WIN32)
536 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
537 // FIXME: "Permissions of created directories are ignored on this system."
539 return ::_mkdir(pathname);
540 // FIXME: "Permissions of created directories are ignored on this system."
542 # error "Don't know how to create a directory on this system."
548 bool FileName::createDirectory(int permission) const
550 LASSERT(!empty(), /**/);
551 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
555 bool FileName::createPath() const
557 LASSERT(!empty(), /**/);
562 bool success = dir.mkpath(d->fi.absoluteFilePath());
564 LYXERR0("Cannot create path '" << *this << "'!");
569 docstring const FileName::absoluteFilePath() const
571 return qstring_to_ucs4(d->fi.absoluteFilePath());
575 docstring FileName::displayName(int threshold) const
577 return makeDisplayPath(absFilename(), threshold);
581 docstring FileName::fileContents(string const & encoding) const
583 if (!isReadableFile()) {
584 LYXERR0("File '" << *this << "' is not redable!");
588 QFile file(d->fi.absoluteFilePath());
589 if (!file.open(QIODevice::ReadOnly)) {
590 LYXERR0("File '" << *this
591 << "' could not be opened in read only mode!");
594 QByteArray contents = file.readAll();
597 if (contents.isEmpty()) {
598 LYXERR(Debug::FILES, "File '" << *this
599 << "' is either empty or some error happened while reading it.");
604 if (encoding.empty() || encoding == "UTF-8")
605 s = QString::fromUtf8(contents.data());
606 else if (encoding == "ascii")
607 s = QString::fromAscii(contents.data());
608 else if (encoding == "local8bit")
609 s = QString::fromLocal8Bit(contents.data());
610 else if (encoding == "latin1")
611 s = QString::fromLatin1(contents.data());
613 return qstring_to_ucs4(s);
617 void FileName::changeExtension(string const & extension)
619 // FIXME: use Qt native methods...
620 string const oldname = absFilename();
621 string::size_type const last_slash = oldname.rfind('/');
622 string::size_type last_dot = oldname.rfind('.');
623 if (last_dot < last_slash && last_slash != string::npos)
624 last_dot = string::npos;
627 // Make sure the extension starts with a dot
628 if (!extension.empty() && extension[0] != '.')
629 ext= '.' + extension;
633 set(oldname.substr(0, last_dot) + ext);
637 string FileName::guessFormatFromContents() const
639 // the different filetypes and what they contain in one of the first lines
640 // (dots are any characters). (Herbert 20020131)
643 // EPS %!PS-Adobe-3.0 EPSF...
650 // PBM P1... or P4 (B/W)
651 // PGM P2... or P5 (Grayscale)
652 // PPM P3... or P6 (color)
653 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
654 // SGI \001\332... (decimal 474)
656 // TIFF II... or MM...
658 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
659 // ...static char *...
660 // XWD \000\000\000\151 (0x00006900) decimal 105
662 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
663 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
664 // Z \037\235 UNIX compress
667 if (empty() || !isReadableFile())
670 ifstream ifs(toFilesystemEncoding().c_str());
672 // Couldn't open file...
676 static string const gzipStamp = "\037\213";
679 static string const zipStamp = "PK";
682 static string const compressStamp = "\037\235";
684 // Maximum strings to read
685 int const max_count = 50;
690 bool firstLine = true;
691 while ((count++ < max_count) && format.empty()) {
693 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
694 << "\tFile type not recognised before EOF!");
699 string const stamp = str.substr(0, 2);
700 if (firstLine && str.size() >= 2) {
701 // at first we check for a zipped file, because this
702 // information is saved in the first bytes of the file!
703 // also some graphic formats which save the information
704 // in the first line, too.
705 if (prefixIs(str, gzipStamp)) {
708 } else if (stamp == zipStamp) {
711 } else if (stamp == compressStamp) {
715 } else if (stamp == "BM") {
718 } else if (stamp == "\001\332") {
722 // Don't need to use str.at(0), str.at(1) because
723 // we already know that str.size() >= 2
724 } else if (str[0] == 'P') {
740 } else if ((stamp == "II") || (stamp == "MM")) {
743 } else if (prefixIs(str,"%TGIF")) {
746 } else if (prefixIs(str,"#FIG")) {
749 } else if (prefixIs(str,"GIF")) {
752 } else if (str.size() > 3) {
753 int const c = ((str[0] << 24) & (str[1] << 16) &
754 (str[2] << 8) & str[3]);
765 else if (contains(str,"EPSF"))
766 // dummy, if we have wrong file description like
767 // %!PS-Adobe-2.0EPSF"
770 else if (contains(str, "Grace"))
773 else if (contains(str, "JFIF"))
776 else if (contains(str, "%PDF"))
779 else if (contains(str, "PNG"))
782 else if (contains(str, "%!PS-Adobe")) {
785 if (contains(str,"EPSF"))
791 else if (contains(str, "_bits[]"))
794 else if (contains(str, "XPM") || contains(str, "static char *"))
797 else if (contains(str, "BITPIX"))
801 if (!format.empty()) {
802 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
806 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
807 << "\tCouldn't find a known format!");
812 bool FileName::isZippedFile() const
814 string const type = guessFormatFromContents();
815 return contains("gzip zip compress", type) && !type.empty();
819 docstring const FileName::relPath(string const & path) const
822 return makeRelPath(absoluteFilePath(), from_utf8(path));
826 bool operator==(FileName const & lhs, FileName const & rhs)
828 return lhs.absFilename() == rhs.absFilename();
832 bool operator!=(FileName const & lhs, FileName const & rhs)
834 return lhs.absFilename() != rhs.absFilename();
838 bool operator<(FileName const & lhs, FileName const & rhs)
840 return lhs.absFilename() < rhs.absFilename();
844 bool operator>(FileName const & lhs, FileName const & rhs)
846 return lhs.absFilename() > rhs.absFilename();
850 ostream & operator<<(ostream & os, FileName const & filename)
852 return os << filename.absFilename();
856 /////////////////////////////////////////////////////////////////////
860 /////////////////////////////////////////////////////////////////////
863 DocFileName::DocFileName()
864 : save_abs_path_(true)
868 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
869 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
873 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
874 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
878 void DocFileName::set(string const & name, string const & buffer_path)
881 bool const nameIsAbsolute = isAbsolute();
882 save_abs_path_ = nameIsAbsolute;
884 FileName::set(makeAbsPath(name, buffer_path).absFilename());
885 zipped_valid_ = false;
889 void DocFileName::erase()
892 zipped_valid_ = false;
896 string DocFileName::relFilename(string const & path) const
899 return to_utf8(relPath(path));
903 string DocFileName::outputFilename(string const & path) const
905 return save_abs_path_ ? absFilename() : relFilename(path);
909 string DocFileName::mangledFilename(string const & dir) const
911 // We need to make sure that every DocFileName instance for a given
912 // filename returns the same mangled name.
913 typedef map<string, string> MangledMap;
914 static MangledMap mangledNames;
915 MangledMap::const_iterator const it = mangledNames.find(absFilename());
916 if (it != mangledNames.end())
919 string const name = absFilename();
921 string mname = os::internal_path(name);
922 // Remove the extension.
923 mname = support::changeExtension(name, string());
924 // The mangled name must be a valid LaTeX name.
925 // The list of characters to keep is probably over-restrictive,
926 // but it is not really a problem.
927 // Apart from non-ASCII characters, at least the following characters
928 // are forbidden: '/', '.', ' ', and ':'.
929 // On windows it is not possible to create files with '<', '>' or '?'
931 static string const keep = "abcdefghijklmnopqrstuvwxyz"
932 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
934 string::size_type pos = 0;
935 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
937 // Add the extension back on
938 mname = support::changeExtension(mname, getExtension(name));
940 // Prepend a counter to the filename. This is necessary to make
941 // the mangled name unique.
942 static int counter = 0;
944 s << counter++ << mname;
947 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
948 // is longer than about 160 characters. MiKTeX's pdflatex
949 // is even pickier. A maximum length of 100 has been proven to work.
950 // If dir.size() > max length, all bets are off for YAP. We truncate
951 // the filename nevertheless, keeping a minimum of 10 chars.
953 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
955 // If the mangled file name is too long, hack it to fit.
956 // We know we're guaranteed to have a unique file name because
958 if (mname.size() > max_length) {
959 int const half = (int(max_length) / 2) - 2;
961 mname = mname.substr(0, half) + "___" +
962 mname.substr(mname.size() - half);
966 mangledNames[absFilename()] = mname;
971 bool DocFileName::isZipped() const
973 if (!zipped_valid_) {
974 zipped_ = isZippedFile();
975 zipped_valid_ = true;
981 string DocFileName::unzippedFilename() const
983 return unzippedFileName(absFilename());
987 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
989 return lhs.absFilename() == rhs.absFilename()
990 && lhs.saveAbsPath() == rhs.saveAbsPath();
994 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
996 return !(lhs == rhs);
999 } // namespace support