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