]> git.lyx.org Git - lyx.git/blob - src/insets/insetexternal.C
08f4a4f2406646d71121c93f4231aa7b53db8e1b
[lyx.git] / src / insets / insetexternal.C
1 /**
2  * \file insetexternal.C
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/renderers.h"
15 #include "insets/ExternalSupport.h"
16 #include "insets/ExternalTemplate.h"
17
18 #include "buffer.h"
19 #include "BufferView.h"
20 #include "debug.h"
21 #include "funcrequest.h"
22 #include "gettext.h"
23 #include "LaTeXFeatures.h"
24 #include "latexrunparams.h"
25 #include "lyxlex.h"
26 #include "lyxrc.h"
27
28 #include "frontends/lyx_gui.h"
29
30 #include "support/lstrings.h"
31 #include "support/lyxlib.h"
32 #include "support/tostr.h"
33 #include "support/translator.h"
34
35 #include <boost/bind.hpp>
36
37 #include "support/std_sstream.h"
38
39 namespace support = lyx::support;
40 namespace external = lyx::external;
41
42 using std::endl;
43 using std::string;
44 using std::auto_ptr;
45 using std::istringstream;
46 using std::ostream;
47 using std::ostringstream;
48 using std::vector;
49
50
51 namespace lyx {
52 namespace graphics {
53
54 /// The translator between the DisplayType and the corresponding lyx string.
55 extern Translator<DisplayType, string> displayTranslator;
56
57 } // namespace graphics
58 } // namespace lyx
59
60
61 namespace {
62
63 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
64
65 unsigned int defaultLyxScale = 100;
66
67 } // namespace anon
68
69
70 namespace lyx {
71 namespace external {
72
73 TempName::TempName()
74 {
75         tempname_ = support::tempName(string(), "lyxext");
76         support::unlink(tempname_);
77         // must have an extension for the converter code to work correctly.
78         tempname_ += ".tmp";
79 }
80
81
82 TempName::TempName(TempName const &)
83 {
84         tempname_ = TempName()();
85 }
86
87
88 TempName::~TempName()
89 {
90         support::unlink(tempname_);
91 }
92
93
94 TempName &
95 TempName::operator=(TempName const & other)
96 {
97         if (this != &other)
98                 tempname_ = TempName()();
99         return *this;
100 }
101
102 } // namespace external
103 } // namespace lyx
104
105
106 InsetExternalParams::InsetExternalParams()
107         : display(defaultDisplayType),
108           lyxscale(defaultLyxScale)
109 {}
110
111
112 namespace {
113
114 template <typename T>
115 void clearIfNotFound(T & data, external::TransformID value,
116                      vector<external::TransformID> const & ids)
117 {
118         typedef vector<external::TransformID>::const_iterator
119                 const_iterator;
120
121         const_iterator it  = ids.begin();
122         const_iterator end = ids.end();
123         it = std::find(it, end, value);
124         if (it == end)
125                 data = T();
126 }
127
128 } // namespace anon
129
130
131 void InsetExternalParams::settemplate(string const & name)
132 {
133         templatename_ = name;
134
135         external::TemplateManager const & etm =
136                 external::TemplateManager::get();
137         external::Template const * const et = etm.getTemplateByName(name);
138         if (!et)
139                 // Be safe. Don't lose data.
140                 return;
141
142         // Ascertain which transforms the template supports.
143         // Empty all those that it doesn't.
144         vector<external::TransformID> const & ids = et->transformIds;
145         clearIfNotFound(clipdata,     external::Clip,   ids);
146         clearIfNotFound(extradata,    external::Extra,  ids);
147         clearIfNotFound(resizedata,   external::Resize, ids);
148         clearIfNotFound(rotationdata, external::Rotate, ids);
149 }
150
151
152 void InsetExternalParams::write(Buffer const & buffer, ostream & os) const
153 {
154         os << "External\n"
155            << "\ttemplate " << templatename() << '\n';
156
157         if (!filename.empty())
158                 os << "\tfilename "
159                    << filename.outputFilename(buffer.filePath())
160                    << '\n';
161
162         if (display != defaultDisplayType)
163                 os << "\tdisplay "
164                    << lyx::graphics::displayTranslator.find(display)
165                    << '\n';
166
167         if (lyxscale != defaultLyxScale)
168                 os << "\tlyxscale " << tostr(lyxscale) << '\n';
169
170         if (!clipdata.bbox.empty())
171                 os << "\tboundingBox " << clipdata.bbox << '\n';
172         if (clipdata.clip)
173                 os << "\tclip\n";
174
175         external::ExtraData::const_iterator it  = extradata.begin();
176         external::ExtraData::const_iterator end = extradata.end();
177         for (; it != end; ++it) {
178                 if (!it->second.empty())
179                         os << "\textra " << it->first << " \""
180                            << it->second << "\"\n";
181         }
182
183         if (!rotationdata.no_rotation()) {
184                 os << "\trotateAngle " << rotationdata.angle() << '\n';
185                 if (rotationdata.origin() != external::RotationData::DEFAULT)
186                         os << "\trotateOrigin "
187                            << rotationdata.originString() << '\n';
188         }
189
190         if (!resizedata.no_resize()) {
191                 using support::float_equal;
192
193                 if (!float_equal(resizedata.scale, 0.0, 0.05)) {
194                         if (!float_equal(resizedata.scale, 100.0, 0.05))
195                                 os << "\tscale "
196                                    << resizedata.scale << '\n';
197                 } else {
198                         if (!resizedata.width.zero())
199                                 os << "\twidth "
200                                    << resizedata.width.asString() << '\n';
201                         if (!resizedata.height.zero())
202                                 os << "\theight "
203                                    << resizedata.height.asString() << '\n';
204                 }
205                 if (resizedata.keepAspectRatio)
206                         os << "\tkeepAspectRatio\n";
207         }
208 }
209
210
211 bool InsetExternalParams::read(Buffer const & buffer, LyXLex & lex)
212 {
213         enum ExternalTags {
214                 EX_TEMPLATE = 1,
215                 EX_FILENAME,
216                 EX_DISPLAY,
217                 EX_LYXSCALE,
218                 EX_BOUNDINGBOX,
219                 EX_CLIP,
220                 EX_EXTRA,
221                 EX_HEIGHT,
222                 EX_KEEPASPECTRATIO,
223                 EX_ROTATEANGLE,
224                 EX_ROTATEORIGIN,
225                 EX_SCALE,
226                 EX_WIDTH,
227                 EX_END
228         };
229
230         keyword_item external_tags[] = {
231                 { "\\end_inset",     EX_END },
232                 { "boundingBox",     EX_BOUNDINGBOX },
233                 { "clip",            EX_CLIP },
234                 { "display",         EX_DISPLAY},
235                 { "extra",           EX_EXTRA },
236                 { "filename",        EX_FILENAME},
237                 { "height",          EX_HEIGHT },
238                 { "keepAspectRatio", EX_KEEPASPECTRATIO },
239                 { "lyxscale",        EX_LYXSCALE},
240                 { "rotateAngle",     EX_ROTATEANGLE },
241                 { "rotateOrigin",    EX_ROTATEORIGIN },
242                 { "scale",           EX_SCALE },
243                 { "template",        EX_TEMPLATE },
244                 { "width",           EX_WIDTH }
245         };
246
247         pushpophelper pph(lex, external_tags, EX_END);
248
249         bool found_end  = false;
250         bool read_error = false;
251
252         while (lex.isOK()) {
253                 switch (lex.lex()) {
254                 case EX_TEMPLATE:
255                         lex.next();
256                         templatename_ = lex.getString();
257                         break;
258
259                 case EX_FILENAME: {
260                         lex.next();
261                         string const name = lex.getString();
262                         filename.set(name, buffer.filePath());
263                         break;
264                 }
265
266                 case EX_DISPLAY: {
267                         lex.next();
268                         string const name = lex.getString();
269                         display = lyx::graphics::displayTranslator.find(name);
270                         break;
271                 }
272
273                 case EX_LYXSCALE:
274                         lex.next();
275                         lyxscale = lex.getInteger();
276                         break;
277
278                 case EX_BOUNDINGBOX:
279                         lex.next();
280                         clipdata.bbox.xl = lex.getInteger();
281                         lex.next();
282                         clipdata.bbox.yb = lex.getInteger();
283                         lex.next();
284                         clipdata.bbox.xr = lex.getInteger();
285                         lex.next();
286                         clipdata.bbox.yt = lex.getInteger();
287                         break;
288
289                 case EX_CLIP:
290                         clipdata.clip = true;
291                         break;
292
293                 case EX_EXTRA: {
294                         lex.next();
295                         string const name = lex.getString();
296                         lex.next();
297                         extradata.set(name, lex.getString());
298                         break;
299                 }
300
301                 case EX_HEIGHT:
302                         lex.next();
303                         resizedata.height = LyXLength(lex.getString());
304                         break;
305
306                 case EX_KEEPASPECTRATIO:
307                         resizedata.keepAspectRatio = true;
308                         break;
309
310                 case EX_ROTATEANGLE:
311                         lex.next();
312                         rotationdata.angle(lex.getFloat());
313                         break;
314
315                 case EX_ROTATEORIGIN:
316                         lex.next();
317                         rotationdata.origin(lex.getString());
318                         break;
319
320                 case EX_SCALE:
321                         lex.next();
322                         resizedata.scale = lex.getFloat();
323                         break;
324
325                 case EX_WIDTH:
326                         lex.next();
327                         resizedata.width = LyXLength(lex.getString());
328                         break;
329
330                 case EX_END:
331                         found_end = true;
332                         break;
333
334                 default:
335                         lex.printError("ExternalInset::read: "
336                                        "Wrong tag: $$Token");
337                         read_error = true;
338                         break;
339                 }
340
341                 if (found_end || read_error)
342                         break;
343         }
344
345         if (!found_end)
346                 lex.printError("ExternalInset::read: Missing \\end_inset.");
347
348         // This is a trick to make sure that the data are self-consistent.
349         settemplate(templatename_);
350
351         if (lyxerr.debugging(Debug::EXTERNAL)) {
352                 lyxerr  << "InsetExternalParams::read:\n";
353                 write(buffer, lyxerr);
354         }
355
356         return !read_error;
357 }
358
359
360 InsetExternal::InsetExternal()
361         : renderer_(new ButtonRenderer)
362 {}
363
364
365 InsetExternal::InsetExternal(InsetExternal const & other)
366         : InsetOld(other),
367           boost::signals::trackable(),
368           params_(other.params_),
369           renderer_(other.renderer_->clone())
370 {
371         GraphicRenderer * ptr =
372                 dynamic_cast<GraphicRenderer *>(renderer_.get());
373         if (ptr)
374                 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
375 }
376
377
378 auto_ptr<InsetBase> InsetExternal::clone() const
379 {
380         return auto_ptr<InsetBase>(new InsetExternal(*this));
381 }
382
383
384 InsetExternal::~InsetExternal()
385 {
386         InsetExternalMailer(*this).hideDialog();
387 }
388
389
390 void InsetExternal::statusChanged()
391 {
392         BufferView * const bv = renderer_->view();
393         if (bv)
394                 bv->updateInset(this);
395 }
396
397
398 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
399 {
400         switch (cmd.action) {
401
402         case LFUN_EXTERNAL_EDIT: {
403                 BOOST_ASSERT(cmd.view());
404
405                 Buffer const & buffer = *cmd.view()->buffer();
406                 InsetExternalParams p;
407                 InsetExternalMailer::string2params(cmd.argument, buffer, p);
408                 external::editExternal(p, buffer);
409                 return DISPATCHED_NOUPDATE;
410         }
411
412         case LFUN_INSET_MODIFY: {
413                 BOOST_ASSERT(cmd.view());
414
415                 Buffer const & buffer = *cmd.view()->buffer();
416                 InsetExternalParams p;
417                 InsetExternalMailer::string2params(cmd.argument, buffer, p);
418                 setParams(p, buffer);
419                 cmd.view()->updateInset(this);
420                 return DISPATCHED;
421         }
422
423         case LFUN_INSET_DIALOG_UPDATE:
424                 InsetExternalMailer(*this).updateDialog(cmd.view());
425                 return DISPATCHED;
426
427         case LFUN_MOUSE_RELEASE:
428         case LFUN_INSET_EDIT:
429                 InsetExternalMailer(*this).showDialog(cmd.view());
430                 return DISPATCHED;
431
432         default:
433                 return UNDISPATCHED;
434         }
435 }
436
437
438 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
439 {
440         renderer_->metrics(mi, dim);
441         dim_ = dim;
442 }
443
444
445 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
446 {
447         renderer_->draw(pi, x, y);
448 }
449
450
451 namespace {
452
453 lyx::graphics::Params get_grfx_params(InsetExternalParams const & eparams)
454 {
455         lyx::graphics::Params gparams;
456
457         gparams.filename = eparams.filename.absFilename();
458         gparams.scale = eparams.lyxscale;
459         if (eparams.clipdata.clip)
460                 gparams.bb = eparams.clipdata.bbox;
461         gparams.angle = eparams.rotationdata.angle();
462
463         gparams.display = eparams.display;
464         if (gparams.display == lyx::graphics::DefaultDisplay)
465                 gparams.display = lyxrc.display_graphics;
466         // Override the above if we're not using a gui
467         if (!lyx_gui::use_gui)
468                 gparams.display = lyx::graphics::NoDisplay;
469
470         return gparams;
471 }
472
473
474 string const getScreenLabel(InsetExternalParams const & params,
475                             Buffer const & buffer)
476 {
477         external::Template const * const ptr =
478                 external::getTemplatePtr(params);
479         if (!ptr)
480                 return support::bformat(_("External template %1$s is not installed"),
481                                         params.templatename());
482         return external::doSubstitution(params, buffer, ptr->guiName);
483 }
484
485 } // namespace anon
486
487
488 InsetExternalParams const & InsetExternal::params() const
489 {
490         return params_;
491 }
492
493
494 void InsetExternal::setParams(InsetExternalParams const & p,
495                               Buffer const & buffer)
496 {
497         // The stored params; what we would like to happen in an ideal world.
498         params_ = p;
499
500         // We display the inset as a button by default.
501         bool display_button = (!external::getTemplatePtr(params_) ||
502                                params_.filename.empty() ||
503                                params_.display == lyx::graphics::NoDisplay);
504
505         if (display_button) {
506                 ButtonRenderer * button_ptr =
507                         dynamic_cast<ButtonRenderer *>(renderer_.get());
508                 if (!button_ptr) {
509                         button_ptr = new ButtonRenderer;
510                         renderer_.reset(button_ptr);
511                 }
512
513                 button_ptr->update(getScreenLabel(params_, buffer), true);
514
515         } else {
516                 GraphicRenderer * graphic_ptr =
517                         dynamic_cast<GraphicRenderer *>(renderer_.get());
518                 if (!graphic_ptr) {
519                         graphic_ptr = new GraphicRenderer;
520                         graphic_ptr->connect(
521                                 boost::bind(&InsetExternal::statusChanged, this));
522                         renderer_.reset(graphic_ptr);
523                 }
524
525                 graphic_ptr->update(get_grfx_params(params_));
526         }
527 }
528
529
530 void InsetExternal::write(Buffer const & buffer, ostream & os) const
531 {
532         params_.write(buffer, os);
533 }
534
535
536 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
537 {
538         InsetExternalParams params;
539         if (params.read(buffer, lex))
540                 setParams(params, buffer);
541 }
542
543
544 int InsetExternal::latex(Buffer const & buf, ostream & os,
545                          LatexRunParams const & runparams) const
546 {
547         // "nice" means that the buffer is exported to LaTeX format but not
548         // run through the LaTeX compiler.
549         // If we're running through the LaTeX compiler, we should write the
550         // generated files in the bufer's temporary directory.
551         bool const external_in_tmpdir =
552                 lyxrc.use_tempdir && !buf.temppath().empty() && !runparams.nice;
553
554         // If the template has specified a PDFLaTeX output, then we try and
555         // use that.
556         if (runparams.flavor == LatexRunParams::PDFLATEX) {
557                 external::Template const * const et_ptr =
558                         external::getTemplatePtr(params_);
559                 if (!et_ptr)
560                         return 0;
561                 external::Template const & et = *et_ptr;
562
563                 external::Template::Formats::const_iterator cit =
564                         et.formats.find("PDFLaTeX");
565                 if (cit != et.formats.end())
566                         return external::writeExternal(params_, "PDFLaTeX",
567                                              buf, os, external_in_tmpdir);
568         }
569
570         return external::writeExternal(params_, "LaTeX",
571                                        buf, os, external_in_tmpdir);
572 }
573
574
575 int InsetExternal::ascii(Buffer const & buf, ostream & os, int) const
576 {
577         return external::writeExternal(params_, "Ascii", buf, os);
578 }
579
580
581 int InsetExternal::linuxdoc(Buffer const & buf, ostream & os) const
582 {
583         return external::writeExternal(params_, "LinuxDoc", buf, os);
584 }
585
586
587 int InsetExternal::docbook(Buffer const & buf, ostream & os, bool) const
588 {
589         return external::writeExternal(params_, "DocBook", buf, os);
590 }
591
592
593 void InsetExternal::validate(LaTeXFeatures & features) const
594 {
595         external::Template const * const et_ptr =
596                 external::getTemplatePtr(params_);
597         if (!et_ptr)
598                 return;
599         external::Template const & et = *et_ptr;
600
601         external::Template::Formats::const_iterator cit =
602                 et.formats.find("LaTeX");
603         if (cit == et.formats.end())
604                 return;
605
606         if (!cit->second.requirement.empty())
607                 features.require(cit->second.requirement);
608
609         external::TemplateManager & etm = external::TemplateManager::get();
610
611         vector<string>::const_iterator it  = cit->second.preambleNames.begin();
612         vector<string>::const_iterator end = cit->second.preambleNames.end();
613         for (; it != end; ++it) {
614                 string const preamble = etm.getPreambleDefByName(*it);
615                 if (!preamble.empty())
616                         features.addExternalPreamble(preamble);
617         }
618 }
619
620
621 string const InsetExternalMailer::name_("external");
622
623 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
624         : inset_(inset)
625 {}
626
627
628 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
629 {
630         return params2string(inset_.params(), buffer);
631 }
632
633
634 void InsetExternalMailer::string2params(string const & in,
635                                         Buffer const & buffer,
636                                         InsetExternalParams & params)
637 {
638         params = InsetExternalParams();
639
640         if (in.empty())
641                 return;
642
643         istringstream data(in);
644         LyXLex lex(0,0);
645         lex.setStream(data);
646
647         if (lex.isOK()) {
648                 lex.next();
649                 string const token = lex.getString();
650                 if (token != name_)
651                         return;
652         }
653
654         // This is part of the inset proper that is usually swallowed
655         // by Buffer::readInset
656         if (lex.isOK()) {
657                 lex.next();
658                 string const token = lex.getString();
659                 if (token != "External")
660                         return;
661         }
662
663         if (lex.isOK()) {
664                 params.read(buffer, lex);
665         }
666 }
667
668
669 string const
670 InsetExternalMailer::params2string(InsetExternalParams const & params,
671                                    Buffer const & buffer)
672 {
673         ostringstream data;
674         data << name_ << ' ';
675         params.write(buffer, data);
676         data << "\\end_inset\n";
677         return data.str();
678 }