]> git.lyx.org Git - lyx.git/blob - src/insets/InsetExternal.cpp
Make the insets accept LFUN_INSET_SETTINGS. These insets did not yet respond to LFUN_...
[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         case LFUN_MOUSE_RELEASE:
418                 if (!cur.selection() && cmd.button() == mouse_button::button1)
419                         cur.bv().showDialog("external",
420                                 params2string(params(), cur.bv().buffer()),
421                                 this);
422                 break;
423
424         default:
425                 Inset::doDispatch(cur, cmd);
426         }
427 }
428
429
430 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
431                 FuncStatus & flag) const
432 {
433         switch (cmd.action) {
434
435         case LFUN_INSET_EDIT:
436         case LFUN_INSET_MODIFY:
437         case LFUN_INSET_DIALOG_UPDATE:
438         case LFUN_INSET_SETTINGS:
439                 flag.setEnabled(true);
440                 return true;
441
442         default:
443                 return Inset::getStatus(cur, cmd, flag);
444         }
445 }
446
447
448 void InsetExternal::edit(Cursor & cur, bool, EntryDirection)
449 {
450         showInsetDialog(&cur.bv());
451 }
452
453
454 bool InsetExternal::showInsetDialog(BufferView * bv) const
455 {
456         bv->showDialog("external", params2string(params(), bv->buffer()),
457                 const_cast<InsetExternal *>(this));
458         return true;
459 }
460
461
462 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
463 {
464         renderer_->metrics(mi, dim);
465 }
466
467
468 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
469 {
470         renderer_->draw(pi, x, y);
471 }
472
473
474 namespace {
475
476 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
477 {
478         graphics::Params gparams;
479
480         gparams.filename = eparams.filename;
481         gparams.scale = eparams.lyxscale;
482         if (eparams.clipdata.clip)
483                 gparams.bb = eparams.clipdata.bbox;
484         gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
485         gparams.display = eparams.display;
486
487         return gparams;
488 }
489
490
491 docstring screenLabel(InsetExternalParams const & params,
492                             Buffer const & buffer)
493 {
494         external::Template const * const ptr =
495                 external::getTemplatePtr(params);
496         if (!ptr)
497                 // FIXME UNICODE
498                 return bformat((_("External template %1$s is not installed")),
499                                         from_utf8(params.templatename()));
500         // FIXME UNICODE
501         docstring gui = _(ptr->guiName);
502         return from_utf8(external::doSubstitution(params, buffer,
503                                 to_utf8(gui), false));
504 }
505
506 } // namespace anon
507
508
509 static bool isPreviewWanted(InsetExternalParams const & params)
510 {
511         return params.display && params.filename.isReadableFile();
512 }
513
514
515 static docstring latexString(InsetExternal const & inset)
516 {
517         odocstringstream os;
518         // We don't need to set runparams.encoding since it is not used by
519         // latex().
520         OutputParams runparams(0);
521         runparams.flavor = OutputParams::LATEX;
522         inset.latex(os, runparams);
523         return os.str();
524 }
525
526
527 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
528                                    InsetExternal const & inset,
529                                    Buffer const & buffer)
530 {
531         InsetExternalParams const & params = inset.params();
532
533         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
534             isPreviewWanted(params)) {
535                 renderer.setAbsFile(params.filename);
536                 docstring const snippet = latexString(inset);
537                 renderer.addPreview(snippet, buffer);
538                 renderer.startLoading(buffer);
539         }
540 }
541
542
543 InsetExternalParams const & InsetExternal::params() const
544 {
545         return params_;
546 }
547
548
549 void InsetExternal::updatePreview()
550 {
551         setParams(params_);
552 }
553
554
555 void InsetExternal::setParams(InsetExternalParams const & p)
556 {
557         params_ = p;
558
559         // Subsequent calls to the InsetExternal::Params default constructor
560         // will use this.
561         defaultTemplateName = params_.templatename();
562
563         if (!external::getTemplatePtr(params_) || params_.filename.empty()
564                 || !params_.display
565                 || !lyxrc.display_graphics
566                 || params_.preview_mode == PREVIEW_OFF
567                 || (params_.preview_mode == PREVIEW_INSTANT
568                     && RenderPreview::status() == LyXRC::PREVIEW_OFF)) {
569                 RenderButton * button_ptr = renderer_->asButton();
570                 if (!button_ptr) {
571                         renderer_.reset(new RenderButton);
572                         button_ptr = renderer_->asButton();
573                 }
574                 button_ptr->update(screenLabel(params_, buffer()), true);
575                 return;
576         }
577
578         switch (params_.preview_mode) {
579         case PREVIEW_OFF:
580                 // Already taken care of above.
581                 LASSERT(false, return);
582                 break;
583         case PREVIEW_INSTANT: {
584                 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
585                 renderer_.reset(new RenderMonitoredPreview(this));
586                 preview_ptr = renderer_->asMonitoredPreview();
587                 preview_ptr->fileChanged(boost::bind(&InsetExternal::fileChanged, this));
588                 if (preview_ptr->monitoring())
589                         preview_ptr->stopMonitoring();
590                 add_preview_and_start_loading(*preview_ptr, *this, buffer());
591                 break;
592         } 
593         case PREVIEW_GRAPHICS: {
594                 RenderGraphic * graphic_ptr = renderer_->asGraphic();
595                 if (!graphic_ptr) {
596                         renderer_.reset(new RenderGraphic(this));
597                         graphic_ptr = renderer_->asGraphic();
598                 }
599                 graphic_ptr->update(get_grfx_params(params_));
600                 break;
601         }
602         }
603 }
604
605
606 void InsetExternal::fileChanged() const
607 {
608         Buffer const * const buffer = updateFrontend();
609         if (!buffer)
610                 return;
611
612         RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
613         LASSERT(ptr, /**/);
614
615         ptr->removePreview(*buffer);
616         add_preview_and_start_loading(*ptr, *this, *buffer);
617 }
618
619
620 void InsetExternal::write(ostream & os) const
621 {
622         params_.write(buffer(), os);
623 }
624
625
626 void InsetExternal::read(Lexer & lex)
627 {
628         InsetExternalParams params;
629         if (params.read(buffer(), lex))
630                 setParams(params);
631 }
632
633
634 int InsetExternal::latex(odocstream & os, OutputParams const & runparams) const
635 {
636         if (params_.draft) {
637                 // FIXME UNICODE
638                 os << "\\fbox{\\ttfamily{}"
639                    << from_utf8(params_.filename.outputFilename(buffer().filePath()))
640                    << "}\n";
641                 return 1;
642         }
643
644         // "nice" means that the buffer is exported to LaTeX format but not
645         // run through the LaTeX compiler.
646         // If we're running through the LaTeX compiler, we should write the
647         // generated files in the buffer's temporary directory.
648         bool const external_in_tmpdir = !runparams.nice;
649         bool const dryrun = runparams.dryrun || runparams.inComment;
650
651         // If the template has specified a PDFLaTeX output, then we try and
652         // use that.
653         if (runparams.flavor == OutputParams::PDFLATEX) {
654                 external::Template const * const et_ptr =
655                         external::getTemplatePtr(params_);
656                 if (!et_ptr)
657                         return 0;
658                 external::Template const & et = *et_ptr;
659
660                 external::Template::Formats::const_iterator cit =
661                         et.formats.find("PDFLaTeX");
662
663                 if (cit != et.formats.end()) {
664                         return external::writeExternal(params_, "PDFLaTeX",
665                                                        buffer(), os,
666                                                        *(runparams.exportdata),
667                                                        external_in_tmpdir,
668                                                        dryrun);
669                 }
670         }
671
672         return external::writeExternal(params_, "LaTeX", buffer(), os,
673                                        *(runparams.exportdata),
674                                        external_in_tmpdir,
675                                        dryrun);
676 }
677
678
679 int InsetExternal::plaintext(odocstream & os,
680                              OutputParams const & runparams) const
681 {
682         os << '\n'; // output external material on a new line
683         external::writeExternal(params_, "Ascii", buffer(), os,
684                                 *(runparams.exportdata), false,
685                                 runparams.dryrun || runparams.inComment);
686         return PLAINTEXT_NEWLINE;
687 }
688
689
690 int InsetExternal::docbook(odocstream & os,
691                            OutputParams const & runparams) const
692 {
693         return external::writeExternal(params_, "DocBook", buffer(), os,
694                                        *(runparams.exportdata), false,
695                                        runparams.dryrun || runparams.inComment);
696 }
697
698
699 void InsetExternal::validate(LaTeXFeatures & features) const
700 {
701         if (params_.draft)
702                 return;
703
704         external::Template const * const et_ptr =
705                 external::getTemplatePtr(params_);
706         if (!et_ptr)
707                 return;
708         external::Template const & et = *et_ptr;
709
710         string format;
711         switch (features.runparams().flavor) {
712         case OutputParams::LATEX:
713                 format = "LaTeX";
714                 break;
715         case OutputParams::PDFLATEX:
716         case OutputParams::XETEX:
717                 format = "PDFLaTeX";
718                 break;
719         case OutputParams::XML:
720                 format = "DocBook";
721                 break;
722         }
723         external::Template::Formats::const_iterator cit =
724                 et.formats.find(format);
725
726         if (cit == et.formats.end()) {
727                 // If the template has not specified a PDFLaTeX output,
728                 // we try the LaTeX format.
729                 if (format == "PDFLaTeX") {
730                         cit = et.formats.find("LaTeX");
731                         if (cit == et.formats.end())
732                                 return;
733                 } else
734                         return;
735         }
736
737         // FIXME: We don't need that always
738         features.require("lyxdot");
739
740         vector<string>::const_iterator it  = cit->second.requirements.begin();
741         vector<string>::const_iterator end = cit->second.requirements.end();
742         for (; it != end; ++it)
743                 features.require(*it);
744
745         external::TemplateManager & etm = external::TemplateManager::get();
746
747         it  = cit->second.preambleNames.begin();
748         end = cit->second.preambleNames.end();
749         for (; it != end; ++it) {
750                 string const preamble = etm.getPreambleDefByName(*it);
751                 if (!preamble.empty())
752                         features.addPreambleSnippet(preamble);
753         }
754 }
755
756
757 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
758 {
759         RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
760         if (!ptr)
761                 return;
762
763         if (isPreviewWanted(params())) {
764                 ptr->setAbsFile(params_.filename);
765                 docstring const snippet = latexString(*this);
766                 ptr->addPreview(snippet, ploader);
767         }
768 }
769
770
771 docstring InsetExternal::contextMenu(BufferView const &, int, int) const
772 {
773         return from_ascii("context-external");
774 }
775
776
777 void InsetExternal::string2params(string const & in, Buffer const & buffer,
778         InsetExternalParams & params)
779 {
780         params = InsetExternalParams();
781         if (in.empty())
782                 return;
783
784         istringstream data(in);
785         Lexer lex;
786         lex.setStream(data);
787
788         string name;
789         lex >> name;
790         if (!lex || name != "external") {
791                 LYXERR0("InsetExternal::string2params(" << in << ")\n"
792                                           "Expected arg 1 to be \"external\"\n");
793                 return;
794         }
795
796         // This is part of the inset proper that is usually swallowed
797         // by Text::readInset
798         string id;
799         lex >> id;
800         if (!lex || id != "External") {
801                 LYXERR0("InsetExternal::string2params(" << in << ")\n"
802                                           "Expected arg 2 to be \"External\"\n");
803                 return;
804         }
805
806         params.read(buffer, lex);
807 }
808
809
810 string InsetExternal::params2string(InsetExternalParams const & params,
811         Buffer const & buffer)
812 {
813         ostringstream data;
814         data << "external" << ' ';
815         params.write(buffer, data);
816         data << "\\end_inset\n";
817         return data.str();
818 }
819
820 } // namespace lyx