]> git.lyx.org Git - features.git/blob - src/insets/InsetExternal.cpp
progress on buffer-reference-in-insets. beware of instabilities...
[features.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 & buf, ostream & os) const
185 {
186         os << "External\n"
187            << "\ttemplate " << templatename() << '\n';
188
189         if (!filename.empty()) {
190                 os << "\tfilename " << filename.outputFilename(buf.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                 { "embed",           EX_EMBED},
272                 { "extra",           EX_EXTRA },
273                 { "filename",        EX_FILENAME},
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                 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                 InsetExternalParams p;
452                 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
453                 if (!p.filename.empty()) {
454                         try {
455                                 p.filename.enable(buffer().embedded(), &buffer());
456                         } catch (ExceptionMessage const & message) {
457                                 Alert::error(message.title_, message.details_);
458                                 // do not set parameter if an error happens
459                                 break;
460                         }
461                 }
462                 setParams(p);
463                 break;
464         }
465
466         case LFUN_INSET_DIALOG_UPDATE:
467                 InsetExternalMailer(*this).updateDialog(&cur.bv());
468                 break;
469
470         case LFUN_MOUSE_RELEASE:
471                 if (!cur.selection())
472                         InsetExternalMailer(*this).showDialog(&cur.bv());
473                 break;
474
475         default:
476                 Inset::doDispatch(cur, cmd);
477         }
478 }
479
480
481 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
482                 FuncStatus & flag) const
483 {
484         switch (cmd.action) {
485
486         case LFUN_EXTERNAL_EDIT:
487         case LFUN_INSET_MODIFY:
488         case LFUN_INSET_DIALOG_UPDATE:
489                 flag.enabled(true);
490                 return true;
491
492         default:
493                 return Inset::getStatus(cur, cmd, flag);
494         }
495 }
496
497
498 void InsetExternal::registerEmbeddedFiles(Buffer const & buffer,
499         EmbeddedFileList & files) const
500 {
501         files.registerFile(params_.filename, this, buffer);
502 }
503
504
505 void InsetExternal::updateEmbeddedFile(Buffer const & buf,
506         EmbeddedFile const & file)
507 {
508         // when embedding is enabled, change of embedding status leads to actions
509         EmbeddedFile temp = file;
510         temp.enable(buf.embedded(), &buf);
511         // this will not be set if an exception is thorwn in enable()
512         params_.filename = temp;
513 }
514
515
516 void InsetExternal::edit(Cursor & cur, bool, EntryDirection)
517 {
518         InsetExternalMailer(*this).showDialog(&cur.bv());
519 }
520
521
522 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
523 {
524         renderer_->metrics(mi, dim);
525 }
526
527
528 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
529 {
530         renderer_->draw(pi, x, y);
531 }
532
533
534 namespace {
535
536 enum RenderType {
537         RENDERBUTTON,
538         RENDERGRAPHIC,
539         RENDERPREVIEW
540 };
541
542
543 RenderType getRenderType(InsetExternalParams const & p)
544 {
545         if (!external::getTemplatePtr(p) ||
546             p.filename.empty() ||
547             p.display == external::NoDisplay)
548                 return RENDERBUTTON;
549
550         if (p.display == external::PreviewDisplay) {
551                 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
552                         return RENDERPREVIEW;
553                 return RENDERBUTTON;
554         }
555
556         if (p.display == external::DefaultDisplay &&
557             lyxrc.display_graphics == graphics::NoDisplay)
558                 return RENDERBUTTON;
559         return RENDERGRAPHIC;
560 }
561
562
563 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
564 {
565         graphics::Params gparams;
566
567         gparams.filename = eparams.filename.availableFile();
568         gparams.icon = eparams.filename.embedded() ? "pin.png" : "";
569         gparams.scale = eparams.lyxscale;
570         if (eparams.clipdata.clip)
571                 gparams.bb = eparams.clipdata.bbox;
572         gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
573
574         switch (eparams.display) {
575         case external::DefaultDisplay:
576                 gparams.display = graphics::DefaultDisplay;
577                 break;
578         case external::MonochromeDisplay:
579                 gparams.display = graphics::MonochromeDisplay;
580                 break;
581         case external::GrayscaleDisplay:
582                 gparams.display = graphics::GrayscaleDisplay;
583                 break;
584         case external::ColorDisplay:
585                 gparams.display = graphics::ColorDisplay;
586                 break;
587         case external::NoDisplay:
588                 gparams.display = graphics::NoDisplay;
589                 break;
590         default:
591                 BOOST_ASSERT(false);
592         }
593         if (gparams.display == graphics::DefaultDisplay)
594                 gparams.display = graphics::DisplayType(lyxrc.display_graphics);
595         // Override the above if we're not using a gui
596         if (!use_gui)
597                 gparams.display = graphics::NoDisplay;
598
599         return gparams;
600 }
601
602
603 docstring screenLabel(InsetExternalParams const & params,
604                             Buffer const & buffer)
605 {
606         external::Template const * const ptr =
607                 external::getTemplatePtr(params);
608         if (!ptr)
609                 // FIXME UNICODE
610                 return bformat((_("External template %1$s is not installed")),
611                                         from_utf8(params.templatename()));
612         // FIXME UNICODE
613         docstring gui = _(ptr->guiName);
614         return from_utf8(external::doSubstitution(params, buffer,
615                                 to_utf8(gui), false));
616 }
617
618 } // namespace anon
619
620
621 static bool isPreviewWanted(InsetExternalParams const & params)
622 {
623         return params.display == external::PreviewDisplay &&
624                 params.filename.isReadableFile();
625 }
626
627
628 static docstring latexString(InsetExternal const & inset)
629 {
630         odocstringstream os;
631         // We don't need to set runparams.encoding since it is not used by
632         // latex().
633         OutputParams runparams(0);
634         runparams.flavor = OutputParams::LATEX;
635         inset.latex(os, runparams);
636         return os.str();
637 }
638
639
640 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
641                                    InsetExternal const & inset,
642                                    Buffer const & buffer)
643 {
644         InsetExternalParams const & params = inset.params();
645
646         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
647             isPreviewWanted(params)) {
648                 renderer.setAbsFile(params.filename);
649                 docstring const snippet = latexString(inset);
650                 renderer.addPreview(snippet, buffer);
651                 renderer.startLoading(buffer);
652         }
653 }
654
655
656 InsetExternalParams const & InsetExternal::params() const
657 {
658         return params_;
659 }
660
661
662 void InsetExternal::setParams(InsetExternalParams const & p)
663 {
664         params_ = p;
665
666         // Subsequent calls to the InsetExternal::Params default constructor
667         // will use this.
668         defaultTemplateName = params_.templatename();
669
670         switch (getRenderType(params_)) {
671         case RENDERBUTTON: {
672                 RenderButton * button_ptr = renderer_->asButton();
673                 if (!button_ptr) {
674                         renderer_.reset(new RenderButton);
675                         button_ptr = renderer_->asButton();
676                 }
677
678                 button_ptr->update(screenLabel(params_, buffer()), true);
679                 break;
680         }
681
682         case RENDERGRAPHIC: {
683                 RenderGraphic * graphic_ptr = renderer_->asGraphic();
684                 if (!graphic_ptr) {
685                         renderer_.reset(new RenderGraphic(this));
686                         graphic_ptr = renderer_->asGraphic();
687                 }
688
689                 graphic_ptr->update(get_grfx_params(params_));
690
691                 break;
692         }
693
694         case RENDERPREVIEW: {
695                 RenderMonitoredPreview * preview_ptr =
696                         renderer_->asMonitoredPreview();
697                 if (!preview_ptr) {
698                         renderer_.reset(new RenderMonitoredPreview(this));
699                         preview_ptr = renderer_->asMonitoredPreview();
700                         preview_ptr->fileChanged(
701                                 boost::bind(&InsetExternal::fileChanged, this));
702                 }
703
704                 if (preview_ptr->monitoring())
705                         preview_ptr->stopMonitoring();
706                 add_preview_and_start_loading(*preview_ptr, *this, buffer());
707
708                 break;
709         }
710         }
711 }
712
713
714 void InsetExternal::fileChanged() const
715 {
716         Buffer const * const buffer = updateFrontend();
717         if (!buffer)
718                 return;
719
720         RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
721         BOOST_ASSERT(ptr);
722
723         ptr->removePreview(*buffer);
724         add_preview_and_start_loading(*ptr, *this, *buffer);
725 }
726
727
728 void InsetExternal::write(ostream & os) const
729 {
730         params_.write(buffer(), os);
731 }
732
733
734 void InsetExternal::read(Lexer & lex)
735 {
736         InsetExternalParams params;
737         if (params.read(buffer(), lex)) {
738                 // exception handling is not needed as long as embedded files are in place.
739                 params.filename.enable(buffer().embedded(), &buffer());
740                 setParams(params);
741         }
742 }
743
744
745 int InsetExternal::latex(odocstream & os, OutputParams const & runparams) const
746 {
747         if (params_.draft) {
748                 // FIXME UNICODE
749                 os << "\\fbox{\\ttfamily{}"
750                    << from_utf8(params_.filename.outputFilename(buffer().filePath()))
751                    << "}\n";
752                 return 1;
753         }
754
755         // "nice" means that the buffer is exported to LaTeX format but not
756         // run through the LaTeX compiler.
757         // If we're running through the LaTeX compiler, we should write the
758         // generated files in the buffer's temporary directory.
759         bool const external_in_tmpdir = !runparams.nice;
760         bool const dryrun = runparams.dryrun || runparams.inComment;
761
762         // If the template has specified a PDFLaTeX output, then we try and
763         // use that.
764         if (runparams.flavor == OutputParams::PDFLATEX) {
765                 external::Template const * const et_ptr =
766                         external::getTemplatePtr(params_);
767                 if (!et_ptr)
768                         return 0;
769                 external::Template const & et = *et_ptr;
770
771                 external::Template::Formats::const_iterator cit =
772                         et.formats.find("PDFLaTeX");
773
774                 if (cit != et.formats.end()) {
775                         return external::writeExternal(params_, "PDFLaTeX",
776                                                        buffer(), os,
777                                                        *(runparams.exportdata),
778                                                        external_in_tmpdir,
779                                                        dryrun);
780                 }
781         }
782
783         return external::writeExternal(params_, "LaTeX", buffer(), os,
784                                        *(runparams.exportdata),
785                                        external_in_tmpdir,
786                                        dryrun);
787 }
788
789
790 int InsetExternal::plaintext(odocstream & os,
791                              OutputParams const & runparams) const
792 {
793         os << '\n'; // output external material on a new line
794         external::writeExternal(params_, "Ascii", buffer(), os,
795                                 *(runparams.exportdata), false,
796                                 runparams.dryrun || runparams.inComment);
797         return PLAINTEXT_NEWLINE;
798 }
799
800
801 int InsetExternal::docbook(odocstream & os,
802                            OutputParams const & runparams) const
803 {
804         return external::writeExternal(params_, "DocBook", buffer(), os,
805                                        *(runparams.exportdata), false,
806                                        runparams.dryrun || runparams.inComment);
807 }
808
809
810 void InsetExternal::validate(LaTeXFeatures & features) const
811 {
812         if (params_.draft)
813                 return;
814
815         external::Template const * const et_ptr =
816                 external::getTemplatePtr(params_);
817         if (!et_ptr)
818                 return;
819         external::Template const & et = *et_ptr;
820
821         string format;
822         switch (features.runparams().flavor) {
823         case OutputParams::LATEX:
824                 format = "LaTeX";
825                 break;
826         case OutputParams::PDFLATEX:
827                 format = "PDFLaTeX";
828                 break;
829         case OutputParams::XML:
830                 format = "DocBook";
831                 break;
832         }
833         external::Template::Formats::const_iterator cit =
834                 et.formats.find(format);
835         if (cit == et.formats.end())
836                 return;
837
838         // FIXME: We don't need that always
839         features.require("lyxdot");
840
841         vector<string>::const_iterator it  = cit->second.requirements.begin();
842         vector<string>::const_iterator end = cit->second.requirements.end();
843         for (; it != end; ++it)
844                 features.require(*it);
845
846         external::TemplateManager & etm = external::TemplateManager::get();
847
848         it  = cit->second.preambleNames.begin();
849         end = cit->second.preambleNames.end();
850         for (; it != end; ++it) {
851                 string const preamble = etm.getPreambleDefByName(*it);
852                 if (!preamble.empty())
853                         features.addPreambleSnippet(preamble);
854         }
855 }
856
857
858 //
859 // preview stuff
860 //
861
862 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
863 {
864         RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
865         if (!ptr)
866                 return;
867
868         if (isPreviewWanted(params())) {
869                 ptr->setAbsFile(params_.filename);
870                 docstring const snippet = latexString(*this);
871                 ptr->addPreview(snippet, ploader);
872         }
873 }
874
875
876 /// Mailer stuff
877
878 string const InsetExternalMailer::name_("external");
879
880 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
881         : inset_(inset)
882 {}
883
884
885 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
886 {
887         return params2string(inset_.params(), buffer);
888 }
889
890
891 void InsetExternalMailer::string2params(string const & in,
892                                         Buffer const & buffer,
893                                         InsetExternalParams & params)
894 {
895         params = InsetExternalParams();
896         if (in.empty())
897                 return;
898
899         istringstream data(in);
900         Lexer lex(0,0);
901         lex.setStream(data);
902
903         string name;
904         lex >> name;
905         if (!lex || name != name_)
906                 return print_mailer_error("InsetExternalMailer", in, 1, name_);
907
908         // This is part of the inset proper that is usually swallowed
909         // by Text::readInset
910         string id;
911         lex >> id;
912         if (!lex || id != "External")
913                 return print_mailer_error("InsetBoxMailer", in, 2, "External");
914
915         params.read(buffer, lex);
916 }
917
918
919 string const
920 InsetExternalMailer::params2string(InsetExternalParams const & params,
921                                    Buffer const & buffer)
922 {
923         ostringstream data;
924         data << name_ << ' ';
925         params.write(buffer, data);
926         data << "\\end_inset\n";
927         return data.str();
928 }
929
930 } // namespace lyx