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/os.h"
26 #include "support/PathChanger.h"
27 #include "support/Systemcall.h"
28 #include "support/textutils.h"
29 #include "support/Translator.h"
35 // FIXME: Q_WS_MACX is not available, it's in Qt
36 #ifdef USE_MACOSX_PACKAGING
37 #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");
59 class FormatNamesEqual : public unary_function<Format, bool> {
61 FormatNamesEqual(string const & name)
64 bool operator()(Format const & f) const
66 return f.name() == name_;
73 class FormatExtensionsEqual : public unary_function<Format, bool> {
75 FormatExtensionsEqual(string const & extension)
76 : extension_(extension)
78 bool operator()(Format const & f) const
80 return f.hasExtension(extension_);
87 class FormatMimeEqual : public unary_function<Format, bool> {
89 FormatMimeEqual(string const & mime)
92 bool operator()(Format const & f) const
94 // The test for empty mime strings is needed since we allow
95 // formats with empty mime types.
96 return f.mime() == mime_ && !mime_.empty();
103 class FormatPrettyNameEqual : public unary_function<Format, bool> {
105 FormatPrettyNameEqual(string const & prettyname)
106 : prettyname_(prettyname)
108 bool operator()(Format const & f) const
110 return f.prettyname() == prettyname_;
118 bool Format::formatSorter(Format const * lhs, Format const * rhs)
120 return _(lhs->prettyname()) < _(rhs->prettyname());
123 bool operator<(Format const & a, Format const & b)
125 return _(a.prettyname()) < _(b.prettyname());
129 Format::Format(string const & n, string const & e, string const & p,
130 string const & s, string const & v, string const & ed,
131 string const & m, int flags)
132 : name_(n), prettyname_(p), shortcut_(s), viewer_(v),
133 editor_(ed), mime_(m), flags_(flags)
135 extension_list_ = getVectorFromString(e, ",");
136 LYXERR(Debug::GRAPHICS, "New Format: n=" << n << ", flags=" << flags);
140 bool Format::dummy() const
142 return extension().empty();
146 string const Format::extensions() const
148 return getStringFromVector(extension_list_, ", ");
152 bool Format::hasExtension(string const & e) const
154 return (find(extension_list_.begin(), extension_list_.end(), e)
155 != extension_list_.end());
159 bool Format::isChildFormat() const
163 return isDigitASCII(name_[name_.length() - 1]);
167 string const Format::parentFormat() const
169 return name_.substr(0, name_.length() - 1);
173 void Format::setExtensions(string const & e)
175 extension_list_ = getVectorFromString(e, ",");
179 // This method should return a reference, and throw an exception
180 // if the format named name cannot be found (Lgb)
181 Format const * Formats::getFormat(string const & name) const
183 FormatList::const_iterator cit =
184 find_if(formatlist.begin(), formatlist.end(),
185 FormatNamesEqual(name));
186 if (cit != formatlist.end())
195 /** Guess the file format name (as in Format::name()) from contents.
196 * Normally you don't want to use this directly, but rather
197 * Formats::getFormatFromFile().
199 string guessFormatFromContents(FileName const & fn)
201 // the different filetypes and what they contain in one of the first lines
202 // (dots are any characters). (Herbert 20020131)
205 // EPS %!PS-Adobe-3.0 EPSF...
212 // PBM P1... or P4 (B/W)
213 // PGM P2... or P5 (Grayscale)
214 // PPM P3... or P6 (color)
215 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
216 // SGI \001\332... (decimal 474)
218 // TIFF II... or MM...
220 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
221 // ...static char *...
222 // XWD \000\000\000\151 (0x00006900) decimal 105
224 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
225 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
226 // Z \037\235 UNIX compress
229 if (fn.empty() || !fn.isReadableFile())
232 ifstream ifs(fn.toFilesystemEncoding().c_str());
234 // Couldn't open file...
238 static string const gzipStamp = "\037\213";
241 static string const zipStamp = "PK";
243 // ZIP containers (koffice, openoffice.org etc).
244 static string const nonzipStamp = "\008\0\0\0mimetypeapplication/";
247 static string const compressStamp = "\037\235";
249 // Maximum strings to read
250 int const max_count = 50;
255 bool firstLine = true;
256 bool backslash = false;
258 while ((count++ < max_count) && format.empty()) {
263 string const stamp = str.substr(0, 2);
264 if (firstLine && str.size() >= 2) {
265 // at first we check for a zipped file, because this
266 // information is saved in the first bytes of the file!
267 // also some graphic formats which save the information
268 // in the first line, too.
269 if (prefixIs(str, gzipStamp)) {
272 } else if (stamp == zipStamp &&
273 !contains(str, nonzipStamp)) {
276 } else if (stamp == compressStamp) {
280 } else if (stamp == "BM") {
283 } else if (stamp == "\001\332") {
287 // Don't need to use str.at(0), str.at(1) because
288 // we already know that str.size() >= 2
289 } else if (str[0] == 'P') {
305 } else if ((stamp == "II") || (stamp == "MM")) {
308 } else if (prefixIs(str,"%TGIF")) {
311 } else if (prefixIs(str,"#FIG")) {
314 } else if (prefixIs(str,"GIF")) {
317 } else if (str.size() > 3) {
318 int const c = ((str[0] << 24) & (str[1] << 16) &
319 (str[2] << 8) & str[3]);
330 else if (contains(str,"EPSF"))
331 // dummy, if we have wrong file description like
332 // %!PS-Adobe-2.0EPSF"
335 else if (contains(str, "Grace"))
338 else if (contains(str, "JFIF"))
341 else if (contains(str, "%PDF"))
342 // autodetect pdf format for graphics inclusion
345 else if (contains(str, "PNG"))
348 else if (contains(str, "%!PS-Adobe")) {
351 if (contains(str,"EPSF"))
357 else if (contains(str, "_bits[]"))
360 else if (contains(str, "XPM") || contains(str, "static char *"))
363 else if (contains(str, "BITPIX"))
366 else if (contains(str, "\\documentclass") ||
367 contains(str, "\\chapter") ||
368 contains(str, "\\section") ||
369 contains(str, "\\begin") ||
370 contains(str, "\\end") ||
371 contains(str, "$$") ||
372 contains(str, "\\[") ||
373 contains(str, "\\]"))
376 if (contains(str, '\\'))
378 dollars += count_char(str, '$');
382 if (format.empty() && backslash && dollars > 1)
386 if (format.empty()) {
388 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
389 "\tFile type not recognised before EOF!");
391 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
395 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
396 << "\tCouldn't find a known format!");
403 string Formats::getFormatFromFile(FileName const & filename) const
405 if (filename.empty())
409 if (filename.exists()) {
410 magic_t magic_cookie = magic_open(MAGIC_MIME);
413 if (magic_load(magic_cookie, NULL) != 0) {
414 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
415 << "\tCouldn't load magic database - "
416 << magic_error(magic_cookie));
418 string mime = magic_file(magic_cookie,
419 filename.toFilesystemEncoding().c_str());
420 mime = token(mime, ';', 0);
421 // we need our own ps/eps detection
422 if ((mime != "application/postscript") && (mime != "text/plain")) {
423 Formats::const_iterator cit =
424 find_if(formatlist.begin(), formatlist.end(),
425 FormatMimeEqual(mime));
426 if (cit != formats.end()) {
427 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
428 << mime << " -> " << cit->name());
429 format = cit->name();
433 magic_close(magic_cookie);
440 string const format = guessFormatFromContents(filename);
441 string const ext = getExtension(filename.absFileName());
442 if (isZippedFileFormat(format) && !ext.empty()) {
443 string const & fmt_name = formats.getFormatFromExtension(ext);
444 if (!fmt_name.empty()) {
445 Format const * p_format = formats.getFormat(fmt_name);
446 if (p_format && p_format->zippedNative())
447 return p_format->name();
453 // try to find a format from the file extension.
454 return getFormatFromExtension(ext);
458 string Formats::getFormatFromExtension(string const & ext) const
461 // this is ambigous if two formats have the same extension,
462 // but better than nothing
463 Formats::const_iterator cit =
464 find_if(formatlist.begin(), formatlist.end(),
465 FormatExtensionsEqual(ext));
466 if (cit != formats.end()) {
467 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
468 << ext << " -> " << cit->name());
476 string Formats::getFormatFromPrettyName(string const & prettyname) const
478 if (!prettyname.empty()) {
479 Formats::const_iterator cit =
480 find_if(formatlist.begin(), formatlist.end(),
481 FormatPrettyNameEqual(prettyname));
482 if (cit != formats.end())
489 /// Used to store last timestamp of file and whether it is (was) zipped
492 std::time_t timestamp;
493 ZippedInfo(bool zipped, std::time_t timestamp)
494 : zipped(zipped), timestamp(timestamp) { }
498 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
499 static std::map<std::string, ZippedInfo> zipped_;
502 bool Formats::isZippedFile(support::FileName const & filename) const {
503 string const & fname = filename.absFileName();
504 time_t timestamp = filename.lastModified();
505 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
506 if (it != zipped_.end() && it->second.timestamp == timestamp)
507 return it->second.zipped;
508 string const & format = getFormatFromFile(filename);
509 bool zipped = (format == "gzip" || format == "zip");
510 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
515 bool Formats::isZippedFileFormat(string const & format)
517 return contains("gzip zip compress", format) && !format.empty();
521 bool Formats::isPostScriptFileFormat(string const & format)
523 return format == "ps" || format == "eps";
526 static string fixCommand(string const & cmd, string const & ext,
527 os::auto_open_mode mode)
529 // configure.py says we do not want a viewer/editor
533 // Does the OS manage this format?
534 if (os::canAutoOpenFile(ext, mode))
537 // if configure.py found nothing, clear the command
538 if (token(cmd, ' ', 0) == "auto")
541 // use the command found by configure.py
546 void Formats::setAutoOpen()
548 FormatList::iterator fit = formatlist.begin();
549 FormatList::iterator const fend = formatlist.end();
550 for ( ; fit != fend ; ++fit) {
551 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
552 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
557 int Formats::getNumber(string const & name) const
559 FormatList::const_iterator cit =
560 find_if(formatlist.begin(), formatlist.end(),
561 FormatNamesEqual(name));
562 if (cit != formatlist.end())
563 return distance(formatlist.begin(), cit);
569 void Formats::add(string const & name)
571 if (!getFormat(name))
572 add(name, name, name, string(), string(), string(),
573 string(), Format::document);
577 void Formats::add(string const & name, string const & extensions,
578 string const & prettyname, string const & shortcut,
579 string const & viewer, string const & editor,
580 string const & mime, int flags)
582 FormatList::iterator it =
583 find_if(formatlist.begin(), formatlist.end(),
584 FormatNamesEqual(name));
585 if (it == formatlist.end())
586 formatlist.push_back(Format(name, extensions, prettyname,
587 shortcut, viewer, editor, mime, flags));
589 *it = Format(name, extensions, prettyname, shortcut, viewer,
590 editor, mime, flags);
594 void Formats::erase(string const & name)
596 FormatList::iterator it =
597 find_if(formatlist.begin(), formatlist.end(),
598 FormatNamesEqual(name));
599 if (it != formatlist.end())
600 formatlist.erase(it);
606 std::sort(formatlist.begin(), formatlist.end());
610 void Formats::setViewer(string const & name, string const & command)
613 FormatList::iterator it =
614 find_if(formatlist.begin(), formatlist.end(),
615 FormatNamesEqual(name));
616 if (it != formatlist.end())
617 it->setViewer(command);
621 void Formats::setEditor(string const & name, string const & command)
624 FormatList::iterator it =
625 find_if(formatlist.begin(), formatlist.end(),
626 FormatNamesEqual(name));
627 if (it != formatlist.end())
628 it->setEditor(command);
632 bool Formats::view(Buffer const & buffer, FileName const & filename,
633 string const & format_name) const
635 if (filename.empty() || !filename.exists()) {
636 Alert::error(_("Cannot view file"),
637 bformat(_("File does not exist: %1$s"),
638 from_utf8(filename.absFileName())));
642 Format const * format = getFormat(format_name);
643 if (format && format->viewer().empty() &&
644 format->isChildFormat())
645 format = getFormat(format->parentFormat());
646 if (!format || format->viewer().empty()) {
647 // FIXME: I believe this is the wrong place to show alerts, it should be done
648 // by the caller (this should be "utility" code)
649 Alert::error(_("Cannot view file"),
650 bformat(_("No information for viewing %1$s"),
651 prettyName(format_name)));
655 if (format->viewer() == "auto") {
656 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
659 Alert::error(_("Cannot view file"),
660 bformat(_("Auto-view file %1$s failed"),
661 from_utf8(filename.absFileName())));
666 string command = libScriptSearch(format->viewer());
668 if (format_name == "dvi" &&
669 !lyxrc.view_dvi_paper_option.empty()) {
670 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
671 if (!paper_size.empty()) {
672 command += ' ' + lyxrc.view_dvi_paper_option;
673 command += ' ' + paper_size;
674 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
675 buffer.params().papersize != PAPER_CUSTOM)
680 if (!contains(command, token_from_format))
681 command += ' ' + token_from_format;
683 command = subst(command, token_from_format, quoteName(onlyFileName(filename.toFilesystemEncoding())));
684 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
685 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
686 LYXERR(Debug::FILES, "Executing command: " << command);
687 // FIXME UNICODE utf8 can be wrong for files
688 buffer.message(_("Executing command: ") + from_utf8(command));
690 PathChanger p(filename.onlyPath());
692 one.startscript(Systemcall::DontWait, command, buffer.filePath());
694 // we can't report any sort of error, since we aren't waiting
699 bool Formats::edit(Buffer const & buffer, FileName const & filename,
700 string const & format_name) const
702 if (filename.empty() || !filename.exists()) {
703 Alert::error(_("Cannot edit file"),
704 bformat(_("File does not exist: %1$s"),
705 from_utf8(filename.absFileName())));
709 // LinkBack files look like PDF, but have the .linkback extension
710 string const ext = getExtension(filename.absFileName());
711 if (format_name == "pdf6" && ext == "linkback") {
712 #ifdef USE_MACOSX_PACKAGING
713 return editLinkBackFile(filename.absFileName().c_str());
715 Alert::error(_("Cannot edit file"),
716 _("LinkBack files can only be edited on Apple Mac OSX."));
718 #endif // USE_MACOSX_PACKAGING
721 Format const * format = getFormat(format_name);
722 if (format && format->editor().empty() &&
723 format->isChildFormat())
724 format = getFormat(format->parentFormat());
725 if (!format || format->editor().empty()) {
726 // FIXME: I believe this is the wrong place to show alerts, it should
727 // be done by the caller (this should be "utility" code)
728 Alert::error(_("Cannot edit file"),
729 bformat(_("No information for editing %1$s"),
730 prettyName(format_name)));
735 if (format->editor() == "auto") {
736 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
739 Alert::error(_("Cannot edit file"),
740 bformat(_("Auto-edit file %1$s failed"),
741 from_utf8(filename.absFileName())));
746 string command = format->editor();
748 if (!contains(command, token_from_format))
749 command += ' ' + token_from_format;
751 command = subst(command, token_from_format, quoteName(filename.toFilesystemEncoding()));
752 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
753 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
754 LYXERR(Debug::FILES, "Executing command: " << command);
755 // FIXME UNICODE utf8 can be wrong for files
756 buffer.message(_("Executing command: ") + from_utf8(command));
759 one.startscript(Systemcall::DontWait, command, buffer.filePath());
761 // we can't report any sort of error, since we aren't waiting
766 docstring const Formats::prettyName(string const & name) const
768 Format const * format = getFormat(name);
770 return from_utf8(format->prettyname());
772 return from_utf8(name);
776 string const Formats::extension(string const & name) const
778 Format const * format = getFormat(name);
780 return format->extension();
786 string const Formats::extensions(string const & name) const
788 Format const * format = getFormat(name);
790 return format->extensions();
798 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
801 FlavorTranslator initFlavorTranslator()
803 FlavorTranslator f(OutputParams::LATEX, "latex");
804 f.addPair(OutputParams::DVILUATEX, "dviluatex");
805 f.addPair(OutputParams::LUATEX, "luatex");
806 f.addPair(OutputParams::PDFLATEX, "pdflatex");
807 f.addPair(OutputParams::XETEX, "xetex");
808 f.addPair(OutputParams::XML, "docbook-xml");
809 f.addPair(OutputParams::HTML, "xhtml");
810 f.addPair(OutputParams::TEXT, "text");
815 FlavorTranslator const & flavorTranslator()
817 static FlavorTranslator translator = initFlavorTranslator();
824 std::string flavor2format(OutputParams::FLAVOR flavor)
826 return flavorTranslator().find(flavor);
830 /* Not currently needed, but I'll leave the code in case it is.
831 OutputParams::FLAVOR format2flavor(std::string fmt)
833 return flavorTranslator().find(fmt);
838 Formats system_formats;