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