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