]> git.lyx.org Git - lyx.git/blob - src/insets/insetexternal.C
f18fbc0a8a730c5ef6bb59630253cb1302944e9a
[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
391 InsetExternal::priv_dispatch(FuncRequest const & cmd, idx_type &, pos_type &)
392 {
393         switch (cmd.action) {
394
395         case LFUN_EXTERNAL_EDIT: {
396                 BOOST_ASSERT(cmd.view());
397
398                 Buffer const & buffer = *cmd.view()->buffer();
399                 InsetExternalParams p;
400                 InsetExternalMailer::string2params(cmd.argument, buffer, p);
401                 external::editExternal(p, buffer);
402                 return DISPATCHED_NOUPDATE;
403         }
404
405         case LFUN_INSET_MODIFY: {
406                 BOOST_ASSERT(cmd.view());
407
408                 Buffer const & buffer = *cmd.view()->buffer();
409                 InsetExternalParams p;
410                 InsetExternalMailer::string2params(cmd.argument, buffer, p);
411                 setParams(p, buffer);
412                 cmd.view()->updateInset(this);
413                 return DISPATCHED;
414         }
415
416         case LFUN_INSET_DIALOG_UPDATE:
417                 InsetExternalMailer(*this).updateDialog(cmd.view());
418                 return DISPATCHED;
419
420         case LFUN_MOUSE_RELEASE:
421         case LFUN_INSET_EDIT:
422                 InsetExternalMailer(*this).showDialog(cmd.view());
423                 return DISPATCHED;
424
425         default:
426                 return UNDISPATCHED;
427         }
428 }
429
430
431 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
432 {
433         renderer_->metrics(mi, dim);
434         dim_ = dim;
435 }
436
437
438 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
439 {
440         renderer_->draw(pi, x, y);
441 }
442
443
444 namespace {
445
446 lyx::graphics::Params get_grfx_params(InsetExternalParams const & eparams)
447 {
448         lyx::graphics::Params gparams;
449
450         gparams.filename = eparams.filename.absFilename();
451         gparams.scale = eparams.lyxscale;
452         if (eparams.clipdata.clip)
453                 gparams.bb = eparams.clipdata.bbox;
454         gparams.angle = eparams.rotationdata.angle();
455
456         gparams.display = eparams.display;
457         if (gparams.display == lyx::graphics::DefaultDisplay)
458                 gparams.display = lyxrc.display_graphics;
459         // Override the above if we're not using a gui
460         if (!lyx_gui::use_gui)
461                 gparams.display = lyx::graphics::NoDisplay;
462
463         return gparams;
464 }
465
466
467 string const getScreenLabel(InsetExternalParams const & params,
468                             Buffer const & buffer)
469 {
470         external::Template const * const ptr =
471                 external::getTemplatePtr(params);
472         if (!ptr)
473                 return support::bformat(_("External template %1$s is not installed"),
474                                         params.templatename());
475         return external::doSubstitution(params, buffer, ptr->guiName);
476 }
477
478 } // namespace anon
479
480
481 InsetExternalParams const & InsetExternal::params() const
482 {
483         return params_;
484 }
485
486
487 void InsetExternal::setParams(InsetExternalParams const & p,
488                               Buffer const & buffer)
489 {
490         // The stored params; what we would like to happen in an ideal world.
491         params_ = p;
492
493         // We display the inset as a button by default.
494         bool display_button = (!external::getTemplatePtr(params_) ||
495                                params_.filename.empty() ||
496                                params_.display == lyx::graphics::NoDisplay);
497
498         if (display_button) {
499                 RenderButton * button_ptr =
500                         dynamic_cast<RenderButton *>(renderer_.get());
501                 if (!button_ptr) {
502                         button_ptr = new RenderButton;
503                         renderer_.reset(button_ptr);
504                 }
505
506                 button_ptr->update(getScreenLabel(params_, buffer), true);
507
508         } else {
509                 RenderGraphic * graphic_ptr =
510                         dynamic_cast<RenderGraphic *>(renderer_.get());
511                 if (!graphic_ptr) {
512                         graphic_ptr = new RenderGraphic;
513                         graphic_ptr->connect(
514                                 boost::bind(&InsetExternal::statusChanged, this));
515                         renderer_.reset(graphic_ptr);
516                 }
517
518                 graphic_ptr->update(get_grfx_params(params_));
519         }
520 }
521
522
523 void InsetExternal::write(Buffer const & buffer, ostream & os) const
524 {
525         params_.write(buffer, os);
526 }
527
528
529 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
530 {
531         InsetExternalParams params;
532         if (params.read(buffer, lex))
533                 setParams(params, buffer);
534 }
535
536
537 int InsetExternal::latex(Buffer const & buf, ostream & os,
538                          LatexRunParams const & runparams) const
539 {
540         // "nice" means that the buffer is exported to LaTeX format but not
541         // run through the LaTeX compiler.
542         // If we're running through the LaTeX compiler, we should write the
543         // generated files in the bufer's temporary directory.
544         bool const external_in_tmpdir =
545                 lyxrc.use_tempdir && !buf.temppath().empty() && !runparams.nice;
546
547         // If the template has specified a PDFLaTeX output, then we try and
548         // use that.
549         if (runparams.flavor == LatexRunParams::PDFLATEX) {
550                 external::Template const * const et_ptr =
551                         external::getTemplatePtr(params_);
552                 if (!et_ptr)
553                         return 0;
554                 external::Template const & et = *et_ptr;
555
556                 external::Template::Formats::const_iterator cit =
557                         et.formats.find("PDFLaTeX");
558                 if (cit != et.formats.end())
559                         return external::writeExternal(params_, "PDFLaTeX",
560                                              buf, os, external_in_tmpdir);
561         }
562
563         return external::writeExternal(params_, "LaTeX",
564                                        buf, os, external_in_tmpdir);
565 }
566
567
568 int InsetExternal::ascii(Buffer const & buf, ostream & os, int) const
569 {
570         return external::writeExternal(params_, "Ascii", buf, os);
571 }
572
573
574 int InsetExternal::linuxdoc(Buffer const & buf, ostream & os) const
575 {
576         return external::writeExternal(params_, "LinuxDoc", buf, os);
577 }
578
579
580 int InsetExternal::docbook(Buffer const & buf, ostream & os, bool) const
581 {
582         return external::writeExternal(params_, "DocBook", buf, os);
583 }
584
585
586 void InsetExternal::validate(LaTeXFeatures & features) const
587 {
588         external::Template const * const et_ptr =
589                 external::getTemplatePtr(params_);
590         if (!et_ptr)
591                 return;
592         external::Template const & et = *et_ptr;
593
594         external::Template::Formats::const_iterator cit =
595                 et.formats.find("LaTeX");
596         if (cit == et.formats.end())
597                 return;
598
599         if (!cit->second.requirement.empty())
600                 features.require(cit->second.requirement);
601
602         external::TemplateManager & etm = external::TemplateManager::get();
603
604         vector<string>::const_iterator it  = cit->second.preambleNames.begin();
605         vector<string>::const_iterator end = cit->second.preambleNames.end();
606         for (; it != end; ++it) {
607                 string const preamble = etm.getPreambleDefByName(*it);
608                 if (!preamble.empty())
609                         features.addExternalPreamble(preamble);
610         }
611 }
612
613
614 string const InsetExternalMailer::name_("external");
615
616 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
617         : inset_(inset)
618 {}
619
620
621 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
622 {
623         return params2string(inset_.params(), buffer);
624 }
625
626
627 void InsetExternalMailer::string2params(string const & in,
628                                         Buffer const & buffer,
629                                         InsetExternalParams & params)
630 {
631         params = InsetExternalParams();
632
633         if (in.empty())
634                 return;
635
636         istringstream data(in);
637         LyXLex lex(0,0);
638         lex.setStream(data);
639
640         if (lex.isOK()) {
641                 lex.next();
642                 string const token = lex.getString();
643                 if (token != name_)
644                         return;
645         }
646
647         // This is part of the inset proper that is usually swallowed
648         // by Buffer::readInset
649         if (lex.isOK()) {
650                 lex.next();
651                 string const token = lex.getString();
652                 if (token != "External")
653                         return;
654         }
655
656         if (lex.isOK()) {
657                 params.read(buffer, lex);
658         }
659 }
660
661
662 string const
663 InsetExternalMailer::params2string(InsetExternalParams const & params,
664                                    Buffer const & buffer)
665 {
666         ostringstream data;
667         data << name_ << ' ';
668         params.write(buffer, data);
669         data << "\\end_inset\n";
670         return data.str();
671 }