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