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