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