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();
105 bool Format::formatSorter(Format const * lhs, Format const * rhs)
107 return compare_locale(_(lhs->prettyname()), _(rhs->prettyname())) < 0;
110 bool operator<(Format const & a, Format const & b)
112 return compare_locale(_(a.prettyname()), _(b.prettyname())) < 0;
116 Format::Format(string const & n, string const & e, string const & p,
117 string const & s, string const & v, string const & ed,
118 string const & m, int flags)
119 : name_(n), prettyname_(p), shortcut_(s), viewer_(v),
120 editor_(ed), mime_(m), flags_(flags)
122 extension_list_ = getVectorFromString(e, ",");
123 LYXERR(Debug::GRAPHICS, "New Format: n=" << n << ", flags=" << flags);
127 bool Format::dummy() const
129 return extension().empty();
133 string const Format::extensions() const
135 return getStringFromVector(extension_list_, ", ");
139 bool Format::hasExtension(string const & e) const
141 return (find(extension_list_.begin(), extension_list_.end(), e)
142 != extension_list_.end());
146 bool Format::isChildFormat() const
150 return isDigitASCII(name_[name_.length() - 1]);
154 string const Format::parentFormat() const
156 return name_.substr(0, name_.length() - 1);
160 void Format::setExtensions(string const & e)
162 extension_list_ = getVectorFromString(e, ",");
166 // This method should return a reference, and throw an exception
167 // if the format named name cannot be found (Lgb)
168 Format const * Formats::getFormat(string const & name) const
170 FormatList::const_iterator cit =
171 find_if(formatlist.begin(), formatlist.end(),
172 FormatNamesEqual(name));
173 if (cit != formatlist.end())
182 /** Guess the file format name (as in Format::name()) from contents.
183 * Normally you don't want to use this directly, but rather
184 * Formats::getFormatFromFile().
186 string guessFormatFromContents(FileName const & fn)
188 // the different filetypes and what they contain in one of the first lines
189 // (dots are any characters). (Herbert 20020131)
192 // EPS %!PS-Adobe-3.0 EPSF...
196 // JPG \377\330... (0xFFD8)
199 // PBM P1... or P4 (B/W)
200 // PGM P2... or P5 (Grayscale)
201 // PPM P3... or P6 (color)
202 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
203 // SGI \001\332... (decimal 474)
205 // TIFF II... or MM...
207 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
208 // ...static char *...
209 // XWD \000\000\000\151 (0x00006900) decimal 105
211 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
212 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
213 // Z \037\235 UNIX compress
216 if (fn.empty() || !fn.isReadableFile())
219 ifstream ifs(fn.toFilesystemEncoding().c_str());
221 // Couldn't open file...
225 static string const gzipStamp = "\037\213";
228 static string const zipStamp = "PK";
230 // ZIP containers (koffice, openoffice.org etc).
231 static string const nonzipStamp = "\008\0\0\0mimetypeapplication/";
234 static string const compressStamp = "\037\235";
236 // DOS binary EPS according to Adobe TN-5002
237 static string const binEPSStamp = "\xC5\xD0\xD3\xC6";
240 // Maximum strings to read
241 int const max_count = 50;
244 // Maximum number of binary chars allowed for latex detection
245 int const max_bin = 5;
249 bool firstLine = true;
250 bool backslash = false;
251 bool maybelatex = false;
254 while ((count++ < max_count) && format.empty() && binchars <= max_bin) {
259 string const stamp = str.substr(0, 2);
260 if (firstLine && str.size() >= 2) {
261 // at first we check for a zipped file, because this
262 // information is saved in the first bytes of the file!
263 // also some graphic formats which save the information
264 // in the first line, too.
265 if (prefixIs(str, gzipStamp)) {
268 } else if (stamp == zipStamp &&
269 !contains(str, nonzipStamp)) {
272 } else if (stamp == compressStamp) {
276 } else if (stamp == "BM") {
279 } else if (stamp == "\377\330") {
282 } else if (stamp == "\001\332") {
284 } else if (prefixIs(str, binEPSStamp)) {
288 // Don't need to use str.at(0), str.at(1) because
289 // we already know that str.size() >= 2
290 } else if (str[0] == 'P') {
306 } else if ((stamp == "II") || (stamp == "MM")) {
309 } else if (prefixIs(str,"%TGIF")) {
312 } else if (prefixIs(str,"#FIG")) {
315 } else if (prefixIs(str,"GIF")) {
318 } else if (str.size() > 3) {
319 int const c = ((str[0] << 24) & (str[1] << 16) &
320 (str[2] << 8) & str[3]);
331 else if (contains(str,"EPSF"))
332 // dummy, if we have wrong file description like
333 // %!PS-Adobe-2.0EPSF"
336 else if (contains(str, "Grace"))
339 else if (contains(str, "%PDF"))
340 // autodetect pdf format for graphics inclusion
343 else if (contains(str, "PNG"))
346 else if (contains(str, "%!PS-Adobe")) {
349 if (contains(str,"EPSF"))
355 else if (contains(str, "_bits[]"))
358 else if (contains(str, "XPM") || contains(str, "static char *"))
361 else if (contains(str, "BITPIX"))
364 else if (contains(str, "\\documentclass") ||
365 contains(str, "\\chapter") ||
366 contains(str, "\\section") ||
367 contains(str, "\\begin") ||
368 contains(str, "\\end") ||
369 contains(str, "$$") ||
370 contains(str, "\\[") ||
371 contains(str, "\\]"))
374 if (contains(str, '\\'))
376 dollars += count_char(str, '$');
377 if (backslash && dollars > 1)
382 binchars += count_bin_chars(str);
385 if (format.empty() && binchars <= max_bin && maybelatex)
388 if (format.empty()) {
390 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
391 "\tFile type not recognised before EOF!");
393 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
397 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
398 << "\tCouldn't find a known format!");
405 string Formats::getFormatFromFile(FileName const & filename) const
407 if (filename.empty())
412 if (filename.exists()) {
413 magic_t magic_cookie = magic_open(MAGIC_MIME);
416 if (magic_load(magic_cookie, NULL) != 0) {
417 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
418 << "\tCouldn't load magic database - "
419 << magic_error(magic_cookie));
421 char const * result = magic_file(magic_cookie,
422 filename.toFilesystemEncoding().c_str());
425 mime = token(result, ';', 0);
427 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
428 << "\tCouldn't query magic database - "
429 << magic_error(magic_cookie));
431 // our own detection is better for binary files (can be anything)
432 // and different plain text formats
433 if (!mime.empty() && mime != "application/octet-stream" &&
434 mime != "text/plain") {
435 Formats::const_iterator cit =
436 find_if(formatlist.begin(), formatlist.end(),
437 FormatMimeEqual(mime));
438 if (cit != formats.end()) {
439 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
440 << mime << " -> " << cit->name());
441 // See special eps/ps handling below
442 if (mime == "application/postscript")
443 psformat = cit->name();
445 format = cit->name();
449 magic_close(magic_cookie);
456 // libmagic does not distinguish eps and ps.
457 // Therefore we need to use our own detection here, but only if it
458 // recognizes either ps or eps. Otherwise the libmagic guess will
459 // be better (bug 9146).
460 string const format = guessFormatFromContents(filename);
461 if (!psformat.empty()) {
462 if (isPostScriptFileFormat(format))
468 string const ext = getExtension(filename.absFileName());
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();
480 // try to find a format from the file extension.
481 return getFormatFromExtension(ext);
485 string Formats::getFormatFromExtension(string const & ext) const
488 // this is ambigous if two formats have the same extension,
489 // but better than nothing
490 Formats::const_iterator cit =
491 find_if(formatlist.begin(), formatlist.end(),
492 FormatExtensionsEqual(ext));
493 if (cit != formats.end()) {
494 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
495 << ext << " -> " << cit->name());
503 /// Used to store last timestamp of file and whether it is (was) zipped
506 std::time_t timestamp;
507 ZippedInfo(bool zipped, std::time_t timestamp)
508 : zipped(zipped), timestamp(timestamp) { }
513 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
514 static std::map<std::string, ZippedInfo> zipped_;
517 bool Formats::isZippedFile(support::FileName const & filename) const {
518 string const & fname = filename.absFileName();
519 time_t timestamp = filename.lastModified();
520 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
521 if (it != zipped_.end() && it->second.timestamp == timestamp)
522 return it->second.zipped;
523 string const & format = getFormatFromFile(filename);
524 bool zipped = (format == "gzip" || format == "zip");
525 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
530 bool Formats::isZippedFileFormat(string const & format)
532 return contains("gzip zip compress", format) && !format.empty();
536 bool Formats::isPostScriptFileFormat(string const & format)
538 return format == "ps" || format == "eps";
541 static string fixCommand(string const & cmd, string const & ext,
542 os::auto_open_mode mode)
544 // configure.py says we do not want a viewer/editor
548 // Does the OS manage this format?
549 if (os::canAutoOpenFile(ext, mode))
552 // if configure.py found nothing, clear the command
553 if (token(cmd, ' ', 0) == "auto")
556 // use the command found by configure.py
561 void Formats::setAutoOpen()
563 FormatList::iterator fit = formatlist.begin();
564 FormatList::iterator const fend = formatlist.end();
565 for ( ; fit != fend ; ++fit) {
566 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
567 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
572 int Formats::getNumber(string const & name) const
574 FormatList::const_iterator cit =
575 find_if(formatlist.begin(), formatlist.end(),
576 FormatNamesEqual(name));
577 if (cit != formatlist.end())
578 return distance(formatlist.begin(), cit);
584 void Formats::add(string const & name)
586 if (!getFormat(name))
587 add(name, name, name, string(), string(), string(),
588 string(), Format::document);
592 void Formats::add(string const & name, string const & extensions,
593 string const & prettyname, string const & shortcut,
594 string const & viewer, string const & editor,
595 string const & mime, int flags)
597 FormatList::iterator it =
598 find_if(formatlist.begin(), formatlist.end(),
599 FormatNamesEqual(name));
600 if (it == formatlist.end())
601 formatlist.push_back(Format(name, extensions, prettyname,
602 shortcut, viewer, editor, mime, flags));
604 *it = Format(name, extensions, prettyname, shortcut, viewer,
605 editor, mime, flags);
609 void Formats::erase(string const & name)
611 FormatList::iterator it =
612 find_if(formatlist.begin(), formatlist.end(),
613 FormatNamesEqual(name));
614 if (it != formatlist.end())
615 formatlist.erase(it);
621 std::sort(formatlist.begin(), formatlist.end());
625 void Formats::setViewer(string const & name, string const & command)
628 FormatList::iterator it =
629 find_if(formatlist.begin(), formatlist.end(),
630 FormatNamesEqual(name));
631 if (it != formatlist.end())
632 it->setViewer(command);
636 void Formats::setEditor(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->setEditor(command);
647 bool Formats::view(Buffer const & buffer, FileName const & filename,
648 string const & format_name) const
650 if (filename.empty() || !filename.exists()) {
651 Alert::error(_("Cannot view file"),
652 bformat(_("File does not exist: %1$s"),
653 from_utf8(filename.absFileName())));
657 Format const * format = getFormat(format_name);
658 if (format && format->viewer().empty() &&
659 format->isChildFormat())
660 format = getFormat(format->parentFormat());
661 if (!format || format->viewer().empty()) {
662 // FIXME: I believe this is the wrong place to show alerts, it should be done
663 // by the caller (this should be "utility" code)
664 Alert::error(_("Cannot view file"),
665 bformat(_("No information for viewing %1$s"),
666 prettyName(format_name)));
670 if (format->viewer() == "auto") {
671 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
674 Alert::error(_("Cannot view file"),
675 bformat(_("Auto-view file %1$s failed"),
676 from_utf8(filename.absFileName())));
681 string command = format->viewer();
683 if (format_name == "dvi" &&
684 !lyxrc.view_dvi_paper_option.empty()) {
685 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
686 if (!paper_size.empty()) {
687 command += ' ' + lyxrc.view_dvi_paper_option;
688 command += ' ' + paper_size;
689 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
690 buffer.params().papersize != PAPER_CUSTOM)
695 if (!contains(command, token_from_format))
696 command += ' ' + token_from_format;
698 command = subst(command, token_from_format, quoteName(onlyFileName(filename.toFilesystemEncoding())));
699 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
700 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
701 LYXERR(Debug::FILES, "Executing command: " << command);
702 // FIXME UNICODE utf8 can be wrong for files
703 buffer.message(_("Executing command: ") + from_utf8(command));
705 PathChanger p(filename.onlyPath());
707 one.startscript(Systemcall::DontWait, command, buffer.filePath());
709 // we can't report any sort of error, since we aren't waiting
714 bool Formats::edit(Buffer const & buffer, FileName const & filename,
715 string const & format_name) const
717 if (filename.empty() || !filename.exists()) {
718 Alert::error(_("Cannot edit file"),
719 bformat(_("File does not exist: %1$s"),
720 from_utf8(filename.absFileName())));
724 // LinkBack files look like PDF, but have the .linkback extension
725 string const ext = getExtension(filename.absFileName());
726 if (format_name == "pdf6" && ext == "linkback") {
727 #ifdef USE_MACOSX_PACKAGING
728 return editLinkBackFile(filename.absFileName().c_str());
730 Alert::error(_("Cannot edit file"),
731 _("LinkBack files can only be edited on Apple Mac OSX."));
733 #endif // USE_MACOSX_PACKAGING
736 Format const * format = getFormat(format_name);
737 if (format && format->editor().empty() &&
738 format->isChildFormat())
739 format = getFormat(format->parentFormat());
740 if (!format || format->editor().empty()) {
741 // FIXME: I believe this is the wrong place to show alerts, it should
742 // be done by the caller (this should be "utility" code)
743 Alert::error(_("Cannot edit file"),
744 bformat(_("No information for editing %1$s"),
745 prettyName(format_name)));
750 if (format->editor() == "auto") {
751 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
754 Alert::error(_("Cannot edit file"),
755 bformat(_("Auto-edit file %1$s failed"),
756 from_utf8(filename.absFileName())));
761 string command = format->editor();
763 if (!contains(command, token_from_format))
764 command += ' ' + token_from_format;
766 command = subst(command, token_from_format, quoteName(filename.toFilesystemEncoding()));
767 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
768 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
769 LYXERR(Debug::FILES, "Executing command: " << command);
770 // FIXME UNICODE utf8 can be wrong for files
771 buffer.message(_("Executing command: ") + from_utf8(command));
774 one.startscript(Systemcall::DontWait, command, buffer.filePath());
776 // we can't report any sort of error, since we aren't waiting
781 docstring const Formats::prettyName(string const & name) const
783 Format const * format = getFormat(name);
785 return from_utf8(format->prettyname());
787 return from_utf8(name);
791 string const Formats::extension(string const & name) const
793 Format const * format = getFormat(name);
795 return format->extension();
801 string const Formats::extensions(string const & name) const
803 Format const * format = getFormat(name);
805 return format->extensions();
813 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
816 FlavorTranslator initFlavorTranslator()
818 FlavorTranslator f(OutputParams::LATEX, "latex");
819 f.addPair(OutputParams::DVILUATEX, "dviluatex");
820 f.addPair(OutputParams::LUATEX, "luatex");
821 f.addPair(OutputParams::PDFLATEX, "pdflatex");
822 f.addPair(OutputParams::XETEX, "xetex");
823 f.addPair(OutputParams::XML, "docbook-xml");
824 f.addPair(OutputParams::HTML, "xhtml");
825 f.addPair(OutputParams::TEXT, "text");
830 FlavorTranslator const & flavorTranslator()
832 static FlavorTranslator const translator = initFlavorTranslator();
839 std::string flavor2format(OutputParams::FLAVOR flavor)
841 return flavorTranslator().find(flavor);
845 /* Not currently needed, but I'll leave the code in case it is.
846 OutputParams::FLAVOR format2flavor(std::string fmt)
848 return flavorTranslator().find(fmt);
853 Formats system_formats;