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);
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 bool FileName::isAbsolute() const
145 return d->fi.isAbsolute();
149 string FileName::absFilename() const
151 return fromqstr(d->fi.absoluteFilePath());
155 void FileName::set(string const & name)
157 d->fi.setFile(toqstr(name));
161 void FileName::erase()
167 bool FileName::copyTo(FileName const & name) const
169 LYXERR(Debug::FILES, "Copying " << name);
170 QFile::remove(name.d->fi.absoluteFilePath());
171 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
173 LYXERR0("FileName::copyTo(): Could not copy file "
174 << *this << " to " << name);
179 bool FileName::renameTo(FileName const & name) const
181 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
183 LYXERR0("Could not rename file " << *this << " to " << name);
188 bool FileName::moveTo(FileName const & name) const
190 QFile::remove(name.d->fi.absoluteFilePath());
192 bool success = QFile::rename(d->fi.absoluteFilePath(),
193 name.d->fi.absoluteFilePath());
195 LYXERR0("Could not move file " << *this << " to " << name);
200 bool FileName::changePermission(unsigned long int mode) const
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 fromqstr(d->fi.fileName());
269 string FileName::onlyFileNameWithoutExt() const
271 return fromqstr(d->fi.baseName());
275 FileName FileName::onlyPath() const
278 path.d->fi.setFile(d->fi.path());
283 bool FileName::isReadableFile() const
285 return d->fi.isFile() && d->fi.isReadable();
289 bool FileName::isWritable() const
291 return d->fi.isWritable();
295 bool FileName::isDirWritable() const
297 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
299 FileName const tmpfl = FileName::tempName(absFilename() + "/lyxwritetest");
309 FileNameList FileName::dirList(string const & ext) const
311 FileNameList dirlist;
312 if (!isDirectory()) {
313 LYXERR0("Directory '" << *this << "' does not exist!");
317 QDir dir = d->fi.absoluteDir();
322 case '.': filter = "*" + toqstr(ext); break;
323 case '*': filter = toqstr(ext); break;
324 default: filter = "*." + toqstr(ext);
326 dir.setNameFilters(QStringList(filter));
327 LYXERR(Debug::FILES, "filtering on extension "
328 << fromqstr(filter) << " is requested.");
331 QFileInfoList list = dir.entryInfoList();
332 for (int i = 0; i != list.size(); ++i) {
333 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
334 dirlist.push_back(fi);
335 LYXERR(Debug::FILES, "found file " << fi);
342 static int make_tempfile(char * templ)
344 #if defined(HAVE_MKSTEMP)
345 return ::mkstemp(templ);
346 #elif defined(HAVE_MKTEMP)
347 // This probably just barely works...
349 # if defined (HAVE_OPEN)
350 # if (!defined S_IRUSR)
351 # define S_IRUSR S_IREAD
352 # define S_IWUSR S_IWRITE
354 return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
355 # elif defined (HAVE__OPEN)
356 return ::_open(templ,
357 _O_RDWR | _O_CREAT | _O_EXCL,
358 _S_IREAD | _S_IWRITE);
360 # error No open() function.
368 FileName FileName::tempName(string const & mask)
370 FileName tmp_name(mask);
372 if (tmp_name.d->fi.isAbsolute())
375 tmpfl = package().temp_dir().absFilename() + "/" + mask;
377 #if defined (HAVE_GETPID)
378 tmpfl += convert<string>(getpid());
379 #elif defined (HAVE__GETPID)
380 tmpfl += convert<string>(_getpid());
382 # error No getpid() function
386 // The supposedly safe mkstemp version
387 // FIXME: why not using std::string directly?
388 boost::scoped_array<char> tmpl(new char[tmpfl.length() + 1]); // + 1 for '\0'
389 tmpfl.copy(tmpl.get(), string::npos);
390 tmpl[tmpfl.length()] = '\0'; // terminator
392 int const tmpf = make_tempfile(tmpl.get());
394 string const t(to_utf8(from_filesystem8bit(tmpl.get())));
395 #if defined (HAVE_CLOSE)
397 #elif defined (HAVE__CLOSE)
400 # error No x() function.
402 LYXERR(Debug::FILES, "Temporary file `" << t << "' created.");
405 LYXERR(Debug::FILES, "LyX Error: Unable to create temporary file.");
410 FileName FileName::getcwd()
412 return FileName(".");
416 time_t FileName::lastModified() const
418 // QFileInfo caches information about the file. So, in case this file has
419 // been touched between the object creation and now, we refresh the file
421 LYXERR0("File: " << *this << ", " << fromqstr(d->fi.lastModified().toString("dd.MM.yyyy hh:MM")));
423 LYXERR0(fromqstr(d->fi.lastModified().toString("dd.MM.yyyy hh:MM")));
424 return d->fi.lastModified().toTime_t();
428 bool FileName::chdir() const
430 return QDir::setCurrent(d->fi.absoluteFilePath());
434 extern unsigned long sum(char const * file);
436 unsigned long FileName::checksum() const
439 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
442 // a directory may be passed here so we need to test it. (bug 3622)
444 LYXERR0('"' << absFilename() << "\" is a directory!");
447 if (!lyxerr.debugging(Debug::FILES))
448 return sum(absFilename().c_str());
452 unsigned long r = sum(absFilename().c_str());
453 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
454 << t.elapsed() << " ms." << endl;
459 bool FileName::removeFile() const
461 bool const success = QFile::remove(d->fi.absoluteFilePath());
462 if (!success && exists())
463 LYXERR0("Could not delete file " << *this);
468 static bool rmdir(QFileInfo const & fi)
470 QDir dir(fi.absoluteFilePath());
471 QFileInfoList list = dir.entryInfoList();
473 for (int i = 0; i != list.size(); ++i) {
474 if (list.at(i).fileName() == ".")
476 if (list.at(i).fileName() == "..")
479 if (list.at(i).isDir()) {
480 LYXERR(Debug::FILES, "Removing dir "
481 << fromqstr(list.at(i).absoluteFilePath()));
482 removed = rmdir(list.at(i));
485 LYXERR(Debug::FILES, "Removing file "
486 << fromqstr(list.at(i).absoluteFilePath()));
487 removed = dir.remove(list.at(i).fileName());
491 LYXERR0("Could not delete "
492 << fromqstr(list.at(i).absoluteFilePath()));
495 QDir parent = fi.absolutePath();
496 success &= parent.rmdir(fi.fileName());
501 bool FileName::destroyDirectory() const
503 bool const success = rmdir(d->fi);
505 LYXERR0("Could not delete " << *this);
511 static int mymkdir(char const * pathname, unsigned long int mode)
513 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
515 # if MKDIR_TAKES_ONE_ARG
517 return ::mkdir(pathname);
518 // FIXME: "Permissions of created directories are ignored on this system."
521 return ::mkdir(pathname, mode_t(mode));
523 #elif defined(_WIN32)
525 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
526 // FIXME: "Permissions of created directories are ignored on this system."
528 return ::_mkdir(pathname);
529 // FIXME: "Permissions of created directories are ignored on this system."
531 # error "Don't know how to create a directory on this system."
537 bool FileName::createDirectory(int permission) const
539 LASSERT(!empty(), /**/);
540 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
544 bool FileName::createPath() const
546 LASSERT(!empty(), /**/);
551 bool success = dir.mkpath(d->fi.absoluteFilePath());
553 LYXERR0("Cannot create path '" << *this << "'!");
558 docstring const FileName::absoluteFilePath() const
560 return qstring_to_ucs4(d->fi.absoluteFilePath());
564 docstring FileName::displayName(int threshold) const
566 return makeDisplayPath(absFilename(), threshold);
570 docstring FileName::fileContents(string const & encoding) const
572 if (!isReadableFile()) {
573 LYXERR0("File '" << *this << "' is not redable!");
577 QFile file(d->fi.absoluteFilePath());
578 if (!file.open(QIODevice::ReadOnly)) {
579 LYXERR0("File '" << *this
580 << "' could not be opened in read only mode!");
583 QByteArray contents = file.readAll();
586 if (contents.isEmpty()) {
587 LYXERR(Debug::FILES, "File '" << *this
588 << "' is either empty or some error happened while reading it.");
593 if (encoding.empty() || encoding == "UTF-8")
594 s = QString::fromUtf8(contents.data());
595 else if (encoding == "ascii")
596 s = QString::fromAscii(contents.data());
597 else if (encoding == "local8bit")
598 s = QString::fromLocal8Bit(contents.data());
599 else if (encoding == "latin1")
600 s = QString::fromLatin1(contents.data());
602 return qstring_to_ucs4(s);
606 void FileName::changeExtension(string const & extension)
608 // FIXME: use Qt native methods...
609 string const oldname = absFilename();
610 string::size_type const last_slash = oldname.rfind('/');
611 string::size_type last_dot = oldname.rfind('.');
612 if (last_dot < last_slash && last_slash != string::npos)
613 last_dot = string::npos;
616 // Make sure the extension starts with a dot
617 if (!extension.empty() && extension[0] != '.')
618 ext= '.' + extension;
622 set(oldname.substr(0, last_dot) + ext);
626 string FileName::guessFormatFromContents() const
628 // the different filetypes and what they contain in one of the first lines
629 // (dots are any characters). (Herbert 20020131)
632 // EPS %!PS-Adobe-3.0 EPSF...
639 // PBM P1... or P4 (B/W)
640 // PGM P2... or P5 (Grayscale)
641 // PPM P3... or P6 (color)
642 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
643 // SGI \001\332... (decimal 474)
645 // TIFF II... or MM...
647 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
648 // ...static char *...
649 // XWD \000\000\000\151 (0x00006900) decimal 105
651 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
652 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
653 // Z \037\235 UNIX compress
656 if (empty() || !isReadableFile())
659 ifstream ifs(toFilesystemEncoding().c_str());
661 // Couldn't open file...
665 static string const gzipStamp = "\037\213";
668 static string const zipStamp = "PK";
671 static string const compressStamp = "\037\235";
673 // Maximum strings to read
674 int const max_count = 50;
679 bool firstLine = true;
680 while ((count++ < max_count) && format.empty()) {
682 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
683 << "\tFile type not recognised before EOF!");
688 string const stamp = str.substr(0, 2);
689 if (firstLine && str.size() >= 2) {
690 // at first we check for a zipped file, because this
691 // information is saved in the first bytes of the file!
692 // also some graphic formats which save the information
693 // in the first line, too.
694 if (prefixIs(str, gzipStamp)) {
697 } else if (stamp == zipStamp) {
700 } else if (stamp == compressStamp) {
704 } else if (stamp == "BM") {
707 } else if (stamp == "\001\332") {
711 // Don't need to use str.at(0), str.at(1) because
712 // we already know that str.size() >= 2
713 } else if (str[0] == 'P') {
729 } else if ((stamp == "II") || (stamp == "MM")) {
732 } else if (prefixIs(str,"%TGIF")) {
735 } else if (prefixIs(str,"#FIG")) {
738 } else if (prefixIs(str,"GIF")) {
741 } else if (str.size() > 3) {
742 int const c = ((str[0] << 24) & (str[1] << 16) &
743 (str[2] << 8) & str[3]);
754 else if (contains(str,"EPSF"))
755 // dummy, if we have wrong file description like
756 // %!PS-Adobe-2.0EPSF"
759 else if (contains(str, "Grace"))
762 else if (contains(str, "JFIF"))
765 else if (contains(str, "%PDF"))
768 else if (contains(str, "PNG"))
771 else if (contains(str, "%!PS-Adobe")) {
774 if (contains(str,"EPSF"))
780 else if (contains(str, "_bits[]"))
783 else if (contains(str, "XPM") || contains(str, "static char *"))
786 else if (contains(str, "BITPIX"))
790 if (!format.empty()) {
791 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
795 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
796 << "\tCouldn't find a known format!");
801 bool FileName::isZippedFile() const
803 string const type = guessFormatFromContents();
804 return contains("gzip zip compress", type) && !type.empty();
808 docstring const FileName::relPath(string const & path) const
811 return makeRelPath(absoluteFilePath(), from_utf8(path));
815 bool operator==(FileName const & lhs, FileName const & rhs)
817 return lhs.absFilename() == rhs.absFilename();
821 bool operator!=(FileName const & lhs, FileName const & rhs)
823 return lhs.absFilename() != rhs.absFilename();
827 bool operator<(FileName const & lhs, FileName const & rhs)
829 return lhs.absFilename() < rhs.absFilename();
833 bool operator>(FileName const & lhs, FileName const & rhs)
835 return lhs.absFilename() > rhs.absFilename();
839 ostream & operator<<(ostream & os, FileName const & filename)
841 return os << filename.absFilename();
845 /////////////////////////////////////////////////////////////////////
849 /////////////////////////////////////////////////////////////////////
852 DocFileName::DocFileName()
853 : save_abs_path_(true)
857 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
858 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
862 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
863 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
867 void DocFileName::set(string const & name, string const & buffer_path)
870 bool const nameIsAbsolute = isAbsolute();
871 save_abs_path_ = nameIsAbsolute;
873 FileName::set(makeAbsPath(name, buffer_path).absFilename());
874 zipped_valid_ = false;
878 void DocFileName::erase()
881 zipped_valid_ = false;
885 string DocFileName::relFilename(string const & path) const
888 return to_utf8(relPath(path));
892 string DocFileName::outputFilename(string const & path) const
894 return save_abs_path_ ? absFilename() : relFilename(path);
898 string DocFileName::mangledFilename(string const & dir) const
900 // We need to make sure that every DocFileName instance for a given
901 // filename returns the same mangled name.
902 typedef map<string, string> MangledMap;
903 static MangledMap mangledNames;
904 MangledMap::const_iterator const it = mangledNames.find(absFilename());
905 if (it != mangledNames.end())
908 string const name = absFilename();
910 string mname = os::internal_path(name);
911 // Remove the extension.
912 mname = support::changeExtension(name, string());
913 // The mangled name must be a valid LaTeX name.
914 // The list of characters to keep is probably over-restrictive,
915 // but it is not really a problem.
916 // Apart from non-ASCII characters, at least the following characters
917 // are forbidden: '/', '.', ' ', and ':'.
918 // On windows it is not possible to create files with '<', '>' or '?'
920 static string const keep = "abcdefghijklmnopqrstuvwxyz"
921 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
923 string::size_type pos = 0;
924 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
926 // Add the extension back on
927 mname = support::changeExtension(mname, getExtension(name));
929 // Prepend a counter to the filename. This is necessary to make
930 // the mangled name unique.
931 static int counter = 0;
933 s << counter++ << mname;
936 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
937 // is longer than about 160 characters. MiKTeX's pdflatex
938 // is even pickier. A maximum length of 100 has been proven to work.
939 // If dir.size() > max length, all bets are off for YAP. We truncate
940 // the filename nevertheless, keeping a minimum of 10 chars.
942 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
944 // If the mangled file name is too long, hack it to fit.
945 // We know we're guaranteed to have a unique file name because
947 if (mname.size() > max_length) {
948 int const half = (int(max_length) / 2) - 2;
950 mname = mname.substr(0, half) + "___" +
951 mname.substr(mname.size() - half);
955 mangledNames[absFilename()] = mname;
960 bool DocFileName::isZipped() const
962 if (!zipped_valid_) {
963 zipped_ = isZippedFile();
964 zipped_valid_ = true;
970 string DocFileName::unzippedFilename() const
972 return unzippedFileName(absFilename());
976 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
978 return lhs.absFilename() == rhs.absFilename()
979 && lhs.saveAbsPath() == rhs.saveAbsPath();
983 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
985 return !(lhs == rhs);
988 } // namespace support