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