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"
38 // FIXME: Q_OS_MAC is not available, it's in Qt
39 #ifdef USE_MACOSX_PACKAGING
40 #include "support/linkback/LinkBackProxy.h"
44 using namespace lyx::support;
48 namespace Alert = frontend::Alert;
49 namespace os = support::os;
53 string const token_from_format("$$i");
54 string const token_path_format("$$p");
55 string const token_socket_format("$$a");
58 class FormatNamesEqual : public unary_function<Format, bool> {
60 FormatNamesEqual(string const & name)
63 bool operator()(Format const & f) const
65 return f.name() == name_;
72 class FormatExtensionsEqual : public unary_function<Format, bool> {
74 FormatExtensionsEqual(string const & extension)
75 : extension_(extension)
77 bool operator()(Format const & f) const
79 return f.hasExtension(extension_);
86 class FormatMimeEqual : public unary_function<Format, bool> {
88 FormatMimeEqual(string const & mime)
91 bool operator()(Format const & f) const
93 // The test for empty mime strings is needed since we allow
94 // formats with empty mime types.
95 return f.mime() == mime_ && !mime_.empty();
104 bool Format::formatSorter(Format const * lhs, Format const * rhs)
106 return compare_locale(translateIfPossible(lhs->prettyname()),
107 translateIfPossible(rhs->prettyname())) < 0;
110 bool operator<(Format const & a, Format const & b)
112 return compare_locale(translateIfPossible(a.prettyname()),
113 translateIfPossible(b.prettyname())) < 0;
117 Format::Format(string const & n, string const & e, docstring const & p,
118 string const & s, string const & v, string const & ed,
119 string const & m, int flags)
120 : name_(n), prettyname_(p), shortcut_(s), viewer_(v),
121 editor_(ed), mime_(m), flags_(flags)
123 extension_list_ = getVectorFromString(e, ",");
124 LYXERR(Debug::GRAPHICS, "New Format: n=" << n << ", flags=" << flags);
128 bool Format::dummy() const
130 return extension().empty();
134 string const Format::extensions() const
136 return getStringFromVector(extension_list_, ", ");
140 bool Format::hasExtension(string const & e) const
142 return (find(extension_list_.begin(), extension_list_.end(), e)
143 != extension_list_.end());
147 bool Format::isChildFormat() const
151 return isDigitASCII(name_[name_.length() - 1]);
155 string const Format::parentFormat() const
157 return name_.substr(0, name_.length() - 1);
161 void Format::setExtensions(string const & e)
163 extension_list_ = getVectorFromString(e, ",");
167 // This method should return a reference, and throw an exception
168 // if the format named name cannot be found (Lgb)
169 Format const * Formats::getFormat(string const & name) const
171 FormatList::const_iterator cit =
172 find_if(formatlist_.begin(), formatlist_.end(),
173 FormatNamesEqual(name));
174 if (cit != formatlist_.end())
183 /** Guess the file format name (as in Format::name()) from contents.
184 * Normally you don't want to use this directly, but rather
185 * Formats::getFormatFromFile().
187 string guessFormatFromContents(FileName const & fn)
189 // the different filetypes and what they contain in one of the first lines
190 // (dots are any characters). (Herbert 20020131)
193 // EPS %!PS-Adobe-3.0 EPSF...
197 // JPG \377\330... (0xFFD8)
200 // PBM P1... or P4 (B/W)
201 // PGM P2... or P5 (Grayscale)
202 // PPM P3... or P6 (color)
203 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
204 // SGI \001\332... (decimal 474)
206 // TIFF II... or MM...
208 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
209 // ...static char *...
210 // XWD \000\000\000\151 (0x00006900) decimal 105
212 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
213 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
214 // Z \037\235 UNIX compress
217 if (fn.empty() || !fn.isReadableFile())
220 ifstream ifs(fn.toFilesystemEncoding().c_str());
222 // Couldn't open file...
226 static string const gzipStamp = "\037\213";
229 static string const zipStamp = "PK";
231 // ZIP containers (koffice, openoffice.org etc).
232 static string const nonzipStamp = "\010\0\0\0mimetypeapplication/";
235 static string const compressStamp = "\037\235";
237 // DOS binary EPS according to Adobe TN-5002
238 static string const binEPSStamp = "\xC5\xD0\xD3\xC6";
241 // Maximum strings to read
242 int const max_count = 50;
247 bool firstLine = true;
248 bool backslash = false;
249 bool maybelatex = false;
251 while ((count++ < max_count) && format.empty() && !maybelatex) {
256 string const stamp = str.substr(0, 2);
257 if (firstLine && str.size() >= 2) {
258 // at first we check for a zipped file, because this
259 // information is saved in the first bytes of the file!
260 // also some graphic formats which save the information
261 // in the first line, too.
262 if (prefixIs(str, gzipStamp)) {
265 } else if (stamp == zipStamp &&
266 !contains(str, nonzipStamp)) {
269 } else if (stamp == compressStamp) {
273 } else if (stamp == "BM") {
276 } else if (stamp == "\377\330") {
279 } else if (stamp == "\001\332") {
281 } else if (prefixIs(str, binEPSStamp)) {
285 // Don't need to use str.at(0), str.at(1) because
286 // we already know that str.size() >= 2
287 } else if (str[0] == 'P') {
303 } else if ((stamp == "II") || (stamp == "MM")) {
306 } else if (prefixIs(str,"%TGIF")) {
309 } else if (prefixIs(str,"#FIG")) {
312 } else if (prefixIs(str,"GIF")) {
315 } else if (str.size() > 3) {
316 int const c = ((str[0] << 24) & (str[1] << 16) &
317 (str[2] << 8) & str[3]);
328 else if (contains(str,"EPSF"))
329 // dummy, if we have wrong file description like
330 // %!PS-Adobe-2.0EPSF"
333 else if (contains(str, "Grace"))
336 else if (contains(str, "%PDF"))
337 // autodetect pdf format for graphics inclusion
340 else if (contains(str, "PNG"))
343 else if (contains(str, "%!PS-Adobe")) {
346 if (contains(str,"EPSF"))
352 else if (contains(str, "_bits[]"))
355 else if (contains(str, "XPM") || contains(str, "static char *"))
358 else if (contains(str, "BITPIX"))
361 else if (contains(str, "\\documentclass") ||
362 contains(str, "\\chapter") ||
363 contains(str, "\\section") ||
364 contains(str, "\\begin") ||
365 contains(str, "\\end") ||
366 contains(str, "$$") ||
367 contains(str, "\\[") ||
368 contains(str, "\\]"))
371 if (contains(str, '\\'))
373 dollars += count_char(str, '$');
374 if (backslash && dollars > 1)
380 if (format.empty() && maybelatex && !isBinaryFile(fn))
383 if (format.empty()) {
385 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
386 "\tFile type not recognised before EOF!");
388 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
392 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
393 << "\tCouldn't find a known format!");
400 string Formats::getFormatFromFile(FileName const & filename) const
402 if (filename.empty())
407 if (filename.exists()) {
408 // one instance of Magic that will be reused for next calls
409 // This avoids to read the magic file everytime
410 // If libmagic is not available, Magic::file returns an empty string.
412 string const result = magic.file(filename.toFilesystemEncoding());
413 string const mime = token(result, ';', 0);
414 // our own detection is better for binary files (can be anything)
415 // and different plain text formats
416 if (!mime.empty() && mime != "application/octet-stream" &&
417 mime != "text/plain") {
418 Formats::const_iterator cit =
419 find_if(formatlist_.begin(), formatlist_.end(),
420 FormatMimeEqual(mime));
421 if (cit != formatlist_.end()) {
422 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
423 << mime << " -> " << cit->name());
424 // See special eps/ps handling below
425 if (mime == "application/postscript")
426 psformat = cit->name();
428 format = cit->name();
432 // libmagic recognizes as latex also some formats of ours
433 // such as pstex and pdftex. Therefore we have to perform
434 // additional checks in this case (bug 9244).
435 if (!format.empty() && format != "latex")
439 string const ext = getExtension(filename.absFileName());
440 if (format.empty()) {
441 // libmagic does not distinguish eps and ps.
442 // Therefore we need to use our own detection here, but only if it
443 // recognizes either ps or eps. Otherwise the libmagic guess will
444 // be better (bug 9146).
445 format = guessFormatFromContents(filename);
446 if (!psformat.empty()) {
447 if (isPostScriptFileFormat(format))
453 if (isZippedFileFormat(format) && !ext.empty()) {
454 string const & fmt_name = getFormatFromExtension(ext);
455 if (!fmt_name.empty()) {
456 Format const * p_format = getFormat(fmt_name);
457 if (p_format && p_format->zippedNative())
458 return p_format->name();
461 // Don't simply return latex (bug 9244).
462 if (!format.empty() && format != "latex")
466 // Both libmagic and our guessing from contents may return as latex
467 // also lyx files and our pstex and pdftex formats. In this case we
468 // give precedence to the format determined by the extension.
469 if (format == "latex") {
470 format = getFormatFromExtension(ext);
471 return format.empty() ? "latex" : format;
474 // try to find a format from the file extension.
475 return getFormatFromExtension(ext);
479 string Formats::getFormatFromExtension(string const & ext) const
482 // this is ambigous if two formats have the same extension,
483 // but better than nothing
484 Formats::const_iterator cit =
485 find_if(formatlist_.begin(), formatlist_.end(),
486 FormatExtensionsEqual(ext));
487 if (cit != formatlist_.end()) {
488 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
489 << ext << " -> " << cit->name());
497 /// Used to store last timestamp of file and whether it is (was) zipped
500 std::time_t timestamp;
501 ZippedInfo(bool zipped, std::time_t timestamp)
502 : zipped(zipped), timestamp(timestamp) { }
506 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
507 static std::map<std::string, ZippedInfo> zipped_;
508 static Mutex zipped_mutex;
511 bool Formats::isZippedFile(support::FileName const & filename) const {
512 string const & fname = filename.absFileName();
513 time_t timestamp = filename.lastModified();
514 Mutex::Locker lock(&zipped_mutex);
515 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
516 if (it != zipped_.end() && it->second.timestamp == timestamp)
517 return it->second.zipped;
518 // FIXME perf: This very expensive function is called on startup on each
519 // file whic is going to be parsed, and also on svgz icons. Maybe there is a
520 // quicker way to check whether a file is zipped? I.e. for icons we
521 // probably just need to check the extension (svgz vs svg).
522 string const & format = getFormatFromFile(filename);
523 bool zipped = (format == "gzip" || format == "zip");
524 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
529 bool Formats::isZippedFileFormat(string const & format)
531 return contains("gzip zip compress", format) && !format.empty();
535 bool Formats::isPostScriptFileFormat(string const & format)
537 return format == "ps" || format == "eps";
540 static string fixCommand(string const & cmd, string const & ext,
541 os::auto_open_mode mode)
543 // configure.py says we do not want a viewer/editor
547 // Does the OS manage this format?
548 if (os::canAutoOpenFile(ext, mode))
551 // if configure.py found nothing, clear the command
552 if (token(cmd, ' ', 0) == "auto")
555 // use the command found by configure.py
560 void Formats::setAutoOpen()
562 FormatList::iterator fit = formatlist_.begin();
563 FormatList::iterator const fend = formatlist_.end();
564 for ( ; fit != fend ; ++fit) {
565 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
566 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
571 int Formats::getNumber(string const & name) const
573 FormatList::const_iterator cit =
574 find_if(formatlist_.begin(), formatlist_.end(),
575 FormatNamesEqual(name));
576 if (cit != formatlist_.end())
577 return distance(formatlist_.begin(), cit);
583 void Formats::add(string const & name)
585 if (!getFormat(name))
586 add(name, name, from_utf8(name), string(), string(), string(),
587 string(), Format::document);
591 void Formats::add(string const & name, string const & extensions,
592 docstring const & prettyname, string const & shortcut,
593 string const & viewer, string const & editor,
594 string const & mime, int flags)
596 FormatList::iterator it =
597 find_if(formatlist_.begin(), formatlist_.end(),
598 FormatNamesEqual(name));
599 if (it == formatlist_.end())
600 formatlist_.push_back(Format(name, extensions, prettyname,
601 shortcut, viewer, editor, mime, flags));
603 *it = Format(name, extensions, prettyname, shortcut, viewer,
604 editor, mime, flags);
608 void Formats::erase(string const & name)
610 FormatList::iterator it =
611 find_if(formatlist_.begin(), formatlist_.end(),
612 FormatNamesEqual(name));
613 if (it != formatlist_.end())
614 formatlist_.erase(it);
620 std::sort(formatlist_.begin(), formatlist_.end());
624 void Formats::setViewer(string const & name, string const & command)
627 FormatList::iterator it =
628 find_if(formatlist_.begin(), formatlist_.end(),
629 FormatNamesEqual(name));
630 if (it != formatlist_.end())
631 it->setViewer(command);
635 void Formats::setEditor(string const & name, string const & command)
638 FormatList::iterator it =
639 find_if(formatlist_.begin(), formatlist_.end(),
640 FormatNamesEqual(name));
641 if (it != formatlist_.end())
642 it->setEditor(command);
646 bool Formats::view(Buffer const & buffer, FileName const & filename,
647 string const & format_name) const
649 if (filename.empty() || !filename.exists()) {
650 Alert::error(_("Cannot view file"),
651 bformat(_("File does not exist: %1$s"),
652 from_utf8(filename.absFileName())));
656 Format const * format = getFormat(format_name);
657 if (format && format->viewer().empty() &&
658 format->isChildFormat())
659 format = getFormat(format->parentFormat());
660 if (!format || format->viewer().empty()) {
661 // FIXME: I believe this is the wrong place to show alerts, it should be done
662 // by the caller (this should be "utility" code)
663 Alert::error(_("Cannot view file"),
664 bformat(_("No information for viewing %1$s"),
665 prettyName(format_name)));
669 if (format->viewer() == "auto") {
670 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
673 Alert::error(_("Cannot view file"),
674 bformat(_("Auto-view file %1$s failed"),
675 from_utf8(filename.absFileName())));
680 string command = format->viewer();
682 if (format_name == "dvi" &&
683 !lyxrc.view_dvi_paper_option.empty()) {
684 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
685 if (!paper_size.empty()) {
686 command += ' ' + lyxrc.view_dvi_paper_option;
687 command += ' ' + paper_size;
688 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
689 buffer.params().papersize != PAPER_CUSTOM)
694 if (!contains(command, token_from_format))
695 command += ' ' + token_from_format;
697 command = subst(command, token_from_format,
698 quoteName(onlyFileName(filename.toFilesystemEncoding()), quote_shell_filename));
699 command = subst(command, token_path_format,
700 quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
701 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
702 LYXERR(Debug::FILES, "Executing command: " << command);
703 // FIXME UNICODE utf8 can be wrong for files
704 buffer.message(_("Executing command: ") + from_utf8(command));
706 PathChanger p(filename.onlyPath());
708 one.startscript(Systemcall::DontWait, command,
709 buffer.filePath(), buffer.layoutPos());
711 // we can't report any sort of error, since we aren't waiting
716 bool Formats::edit(Buffer const & buffer, FileName const & filename,
717 string const & format_name) const
719 if (filename.empty() || !filename.exists()) {
720 Alert::error(_("Cannot edit file"),
721 bformat(_("File does not exist: %1$s"),
722 from_utf8(filename.absFileName())));
726 // LinkBack files look like PDF, but have the .linkback extension
727 string const ext = getExtension(filename.absFileName());
728 if (format_name == "pdf6" && ext == "linkback") {
729 #ifdef USE_MACOSX_PACKAGING
730 return editLinkBackFile(filename.absFileName().c_str());
732 Alert::error(_("Cannot edit file"),
733 _("LinkBack files can only be edited on Apple Mac OSX."));
735 #endif // USE_MACOSX_PACKAGING
738 Format const * format = getFormat(format_name);
739 if (format && format->editor().empty() &&
740 format->isChildFormat())
741 format = getFormat(format->parentFormat());
742 if (!format || format->editor().empty()) {
743 // FIXME: I believe this is the wrong place to show alerts, it should
744 // be done by the caller (this should be "utility" code)
745 Alert::error(_("Cannot edit file"),
746 bformat(_("No information for editing %1$s"),
747 prettyName(format_name)));
752 if (format->editor() == "auto") {
753 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
756 Alert::error(_("Cannot edit file"),
757 bformat(_("Auto-edit file %1$s failed"),
758 from_utf8(filename.absFileName())));
763 string command = format->editor();
765 if (!contains(command, token_from_format))
766 command += ' ' + token_from_format;
768 command = subst(command, token_from_format,
769 quoteName(filename.toFilesystemEncoding(), quote_shell_filename));
770 command = subst(command, token_path_format,
771 quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
772 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
773 LYXERR(Debug::FILES, "Executing command: " << command);
774 // FIXME UNICODE utf8 can be wrong for files
775 buffer.message(_("Executing command: ") + from_utf8(command));
778 one.startscript(Systemcall::DontWait, command,
779 buffer.filePath(), buffer.layoutPos());
781 // we can't report any sort of error, since we aren't waiting
786 docstring const Formats::prettyName(string const & name) const
788 Format const * format = getFormat(name);
790 return format->prettyname();
792 return from_utf8(name);
796 string const Formats::extension(string const & name) const
798 Format const * format = getFormat(name);
800 return format->extension();
806 string const Formats::extensions(string const & name) const
808 Format const * format = getFormat(name);
810 return format->extensions();
818 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
821 FlavorTranslator initFlavorTranslator()
823 FlavorTranslator f(OutputParams::LATEX, "latex");
824 f.addPair(OutputParams::DVILUATEX, "dviluatex");
825 f.addPair(OutputParams::LUATEX, "luatex");
826 f.addPair(OutputParams::PDFLATEX, "pdflatex");
827 f.addPair(OutputParams::XETEX, "xetex");
828 f.addPair(OutputParams::XML, "docbook-xml");
829 f.addPair(OutputParams::HTML, "xhtml");
830 f.addPair(OutputParams::TEXT, "text");
831 f.addPair(OutputParams::LYX, "lyx");
836 FlavorTranslator const & flavorTranslator()
838 static FlavorTranslator const translator = initFlavorTranslator();
845 std::string flavor2format(OutputParams::FLAVOR flavor)
847 return flavorTranslator().find(flavor);
851 /* Not currently needed, but I'll leave the code in case it is.
852 OutputParams::FLAVOR format2flavor(std::string fmt)
854 return flavorTranslator().find(fmt);