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