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