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 FileName FileName::tempPath()
431 return FileName(fromqstr(QDir::tempPath()));
435 time_t FileName::lastModified() const
437 // QFileInfo caches information about the file. So, in case this file has
438 // been touched between the object creation and now, we refresh the file
441 return d->fi.lastModified().toTime_t();
445 bool FileName::chdir() const
447 return QDir::setCurrent(d->fi.absoluteFilePath());
451 extern unsigned long sum(char const * file);
453 unsigned long FileName::checksum() const
456 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
459 // a directory may be passed here so we need to test it. (bug 3622)
461 LYXERR0('"' << absFilename() << "\" is a directory!");
464 if (!lyxerr.debugging(Debug::FILES))
465 return sum(absFilename().c_str());
469 unsigned long r = sum(absFilename().c_str());
470 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
471 << t.elapsed() << " ms." << endl;
476 bool FileName::removeFile() const
478 bool const success = QFile::remove(d->fi.absoluteFilePath());
479 if (!success && exists())
480 LYXERR0("Could not delete file " << *this);
485 static bool rmdir(QFileInfo const & fi)
487 QDir dir(fi.absoluteFilePath());
488 QFileInfoList list = dir.entryInfoList();
490 for (int i = 0; i != list.size(); ++i) {
491 if (list.at(i).fileName() == ".")
493 if (list.at(i).fileName() == "..")
496 if (list.at(i).isDir()) {
497 LYXERR(Debug::FILES, "Removing dir "
498 << fromqstr(list.at(i).absoluteFilePath()));
499 removed = rmdir(list.at(i));
502 LYXERR(Debug::FILES, "Removing file "
503 << fromqstr(list.at(i).absoluteFilePath()));
504 removed = dir.remove(list.at(i).fileName());
508 LYXERR0("Could not delete "
509 << fromqstr(list.at(i).absoluteFilePath()));
512 QDir parent = fi.absolutePath();
513 success &= parent.rmdir(fi.fileName());
518 bool FileName::destroyDirectory() const
520 bool const success = rmdir(d->fi);
522 LYXERR0("Could not delete " << *this);
528 static int mymkdir(char const * pathname, unsigned long int mode)
530 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
532 # if MKDIR_TAKES_ONE_ARG
534 return ::mkdir(pathname);
535 // FIXME: "Permissions of created directories are ignored on this system."
538 return ::mkdir(pathname, mode_t(mode));
540 #elif defined(_WIN32)
542 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
543 // FIXME: "Permissions of created directories are ignored on this system."
545 return ::_mkdir(pathname);
546 // FIXME: "Permissions of created directories are ignored on this system."
548 # error "Don't know how to create a directory on this system."
554 bool FileName::createDirectory(int permission) const
556 LASSERT(!empty(), /**/);
557 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
561 bool FileName::createPath() const
563 LASSERT(!empty(), /**/);
568 bool success = dir.mkpath(d->fi.absoluteFilePath());
570 LYXERR0("Cannot create path '" << *this << "'!");
575 docstring const FileName::absoluteFilePath() const
577 return qstring_to_ucs4(d->fi.absoluteFilePath());
581 docstring FileName::displayName(int threshold) const
583 return makeDisplayPath(absFilename(), threshold);
587 docstring FileName::fileContents(string const & encoding) const
589 if (!isReadableFile()) {
590 LYXERR0("File '" << *this << "' is not redable!");
594 QFile file(d->fi.absoluteFilePath());
595 if (!file.open(QIODevice::ReadOnly)) {
596 LYXERR0("File '" << *this
597 << "' could not be opened in read only mode!");
600 QByteArray contents = file.readAll();
603 if (contents.isEmpty()) {
604 LYXERR(Debug::FILES, "File '" << *this
605 << "' is either empty or some error happened while reading it.");
610 if (encoding.empty() || encoding == "UTF-8")
611 s = QString::fromUtf8(contents.data());
612 else if (encoding == "ascii")
613 s = QString::fromAscii(contents.data());
614 else if (encoding == "local8bit")
615 s = QString::fromLocal8Bit(contents.data());
616 else if (encoding == "latin1")
617 s = QString::fromLatin1(contents.data());
619 return qstring_to_ucs4(s);
623 void FileName::changeExtension(string const & extension)
625 // FIXME: use Qt native methods...
626 string const oldname = absFilename();
627 string::size_type const last_slash = oldname.rfind('/');
628 string::size_type last_dot = oldname.rfind('.');
629 if (last_dot < last_slash && last_slash != string::npos)
630 last_dot = string::npos;
633 // Make sure the extension starts with a dot
634 if (!extension.empty() && extension[0] != '.')
635 ext= '.' + extension;
639 set(oldname.substr(0, last_dot) + ext);
643 string FileName::guessFormatFromContents() const
645 // the different filetypes and what they contain in one of the first lines
646 // (dots are any characters). (Herbert 20020131)
649 // EPS %!PS-Adobe-3.0 EPSF...
656 // PBM P1... or P4 (B/W)
657 // PGM P2... or P5 (Grayscale)
658 // PPM P3... or P6 (color)
659 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
660 // SGI \001\332... (decimal 474)
662 // TIFF II... or MM...
664 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
665 // ...static char *...
666 // XWD \000\000\000\151 (0x00006900) decimal 105
668 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
669 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
670 // Z \037\235 UNIX compress
673 if (empty() || !isReadableFile())
676 ifstream ifs(toFilesystemEncoding().c_str());
678 // Couldn't open file...
682 static string const gzipStamp = "\037\213";
685 static string const zipStamp = "PK";
688 static string const compressStamp = "\037\235";
690 // Maximum strings to read
691 int const max_count = 50;
696 bool firstLine = true;
697 while ((count++ < max_count) && format.empty()) {
699 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
700 << "\tFile type not recognised before EOF!");
705 string const stamp = str.substr(0, 2);
706 if (firstLine && str.size() >= 2) {
707 // at first we check for a zipped file, because this
708 // information is saved in the first bytes of the file!
709 // also some graphic formats which save the information
710 // in the first line, too.
711 if (prefixIs(str, gzipStamp)) {
714 } else if (stamp == zipStamp) {
717 } else if (stamp == compressStamp) {
721 } else if (stamp == "BM") {
724 } else if (stamp == "\001\332") {
728 // Don't need to use str.at(0), str.at(1) because
729 // we already know that str.size() >= 2
730 } else if (str[0] == 'P') {
746 } else if ((stamp == "II") || (stamp == "MM")) {
749 } else if (prefixIs(str,"%TGIF")) {
752 } else if (prefixIs(str,"#FIG")) {
755 } else if (prefixIs(str,"GIF")) {
758 } else if (str.size() > 3) {
759 int const c = ((str[0] << 24) & (str[1] << 16) &
760 (str[2] << 8) & str[3]);
771 else if (contains(str,"EPSF"))
772 // dummy, if we have wrong file description like
773 // %!PS-Adobe-2.0EPSF"
776 else if (contains(str, "Grace"))
779 else if (contains(str, "JFIF"))
782 else if (contains(str, "%PDF"))
785 else if (contains(str, "PNG"))
788 else if (contains(str, "%!PS-Adobe")) {
791 if (contains(str,"EPSF"))
797 else if (contains(str, "_bits[]"))
800 else if (contains(str, "XPM") || contains(str, "static char *"))
803 else if (contains(str, "BITPIX"))
807 if (!format.empty()) {
808 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
812 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
813 << "\tCouldn't find a known format!");
818 bool FileName::isZippedFile() const
820 string const type = guessFormatFromContents();
821 return contains("gzip zip compress", type) && !type.empty();
825 docstring const FileName::relPath(string const & path) const
828 return makeRelPath(absoluteFilePath(), from_utf8(path));
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 bool operator>(FileName const & lhs, FileName const & rhs)
852 return lhs.absFilename() > rhs.absFilename();
856 ostream & operator<<(ostream & os, FileName const & filename)
858 return os << filename.absFilename();
862 /////////////////////////////////////////////////////////////////////
866 /////////////////////////////////////////////////////////////////////
869 DocFileName::DocFileName()
870 : save_abs_path_(true)
874 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
875 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
879 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
880 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
884 void DocFileName::set(string const & name, string const & buffer_path)
887 bool const nameIsAbsolute = isAbsolute();
888 save_abs_path_ = nameIsAbsolute;
890 FileName::set(makeAbsPath(name, buffer_path).absFilename());
891 zipped_valid_ = false;
895 void DocFileName::erase()
898 zipped_valid_ = false;
902 string DocFileName::relFilename(string const & path) const
905 return to_utf8(relPath(path));
909 string DocFileName::outputFilename(string const & path) const
911 return save_abs_path_ ? absFilename() : relFilename(path);
915 string DocFileName::mangledFilename(string const & dir) const
917 // We need to make sure that every DocFileName instance for a given
918 // filename returns the same mangled name.
919 typedef map<string, string> MangledMap;
920 static MangledMap mangledNames;
921 MangledMap::const_iterator const it = mangledNames.find(absFilename());
922 if (it != mangledNames.end())
925 string const name = absFilename();
927 string mname = os::internal_path(name);
928 // Remove the extension.
929 mname = support::changeExtension(name, string());
930 // The mangled name must be a valid LaTeX name.
931 // The list of characters to keep is probably over-restrictive,
932 // but it is not really a problem.
933 // Apart from non-ASCII characters, at least the following characters
934 // are forbidden: '/', '.', ' ', and ':'.
935 // On windows it is not possible to create files with '<', '>' or '?'
937 static string const keep = "abcdefghijklmnopqrstuvwxyz"
938 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
940 string::size_type pos = 0;
941 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
943 // Add the extension back on
944 mname = support::changeExtension(mname, getExtension(name));
946 // Prepend a counter to the filename. This is necessary to make
947 // the mangled name unique.
948 static int counter = 0;
950 s << counter++ << mname;
953 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
954 // is longer than about 160 characters. MiKTeX's pdflatex
955 // is even pickier. A maximum length of 100 has been proven to work.
956 // If dir.size() > max length, all bets are off for YAP. We truncate
957 // the filename nevertheless, keeping a minimum of 10 chars.
959 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
961 // If the mangled file name is too long, hack it to fit.
962 // We know we're guaranteed to have a unique file name because
964 if (mname.size() > max_length) {
965 int const half = (int(max_length) / 2) - 2;
967 mname = mname.substr(0, half) + "___" +
968 mname.substr(mname.size() - half);
972 mangledNames[absFilename()] = mname;
977 bool DocFileName::isZipped() const
979 if (!zipped_valid_) {
980 zipped_ = isZippedFile();
981 zipped_valid_ = true;
987 string DocFileName::unzippedFilename() const
989 return unzippedFileName(absFilename());
993 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
995 return lhs.absFilename() == rhs.absFilename()
996 && lhs.saveAbsPath() == rhs.saveAbsPath();
1000 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1002 return !(lhs == rhs);
1005 } // namespace support