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 string FileName::absFilename() const
145 return fromqstr(d->fi.absoluteFilePath());
149 void FileName::set(string const & name)
151 d->fi.setFile(toqstr(name));
152 BOOST_ASSERT(d->fi.isAbsolute());
156 void FileName::erase()
162 bool FileName::copyTo(FileName const & name) const
164 QFile::remove(name.d->fi.absoluteFilePath());
165 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
167 lyxerr << "FileName::copyTo(): Could not copy file "
168 << *this << " to " << name << endl;
173 bool FileName::renameTo(FileName const & name) const
175 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
177 LYXERR0("Could not rename file " << *this << " to " << name);
182 bool FileName::moveTo(FileName const & name) const
184 QFile::remove(name.d->fi.absoluteFilePath());
186 bool success = QFile::rename(d->fi.absoluteFilePath(),
187 name.d->fi.absoluteFilePath());
189 LYXERR0("Could not move file " << *this << " to " << name);
194 bool FileName::changePermission(unsigned long int mode) const
197 LYXERR0("File " << *this << " is not writable!");
201 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
202 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
203 LYXERR0("File " << *this << ": cannot change permission to "
212 string FileName::toFilesystemEncoding() const
214 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
215 return string(encoded.begin(), encoded.end());
219 FileName FileName::fromFilesystemEncoding(string const & name)
221 QByteArray const encoded(name.c_str(), name.length());
222 return FileName(fromqstr(QFile::decodeName(encoded)));
226 bool FileName::exists() const
228 return d->fi.exists();
232 bool FileName::isSymLink() const
234 return d->fi.isSymLink();
238 bool FileName::isFileEmpty() const
240 return d->fi.size() == 0;
244 bool FileName::isDirectory() const
246 return d->fi.isDir();
250 bool FileName::isReadOnly() const
252 return d->fi.isReadable() && !d->fi.isWritable();
256 bool FileName::isReadableDirectory() const
258 return d->fi.isDir() && d->fi.isReadable();
262 string FileName::onlyFileName() const
264 return support::onlyFilename(absFilename());
268 FileName FileName::onlyPath() const
270 return FileName(support::onlyPath(absFilename()));
274 bool FileName::isReadableFile() const
276 return d->fi.isFile() && d->fi.isReadable();
280 bool FileName::isWritable() const
282 return d->fi.isWritable();
286 bool FileName::isDirWritable() const
288 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
290 FileName const tmpfl = FileName::tempName(absFilename() + "/lyxwritetest");
300 FileNameList FileName::dirList(string const & ext) const
302 FileNameList dirlist;
303 if (!isDirectory()) {
304 LYXERR0("Directory '" << *this << "' does not exist!");
308 QDir dir = d->fi.absoluteDir();
313 case '.': filter = "*" + toqstr(ext); break;
314 case '*': filter = toqstr(ext); break;
315 default: filter = "*." + toqstr(ext);
317 dir.setNameFilters(QStringList(filter));
318 LYXERR(Debug::FILES, "filtering on extension "
319 << fromqstr(filter) << " is requested.");
322 QFileInfoList list = dir.entryInfoList();
323 for (int i = 0; i != list.size(); ++i) {
324 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
325 dirlist.push_back(fi);
326 LYXERR(Debug::FILES, "found file " << fi);
333 static int make_tempfile(char * templ)
335 #if defined(HAVE_MKSTEMP)
336 return ::mkstemp(templ);
337 #elif defined(HAVE_MKTEMP)
338 // This probably just barely works...
340 # if defined (HAVE_OPEN)
341 # if (!defined S_IRUSR)
342 # define S_IRUSR S_IREAD
343 # define S_IWUSR S_IWRITE
345 return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
346 # elif defined (HAVE__OPEN)
347 return ::_open(templ,
348 _O_RDWR | _O_CREAT | _O_EXCL,
349 _S_IREAD | _S_IWRITE);
351 # error No open() function.
359 FileName FileName::tempName(string const & mask)
361 FileName tmp_name(mask);
363 if (tmp_name.d->fi.isAbsolute())
366 tmpfl = package().temp_dir().absFilename() + "/" + mask;
368 #if defined (HAVE_GETPID)
369 tmpfl += convert<string>(getpid());
370 #elif defined (HAVE__GETPID)
371 tmpfl += convert<string>(_getpid());
373 # error No getpid() function
377 // The supposedly safe mkstemp version
378 // FIXME: why not using std::string directly?
379 boost::scoped_array<char> tmpl(new char[tmpfl.length() + 1]); // + 1 for '\0'
380 tmpfl.copy(tmpl.get(), string::npos);
381 tmpl[tmpfl.length()] = '\0'; // terminator
383 int const tmpf = make_tempfile(tmpl.get());
385 string const t(to_utf8(from_filesystem8bit(tmpl.get())));
386 #if defined (HAVE_CLOSE)
388 #elif defined (HAVE__CLOSE)
391 # error No x() function.
393 LYXERR(Debug::FILES, "Temporary file `" << t << "' created.");
396 LYXERR(Debug::FILES, "LyX Error: Unable to create temporary file.");
401 FileName FileName::getcwd()
403 return FileName(".");
407 time_t FileName::lastModified() const
409 return d->fi.lastModified().toTime_t();
413 bool FileName::chdir() const
415 return QDir::setCurrent(d->fi.absoluteFilePath());
419 extern unsigned long sum(char const * file);
421 unsigned long FileName::checksum() const
424 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
427 // a directory may be passed here so we need to test it. (bug 3622)
429 LYXERR0('"' << absFilename() << "\" is a directory!");
432 if (!lyxerr.debugging(Debug::FILES))
433 return sum(absFilename().c_str());
437 unsigned long r = sum(absFilename().c_str());
438 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
439 << t.elapsed() << " ms." << endl;
444 bool FileName::removeFile() const
446 bool const success = QFile::remove(d->fi.absoluteFilePath());
447 if (!success && exists())
448 LYXERR0("Could not delete file " << *this);
453 static bool rmdir(QFileInfo const & fi)
455 QDir dir(fi.absoluteFilePath());
456 QFileInfoList list = dir.entryInfoList();
458 for (int i = 0; i != list.size(); ++i) {
459 if (list.at(i).fileName() == ".")
461 if (list.at(i).fileName() == "..")
464 if (list.at(i).isDir()) {
465 LYXERR(Debug::FILES, "Removing dir "
466 << fromqstr(list.at(i).absoluteFilePath()));
467 removed = rmdir(list.at(i));
470 LYXERR(Debug::FILES, "Removing file "
471 << fromqstr(list.at(i).absoluteFilePath()));
472 removed = dir.remove(list.at(i).fileName());
476 LYXERR0("Could not delete "
477 << fromqstr(list.at(i).absoluteFilePath()));
480 QDir parent = fi.absolutePath();
481 success &= parent.rmdir(fi.fileName());
486 bool FileName::destroyDirectory() const
488 bool const success = rmdir(d->fi);
490 LYXERR0("Could not delete " << *this);
496 static int mymkdir(char const * pathname, unsigned long int mode)
498 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
500 # if MKDIR_TAKES_ONE_ARG
502 return ::mkdir(pathname);
503 // FIXME: "Permissions of created directories are ignored on this system."
506 return ::mkdir(pathname, mode_t(mode));
508 #elif defined(_WIN32)
510 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
511 // FIXME: "Permissions of created directories are ignored on this system."
513 return ::_mkdir(pathname);
514 // FIXME: "Permissions of created directories are ignored on this system."
516 # error "Don't know how to create a directory on this system."
522 bool FileName::createDirectory(int permission) const
524 BOOST_ASSERT(!empty());
525 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
529 bool FileName::createPath() const
531 BOOST_ASSERT(!empty());
536 bool success = dir.mkpath(d->fi.absoluteFilePath());
538 LYXERR0("Cannot create path '" << *this << "'!");
543 docstring const FileName::absoluteFilePath() const
545 return qstring_to_ucs4(d->fi.absoluteFilePath());
549 docstring FileName::displayName(int threshold) const
551 return makeDisplayPath(absFilename(), threshold);
555 docstring FileName::fileContents(string const & encoding) const
557 if (!isReadableFile()) {
558 LYXERR0("File '" << *this << "' is not redable!");
562 QFile file(d->fi.absoluteFilePath());
563 if (!file.open(QIODevice::ReadOnly)) {
564 LYXERR0("File '" << *this
565 << "' could not be opened in read only mode!");
568 QByteArray contents = file.readAll();
571 if (contents.isEmpty()) {
572 LYXERR(Debug::FILES, "File '" << *this
573 << "' is either empty or some error happened while reading it.");
578 if (encoding.empty() || encoding == "UTF-8")
579 s = QString::fromUtf8(contents.data());
580 else if (encoding == "ascii")
581 s = QString::fromAscii(contents.data());
582 else if (encoding == "local8bit")
583 s = QString::fromLocal8Bit(contents.data());
584 else if (encoding == "latin1")
585 s = QString::fromLatin1(contents.data());
587 return qstring_to_ucs4(s);
591 void FileName::changeExtension(string const & extension)
593 // FIXME: use Qt native methods...
594 string const oldname = absFilename();
595 string::size_type const last_slash = oldname.rfind('/');
596 string::size_type last_dot = oldname.rfind('.');
597 if (last_dot < last_slash && last_slash != string::npos)
598 last_dot = string::npos;
601 // Make sure the extension starts with a dot
602 if (!extension.empty() && extension[0] != '.')
603 ext= '.' + extension;
607 set(oldname.substr(0, last_dot) + ext);
611 string FileName::guessFormatFromContents() const
613 // the different filetypes and what they contain in one of the first lines
614 // (dots are any characters). (Herbert 20020131)
617 // EPS %!PS-Adobe-3.0 EPSF...
624 // PBM P1... or P4 (B/W)
625 // PGM P2... or P5 (Grayscale)
626 // PPM P3... or P6 (color)
627 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
628 // SGI \001\332... (decimal 474)
630 // TIFF II... or MM...
632 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
633 // ...static char *...
634 // XWD \000\000\000\151 (0x00006900) decimal 105
636 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
637 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
638 // Z \037\235 UNIX compress
641 if (empty() || !isReadableFile())
644 ifstream ifs(toFilesystemEncoding().c_str());
646 // Couldn't open file...
650 static string const gzipStamp = "\037\213";
653 static string const zipStamp = "PK";
656 static string const compressStamp = "\037\235";
658 // Maximum strings to read
659 int const max_count = 50;
664 bool firstLine = true;
665 while ((count++ < max_count) && format.empty()) {
667 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
668 << "\tFile type not recognised before EOF!");
673 string const stamp = str.substr(0, 2);
674 if (firstLine && str.size() >= 2) {
675 // at first we check for a zipped file, because this
676 // information is saved in the first bytes of the file!
677 // also some graphic formats which save the information
678 // in the first line, too.
679 if (prefixIs(str, gzipStamp)) {
682 } else if (stamp == zipStamp) {
685 } else if (stamp == compressStamp) {
689 } else if (stamp == "BM") {
692 } else if (stamp == "\001\332") {
696 // Don't need to use str.at(0), str.at(1) because
697 // we already know that str.size() >= 2
698 } else if (str[0] == 'P') {
714 } else if ((stamp == "II") || (stamp == "MM")) {
717 } else if (prefixIs(str,"%TGIF")) {
720 } else if (prefixIs(str,"#FIG")) {
723 } else if (prefixIs(str,"GIF")) {
726 } else if (str.size() > 3) {
727 int const c = ((str[0] << 24) & (str[1] << 16) &
728 (str[2] << 8) & str[3]);
739 else if (contains(str,"EPSF"))
740 // dummy, if we have wrong file description like
741 // %!PS-Adobe-2.0EPSF"
744 else if (contains(str, "Grace"))
747 else if (contains(str, "JFIF"))
750 else if (contains(str, "%PDF"))
753 else if (contains(str, "PNG"))
756 else if (contains(str, "%!PS-Adobe")) {
759 if (contains(str,"EPSF"))
765 else if (contains(str, "_bits[]"))
768 else if (contains(str, "XPM") || contains(str, "static char *"))
771 else if (contains(str, "BITPIX"))
775 if (!format.empty()) {
776 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
780 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
781 << "\tCouldn't find a known format!");
786 bool FileName::isZippedFile() const
788 string const type = guessFormatFromContents();
789 return contains("gzip zip compress", type) && !type.empty();
793 docstring const FileName::relPath(string const & path) const
796 return makeRelPath(absoluteFilePath(), from_utf8(path));
800 bool operator==(FileName const & lhs, FileName const & rhs)
802 return lhs.absFilename() == rhs.absFilename();
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 ostream & operator<<(ostream & os, FileName const & filename)
826 return os << filename.absFilename();
830 /////////////////////////////////////////////////////////////////////
834 /////////////////////////////////////////////////////////////////////
837 DocFileName::DocFileName()
838 : save_abs_path_(true)
842 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
843 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
847 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
848 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
852 void DocFileName::set(string const & name, string const & buffer_path)
854 save_abs_path_ = absolutePath(name);
855 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
856 zipped_valid_ = false;
860 void DocFileName::erase()
863 zipped_valid_ = false;
867 string DocFileName::relFilename(string const & path) const
870 return to_utf8(relPath(path));
874 string DocFileName::outputFilename(string const & path) const
876 return save_abs_path_ ? absFilename() : relFilename(path);
880 string DocFileName::mangledFilename(string const & dir) const
882 // We need to make sure that every DocFileName instance for a given
883 // filename returns the same mangled name.
884 typedef map<string, string> MangledMap;
885 static MangledMap mangledNames;
886 MangledMap::const_iterator const it = mangledNames.find(absFilename());
887 if (it != mangledNames.end())
890 string const name = absFilename();
892 string mname = os::internal_path(name);
893 // Remove the extension.
894 mname = support::changeExtension(name, string());
895 // The mangled name must be a valid LaTeX name.
896 // The list of characters to keep is probably over-restrictive,
897 // but it is not really a problem.
898 // Apart from non-ASCII characters, at least the following characters
899 // are forbidden: '/', '.', ' ', and ':'.
900 // On windows it is not possible to create files with '<', '>' or '?'
902 static string const keep = "abcdefghijklmnopqrstuvwxyz"
903 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
905 string::size_type pos = 0;
906 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
908 // Add the extension back on
909 mname = support::changeExtension(mname, getExtension(name));
911 // Prepend a counter to the filename. This is necessary to make
912 // the mangled name unique.
913 static int counter = 0;
915 s << counter++ << mname;
918 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
919 // is longer than about 160 characters. MiKTeX's pdflatex
920 // is even pickier. A maximum length of 100 has been proven to work.
921 // If dir.size() > max length, all bets are off for YAP. We truncate
922 // the filename nevertheless, keeping a minimum of 10 chars.
924 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
926 // If the mangled file name is too long, hack it to fit.
927 // We know we're guaranteed to have a unique file name because
929 if (mname.size() > max_length) {
930 int const half = (int(max_length) / 2) - 2;
932 mname = mname.substr(0, half) + "___" +
933 mname.substr(mname.size() - half);
937 mangledNames[absFilename()] = mname;
942 bool DocFileName::isZipped() const
944 if (!zipped_valid_) {
945 zipped_ = isZippedFile();
946 zipped_valid_ = true;
952 string DocFileName::unzippedFilename() const
954 return unzippedFileName(absFilename());
958 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
960 return lhs.absFilename() == rhs.absFilename()
961 && lhs.saveAbsPath() == rhs.saveAbsPath();
965 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
967 return !(lhs == rhs);
970 } // namespace support