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/filetools.h"
23 #include "support/gettext.h"
24 #include "support/lstrings.h"
25 #include "support/mutex.h"
26 #include "support/docstream.h"
27 #include "support/os.h"
28 #include "support/PathChanger.h"
29 #include "support/Systemcall.h"
30 #include "support/textutils.h"
31 #include "support/Translator.h"
37 // FIXME: Q_OS_MAC is not available, it's in Qt
38 #ifdef USE_MACOSX_PACKAGING
39 #include "support/linkback/LinkBackProxy.h"
47 using namespace lyx::support;
51 namespace Alert = frontend::Alert;
52 namespace os = support::os;
56 string const token_from_format("$$i");
57 string const token_path_format("$$p");
58 string const token_socket_format("$$a");
61 class FormatNamesEqual : public unary_function<Format, bool> {
63 FormatNamesEqual(string const & name)
66 bool operator()(Format const & f) const
68 return f.name() == name_;
75 class FormatExtensionsEqual : public unary_function<Format, bool> {
77 FormatExtensionsEqual(string const & extension)
78 : extension_(extension)
80 bool operator()(Format const & f) const
82 return f.hasExtension(extension_);
89 class FormatMimeEqual : public unary_function<Format, bool> {
91 FormatMimeEqual(string const & mime)
94 bool operator()(Format const & f) const
96 // The test for empty mime strings is needed since we allow
97 // formats with empty mime types.
98 return f.mime() == mime_ && !mime_.empty();
107 bool Format::formatSorter(Format const * lhs, Format const * rhs)
109 return compare_locale(_(lhs->prettyname()), _(rhs->prettyname())) < 0;
112 bool operator<(Format const & a, Format const & b)
114 return compare_locale(_(a.prettyname()), _(b.prettyname())) < 0;
118 Format::Format(string const & n, string const & e, string const & p,
119 string const & s, string const & v, string const & ed,
120 string const & m, int flags)
121 : name_(n), prettyname_(p), shortcut_(s), viewer_(v),
122 editor_(ed), mime_(m), flags_(flags)
124 extension_list_ = getVectorFromString(e, ",");
125 LYXERR(Debug::GRAPHICS, "New Format: n=" << n << ", flags=" << flags);
129 bool Format::dummy() const
131 return extension().empty();
135 string const Format::extensions() const
137 return getStringFromVector(extension_list_, ", ");
141 bool Format::hasExtension(string const & e) const
143 return (find(extension_list_.begin(), extension_list_.end(), e)
144 != extension_list_.end());
148 bool Format::isChildFormat() const
152 return isDigitASCII(name_[name_.length() - 1]);
156 string const Format::parentFormat() const
158 return name_.substr(0, name_.length() - 1);
162 void Format::setExtensions(string const & e)
164 extension_list_ = getVectorFromString(e, ",");
168 // This method should return a reference, and throw an exception
169 // if the format named name cannot be found (Lgb)
170 Format const * Formats::getFormat(string const & name) const
172 FormatList::const_iterator cit =
173 find_if(formatlist.begin(), formatlist.end(),
174 FormatNamesEqual(name));
175 if (cit != formatlist.end())
184 /** Guess the file format name (as in Format::name()) from contents.
185 * Normally you don't want to use this directly, but rather
186 * Formats::getFormatFromFile().
188 string guessFormatFromContents(FileName const & fn)
190 // the different filetypes and what they contain in one of the first lines
191 // (dots are any characters). (Herbert 20020131)
194 // EPS %!PS-Adobe-3.0 EPSF...
198 // JPG \377\330... (0xFFD8)
201 // PBM P1... or P4 (B/W)
202 // PGM P2... or P5 (Grayscale)
203 // PPM P3... or P6 (color)
204 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
205 // SGI \001\332... (decimal 474)
207 // TIFF II... or MM...
209 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
210 // ...static char *...
211 // XWD \000\000\000\151 (0x00006900) decimal 105
213 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
214 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
215 // Z \037\235 UNIX compress
218 if (fn.empty() || !fn.isReadableFile())
221 ifstream ifs(fn.toFilesystemEncoding().c_str());
223 // Couldn't open file...
227 static string const gzipStamp = "\037\213";
230 static string const zipStamp = "PK";
232 // ZIP containers (koffice, openoffice.org etc).
233 static string const nonzipStamp = "\008\0\0\0mimetypeapplication/";
236 static string const compressStamp = "\037\235";
238 // DOS binary EPS according to Adobe TN-5002
239 static string const binEPSStamp = "\xC5\xD0\xD3\xC6";
242 // Maximum strings to read
243 int const max_count = 50;
248 bool firstLine = true;
249 bool backslash = false;
250 bool maybelatex = false;
252 while ((count++ < max_count) && format.empty() && !maybelatex) {
257 string const stamp = str.substr(0, 2);
258 if (firstLine && str.size() >= 2) {
259 // at first we check for a zipped file, because this
260 // information is saved in the first bytes of the file!
261 // also some graphic formats which save the information
262 // in the first line, too.
263 if (prefixIs(str, gzipStamp)) {
266 } else if (stamp == zipStamp &&
267 !contains(str, nonzipStamp)) {
270 } else if (stamp == compressStamp) {
274 } else if (stamp == "BM") {
277 } else if (stamp == "\377\330") {
280 } else if (stamp == "\001\332") {
282 } else if (prefixIs(str, binEPSStamp)) {
286 // Don't need to use str.at(0), str.at(1) because
287 // we already know that str.size() >= 2
288 } else if (str[0] == 'P') {
304 } else if ((stamp == "II") || (stamp == "MM")) {
307 } else if (prefixIs(str,"%TGIF")) {
310 } else if (prefixIs(str,"#FIG")) {
313 } else if (prefixIs(str,"GIF")) {
316 } else if (str.size() > 3) {
317 int const c = ((str[0] << 24) & (str[1] << 16) &
318 (str[2] << 8) & str[3]);
329 else if (contains(str,"EPSF"))
330 // dummy, if we have wrong file description like
331 // %!PS-Adobe-2.0EPSF"
334 else if (contains(str, "Grace"))
337 else if (contains(str, "%PDF"))
338 // autodetect pdf format for graphics inclusion
341 else if (contains(str, "PNG"))
344 else if (contains(str, "%!PS-Adobe")) {
347 if (contains(str,"EPSF"))
353 else if (contains(str, "_bits[]"))
356 else if (contains(str, "XPM") || contains(str, "static char *"))
359 else if (contains(str, "BITPIX"))
362 else if (contains(str, "\\documentclass") ||
363 contains(str, "\\chapter") ||
364 contains(str, "\\section") ||
365 contains(str, "\\begin") ||
366 contains(str, "\\end") ||
367 contains(str, "$$") ||
368 contains(str, "\\[") ||
369 contains(str, "\\]"))
372 if (contains(str, '\\'))
374 dollars += count_char(str, '$');
375 if (backslash && dollars > 1)
381 if (format.empty() && maybelatex && !isBinaryFile(fn))
384 if (format.empty()) {
386 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
387 "\tFile type not recognised before EOF!");
389 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
393 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
394 << "\tCouldn't find a known format!");
401 string Formats::getFormatFromFile(FileName const & filename) const
403 if (filename.empty())
409 if (filename.exists()) {
410 magic_t magic_cookie = magic_open(MAGIC_MIME);
412 if (magic_load(magic_cookie, NULL) != 0) {
413 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
414 << "\tCouldn't load magic database - "
415 << magic_error(magic_cookie));
417 char const * result = magic_file(magic_cookie,
418 filename.toFilesystemEncoding().c_str());
421 mime = token(result, ';', 0);
423 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
424 << "\tCouldn't query magic database - "
425 << magic_error(magic_cookie));
427 // our own detection is better for binary files (can be anything)
428 // and different plain text formats
429 if (!mime.empty() && mime != "application/octet-stream" &&
430 mime != "text/plain") {
431 Formats::const_iterator cit =
432 find_if(formatlist.begin(), formatlist.end(),
433 FormatMimeEqual(mime));
434 if (cit != formats.end()) {
435 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
436 << mime << " -> " << cit->name());
437 // See special eps/ps handling below
438 if (mime == "application/postscript")
439 psformat = cit->name();
441 format = cit->name();
445 magic_close(magic_cookie);
446 // libmagic recognizes as latex also some formats of ours
447 // such as pstex and pdftex. Therefore we have to perform
448 // additional checks in this case (bug 9244).
449 if (!format.empty() && format != "latex")
455 string const ext = getExtension(filename.absFileName());
456 if (format.empty()) {
457 // libmagic does not distinguish eps and ps.
458 // Therefore we need to use our own detection here, but only if it
459 // recognizes either ps or eps. Otherwise the libmagic guess will
460 // be better (bug 9146).
461 format = guessFormatFromContents(filename);
462 if (!psformat.empty()) {
463 if (isPostScriptFileFormat(format))
469 if (isZippedFileFormat(format) && !ext.empty()) {
470 string const & fmt_name = formats.getFormatFromExtension(ext);
471 if (!fmt_name.empty()) {
472 Format const * p_format = formats.getFormat(fmt_name);
473 if (p_format && p_format->zippedNative())
474 return p_format->name();
477 // Don't simply return latex (bug 9244).
478 if (!format.empty() && format != "latex")
482 // Both libmagic and our guessing from contents may return as latex
483 // also lyx files and our pstex and pdftex formats. In this case we
484 // give precedence to the format determined by the extension.
485 if (format == "latex") {
486 format = getFormatFromExtension(ext);
487 return format.empty() ? "latex" : format;
490 // try to find a format from the file extension.
491 return getFormatFromExtension(ext);
495 string Formats::getFormatFromExtension(string const & ext) const
498 // this is ambigous if two formats have the same extension,
499 // but better than nothing
500 Formats::const_iterator cit =
501 find_if(formatlist.begin(), formatlist.end(),
502 FormatExtensionsEqual(ext));
503 if (cit != formats.end()) {
504 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
505 << ext << " -> " << cit->name());
513 /// Used to store last timestamp of file and whether it is (was) zipped
516 std::time_t timestamp;
517 ZippedInfo(bool zipped, std::time_t timestamp)
518 : zipped(zipped), timestamp(timestamp) { }
522 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
523 static std::map<std::string, ZippedInfo> zipped_;
524 static Mutex zipped_mutex;
527 bool Formats::isZippedFile(support::FileName const & filename) const {
528 string const & fname = filename.absFileName();
529 time_t timestamp = filename.lastModified();
530 Mutex::Locker lock(&zipped_mutex);
531 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
532 if (it != zipped_.end() && it->second.timestamp == timestamp)
533 return it->second.zipped;
534 string const & format = getFormatFromFile(filename);
535 bool zipped = (format == "gzip" || format == "zip");
536 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
541 bool Formats::isZippedFileFormat(string const & format)
543 return contains("gzip zip compress", format) && !format.empty();
547 bool Formats::isPostScriptFileFormat(string const & format)
549 return format == "ps" || format == "eps";
552 static string fixCommand(string const & cmd, string const & ext,
553 os::auto_open_mode mode)
555 // configure.py says we do not want a viewer/editor
559 // Does the OS manage this format?
560 if (os::canAutoOpenFile(ext, mode))
563 // if configure.py found nothing, clear the command
564 if (token(cmd, ' ', 0) == "auto")
567 // use the command found by configure.py
572 void Formats::setAutoOpen()
574 FormatList::iterator fit = formatlist.begin();
575 FormatList::iterator const fend = formatlist.end();
576 for ( ; fit != fend ; ++fit) {
577 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
578 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
583 int Formats::getNumber(string const & name) const
585 FormatList::const_iterator cit =
586 find_if(formatlist.begin(), formatlist.end(),
587 FormatNamesEqual(name));
588 if (cit != formatlist.end())
589 return distance(formatlist.begin(), cit);
595 void Formats::add(string const & name)
597 if (!getFormat(name))
598 add(name, name, name, string(), string(), string(),
599 string(), Format::document);
603 void Formats::add(string const & name, string const & extensions,
604 string const & prettyname, string const & shortcut,
605 string const & viewer, string const & editor,
606 string const & mime, int flags)
608 FormatList::iterator it =
609 find_if(formatlist.begin(), formatlist.end(),
610 FormatNamesEqual(name));
611 if (it == formatlist.end())
612 formatlist.push_back(Format(name, extensions, prettyname,
613 shortcut, viewer, editor, mime, flags));
615 *it = Format(name, extensions, prettyname, shortcut, viewer,
616 editor, mime, flags);
620 void Formats::erase(string const & name)
622 FormatList::iterator it =
623 find_if(formatlist.begin(), formatlist.end(),
624 FormatNamesEqual(name));
625 if (it != formatlist.end())
626 formatlist.erase(it);
632 std::sort(formatlist.begin(), formatlist.end());
636 void Formats::setViewer(string const & name, string const & command)
639 FormatList::iterator it =
640 find_if(formatlist.begin(), formatlist.end(),
641 FormatNamesEqual(name));
642 if (it != formatlist.end())
643 it->setViewer(command);
647 void Formats::setEditor(string const & name, string const & command)
650 FormatList::iterator it =
651 find_if(formatlist.begin(), formatlist.end(),
652 FormatNamesEqual(name));
653 if (it != formatlist.end())
654 it->setEditor(command);
658 bool Formats::view(Buffer const & buffer, FileName const & filename,
659 string const & format_name) const
661 if (filename.empty() || !filename.exists()) {
662 Alert::error(_("Cannot view file"),
663 bformat(_("File does not exist: %1$s"),
664 from_utf8(filename.absFileName())));
668 Format const * format = getFormat(format_name);
669 if (format && format->viewer().empty() &&
670 format->isChildFormat())
671 format = getFormat(format->parentFormat());
672 if (!format || format->viewer().empty()) {
673 // FIXME: I believe this is the wrong place to show alerts, it should be done
674 // by the caller (this should be "utility" code)
675 Alert::error(_("Cannot view file"),
676 bformat(_("No information for viewing %1$s"),
677 prettyName(format_name)));
681 if (format->viewer() == "auto") {
682 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
685 Alert::error(_("Cannot view file"),
686 bformat(_("Auto-view file %1$s failed"),
687 from_utf8(filename.absFileName())));
692 string command = format->viewer();
694 if (format_name == "dvi" &&
695 !lyxrc.view_dvi_paper_option.empty()) {
696 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
697 if (!paper_size.empty()) {
698 command += ' ' + lyxrc.view_dvi_paper_option;
699 command += ' ' + paper_size;
700 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
701 buffer.params().papersize != PAPER_CUSTOM)
706 if (!contains(command, token_from_format))
707 command += ' ' + token_from_format;
709 command = subst(command, token_from_format,
710 quoteName(onlyFileName(filename.toFilesystemEncoding()), quote_shell_filename));
711 command = subst(command, token_path_format,
712 quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
713 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
714 LYXERR(Debug::FILES, "Executing command: " << command);
715 // FIXME UNICODE utf8 can be wrong for files
716 buffer.message(_("Executing command: ") + from_utf8(command));
718 PathChanger p(filename.onlyPath());
720 one.startscript(Systemcall::DontWait, command,
721 buffer.filePath(), buffer.layoutPos());
723 // we can't report any sort of error, since we aren't waiting
728 bool Formats::edit(Buffer const & buffer, FileName const & filename,
729 string const & format_name) const
731 if (filename.empty() || !filename.exists()) {
732 Alert::error(_("Cannot edit file"),
733 bformat(_("File does not exist: %1$s"),
734 from_utf8(filename.absFileName())));
738 // LinkBack files look like PDF, but have the .linkback extension
739 string const ext = getExtension(filename.absFileName());
740 if (format_name == "pdf6" && ext == "linkback") {
741 #ifdef USE_MACOSX_PACKAGING
742 return editLinkBackFile(filename.absFileName().c_str());
744 Alert::error(_("Cannot edit file"),
745 _("LinkBack files can only be edited on Apple Mac OSX."));
747 #endif // USE_MACOSX_PACKAGING
750 Format const * format = getFormat(format_name);
751 if (format && format->editor().empty() &&
752 format->isChildFormat())
753 format = getFormat(format->parentFormat());
754 if (!format || format->editor().empty()) {
755 // FIXME: I believe this is the wrong place to show alerts, it should
756 // be done by the caller (this should be "utility" code)
757 Alert::error(_("Cannot edit file"),
758 bformat(_("No information for editing %1$s"),
759 prettyName(format_name)));
764 if (format->editor() == "auto") {
765 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
768 Alert::error(_("Cannot edit file"),
769 bformat(_("Auto-edit file %1$s failed"),
770 from_utf8(filename.absFileName())));
775 string command = format->editor();
777 if (!contains(command, token_from_format))
778 command += ' ' + token_from_format;
780 command = subst(command, token_from_format,
781 quoteName(filename.toFilesystemEncoding(), quote_shell_filename));
782 command = subst(command, token_path_format,
783 quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
784 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
785 LYXERR(Debug::FILES, "Executing command: " << command);
786 // FIXME UNICODE utf8 can be wrong for files
787 buffer.message(_("Executing command: ") + from_utf8(command));
790 one.startscript(Systemcall::DontWait, command,
791 buffer.filePath(), buffer.layoutPos());
793 // we can't report any sort of error, since we aren't waiting
798 docstring const Formats::prettyName(string const & name) const
800 Format const * format = getFormat(name);
802 return from_utf8(format->prettyname());
804 return from_utf8(name);
808 string const Formats::extension(string const & name) const
810 Format const * format = getFormat(name);
812 return format->extension();
818 string const Formats::extensions(string const & name) const
820 Format const * format = getFormat(name);
822 return format->extensions();
830 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
833 FlavorTranslator initFlavorTranslator()
835 FlavorTranslator f(OutputParams::LATEX, "latex");
836 f.addPair(OutputParams::DVILUATEX, "dviluatex");
837 f.addPair(OutputParams::LUATEX, "luatex");
838 f.addPair(OutputParams::PDFLATEX, "pdflatex");
839 f.addPair(OutputParams::XETEX, "xetex");
840 f.addPair(OutputParams::XML, "docbook-xml");
841 f.addPair(OutputParams::HTML, "xhtml");
842 f.addPair(OutputParams::TEXT, "text");
847 FlavorTranslator const & flavorTranslator()
849 static FlavorTranslator const translator = initFlavorTranslator();
856 std::string flavor2format(OutputParams::FLAVOR flavor)
858 return flavorTranslator().find(flavor);
862 /* Not currently needed, but I'll leave the code in case it is.
863 OutputParams::FLAVOR format2flavor(std::string fmt)
865 return flavorTranslator().find(fmt);
870 Formats system_formats;