3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
15 #include "BufferParams.h"
17 #include "ServerSocket.h"
19 #include "frontends/alert.h" //to be removed?
21 #include "support/debug.h"
22 #include "support/docstream.h"
23 #include "support/filetools.h"
24 #include "support/gettext.h"
25 #include "support/lstrings.h"
26 #include "support/lyxmagic.h"
27 #include "support/mutex.h"
28 #include "support/os.h"
29 #include "support/PathChanger.h"
30 #include "support/Systemcall.h"
31 #include "support/textutils.h"
32 #include "support/Translator.h"
39 // FIXME: Q_OS_MAC is not available, it's in Qt
40 #ifdef USE_MACOSX_PACKAGING
41 #include "support/linkback/LinkBackProxy.h"
45 using namespace lyx::support;
49 namespace Alert = frontend::Alert;
50 namespace os = support::os;
54 string const token_from_format("$$i");
55 string const token_path_format("$$p");
56 string const token_socket_format("$$a");
61 bool Format::formatSorter(Format const * lhs, Format const * rhs)
63 return compare_locale(translateIfPossible(lhs->prettyname()),
64 translateIfPossible(rhs->prettyname())) < 0;
67 bool operator<(Format const & a, Format const & b)
69 return compare_locale(translateIfPossible(a.prettyname()),
70 translateIfPossible(b.prettyname())) < 0;
74 Format::Format(string const & n, string const & e, docstring const & p,
75 string const & s, string const & v, string const & ed,
76 string const & m, int flags)
77 : name_(n), prettyname_(p), shortcut_(s), viewer_(v),
78 editor_(ed), mime_(m), flags_(flags)
80 extension_list_ = getVectorFromString(e, ",");
81 LYXERR(Debug::GRAPHICS, "New Format: n=" << n << ", flags=" << flags);
85 bool Format::dummy() const
87 return extension().empty();
91 string const Format::extensions() const
93 return getStringFromVector(extension_list_, ", ");
97 bool Format::hasExtension(string const & ext) const
99 return (find(extension_list_.begin(), extension_list_.end(), ext)
100 != extension_list_.end());
104 bool Format::isChildFormat() const
108 return isDigitASCII(name_[name_.length() - 1]);
112 string const Format::parentFormat() const
114 return name_.substr(0, name_.length() - 1);
118 void Format::setExtensions(string const & e)
120 extension_list_ = getVectorFromString(e, ",");
126 std::function<bool (Format const &)> FormatNameIs(string const & name)
128 return [name](Format const & f){ return f.name() == name; };
133 // This method should return a reference, and throw an exception
134 // if the format named name cannot be found (Lgb)
135 Format const * Formats::getFormat(string const & name) const
137 FormatList::const_iterator cit =
138 find_if(formatlist_.begin(), formatlist_.end(),
140 if (cit != formatlist_.end())
147 Format * Formats::getFormat(string const & name)
149 FormatList::iterator it =
150 find_if(formatlist_.begin(), formatlist_.end(),
153 if (it != formatlist_.end())
162 /** Guess the file format name (as in Format::name()) from contents.
163 * Normally you don't want to use this directly, but rather
164 * Formats::getFormatFromFile().
166 string guessFormatFromContents(FileName const & fn)
168 // the different filetypes and what they contain in one of the first lines
169 // (dots are any characters). (Herbert 20020131)
172 // EPS %!PS-Adobe-3.0 EPSF...
176 // JPG \377\330... (0xFFD8)
179 // PBM P1... or P4 (B/W)
180 // PGM P2... or P5 (Grayscale)
181 // PPM P3... or P6 (color)
182 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
183 // SGI \001\332... (decimal 474)
185 // TIFF II... or MM...
187 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
188 // ...static char *...
189 // XWD \000\000\000\151 (0x00006900) decimal 105
191 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
192 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
193 // Z \037\235 UNIX compress
196 if (fn.empty() || !fn.isReadableFile())
199 ifstream ifs(fn.toFilesystemEncoding().c_str());
201 // Couldn't open file...
205 static string const gzipStamp = "\037\213";
208 static string const zipStamp = "PK";
210 // ZIP containers (koffice, openoffice.org etc).
211 static string const nonzipStamp = "\010\0\0\0mimetypeapplication/";
214 static string const compressStamp = "\037\235";
216 // DOS binary EPS according to Adobe TN-5002
217 static string const binEPSStamp = "\xC5\xD0\xD3\xC6";
220 // Maximum strings to read
221 int const max_count = 50;
226 bool firstLine = true;
227 bool backslash = false;
228 bool maybelatex = false;
230 while ((count++ < max_count) && format.empty() && !maybelatex) {
235 string const stamp = str.substr(0, 2);
236 if (firstLine && str.size() >= 2) {
237 // at first we check for a zipped file, because this
238 // information is saved in the first bytes of the file!
239 // also some graphic formats which save the information
240 // in the first line, too.
241 if (prefixIs(str, gzipStamp)) {
244 } else if (stamp == zipStamp &&
245 !contains(str, nonzipStamp)) {
248 } else if (stamp == compressStamp) {
252 } else if (stamp == "BM") {
255 } else if (stamp == "\377\330") {
258 } else if (prefixIs(str, "\x89PNG")) {
261 } else if (stamp == "\001\332") {
264 } else if (prefixIs(str, binEPSStamp)) {
268 // Don't need to use str.at(0), str.at(1) because
269 // we already know that str.size() >= 2
270 } else if (str[0] == 'P') {
286 } else if ((stamp == "II") || (stamp == "MM")) {
289 } else if (prefixIs(str,"%TGIF")) {
292 } else if (prefixIs(str,"#FIG")) {
295 } else if (prefixIs(str,"GIF")) {
298 } else if (str.size() > 3) {
299 int const c = ((str[0] << 24) & (str[1] << 16) &
300 (str[2] << 8) & str[3]);
311 else if (contains(str,"EPSF"))
312 // dummy, if we have wrong file description like
313 // %!PS-Adobe-2.0EPSF"
316 else if (contains(str, "Grace"))
319 else if (contains(str, "%PDF"))
320 // autodetect pdf format for graphics inclusion
323 else if (contains(str, " EMF"))
326 else if (contains(str, "%!PS-Adobe")) {
329 if (contains(str,"EPSF"))
335 else if (contains(str, "_bits[]"))
338 else if (contains(str, "XPM") || contains(str, "static char *"))
341 else if (contains(str, "BITPIX"))
344 else if (contains(str, "\\documentclass") ||
345 contains(str, "\\chapter") ||
346 contains(str, "\\section") ||
347 contains(str, "\\begin") ||
348 contains(str, "\\end") ||
349 contains(str, "$$") ||
350 contains(str, "\\[") ||
351 contains(str, "\\]"))
354 if (contains(str, '\\'))
356 dollars += count_char(str, '$');
357 if (backslash && dollars > 1)
363 if (format.empty() && maybelatex && !isBinaryFile(fn))
366 if (format.empty()) {
368 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
369 "\tFile type not recognised before EOF!");
371 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
375 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
376 << "\tCouldn't find a known format!");
383 string Formats::getFormatFromFile(FileName const & filename) const
385 if (filename.empty())
390 if (filename.exists()) {
391 // one instance of Magic that will be reused for next calls
392 // This avoids to read the magic file everytime
393 // If libmagic is not available, Magic::file returns an empty string.
395 string const result = magic.file(filename.toFilesystemEncoding());
396 string const mime = token(result, ';', 0);
397 // our own detection is better for binary files (can be anything)
398 // and different plain text formats
399 if (!mime.empty() && mime != "application/octet-stream" &&
400 mime != "text/plain") {
401 Formats::const_iterator cit =
402 find_if(formatlist_.begin(), formatlist_.end(),
403 [mime](Format const & f){ return f.mime() == mime; });
404 if (cit != formatlist_.end()) {
405 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
406 << mime << " -> " << cit->name());
407 // See special eps/ps handling below
408 if (mime == "application/postscript")
409 psformat = cit->name();
411 format = cit->name();
415 // libmagic recognizes as latex also some formats of ours
416 // such as pstex and pdftex. Therefore we have to perform
417 // additional checks in this case (bug 9244).
418 if (!format.empty() && format != "latex")
422 string const ext = getExtension(filename.absFileName());
423 if (format.empty()) {
424 // libmagic does not distinguish eps and ps.
425 // Therefore we need to use our own detection here, but only if it
426 // recognizes either ps or eps. Otherwise the libmagic guess will
427 // be better (bug 9146).
428 format = guessFormatFromContents(filename);
429 if (!psformat.empty()) {
430 if (isPostScriptFileFormat(format))
436 if (isZippedFileFormat(format) && !ext.empty()) {
437 string const & fmt_name = getFormatFromExtension(ext);
438 if (!fmt_name.empty()) {
439 Format const * p_format = getFormat(fmt_name);
440 if (p_format && p_format->zippedNative())
441 return p_format->name();
444 // Don't simply return latex (bug 9244).
445 if (!format.empty() && format != "latex")
449 // Both libmagic and our guessing from contents may return as latex
450 // also lyx files and our pstex and pdftex formats. In this case we
451 // give precedence to the format determined by the extension.
452 if (format == "latex") {
453 format = getFormatFromExtension(ext);
454 return format.empty() ? "latex" : format;
457 // try to find a format from the file extension.
458 return getFormatFromExtension(ext);
462 string Formats::getFormatFromExtension(string const & ext) const
465 // this is ambigous if two formats have the same extension,
466 // but better than nothing
467 Formats::const_iterator cit =
468 find_if(formatlist_.begin(), formatlist_.end(),
469 [ext](Format const & f){ return f.hasExtension(ext); });
470 if (cit != formatlist_.end()) {
471 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
472 << ext << " -> " << cit->name());
480 /// Used to store last timestamp of file and whether it is (was) zipped
483 std::time_t timestamp;
484 ZippedInfo(bool zipped, std::time_t timestamp)
485 : zipped(zipped), timestamp(timestamp) { }
489 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
490 static std::map<std::string, ZippedInfo> zipped_;
491 static Mutex zipped_mutex;
494 bool Formats::isZippedFile(support::FileName const & filename) const {
495 string const & fname = filename.absFileName();
496 time_t timestamp = filename.lastModified();
497 Mutex::Locker lock(&zipped_mutex);
498 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
499 if (it != zipped_.end() && it->second.timestamp == timestamp)
500 return it->second.zipped;
501 // FIXME perf: This very expensive function is called on startup on each
502 // file whic is going to be parsed, and also on svgz icons. Maybe there is a
503 // quicker way to check whether a file is zipped? I.e. for icons we
504 // probably just need to check the extension (svgz vs svg).
505 string const & format = getFormatFromFile(filename);
506 bool zipped = (format == "gzip" || format == "zip");
507 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
512 bool Formats::isZippedFileFormat(string const & format)
514 return contains("gzip zip compress", format) && !format.empty();
518 bool Formats::isPostScriptFileFormat(string const & format)
520 return format == "ps" || format == "eps";
523 static string fixCommand(string const & cmd, string const & ext,
524 os::auto_open_mode mode)
526 // configure.py says we do not want a viewer/editor
530 // Does the OS manage this format?
531 if (os::canAutoOpenFile(ext, mode))
534 // if configure.py found nothing, clear the command
535 if (token(cmd, ' ', 0) == "auto")
538 // use the command found by configure.py
543 void Formats::setAutoOpen()
545 FormatList::iterator fit = formatlist_.begin();
546 FormatList::iterator const fend = formatlist_.end();
547 for ( ; fit != fend ; ++fit) {
548 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
549 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
554 int Formats::getNumber(string const & name) const
556 FormatList::const_iterator cit =
557 find_if(formatlist_.begin(), formatlist_.end(),
559 if (cit == formatlist_.end())
562 return distance(formatlist_.begin(), cit);
566 void Formats::add(string const & name)
568 if (!getFormat(name))
569 add(name, name, from_utf8(name), string(), string(), string(),
570 string(), Format::document);
574 void Formats::add(string const & name, string const & extensions,
575 docstring const & prettyname, string const & shortcut,
576 string const & viewer, string const & editor,
577 string const & mime, int flags)
579 Format * format = getFormat(name);
581 *format = Format(name, extensions, prettyname, shortcut, viewer,
582 editor, mime, flags);
584 formatlist_.push_back(Format(name, extensions, prettyname,
585 shortcut, viewer, editor, mime, flags));
589 void Formats::erase(string const & name)
591 FormatList::iterator it =
592 find_if(formatlist_.begin(), formatlist_.end(),
594 if (it != formatlist_.end())
595 formatlist_.erase(it);
601 std::sort(formatlist_.begin(), formatlist_.end());
605 void Formats::setViewer(string const & name, string const & command)
608 Format * format = getFormat(name);
610 format->setViewer(command);
612 LYXERR0("Unable to set viewer for non-existent format: " << name);
616 void Formats::setEditor(string const & name, string const & command)
619 Format * format = getFormat(name);
621 format->setEditor(command);
623 LYXERR0("Unable to set editor for non-existent format: " << name);
627 bool Formats::view(Buffer const & buffer, FileName const & filename,
628 string const & format_name) const
630 if (filename.empty() || !filename.exists()) {
631 Alert::error(_("Cannot view file"),
632 bformat(_("File does not exist: %1$s"),
633 from_utf8(filename.absFileName())));
637 Format const * format = getFormat(format_name);
638 if (format && format->viewer().empty() &&
639 format->isChildFormat())
640 format = getFormat(format->parentFormat());
641 if (!format || format->viewer().empty()) {
642 // FIXME: I believe this is the wrong place to show alerts, it should be done
643 // by the caller (this should be "utility" code)
644 Alert::error(_("Cannot view file"),
645 bformat(_("No information for viewing %1$s"),
646 translateIfPossible(prettyName(format_name))));
650 if (format->viewer() == "auto") {
651 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
654 Alert::error(_("Cannot view file"),
655 bformat(_("Auto-view file %1$s failed"),
656 from_utf8(filename.absFileName())));
661 string command = format->viewer();
663 // Escape backslashes if not already in double or single quotes.
664 // We cannot simply quote the whole command as there may be arguments.
665 if (contains(command, '\\')) {
666 bool inquote1 = false;
667 bool inquote2 = false;
668 string::iterator cit = command.begin();
669 for (; cit != command.end(); ++cit) {
672 inquote1 = !inquote1;
675 inquote2 = !inquote2;
678 if (!inquote1 && !inquote2)
679 cit = ++command.insert(cit, '\\');
685 if (format_name == "dvi" &&
686 !lyxrc.view_dvi_paper_option.empty()) {
687 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
688 if (!paper_size.empty()) {
689 command += ' ' + lyxrc.view_dvi_paper_option;
690 command += ' ' + paper_size;
691 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
692 buffer.params().papersize != PAPER_CUSTOM)
697 if (!contains(command, token_from_format))
698 command += ' ' + token_from_format;
700 command = subst(command, token_from_format,
701 quoteName(onlyFileName(filename.toFilesystemEncoding()), quote_shell_filename));
702 command = subst(command, token_path_format,
703 quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
704 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
705 LYXERR(Debug::FILES, "Executing command: " << command);
706 // FIXME UNICODE utf8 can be wrong for files
707 buffer.message(_("Executing command: ") + from_utf8(command));
709 PathChanger p(filename.onlyPath());
711 one.startscript(Systemcall::DontWait, command,
712 buffer.filePath(), buffer.layoutPos());
714 // we can't report any sort of error, since we aren't waiting
719 bool Formats::edit(Buffer const & buffer, FileName const & filename,
720 string const & format_name) const
722 if (filename.empty() || !filename.exists()) {
723 Alert::error(_("Cannot edit file"),
724 bformat(_("File does not exist: %1$s"),
725 from_utf8(filename.absFileName())));
729 // LinkBack files look like PDF, but have the .linkback extension
730 string const ext = getExtension(filename.absFileName());
731 if (format_name == "pdf6" && ext == "linkback") {
732 #ifdef USE_MACOSX_PACKAGING
733 return editLinkBackFile(filename.absFileName().c_str());
735 Alert::error(_("Cannot edit file"),
736 _("LinkBack files can only be edited on Apple Mac OSX."));
738 #endif // USE_MACOSX_PACKAGING
741 Format const * format = getFormat(format_name);
742 if (format && format->editor().empty() &&
743 format->isChildFormat())
744 format = getFormat(format->parentFormat());
745 if (!format || format->editor().empty()) {
746 // FIXME: I believe this is the wrong place to show alerts, it should
747 // be done by the caller (this should be "utility" code)
748 Alert::error(_("Cannot edit file"),
749 bformat(_("No information for editing %1$s"),
750 translateIfPossible(prettyName(format_name))));
755 if (format->editor() == "auto") {
756 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
759 Alert::error(_("Cannot edit file"),
760 bformat(_("Auto-edit file %1$s failed"),
761 from_utf8(filename.absFileName())));
766 string command = format->editor();
768 if (!contains(command, token_from_format))
769 command += ' ' + token_from_format;
771 command = subst(command, token_from_format,
772 quoteName(filename.toFilesystemEncoding(), quote_shell_filename));
773 command = subst(command, token_path_format,
774 quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
775 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
776 LYXERR(Debug::FILES, "Executing command: " << command);
777 // FIXME UNICODE utf8 can be wrong for files
778 buffer.message(_("Executing command: ") + from_utf8(command));
781 one.startscript(Systemcall::DontWait, command,
782 buffer.filePath(), buffer.layoutPos());
784 // we can't report any sort of error, since we aren't waiting
789 docstring const Formats::prettyName(string const & name) const
791 Format const * format = getFormat(name);
793 return format->prettyname();
795 return from_utf8(name);
799 string const Formats::extension(string const & name) const
801 Format const * format = getFormat(name);
803 return format->extension();
809 string const Formats::extensions(string const & name) const
811 Format const * format = getFormat(name);
813 return format->extensions();
821 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
824 FlavorTranslator initFlavorTranslator()
826 FlavorTranslator f(OutputParams::LATEX, "latex");
827 f.addPair(OutputParams::DVILUATEX, "dviluatex");
828 f.addPair(OutputParams::LUATEX, "luatex");
829 f.addPair(OutputParams::PDFLATEX, "pdflatex");
830 f.addPair(OutputParams::XETEX, "xetex");
831 f.addPair(OutputParams::DOCBOOK5, "docbook-xml");
832 f.addPair(OutputParams::HTML, "xhtml");
833 f.addPair(OutputParams::TEXT, "text");
834 f.addPair(OutputParams::LYX, "lyx");
839 FlavorTranslator const & flavorTranslator()
841 static FlavorTranslator const translator = initFlavorTranslator();
848 std::string flavor2format(OutputParams::FLAVOR flavor)
850 return flavorTranslator().find(flavor);
854 /* Not currently needed, but I'll leave the code in case it is.
855 OutputParams::FLAVOR format2flavor(std::string fmt)
857 return flavorTranslator().find(fmt);