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