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 while ((count++ < max_count) && format.empty()) {
258 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
259 << "\tFile type not recognised before EOF!");
264 string const stamp = str.substr(0, 2);
265 if (firstLine && str.size() >= 2) {
266 // at first we check for a zipped file, because this
267 // information is saved in the first bytes of the file!
268 // also some graphic formats which save the information
269 // in the first line, too.
270 if (prefixIs(str, gzipStamp)) {
273 } else if (stamp == zipStamp &&
274 !contains(str, nonzipStamp)) {
277 } else if (stamp == compressStamp) {
281 } else if (stamp == "BM") {
284 } else if (stamp == "\001\332") {
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, "JFIF"))
342 else if (contains(str, "%PDF"))
343 // autodetect pdf format for graphics inclusion
346 else if (contains(str, "PNG"))
349 else if (contains(str, "%!PS-Adobe")) {
352 if (contains(str,"EPSF"))
358 else if (contains(str, "_bits[]"))
361 else if (contains(str, "XPM") || contains(str, "static char *"))
364 else if (contains(str, "BITPIX"))
368 if (!format.empty()) {
369 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
373 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
374 << "\tCouldn't find a known format!");
381 string Formats::getFormatFromFile(FileName const & filename) const
383 if (filename.empty())
387 if (filename.exists()) {
388 magic_t magic_cookie = magic_open(MAGIC_MIME);
391 if (magic_load(magic_cookie, NULL) != 0) {
392 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
393 << "\tCouldn't load magic database - "
394 << magic_error(magic_cookie));
396 string mime = magic_file(magic_cookie,
397 filename.toFilesystemEncoding().c_str());
398 mime = token(mime, ';', 0);
399 // we need our own ps/eps detection
400 if ((mime != "application/postscript") && (mime != "text/plain")) {
401 Formats::const_iterator cit =
402 find_if(formatlist.begin(), formatlist.end(),
403 FormatMimeEqual(mime));
404 if (cit != formats.end()) {
405 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
406 << mime << " -> " << cit->name());
407 format = cit->name();
411 magic_close(magic_cookie);
418 string const format = guessFormatFromContents(filename);
419 string const ext = getExtension(filename.absFileName());
420 if (isZippedFileFormat(format) && !ext.empty()) {
421 string const & fmt_name = formats.getFormatFromExtension(ext);
422 if (!fmt_name.empty()) {
423 Format const * p_format = formats.getFormat(fmt_name);
424 if (p_format && p_format->zippedNative())
425 return p_format->name();
431 // try to find a format from the file extension.
432 return getFormatFromExtension(ext);
436 string Formats::getFormatFromExtension(string const & ext) const
439 // this is ambigous if two formats have the same extension,
440 // but better than nothing
441 Formats::const_iterator cit =
442 find_if(formatlist.begin(), formatlist.end(),
443 FormatExtensionsEqual(ext));
444 if (cit != formats.end()) {
445 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
446 << ext << " -> " << cit->name());
454 string Formats::getFormatFromPrettyName(string const & prettyname) const
456 if (!prettyname.empty()) {
457 Formats::const_iterator cit =
458 find_if(formatlist.begin(), formatlist.end(),
459 FormatPrettyNameEqual(prettyname));
460 if (cit != formats.end())
467 /// Used to store last timestamp of file and whether it is (was) zipped
470 std::time_t timestamp;
471 ZippedInfo(bool zipped, std::time_t timestamp)
472 : zipped(zipped), timestamp(timestamp) { }
476 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
477 static std::map<std::string, ZippedInfo> zipped_;
480 bool Formats::isZippedFile(support::FileName const & filename) const {
481 string const & fname = filename.absFileName();
482 time_t timestamp = filename.lastModified();
483 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
484 if (it != zipped_.end() && it->second.timestamp == timestamp)
485 return it->second.zipped;
486 string const & format = getFormatFromFile(filename);
487 bool zipped = (format == "gzip" || format == "zip");
488 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
493 bool Formats::isZippedFileFormat(string const & format)
495 return contains("gzip zip compress", format) && !format.empty();
499 bool Formats::isPostScriptFileFormat(string const & format)
501 return format == "ps" || format == "eps";
504 static string fixCommand(string const & cmd, string const & ext,
505 os::auto_open_mode mode)
507 // configure.py says we do not want a viewer/editor
511 // Does the OS manage this format?
512 if (os::canAutoOpenFile(ext, mode))
515 // if configure.py found nothing, clear the command
516 if (token(cmd, ' ', 0) == "auto")
519 // use the command found by configure.py
524 void Formats::setAutoOpen()
526 FormatList::iterator fit = formatlist.begin();
527 FormatList::iterator const fend = formatlist.end();
528 for ( ; fit != fend ; ++fit) {
529 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
530 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
535 int Formats::getNumber(string const & name) const
537 FormatList::const_iterator cit =
538 find_if(formatlist.begin(), formatlist.end(),
539 FormatNamesEqual(name));
540 if (cit != formatlist.end())
541 return distance(formatlist.begin(), cit);
547 void Formats::add(string const & name)
549 if (!getFormat(name))
550 add(name, name, name, string(), string(), string(),
551 string(), Format::document);
555 void Formats::add(string const & name, string const & extensions,
556 string const & prettyname, string const & shortcut,
557 string const & viewer, string const & editor,
558 string const & mime, int flags)
560 FormatList::iterator it =
561 find_if(formatlist.begin(), formatlist.end(),
562 FormatNamesEqual(name));
563 if (it == formatlist.end())
564 formatlist.push_back(Format(name, extensions, prettyname,
565 shortcut, viewer, editor, mime, flags));
567 *it = Format(name, extensions, prettyname, shortcut, viewer,
568 editor, mime, flags);
572 void Formats::erase(string const & name)
574 FormatList::iterator it =
575 find_if(formatlist.begin(), formatlist.end(),
576 FormatNamesEqual(name));
577 if (it != formatlist.end())
578 formatlist.erase(it);
584 std::sort(formatlist.begin(), formatlist.end());
588 void Formats::setViewer(string const & name, string const & command)
591 FormatList::iterator it =
592 find_if(formatlist.begin(), formatlist.end(),
593 FormatNamesEqual(name));
594 if (it != formatlist.end())
595 it->setViewer(command);
599 void Formats::setEditor(string const & name, string const & command)
602 FormatList::iterator it =
603 find_if(formatlist.begin(), formatlist.end(),
604 FormatNamesEqual(name));
605 if (it != formatlist.end())
606 it->setEditor(command);
610 bool Formats::view(Buffer const & buffer, FileName const & filename,
611 string const & format_name) const
613 if (filename.empty() || !filename.exists()) {
614 Alert::error(_("Cannot view file"),
615 bformat(_("File does not exist: %1$s"),
616 from_utf8(filename.absFileName())));
620 Format const * format = getFormat(format_name);
621 if (format && format->viewer().empty() &&
622 format->isChildFormat())
623 format = getFormat(format->parentFormat());
624 if (!format || format->viewer().empty()) {
625 // FIXME: I believe this is the wrong place to show alerts, it should be done
626 // by the caller (this should be "utility" code)
627 Alert::error(_("Cannot view file"),
628 bformat(_("No information for viewing %1$s"),
629 prettyName(format_name)));
633 if (format->viewer() == "auto") {
634 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
637 Alert::error(_("Cannot view file"),
638 bformat(_("Auto-view file %1$s failed"),
639 from_utf8(filename.absFileName())));
644 string command = libScriptSearch(format->viewer());
646 if (format_name == "dvi" &&
647 !lyxrc.view_dvi_paper_option.empty()) {
648 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
649 if (!paper_size.empty()) {
650 command += ' ' + lyxrc.view_dvi_paper_option;
651 command += ' ' + paper_size;
652 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
653 buffer.params().papersize != PAPER_CUSTOM)
658 if (!contains(command, token_from_format))
659 command += ' ' + token_from_format;
661 command = subst(command, token_from_format, quoteName(onlyFileName(filename.toFilesystemEncoding())));
662 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
663 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
664 LYXERR(Debug::FILES, "Executing command: " << command);
665 // FIXME UNICODE utf8 can be wrong for files
666 buffer.message(_("Executing command: ") + from_utf8(command));
668 PathChanger p(filename.onlyPath());
670 one.startscript(Systemcall::DontWait, command, buffer.filePath());
672 // we can't report any sort of error, since we aren't waiting
677 bool Formats::edit(Buffer const & buffer, FileName const & filename,
678 string const & format_name) const
680 if (filename.empty() || !filename.exists()) {
681 Alert::error(_("Cannot edit file"),
682 bformat(_("File does not exist: %1$s"),
683 from_utf8(filename.absFileName())));
687 // LinkBack files look like PDF, but have the .linkback extension
688 string const ext = getExtension(filename.absFileName());
689 if (format_name == "pdf6" && ext == "linkback") {
690 #ifdef USE_MACOSX_PACKAGING
691 return editLinkBackFile(filename.absFileName().c_str());
693 Alert::error(_("Cannot edit file"),
694 _("LinkBack files can only be edited on Apple Mac OSX."));
696 #endif // USE_MACOSX_PACKAGING
699 Format const * format = getFormat(format_name);
700 if (format && format->editor().empty() &&
701 format->isChildFormat())
702 format = getFormat(format->parentFormat());
703 if (!format || format->editor().empty()) {
704 // FIXME: I believe this is the wrong place to show alerts, it should
705 // be done by the caller (this should be "utility" code)
706 Alert::error(_("Cannot edit file"),
707 bformat(_("No information for editing %1$s"),
708 prettyName(format_name)));
713 if (format->editor() == "auto") {
714 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
717 Alert::error(_("Cannot edit file"),
718 bformat(_("Auto-edit file %1$s failed"),
719 from_utf8(filename.absFileName())));
724 string command = format->editor();
726 if (!contains(command, token_from_format))
727 command += ' ' + token_from_format;
729 command = subst(command, token_from_format, quoteName(filename.toFilesystemEncoding()));
730 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
731 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
732 LYXERR(Debug::FILES, "Executing command: " << command);
733 // FIXME UNICODE utf8 can be wrong for files
734 buffer.message(_("Executing command: ") + from_utf8(command));
737 one.startscript(Systemcall::DontWait, command, buffer.filePath());
739 // we can't report any sort of error, since we aren't waiting
744 docstring const Formats::prettyName(string const & name) const
746 Format const * format = getFormat(name);
748 return from_utf8(format->prettyname());
750 return from_utf8(name);
754 string const Formats::extension(string const & name) const
756 Format const * format = getFormat(name);
758 return format->extension();
764 string const Formats::extensions(string const & name) const
766 Format const * format = getFormat(name);
768 return format->extensions();
776 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
779 FlavorTranslator initFlavorTranslator()
781 FlavorTranslator f(OutputParams::LATEX, "latex");
782 f.addPair(OutputParams::DVILUATEX, "dviluatex");
783 f.addPair(OutputParams::LUATEX, "luatex");
784 f.addPair(OutputParams::PDFLATEX, "pdflatex");
785 f.addPair(OutputParams::XETEX, "xetex");
786 f.addPair(OutputParams::XML, "docbook-xml");
787 f.addPair(OutputParams::HTML, "xhtml");
788 f.addPair(OutputParams::TEXT, "text");
793 FlavorTranslator const & flavorTranslator()
795 static FlavorTranslator translator = initFlavorTranslator();
802 std::string flavor2format(OutputParams::FLAVOR flavor)
804 return flavorTranslator().find(flavor);
808 /* Not currently needed, but I'll leave the code in case it is.
809 OutputParams::FLAVOR format2flavor(std::string fmt)
811 return flavorTranslator().find(fmt);
816 Formats system_formats;