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