]> git.lyx.org Git - lyx.git/blob - src/insets/InsetExternal.cpp
Update Win installer for new dictionary links. Untested.
[lyx.git] / src / insets / InsetExternal.cpp
1 /**
2  * \file InsetExternal.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup Nielsen
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetExternal.h"
14 #include "insets/ExternalSupport.h"
15 #include "insets/RenderButton.h"
16 #include "insets/RenderGraphic.h"
17 #include "insets/RenderPreview.h"
18
19 #include "Buffer.h"
20 #include "BufferView.h"
21 #include "Converter.h"
22 #include "Cursor.h"
23 #include "DispatchResult.h"
24 #include "Exporter.h"
25 #include "FuncStatus.h"
26 #include "FuncRequest.h"
27 #include "LaTeXFeatures.h"
28 #include "Lexer.h"
29 #include "LyX.h" // use_gui
30 #include "LyXRC.h"
31 #include "MetricsInfo.h"
32 #include "output_latex.h"
33 #include "output_xhtml.h"
34 #include "texstream.h"
35 #include "xml.h"
36 #include "TocBackend.h"
37
38 #include "frontends/alert.h"
39 #include "frontends/Application.h"
40
41 #include "graphics/PreviewLoader.h"
42
43 #include "support/convert.h"
44 #include "support/debug.h"
45 #include "support/ExceptionMessage.h"
46 #include "support/filetools.h"
47 #include "support/gettext.h"
48 #include "support/lassert.h"
49 #include "support/lstrings.h"
50 #include "support/lyxlib.h"
51 #include "support/TempFile.h"
52
53 #include <sstream>
54 #include <vector>
55
56 using namespace std;
57 using namespace lyx::support;
58
59 namespace {
60
61 unsigned int const defaultLyxScale = 100;
62
63 string defaultTemplateName;
64
65 } // namespace
66
67
68 namespace lyx {
69
70 namespace Alert = frontend::Alert;
71
72 namespace external {
73
74 TempName::TempName()
75 {
76         // must have an extension for the converter code to work correctly.
77         support::TempFile f("lyxextXXXXXX.tmp");
78         // Let f go out of scope here and delete the file ourselves in
79         // ~TempName(), since otherwise external processes would not be able
80         // to use the file on windows (bug 9925). This is not as safe as
81         // keeping a support::TempFile member would be, but the best we can do.
82         f.setAutoRemove(false);
83         tempname_ = f.name();
84 }
85
86
87 TempName::TempName(TempName const & that)
88 {
89         *this = that;
90 }
91
92
93 TempName::~TempName()
94 {
95         tempname_.removeFile();
96 }
97
98
99 TempName & TempName::operator=(TempName const & other)
100 {
101         if (this != &other) {
102                 if (!tempname_.empty())
103                         tempname_.removeFile();
104                 support::TempFile f("lyxextXXXXXX.tmp");
105                 f.setAutoRemove(false);
106                 tempname_ = f.name();
107         }
108         return *this;
109 }
110
111
112 support::FileName TempName::operator()() const
113 {
114         return tempname_;
115 }
116
117 } // namespace external
118
119
120 InsetExternalParams::InsetExternalParams()
121         : display(true),
122           preview_mode(PREVIEW_OFF),
123           lyxscale(defaultLyxScale),
124           draft(false)
125 {
126         if (defaultTemplateName.empty()) {
127                 external::TemplateManager const & etm =
128                         external::TemplateManager::get();
129                 if (!etm.getTemplates().empty())
130                         templatename_ = etm.getTemplates().begin()->first;
131         } else
132                 templatename_ = defaultTemplateName;
133 }
134
135
136 namespace {
137
138 template <typename T>
139 void clearIfNotFound(T & data, external::TransformID value,
140                      vector<external::TransformID> const & ids)
141 {
142         typedef vector<external::TransformID>::const_iterator
143                 const_iterator;
144
145         const_iterator it  = ids.begin();
146         const_iterator end = ids.end();
147         it = find(it, end, value);
148         if (it == end)
149                 data = T();
150 }
151
152 } // namespace
153
154
155 void InsetExternalParams::settemplate(string const & name)
156 {
157         templatename_ = name;
158
159         external::TemplateManager const & etm =
160                 external::TemplateManager::get();
161         external::Template const * const et = etm.getTemplateByName(name);
162         if (!et)
163                 // Be safe. Don't lose data.
164                 return;
165
166         // Ascertain which transforms the template supports.
167         // Empty all those that it doesn't.
168         vector<external::TransformID> const & ids = et->transformIds;
169         clearIfNotFound(clipdata,     external::Clip,   ids);
170         clearIfNotFound(extradata,    external::Extra,  ids);
171         clearIfNotFound(resizedata,   external::Resize, ids);
172         clearIfNotFound(rotationdata, external::Rotate, ids);
173
174         //
175         preview_mode = et->preview_mode;
176 }
177
178
179 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
180 {
181         os << "External\n"
182            << "\ttemplate " << templatename() << '\n';
183
184         if (!filename.empty())
185                 os << "\tfilename " << filename.outputFileName(buf.filePath()) << '\n';
186
187         if (!display)
188                 os << "\tdisplay false\n";
189
190         if (lyxscale != defaultLyxScale)
191                 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
192
193         if (draft)
194                 os << "\tdraft\n";
195
196         if (!clipdata.bbox.empty())
197                 os << "\tboundingBox " << clipdata.bbox << '\n';
198         if (clipdata.clip)
199                 os << "\tclip\n";
200
201         external::ExtraData::const_iterator it  = extradata.begin();
202         external::ExtraData::const_iterator end = extradata.end();
203         for (; it != end; ++it) {
204                 if (!it->second.empty())
205                         os << "\textra " << it->first << " \""
206                            << it->second << "\"\n";
207         }
208
209         if (!rotationdata.no_rotation()) {
210                 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
211                 if (rotationdata.origin() != external::RotationData::DEFAULT)
212                         os << "\trotateOrigin "
213                            << rotationdata.originString() << '\n';
214         }
215
216         if (!resizedata.no_resize()) {
217                 double const scl = convert<double>(resizedata.scale);
218                 if (!float_equal(scl, 0.0, 0.05)) {
219                         if (!float_equal(scl, 100.0, 0.05))
220                                 os << "\tscale "
221                                    << resizedata.scale << '\n';
222                 } else {
223                         if (!resizedata.width.zero())
224                                 os << "\twidth "
225                                    << resizedata.width.asString() << '\n';
226                         if (!resizedata.height.zero())
227                                 os << "\theight "
228                                    << resizedata.height.asString() << '\n';
229                 }
230                 if (resizedata.keepAspectRatio)
231                         os << "\tkeepAspectRatio\n";
232         }
233 }
234
235
236 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
237 {
238         enum {
239                 EX_TEMPLATE = 1,
240                 EX_FILENAME,
241                 EX_DISPLAY,
242                 EX_LYXSCALE,
243                 EX_DRAFT,
244                 EX_BOUNDINGBOX,
245                 EX_CLIP,
246                 EX_EXTRA,
247                 EX_HEIGHT,
248                 EX_KEEPASPECTRATIO,
249                 EX_ROTATEANGLE,
250                 EX_ROTATEORIGIN,
251                 EX_SCALE,
252                 EX_WIDTH,
253                 EX_END
254         };
255
256         LexerKeyword external_tags[] = {
257                 { "\\end_inset",     EX_END },
258                 { "boundingBox",     EX_BOUNDINGBOX },
259                 { "clip",            EX_CLIP },
260                 { "display",         EX_DISPLAY},
261                 { "draft",           EX_DRAFT},
262                 { "extra",           EX_EXTRA },
263                 { "filename",        EX_FILENAME},
264                 { "height",          EX_HEIGHT },
265                 { "keepAspectRatio", EX_KEEPASPECTRATIO },
266                 { "lyxscale",        EX_LYXSCALE},
267                 { "rotateAngle",     EX_ROTATEANGLE },
268                 { "rotateOrigin",    EX_ROTATEORIGIN },
269                 { "scale",           EX_SCALE },
270                 { "template",        EX_TEMPLATE },
271                 { "width",           EX_WIDTH }
272         };
273
274         PushPopHelper pph(lex, external_tags);
275
276         bool found_end  = false;
277         bool read_error = false;
278
279         while (lex.isOK()) {
280                 switch (lex.lex()) {
281                 case EX_TEMPLATE:
282                         lex.next();
283                         templatename_ = lex.getString();
284                         break;
285
286                 case EX_FILENAME: {
287                         lex.eatLine();
288                         string const name = lex.getString();
289                         filename = buffer.getReferencedFileName(name);
290                         break;
291                 }
292
293                 case EX_DISPLAY: {
294                         lex.next();
295                         display = lex.getString() != "false";
296                         break;
297                 }
298
299                 case EX_LYXSCALE: {
300                         lex.next();
301                         int const ls = lex.getInteger();
302                         // negative values are not accepted.
303                         if (ls >= 0)
304                                 lyxscale = ls;
305                         else
306                                 lex.printError("ExternalInset::read: Wrong lyxscale: $$Token");
307                         break;
308                 }
309
310                 case EX_DRAFT:
311                         draft = true;
312                         break;
313
314                 case EX_BOUNDINGBOX:
315                         lex.next();
316                         clipdata.bbox.xl = Length(lex.getString());
317                         lex.next();
318                         clipdata.bbox.yb = Length(lex.getString());
319                         lex.next();
320                         clipdata.bbox.xr = Length(lex.getString());
321                         lex.next();
322                         clipdata.bbox.yt = Length(lex.getString());
323                         break;
324
325                 case EX_CLIP:
326                         clipdata.clip = true;
327                         break;
328
329                 case EX_EXTRA: {
330                         lex.next();
331                         string const name = lex.getString();
332                         lex.next();
333                         extradata.set(name, lex.getString());
334                         break;
335                 }
336
337                 case EX_HEIGHT:
338                         lex.next();
339                         resizedata.height = Length(lex.getString());
340                         break;
341
342                 case EX_KEEPASPECTRATIO:
343                         resizedata.keepAspectRatio = true;
344                         break;
345
346                 case EX_ROTATEANGLE:
347                         lex.next();
348                         rotationdata.angle = lex.getString();
349                         break;
350
351                 case EX_ROTATEORIGIN:
352                         lex.next();
353                         rotationdata.origin(lex.getString());
354                         break;
355
356                 case EX_SCALE:
357                         lex.next();
358                         resizedata.scale = lex.getString();
359                         break;
360
361                 case EX_WIDTH:
362                         lex.next();
363                         resizedata.width = Length(lex.getString());
364                         break;
365
366                 case EX_END:
367                         found_end = true;
368                         break;
369
370                 default:
371                         lex.printError("ExternalInset::read: Wrong tag: $$Token");
372                         read_error = true;
373                         break;
374                 }
375
376                 if (found_end || read_error)
377                         break;
378         }
379
380         if (!found_end)
381                 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
382
383         // This is a trick to make sure that the data are self-consistent.
384         settemplate(templatename_);
385
386         if (lyxerr.debugging(Debug::EXTERNAL)) {
387                 lyxerr  << "InsetExternalParams::read:\n";
388                 write(buffer, lyxerr);
389         }
390
391         return !read_error;
392 }
393
394
395 namespace {
396
397 docstring screenLabel(InsetExternalParams const & params,
398                             Buffer const & buffer)
399 {
400         external::Template const * const ptr =
401                 external::getTemplatePtr(params);
402         if (!ptr)
403                 // FIXME UNICODE
404                 return bformat((_("External template %1$s is not installed")),
405                                         from_utf8(params.templatename()));
406         // FIXME UNICODE
407         docstring gui = _(ptr->guiName);
408         gui += ": ";
409
410         if (params.filename.empty())
411                 gui += "???";
412         else
413                 gui += from_utf8(params.filename.relFileName(buffer.filePath()));
414
415         return gui;
416 }
417
418 } // namespace
419
420
421 InsetExternal::InsetExternal(Buffer * buf)
422         : Inset(buf), renderer_(new RenderButton)
423 {
424 }
425
426
427 // Mouse hover is not copied and remains empty
428 InsetExternal::InsetExternal(InsetExternal const & other)
429         : Inset(other),
430           params_(other.params_),
431           renderer_(other.renderer_->clone(this))
432 {}
433
434
435 InsetExternal::~InsetExternal()
436 {
437         hideDialogs("external", this);
438
439         map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
440         map<BufferView const *, bool>::iterator end = mouse_hover_.end();
441         for (; it != end; ++it)
442                 if (it->second)
443                         it->first->clearLastInset(this);
444 }
445
446
447 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
448 {
449         mouse_hover_[bv] = mouse_hover;
450         return true;
451 }
452
453
454 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
455 {
456         switch (cmd.action()) {
457
458         case LFUN_INSET_EDIT: {
459                 InsetExternalParams p =  params();
460                 if (!cmd.argument().empty())
461                         string2params(to_utf8(cmd.argument()), buffer(), p);
462                 external::editExternal(p, buffer());
463                 break;
464         }
465
466         case LFUN_INSET_MODIFY: {
467                 InsetExternalParams p;
468                 string2params(to_utf8(cmd.argument()), buffer(), p);
469                 cur.recordUndo();
470                 setParams(p);
471                 break;
472         }
473
474         case LFUN_INSET_DIALOG_UPDATE:
475                 cur.bv().updateDialog("external",
476                         params2string(params(), cur.bv().buffer()));
477                 break;
478
479         default:
480                 Inset::doDispatch(cur, cmd);
481         }
482 }
483
484
485 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
486                 FuncStatus & flag) const
487 {
488         switch (cmd.action()) {
489
490         case LFUN_INSET_EDIT:
491         case LFUN_INSET_MODIFY:
492         case LFUN_INSET_DIALOG_UPDATE:
493                 flag.setEnabled(true);
494                 return true;
495
496         default:
497                 return Inset::getStatus(cur, cmd, flag);
498         }
499 }
500
501
502 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
503                                                          UpdateType, TocBackend & backend) const
504 {
505         docstring str = screenLabel(params_, buffer());
506         TocBuilder & b = backend.builder("external");
507         b.pushItem(cpit, str, output_active);
508         b.pop();
509 }
510
511
512 bool InsetExternal::showInsetDialog(BufferView * bv) const
513 {
514         bv->showDialog("external", params2string(params(), bv->buffer()),
515                 const_cast<InsetExternal *>(this));
516         return true;
517 }
518
519
520 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
521 {
522         if (!isRendererValid())
523                 updatePreview();
524
525         renderer_->metrics(mi, dim);
526 }
527
528
529 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
530 {
531         if (!isRendererValid())
532                 updatePreview();
533
534         if (renderer_->asButton())
535                 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
536         renderer_->draw(pi, x, y);
537 }
538
539
540 namespace {
541
542 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
543 {
544         graphics::Params gparams;
545
546         gparams.filename = eparams.filename;
547         gparams.scale = eparams.lyxscale;
548         if (eparams.clipdata.clip)
549                 gparams.bb = eparams.clipdata.bbox;
550         gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
551         gparams.display = eparams.display;
552
553         return gparams;
554 }
555
556 } // namespace
557
558
559 static bool isPreviewWanted(InsetExternalParams const & params)
560 {
561         return params.display && params.filename.isReadableFile();
562 }
563
564
565 static docstring latexString(InsetExternal const & inset)
566 {
567         odocstringstream ods;
568         otexstream os(ods);
569         // We don't need to set runparams.encoding since it is not used by
570         // latex().
571         OutputParams runparams(0);
572         runparams.flavor = Flavor::LaTeX;
573         inset.latex(os, runparams);
574         return ods.str();
575 }
576
577
578 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
579                                    InsetExternal const & inset,
580                                    Buffer const & buffer)
581 {
582         InsetExternalParams const & params = inset.params();
583
584         if (RenderPreview::previewText() && isPreviewWanted(params)) {
585                 renderer.setAbsFile(params.filename);
586                 docstring const snippet = latexString(inset);
587                 renderer.addPreview(snippet, buffer);
588                 renderer.startLoading(buffer);
589         }
590 }
591
592
593 InsetExternalParams const & InsetExternal::params() const
594 {
595         return params_;
596 }
597
598
599 bool InsetExternal::isPreviewed() const
600 {
601         return (external::getTemplatePtr(params_) && !params_.filename.empty()
602                 && params_.display
603                 && lyxrc.display_graphics
604                 && params_.preview_mode != PREVIEW_OFF
605                 && (params_.preview_mode != PREVIEW_INSTANT
606                     || RenderPreview::previewText()));
607 }
608
609
610 bool InsetExternal::isRendererValid() const
611 {
612         if (!renderer_->asButton())
613                 return isPreviewed();
614         return !isPreviewed();
615 }
616
617
618 void InsetExternal::setParams(InsetExternalParams const & p)
619 {
620         params_ = p;
621
622         // Subsequent calls to the InsetExternal::Params default constructor
623         // will use this.
624         defaultTemplateName = params_.templatename();
625
626         updatePreview();
627 }
628
629
630 void InsetExternal::updatePreview() const
631 {
632         if (!isPreviewed()) {
633                 RenderButton * button_ptr = renderer_->asButton();
634                 if (!button_ptr) {
635                         renderer_.reset(new RenderButton);
636                         button_ptr = renderer_->asButton();
637                 }
638                 button_ptr->update(screenLabel(params_, buffer()), true, false);
639                 return;
640         }
641
642         switch (params_.preview_mode) {
643         case PREVIEW_OFF:
644                 // Already taken care of above.
645                 LASSERT(false, return);
646                 break;
647         case PREVIEW_INSTANT: {
648                 renderer_ = make_unique<RenderMonitoredPreview>(this);
649                 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
650                 // This connection is closed at the same time as this is destroyed.
651                 preview_ptr->connect([this]() { fileChanged(); });
652                 add_preview_and_start_loading(*preview_ptr, *this, buffer());
653                 break;
654         }
655         case PREVIEW_GRAPHICS: {
656                 RenderGraphic * graphic_ptr = renderer_->asGraphic();
657                 if (!graphic_ptr) {
658                         renderer_.reset(new RenderGraphic(this));
659                         graphic_ptr = renderer_->asGraphic();
660                 }
661                 graphic_ptr->update(get_grfx_params(params_));
662                 break;
663         }
664         }
665 }
666
667
668 void InsetExternal::fileChanged() const
669 {
670         Buffer const * const buffer = updateFrontend();
671         if (!buffer)
672                 return;
673
674         RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
675         LASSERT(ptr, return);
676
677         ptr->removePreview(*buffer);
678         add_preview_and_start_loading(*ptr, *this, *buffer);
679 }
680
681
682 void InsetExternal::write(ostream & os) const
683 {
684         params_.write(buffer(), os);
685 }
686
687
688 void InsetExternal::read(Lexer & lex)
689 {
690         InsetExternalParams params;
691         if (params.read(buffer(), lex))
692                 setParams(params);
693 }
694
695
696 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
697 {
698         if (params_.draft) {
699                 // FIXME UNICODE
700                 os << "\\fbox{\\ttfamily{}"
701                    << from_utf8(params_.filename.outputFileName(buffer().filePath()))
702                    << "}\n";
703                 return;
704         }
705
706         // "nice" means that the buffer is exported to LaTeX format but not
707         // run through the LaTeX compiler.
708         // If we're running through the LaTeX compiler, we should write the
709         // generated files in the buffer's temporary directory.
710         bool const external_in_tmpdir = !runparams.nice;
711         bool const dryrun = runparams.dryrun || runparams.inComment;
712
713         // If the template has specified a PDFLaTeX output, then we try and
714         // use that.
715         if (runparams.flavor == Flavor::PdfLaTeX) {
716                 external::Template const * const et_ptr =
717                         external::getTemplatePtr(params_);
718                 if (!et_ptr)
719                         return;
720                 external::Template const & et = *et_ptr;
721
722                 external::Template::Formats::const_iterator cit =
723                         et.formats.find("PDFLaTeX");
724
725                 if (cit != et.formats.end()) {
726                         external::RetVal retval =
727                                 external::writeExternal(params_, "PDFLaTeX", buffer(), os,
728                                     *(runparams.exportdata), external_in_tmpdir, dryrun);
729                         if (retval == external::KILLED) {
730                                 LYXERR0("External template preparation killed.");
731                                 if (buffer().isClone() && buffer().isExporting())
732                                         throw ConversionException();
733                         }
734                         return;
735                 }
736         }
737
738         external::RetVal retval =
739                 external::writeExternal(params_, "LaTeX", buffer(), os,
740                     *(runparams.exportdata), external_in_tmpdir, dryrun);
741         if (retval == external::KILLED) {
742                 LYXERR0("External template preparation killed.");
743                 if (buffer().isClone() && buffer().isExporting())
744                         throw ConversionException();
745         }
746 }
747
748
749 int InsetExternal::plaintext(odocstringstream & os,
750                              OutputParams const & runparams, size_t) const
751 {
752         // this is too slow for constant use
753         if (runparams.for_tooltip)
754                 return 0;
755
756         bool const external_in_tmpdir = !runparams.nice;
757         bool const dryrun = runparams.dryrun || runparams.inComment;
758         otexstream ots(os);
759         ots << '\n'; // output external material on a new line
760         external::RetVal retval =
761                 external::writeExternal(params_, "Ascii", buffer(), ots,
762                     *(runparams.exportdata), external_in_tmpdir, dryrun);
763         if (retval == external::KILLED) {
764                 LYXERR0("External template preparation killed.");
765                 if (buffer().isClone() && buffer().isExporting())
766                         throw ConversionException();
767         }
768         return PLAINTEXT_NEWLINE;
769 }
770
771
772 void InsetExternal::generateXML(XMLStream & xs, OutputParams const & runparams, std::string const & format) const
773 {
774         bool const external_in_tmpdir = !runparams.nice;
775         bool const dryrun = runparams.dryrun || runparams.inComment;
776         odocstringstream ods;
777         otexstream ots(ods);
778         external::RetVal retval =
779                         external::writeExternal(params_, format, buffer(), ots,
780                                                 *(runparams.exportdata), external_in_tmpdir, dryrun);
781         if (retval == external::KILLED) {
782                 LYXERR0("External template preparation killed.");
783                 if (buffer().isClone() && buffer().isExporting())
784                         throw ConversionException();
785         }
786         xs << XMLStream::ESCAPE_NONE << ods.str();
787 }
788
789
790 void InsetExternal::docbook(XMLStream & xs,
791                             OutputParams const & runparams) const
792 {
793         generateXML(xs, runparams, "DocBook");
794 }
795
796
797 docstring InsetExternal::xhtml(XMLStream & xs,
798                         OutputParams const & runparams) const
799 {
800         generateXML(xs, runparams, "XHTML");
801         return docstring();
802 }
803
804
805 void InsetExternal::validate(LaTeXFeatures & features) const
806 {
807         if (params_.draft)
808                 return;
809
810         external::Template const * const et_ptr =
811                 external::getTemplatePtr(params_);
812         if (!et_ptr)
813                 return;
814         external::Template const & et = *et_ptr;
815
816         string format;
817         switch (features.runparams().flavor) {
818         case Flavor::LaTeX:
819         case Flavor::DviLuaTeX:
820                 format = "LaTeX";
821                 break;
822         case Flavor::LuaTeX:
823         case Flavor::PdfLaTeX:
824         case Flavor::XeTeX:
825                 format = "PDFLaTeX";
826                 break;
827         case Flavor::DocBook5:
828                 format = "DocBook";
829                 break;
830         case Flavor::Html:
831                 format = "html";
832                 break;
833         case Flavor::Text:
834                 format = "text";
835                 break;
836         case Flavor::LyX:
837                 format = "lyx";
838                 break;
839         }
840         external::Template::Formats::const_iterator cit =
841                 et.formats.find(format);
842
843         if (cit == et.formats.end()) {
844                 // If the template has not specified a PDFLaTeX output,
845                 // we try the LaTeX format.
846                 if (format == "PDFLaTeX") {
847                         cit = et.formats.find("LaTeX");
848                         if (cit == et.formats.end())
849                                 return;
850                 } else
851                         return;
852         }
853
854         // FIXME: We don't need that always, see InsetGraphics
855         features.require("lyxdot");
856
857         vector<string>::const_iterator it  = cit->second.requirements.begin();
858         vector<string>::const_iterator end = cit->second.requirements.end();
859         for (; it != end; ++it)
860                 features.require(*it);
861
862         external::TemplateManager & etm = external::TemplateManager::get();
863
864         for (string const & name : cit->second.preambleNames) {
865                 docstring const preamble = etm.getPreambleDefByName(name);
866                 if (!preamble.empty())
867                         features.addPreambleSnippet(preamble);
868         }
869 }
870
871
872 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
873                                graphics::PreviewLoader & ploader) const
874 {
875         RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
876         if (!ptr)
877                 return;
878
879         if (isPreviewWanted(params())) {
880                 ptr->setAbsFile(params_.filename);
881                 docstring const snippet = latexString(*this);
882                 ptr->addPreview(snippet, ploader);
883         }
884 }
885
886
887 string InsetExternal::contextMenuName() const
888 {
889         return "context-external";
890 }
891
892
893 void InsetExternal::string2params(string const & in, Buffer const & buffer,
894         InsetExternalParams & params)
895 {
896         params = InsetExternalParams();
897         if (in.empty())
898                 return;
899
900         istringstream data(in);
901         Lexer lex;
902         lex.setStream(data);
903
904         string name;
905         lex >> name;
906         if (!lex || name != "external") {
907                 LYXERR0("InsetExternal::string2params(" << in << ")\n"
908                                           "Expected arg 1 to be \"external\"\n");
909                 return;
910         }
911
912         // This is part of the inset proper that is usually swallowed
913         // by Text::readInset
914         string id;
915         lex >> id;
916         if (!lex || id != "External") {
917                 LYXERR0("InsetExternal::string2params(" << in << ")\n"
918                                           "Expected arg 2 to be \"External\"\n");
919                 return;
920         }
921
922         params.read(buffer, lex);
923 }
924
925
926 string InsetExternal::params2string(InsetExternalParams const & params,
927         Buffer const & buffer)
928 {
929         ostringstream data;
930         data << "external" << ' ';
931         params.write(buffer, data);
932         data << "\\end_inset\n";
933         return data.str();
934 }
935
936
937 docstring InsetExternal::toolTip(BufferView const &, int, int) const
938 {
939         return from_utf8(params().filename.onlyFileName());
940 }
941
942 } // namespace lyx