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