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