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 & e) const
99 return (find(extension_list_.begin(), extension_list_.end(), e)
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 (stamp == "\001\332") {
260 } else if (prefixIs(str, binEPSStamp)) {
264 // Don't need to use str.at(0), str.at(1) because
265 // we already know that str.size() >= 2
266 } else if (str[0] == 'P') {
282 } else if ((stamp == "II") || (stamp == "MM")) {
285 } else if (prefixIs(str,"%TGIF")) {
288 } else if (prefixIs(str,"#FIG")) {
291 } else if (prefixIs(str,"GIF")) {
294 } else if (str.size() > 3) {
295 int const c = ((str[0] << 24) & (str[1] << 16) &
296 (str[2] << 8) & str[3]);
307 else if (contains(str,"EPSF"))
308 // dummy, if we have wrong file description like
309 // %!PS-Adobe-2.0EPSF"
312 else if (contains(str, "Grace"))
315 else if (contains(str, "%PDF"))
316 // autodetect pdf format for graphics inclusion
319 else if (contains(str, " EMF"))
322 else if (contains(str, "PNG"))
325 else if (contains(str, "%!PS-Adobe")) {
328 if (contains(str,"EPSF"))
334 else if (contains(str, "_bits[]"))
337 else if (contains(str, "XPM") || contains(str, "static char *"))
340 else if (contains(str, "BITPIX"))
343 else if (contains(str, "\\documentclass") ||
344 contains(str, "\\chapter") ||
345 contains(str, "\\section") ||
346 contains(str, "\\begin") ||
347 contains(str, "\\end") ||
348 contains(str, "$$") ||
349 contains(str, "\\[") ||
350 contains(str, "\\]"))
353 if (contains(str, '\\'))
355 dollars += count_char(str, '$');
356 if (backslash && dollars > 1)
362 if (format.empty() && maybelatex && !isBinaryFile(fn))
365 if (format.empty()) {
367 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
368 "\tFile type not recognised before EOF!");
370 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
374 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
375 << "\tCouldn't find a known format!");
382 string Formats::getFormatFromFile(FileName const & filename) const
384 if (filename.empty())
389 if (filename.exists()) {
390 // one instance of Magic that will be reused for next calls
391 // This avoids to read the magic file everytime
392 // If libmagic is not available, Magic::file returns an empty string.
394 string const result = magic.file(filename.toFilesystemEncoding());
395 string const mime = token(result, ';', 0);
396 // our own detection is better for binary files (can be anything)
397 // and different plain text formats
398 if (!mime.empty() && mime != "application/octet-stream" &&
399 mime != "text/plain") {
400 Formats::const_iterator cit =
401 find_if(formatlist_.begin(), formatlist_.end(),
402 [mime](Format const & f){ return f.mime() == mime; });
403 if (cit != formatlist_.end()) {
404 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
405 << mime << " -> " << cit->name());
406 // See special eps/ps handling below
407 if (mime == "application/postscript")
408 psformat = cit->name();
410 format = cit->name();
414 // libmagic recognizes as latex also some formats of ours
415 // such as pstex and pdftex. Therefore we have to perform
416 // additional checks in this case (bug 9244).
417 if (!format.empty() && format != "latex")
421 string const ext = getExtension(filename.absFileName());
422 if (format.empty()) {
423 // libmagic does not distinguish eps and ps.
424 // Therefore we need to use our own detection here, but only if it
425 // recognizes either ps or eps. Otherwise the libmagic guess will
426 // be better (bug 9146).
427 format = guessFormatFromContents(filename);
428 if (!psformat.empty()) {
429 if (isPostScriptFileFormat(format))
435 if (isZippedFileFormat(format) && !ext.empty()) {
436 string const & fmt_name = getFormatFromExtension(ext);
437 if (!fmt_name.empty()) {
438 Format const * p_format = getFormat(fmt_name);
439 if (p_format && p_format->zippedNative())
440 return p_format->name();
443 // Don't simply return latex (bug 9244).
444 if (!format.empty() && format != "latex")
448 // Both libmagic and our guessing from contents may return as latex
449 // also lyx files and our pstex and pdftex formats. In this case we
450 // give precedence to the format determined by the extension.
451 if (format == "latex") {
452 format = getFormatFromExtension(ext);
453 return format.empty() ? "latex" : format;
456 // try to find a format from the file extension.
457 return getFormatFromExtension(ext);
461 string Formats::getFormatFromExtension(string const & ext) const
464 // this is ambigous if two formats have the same extension,
465 // but better than nothing
466 Formats::const_iterator cit =
467 find_if(formatlist_.begin(), formatlist_.end(),
468 [ext](Format const & f){ return f.hasExtension(ext); });
469 if (cit != formatlist_.end()) {
470 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
471 << ext << " -> " << cit->name());
479 /// Used to store last timestamp of file and whether it is (was) zipped
482 std::time_t timestamp;
483 ZippedInfo(bool zipped, std::time_t timestamp)
484 : zipped(zipped), timestamp(timestamp) { }
488 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
489 static std::map<std::string, ZippedInfo> zipped_;
490 static Mutex zipped_mutex;
493 bool Formats::isZippedFile(support::FileName const & filename) const {
494 string const & fname = filename.absFileName();
495 time_t timestamp = filename.lastModified();
496 Mutex::Locker lock(&zipped_mutex);
497 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
498 if (it != zipped_.end() && it->second.timestamp == timestamp)
499 return it->second.zipped;
500 // FIXME perf: This very expensive function is called on startup on each
501 // file whic is going to be parsed, and also on svgz icons. Maybe there is a
502 // quicker way to check whether a file is zipped? I.e. for icons we
503 // probably just need to check the extension (svgz vs svg).
504 string const & format = getFormatFromFile(filename);
505 bool zipped = (format == "gzip" || format == "zip");
506 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
511 bool Formats::isZippedFileFormat(string const & format)
513 return contains("gzip zip compress", format) && !format.empty();
517 bool Formats::isPostScriptFileFormat(string const & format)
519 return format == "ps" || format == "eps";
522 static string fixCommand(string const & cmd, string const & ext,
523 os::auto_open_mode mode)
525 // configure.py says we do not want a viewer/editor
529 // Does the OS manage this format?
530 if (os::canAutoOpenFile(ext, mode))
533 // if configure.py found nothing, clear the command
534 if (token(cmd, ' ', 0) == "auto")
537 // use the command found by configure.py
542 void Formats::setAutoOpen()
544 FormatList::iterator fit = formatlist_.begin();
545 FormatList::iterator const fend = formatlist_.end();
546 for ( ; fit != fend ; ++fit) {
547 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
548 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
553 int Formats::getNumber(string const & name) const
555 FormatList::const_iterator cit =
556 find_if(formatlist_.begin(), formatlist_.end(),
558 if (cit == formatlist_.end())
561 return distance(formatlist_.begin(), cit);
565 void Formats::add(string const & name)
567 if (!getFormat(name))
568 add(name, name, from_utf8(name), string(), string(), string(),
569 string(), Format::document);
573 void Formats::add(string const & name, string const & extensions,
574 docstring const & prettyname, string const & shortcut,
575 string const & viewer, string const & editor,
576 string const & mime, int flags)
578 Format * format = getFormat(name);
580 *format = Format(name, extensions, prettyname, shortcut, viewer,
581 editor, mime, flags);
583 formatlist_.push_back(Format(name, extensions, prettyname,
584 shortcut, viewer, editor, mime, flags));
588 void Formats::erase(string const & name)
590 FormatList::iterator it =
591 find_if(formatlist_.begin(), formatlist_.end(),
593 if (it != formatlist_.end())
594 formatlist_.erase(it);
600 std::sort(formatlist_.begin(), formatlist_.end());
604 void Formats::setViewer(string const & name, string const & command)
607 Format * format = getFormat(name);
609 format->setViewer(command);
611 LYXERR0("Unable to set viewer for non-existent format: " << name);
615 void Formats::setEditor(string const & name, string const & command)
618 Format * format = getFormat(name);
620 format->setEditor(command);
622 LYXERR0("Unable to set editor for non-existent format: " << name);
626 bool Formats::view(Buffer const & buffer, FileName const & filename,
627 string const & format_name) const
629 if (filename.empty() || !filename.exists()) {
630 Alert::error(_("Cannot view file"),
631 bformat(_("File does not exist: %1$s"),
632 from_utf8(filename.absFileName())));
636 Format const * format = getFormat(format_name);
637 if (format && format->viewer().empty() &&
638 format->isChildFormat())
639 format = getFormat(format->parentFormat());
640 if (!format || format->viewer().empty()) {
641 // FIXME: I believe this is the wrong place to show alerts, it should be done
642 // by the caller (this should be "utility" code)
643 Alert::error(_("Cannot view file"),
644 bformat(_("No information for viewing %1$s"),
645 translateIfPossible(prettyName(format_name))));
649 if (format->viewer() == "auto") {
650 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
653 Alert::error(_("Cannot view file"),
654 bformat(_("Auto-view file %1$s failed"),
655 from_utf8(filename.absFileName())));
660 string command = format->viewer();
662 // Escape backslashes if not already in double or single quotes.
663 // We cannot simply quote the whole command as there may be arguments.
664 if (contains(command, '\\')) {
665 bool inquote1 = false;
666 bool inquote2 = false;
667 string::iterator cit = command.begin();
668 for (; cit != command.end(); ++cit) {
671 inquote1 = !inquote1;
674 inquote2 = !inquote2;
677 if (!inquote1 && !inquote2)
678 cit = ++command.insert(cit, '\\');
684 if (format_name == "dvi" &&
685 !lyxrc.view_dvi_paper_option.empty()) {
686 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
687 if (!paper_size.empty()) {
688 command += ' ' + lyxrc.view_dvi_paper_option;
689 command += ' ' + paper_size;
690 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
691 buffer.params().papersize != PAPER_CUSTOM)
696 if (!contains(command, token_from_format))
697 command += ' ' + token_from_format;
699 command = subst(command, token_from_format,
700 quoteName(onlyFileName(filename.toFilesystemEncoding()), quote_shell_filename));
701 command = subst(command, token_path_format,
702 quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
703 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
704 LYXERR(Debug::FILES, "Executing command: " << command);
705 // FIXME UNICODE utf8 can be wrong for files
706 buffer.message(_("Executing command: ") + from_utf8(command));
708 PathChanger p(filename.onlyPath());
710 one.startscript(Systemcall::DontWait, command,
711 buffer.filePath(), buffer.layoutPos());
713 // we can't report any sort of error, since we aren't waiting
718 bool Formats::edit(Buffer const & buffer, FileName const & filename,
719 string const & format_name) const
721 if (filename.empty() || !filename.exists()) {
722 Alert::error(_("Cannot edit file"),
723 bformat(_("File does not exist: %1$s"),
724 from_utf8(filename.absFileName())));
728 // LinkBack files look like PDF, but have the .linkback extension
729 string const ext = getExtension(filename.absFileName());
730 if (format_name == "pdf6" && ext == "linkback") {
731 #ifdef USE_MACOSX_PACKAGING
732 return editLinkBackFile(filename.absFileName().c_str());
734 Alert::error(_("Cannot edit file"),
735 _("LinkBack files can only be edited on Apple Mac OSX."));
737 #endif // USE_MACOSX_PACKAGING
740 Format const * format = getFormat(format_name);
741 if (format && format->editor().empty() &&
742 format->isChildFormat())
743 format = getFormat(format->parentFormat());
744 if (!format || format->editor().empty()) {
745 // FIXME: I believe this is the wrong place to show alerts, it should
746 // be done by the caller (this should be "utility" code)
747 Alert::error(_("Cannot edit file"),
748 bformat(_("No information for editing %1$s"),
749 translateIfPossible(prettyName(format_name))));
754 if (format->editor() == "auto") {
755 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
758 Alert::error(_("Cannot edit file"),
759 bformat(_("Auto-edit file %1$s failed"),
760 from_utf8(filename.absFileName())));
765 string command = format->editor();
767 if (!contains(command, token_from_format))
768 command += ' ' + token_from_format;
770 command = subst(command, token_from_format,
771 quoteName(filename.toFilesystemEncoding(), quote_shell_filename));
772 command = subst(command, token_path_format,
773 quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
774 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
775 LYXERR(Debug::FILES, "Executing command: " << command);
776 // FIXME UNICODE utf8 can be wrong for files
777 buffer.message(_("Executing command: ") + from_utf8(command));
780 one.startscript(Systemcall::DontWait, command,
781 buffer.filePath(), buffer.layoutPos());
783 // we can't report any sort of error, since we aren't waiting
788 docstring const Formats::prettyName(string const & name) const
790 Format const * format = getFormat(name);
792 return format->prettyname();
794 return from_utf8(name);
798 string const Formats::extension(string const & name) const
800 Format const * format = getFormat(name);
802 return format->extension();
808 string const Formats::extensions(string const & name) const
810 Format const * format = getFormat(name);
812 return format->extensions();
820 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
823 FlavorTranslator initFlavorTranslator()
825 FlavorTranslator f(OutputParams::LATEX, "latex");
826 f.addPair(OutputParams::DVILUATEX, "dviluatex");
827 f.addPair(OutputParams::LUATEX, "luatex");
828 f.addPair(OutputParams::PDFLATEX, "pdflatex");
829 f.addPair(OutputParams::XETEX, "xetex");
830 f.addPair(OutputParams::DOCBOOK5, "docbook-xml");
831 f.addPair(OutputParams::HTML, "xhtml");
832 f.addPair(OutputParams::TEXT, "text");
833 f.addPair(OutputParams::LYX, "lyx");
838 FlavorTranslator const & flavorTranslator()
840 static FlavorTranslator const translator = initFlavorTranslator();
847 std::string flavor2format(OutputParams::FLAVOR flavor)
849 return flavorTranslator().find(flavor);
853 /* Not currently needed, but I'll leave the code in case it is.
854 OutputParams::FLAVOR format2flavor(std::string fmt)
856 return flavorTranslator().find(fmt);