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, " EMF"))
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)
383 if (format.empty() && maybelatex && !isBinaryFile(fn))
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())
410 if (filename.exists()) {
411 // one instance of Magic that will be reused for next calls
412 // This avoids to read the magic file everytime
413 // If libmagic is not available, Magic::file returns an empty string.
415 string const result = magic.file(filename.toFilesystemEncoding());
416 string const mime = token(result, ';', 0);
417 // our own detection is better for binary files (can be anything)
418 // and different plain text formats
419 if (!mime.empty() && mime != "application/octet-stream" &&
420 mime != "text/plain") {
421 Formats::const_iterator cit =
422 find_if(formatlist_.begin(), formatlist_.end(),
423 FormatMimeEqual(mime));
424 if (cit != formatlist_.end()) {
425 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
426 << mime << " -> " << cit->name());
427 // See special eps/ps handling below
428 if (mime == "application/postscript")
429 psformat = cit->name();
431 format = cit->name();
435 // libmagic recognizes as latex also some formats of ours
436 // such as pstex and pdftex. Therefore we have to perform
437 // additional checks in this case (bug 9244).
438 if (!format.empty() && format != "latex")
442 string const ext = getExtension(filename.absFileName());
443 if (format.empty()) {
444 // libmagic does not distinguish eps and ps.
445 // Therefore we need to use our own detection here, but only if it
446 // recognizes either ps or eps. Otherwise the libmagic guess will
447 // be better (bug 9146).
448 format = guessFormatFromContents(filename);
449 if (!psformat.empty()) {
450 if (isPostScriptFileFormat(format))
456 if (isZippedFileFormat(format) && !ext.empty()) {
457 string const & fmt_name = getFormatFromExtension(ext);
458 if (!fmt_name.empty()) {
459 Format const * p_format = getFormat(fmt_name);
460 if (p_format && p_format->zippedNative())
461 return p_format->name();
464 // Don't simply return latex (bug 9244).
465 if (!format.empty() && format != "latex")
469 // Both libmagic and our guessing from contents may return as latex
470 // also lyx files and our pstex and pdftex formats. In this case we
471 // give precedence to the format determined by the extension.
472 if (format == "latex") {
473 format = getFormatFromExtension(ext);
474 return format.empty() ? "latex" : format;
477 // try to find a format from the file extension.
478 return getFormatFromExtension(ext);
482 string Formats::getFormatFromExtension(string const & ext) const
485 // this is ambigous if two formats have the same extension,
486 // but better than nothing
487 Formats::const_iterator cit =
488 find_if(formatlist_.begin(), formatlist_.end(),
489 FormatExtensionsEqual(ext));
490 if (cit != formatlist_.end()) {
491 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
492 << ext << " -> " << cit->name());
500 /// Used to store last timestamp of file and whether it is (was) zipped
503 std::time_t timestamp;
504 ZippedInfo(bool zipped, std::time_t timestamp)
505 : zipped(zipped), timestamp(timestamp) { }
509 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
510 static std::map<std::string, ZippedInfo> zipped_;
511 static Mutex zipped_mutex;
514 bool Formats::isZippedFile(support::FileName const & filename) const {
515 string const & fname = filename.absFileName();
516 time_t timestamp = filename.lastModified();
517 Mutex::Locker lock(&zipped_mutex);
518 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
519 if (it != zipped_.end() && it->second.timestamp == timestamp)
520 return it->second.zipped;
521 // FIXME perf: This very expensive function is called on startup on each
522 // file whic is going to be parsed, and also on svgz icons. Maybe there is a
523 // quicker way to check whether a file is zipped? I.e. for icons we
524 // probably just need to check the extension (svgz vs svg).
525 string const & format = getFormatFromFile(filename);
526 bool zipped = (format == "gzip" || format == "zip");
527 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
532 bool Formats::isZippedFileFormat(string const & format)
534 return contains("gzip zip compress", format) && !format.empty();
538 bool Formats::isPostScriptFileFormat(string const & format)
540 return format == "ps" || format == "eps";
543 static string fixCommand(string const & cmd, string const & ext,
544 os::auto_open_mode mode)
546 // configure.py says we do not want a viewer/editor
550 // Does the OS manage this format?
551 if (os::canAutoOpenFile(ext, mode))
554 // if configure.py found nothing, clear the command
555 if (token(cmd, ' ', 0) == "auto")
558 // use the command found by configure.py
563 void Formats::setAutoOpen()
565 FormatList::iterator fit = formatlist_.begin();
566 FormatList::iterator const fend = formatlist_.end();
567 for ( ; fit != fend ; ++fit) {
568 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
569 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
574 int Formats::getNumber(string const & name) const
576 FormatList::const_iterator cit =
577 find_if(formatlist_.begin(), formatlist_.end(),
578 FormatNamesEqual(name));
579 if (cit != formatlist_.end())
580 return distance(formatlist_.begin(), cit);
586 void Formats::add(string const & name)
588 if (!getFormat(name))
589 add(name, name, from_utf8(name), string(), string(), string(),
590 string(), Format::document);
594 void Formats::add(string const & name, string const & extensions,
595 docstring const & prettyname, string const & shortcut,
596 string const & viewer, string const & editor,
597 string const & mime, int flags)
599 FormatList::iterator it =
600 find_if(formatlist_.begin(), formatlist_.end(),
601 FormatNamesEqual(name));
602 if (it == formatlist_.end())
603 formatlist_.push_back(Format(name, extensions, prettyname,
604 shortcut, viewer, editor, mime, flags));
606 *it = Format(name, extensions, prettyname, shortcut, viewer,
607 editor, mime, flags);
611 void Formats::erase(string const & name)
613 FormatList::iterator it =
614 find_if(formatlist_.begin(), formatlist_.end(),
615 FormatNamesEqual(name));
616 if (it != formatlist_.end())
617 formatlist_.erase(it);
623 std::sort(formatlist_.begin(), formatlist_.end());
627 void Formats::setViewer(string const & name, string const & command)
630 FormatList::iterator it =
631 find_if(formatlist_.begin(), formatlist_.end(),
632 FormatNamesEqual(name));
633 if (it != formatlist_.end())
634 it->setViewer(command);
638 void Formats::setEditor(string const & name, string const & command)
641 FormatList::iterator it =
642 find_if(formatlist_.begin(), formatlist_.end(),
643 FormatNamesEqual(name));
644 if (it != formatlist_.end())
645 it->setEditor(command);
649 bool Formats::view(Buffer const & buffer, FileName const & filename,
650 string const & format_name) const
652 if (filename.empty() || !filename.exists()) {
653 Alert::error(_("Cannot view file"),
654 bformat(_("File does not exist: %1$s"),
655 from_utf8(filename.absFileName())));
659 Format const * format = getFormat(format_name);
660 if (format && format->viewer().empty() &&
661 format->isChildFormat())
662 format = getFormat(format->parentFormat());
663 if (!format || format->viewer().empty()) {
664 // FIXME: I believe this is the wrong place to show alerts, it should be done
665 // by the caller (this should be "utility" code)
666 Alert::error(_("Cannot view file"),
667 bformat(_("No information for viewing %1$s"),
668 prettyName(format_name)));
672 if (format->viewer() == "auto") {
673 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
676 Alert::error(_("Cannot view file"),
677 bformat(_("Auto-view file %1$s failed"),
678 from_utf8(filename.absFileName())));
683 string command = format->viewer();
685 // Escape backslashes if not already in double or single quotes.
686 // We cannot simply quote the whole command as there may be arguments.
687 if (contains(command, '\\')) {
688 bool inquote1 = false;
689 bool inquote2 = false;
690 string::iterator cit = command.begin();
691 for (; cit != command.end(); ++cit) {
694 inquote1 = !inquote1;
697 inquote2 = !inquote2;
700 if (!inquote1 && !inquote2)
701 cit = ++command.insert(cit, '\\');
707 if (format_name == "dvi" &&
708 !lyxrc.view_dvi_paper_option.empty()) {
709 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
710 if (!paper_size.empty()) {
711 command += ' ' + lyxrc.view_dvi_paper_option;
712 command += ' ' + paper_size;
713 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
714 buffer.params().papersize != PAPER_CUSTOM)
719 if (!contains(command, token_from_format))
720 command += ' ' + token_from_format;
722 command = subst(command, token_from_format,
723 quoteName(onlyFileName(filename.toFilesystemEncoding()), quote_shell_filename));
724 command = subst(command, token_path_format,
725 quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
726 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
727 LYXERR(Debug::FILES, "Executing command: " << command);
728 // FIXME UNICODE utf8 can be wrong for files
729 buffer.message(_("Executing command: ") + from_utf8(command));
731 PathChanger p(filename.onlyPath());
733 one.startscript(Systemcall::DontWait, command,
734 buffer.filePath(), buffer.layoutPos());
736 // we can't report any sort of error, since we aren't waiting
741 bool Formats::edit(Buffer const & buffer, FileName const & filename,
742 string const & format_name) const
744 if (filename.empty() || !filename.exists()) {
745 Alert::error(_("Cannot edit file"),
746 bformat(_("File does not exist: %1$s"),
747 from_utf8(filename.absFileName())));
751 // LinkBack files look like PDF, but have the .linkback extension
752 string const ext = getExtension(filename.absFileName());
753 if (format_name == "pdf6" && ext == "linkback") {
754 #ifdef USE_MACOSX_PACKAGING
755 return editLinkBackFile(filename.absFileName().c_str());
757 Alert::error(_("Cannot edit file"),
758 _("LinkBack files can only be edited on Apple Mac OSX."));
760 #endif // USE_MACOSX_PACKAGING
763 Format const * format = getFormat(format_name);
764 if (format && format->editor().empty() &&
765 format->isChildFormat())
766 format = getFormat(format->parentFormat());
767 if (!format || format->editor().empty()) {
768 // FIXME: I believe this is the wrong place to show alerts, it should
769 // be done by the caller (this should be "utility" code)
770 Alert::error(_("Cannot edit file"),
771 bformat(_("No information for editing %1$s"),
772 prettyName(format_name)));
777 if (format->editor() == "auto") {
778 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
781 Alert::error(_("Cannot edit file"),
782 bformat(_("Auto-edit file %1$s failed"),
783 from_utf8(filename.absFileName())));
788 string command = format->editor();
790 if (!contains(command, token_from_format))
791 command += ' ' + token_from_format;
793 command = subst(command, token_from_format,
794 quoteName(filename.toFilesystemEncoding(), quote_shell_filename));
795 command = subst(command, token_path_format,
796 quoteName(onlyPath(filename.toFilesystemEncoding()), quote_shell_filename));
797 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
798 LYXERR(Debug::FILES, "Executing command: " << command);
799 // FIXME UNICODE utf8 can be wrong for files
800 buffer.message(_("Executing command: ") + from_utf8(command));
803 one.startscript(Systemcall::DontWait, command,
804 buffer.filePath(), buffer.layoutPos());
806 // we can't report any sort of error, since we aren't waiting
811 docstring const Formats::prettyName(string const & name) const
813 Format const * format = getFormat(name);
815 return format->prettyname();
817 return from_utf8(name);
821 string const Formats::extension(string const & name) const
823 Format const * format = getFormat(name);
825 return format->extension();
831 string const Formats::extensions(string const & name) const
833 Format const * format = getFormat(name);
835 return format->extensions();
843 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
846 FlavorTranslator initFlavorTranslator()
848 FlavorTranslator f(OutputParams::LATEX, "latex");
849 f.addPair(OutputParams::DVILUATEX, "dviluatex");
850 f.addPair(OutputParams::LUATEX, "luatex");
851 f.addPair(OutputParams::PDFLATEX, "pdflatex");
852 f.addPair(OutputParams::XETEX, "xetex");
853 f.addPair(OutputParams::XML, "docbook-xml");
854 f.addPair(OutputParams::HTML, "xhtml");
855 f.addPair(OutputParams::TEXT, "text");
856 f.addPair(OutputParams::LYX, "lyx");
861 FlavorTranslator const & flavorTranslator()
863 static FlavorTranslator const translator = initFlavorTranslator();
870 std::string flavor2format(OutputParams::FLAVOR flavor)
872 return flavorTranslator().find(flavor);
876 /* Not currently needed, but I'll leave the code in case it is.
877 OutputParams::FLAVOR format2flavor(std::string fmt)
879 return flavorTranslator().find(fmt);