]> git.lyx.org Git - lyx.git/blob - src/insets/insetexternal.C
a40280cd68feab1ebc79679215bef2f6144c02a3
[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 string const InsetExternal::editMessage() const
265 {
266         return getScreenLabel(params_);
267 }
268
269
270 void InsetExternal::write(Buffer const * buffer, ostream & os) const
271 {
272         os << "External\n"
273            << "\ttemplate " << params_.templatename << '\n';
274
275         if (!params_.filename.empty())
276                 os << "\tfilename "
277                    << params_.filename.outputFilename(buffer->filePath())
278                    << '\n';
279
280         if (params_.display != defaultDisplayType)
281                 os << "\tdisplay " << lyx::graphics::displayTranslator.find(params_.display)
282                    << '\n';
283
284         if (params_.lyxscale != defaultLyxScale)
285                 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
286 }
287
288
289 void InsetExternal::read(Buffer const * buffer, LyXLex & lex)
290 {
291         enum ExternalTags {
292                 EX_TEMPLATE = 1,
293                 EX_FILENAME,
294                 EX_DISPLAY,
295                 EX_LYXSCALE,
296                 EX_END
297         };
298
299         keyword_item external_tags[] = {
300                 { "\\end_inset", EX_END },
301                 { "display", EX_DISPLAY},
302                 { "filename", EX_FILENAME},
303                 { "lyxscale", EX_LYXSCALE},
304                 { "template", EX_TEMPLATE }
305         };
306
307         lex.pushTable(external_tags, EX_END);
308
309         bool found_end  = false;
310         bool read_error = false;
311
312         InsetExternal::Params params;
313         while (lex.isOK()) {
314                 switch (lex.lex()) {
315                 case EX_TEMPLATE: {
316                         lex.next();
317                         params.templatename = lex.getString();
318                         break;
319                 }
320
321                 case EX_FILENAME: {
322                         lex.next();
323                         string const name = lex.getString();
324                         params.filename.set(name, buffer->filePath());
325                         break;
326                 }
327
328                 case EX_DISPLAY: {
329                         lex.next();
330                         string const name = lex.getString();
331                         params.display = lyx::graphics::displayTranslator.find(name);
332                         break;
333                 }
334
335                 case EX_LYXSCALE: {
336                         lex.next();
337                         params.lyxscale = lex.getInteger();
338                         break;
339                 }
340
341                 case EX_END:
342                         found_end = true;
343                         break;
344
345                 default:
346                         lex.printError("ExternalInset::read: "
347                                        "Wrong tag: $$Token");
348                         read_error = true;
349                         break;
350                 }
351
352                 if (found_end || read_error)
353                         break;
354         }
355
356         if (!found_end) {
357                 lex.printError("ExternalInset::read: "
358                                "Missing \\end_inset.");
359         }
360
361         lex.popTable();
362
363         // Replace the inset's store
364         setParams(params);
365
366         lyxerr[Debug::INFO] << "InsetExternal::Read: "
367                             << "template: '" << params_.templatename
368                             << "' filename: '" << params_.filename.absFilename()
369                             << "' display: '" << params_.display
370                             << "' scale: '" << params_.lyxscale
371                             << '\'' << endl;
372 }
373
374
375 int InsetExternal::write(string const & format,
376                          Buffer const * buf, ostream & os,
377                          bool external_in_tmpdir) const
378 {
379         ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
380         if (!et_ptr)
381                 return 0;
382         ExternalTemplate const & et = *et_ptr;
383
384         ExternalTemplate::Formats::const_iterator cit =
385                 et.formats.find(format);
386         if (cit == et.formats.end()) {
387                 lyxerr << "External template format '" << format
388                        << "' not specified in template "
389                        << params_.templatename << endl;
390                 return 0;
391         }
392
393         updateExternal(format, buf, external_in_tmpdir);
394         string const str = doSubstitution(params_, buf, cit->second.product);
395         os << str;
396         return int(lyx::count(str.begin(), str.end(),'\n') + 1);
397 }
398
399
400 int InsetExternal::latex(Buffer const * buf, ostream & os,
401                          LatexRunParams const & runparams) const
402 {
403         // "nice" means that the buffer is exported to LaTeX format but not
404         // run through the LaTeX compiler.
405         // If we're running through the LaTeX compiler, we should write the
406         // generated files in the bufer's temporary directory.
407         bool const external_in_tmpdir =
408                 lyxrc.use_tempdir && !buf->tmppath.empty() && !runparams.nice;
409
410         // If the template has specified a PDFLaTeX output, then we try and
411         // use that.
412         if (runparams.flavor == LatexRunParams::PDFLATEX) {
413                 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
414                 if (!et_ptr)
415                         return 0;
416                 ExternalTemplate const & et = *et_ptr;
417
418                 ExternalTemplate::Formats::const_iterator cit =
419                         et.formats.find("PDFLaTeX");
420                 if (cit != et.formats.end())
421                         return write("PDFLaTeX", buf, os, external_in_tmpdir);
422         }
423
424         return write("LaTeX", buf, os, external_in_tmpdir);
425 }
426
427
428 int InsetExternal::ascii(Buffer const * buf, ostream & os, int) const
429 {
430         return write("Ascii", buf, os);
431 }
432
433
434 int InsetExternal::linuxdoc(Buffer const * buf, ostream & os) const
435 {
436         return write("LinuxDoc", buf, os);
437 }
438
439
440 int InsetExternal::docbook(Buffer const * buf, ostream & os, bool) const
441 {
442         return write("DocBook", buf, os);
443 }
444
445
446 void InsetExternal::validate(LaTeXFeatures & features) const
447 {
448         ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
449         if (!et_ptr)
450                 return;
451         ExternalTemplate const & et = *et_ptr;
452
453         ExternalTemplate::Formats::const_iterator cit =
454                 et.formats.find("LaTeX");
455
456         if (cit == et.formats.end())
457                 return;
458
459         if (!cit->second.requirement.empty()) {
460                 features.require(cit->second.requirement);
461         }
462         if (!cit->second.preamble.empty()) {
463                 features.addExternalPreamble(cit->second.preamble + "\n");
464         }
465 }
466
467
468 void InsetExternal::updateExternal(string const & format,
469                                    Buffer const * buf,
470                                    bool external_in_tmpdir) const
471 {
472         ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
473         if (!et_ptr)
474                 return;
475         ExternalTemplate const & et = *et_ptr;
476
477         if (!et.automaticProduction)
478                 return;
479
480         ExternalTemplate::Formats::const_iterator cit =
481                 et.formats.find(format);
482         if (cit == et.formats.end())
483                 return;
484
485         ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
486         if (outputFormat.updateResult.empty())
487                 return;
488
489         string from_format = et.inputFormat;
490         if (from_format.empty())
491                 return;
492
493         string from_file = params_.filename.absFilename();
494
495         if (from_format == "*") {
496                 if (from_file.empty())
497                         return;
498
499                 // Try and ascertain the file format from its contents.
500                 from_format = getExtFromContents(from_file);
501                 if (from_format.empty())
502                         return;
503         }
504
505         string const to_format = outputFormat.updateFormat;
506         if (to_format.empty())
507                 return;
508
509         if (!converters.isReachable(from_format, to_format)) {
510                 lyxerr << "InsetExternal::updateExternal. "
511                         "Unable to convert from "
512                        << from_format << " to " << to_format << endl;
513                 return;
514         }
515
516         if (external_in_tmpdir && !from_file.empty()) {
517                 // We are running stuff through LaTeX
518                 from_file = copyFileToDir(buf->tmppath, from_file);
519                 if (from_file.empty())
520                         return;
521         }
522
523         string const to_file = doSubstitution(params_, buf,
524                                               outputFormat.updateResult);
525
526         FileInfo fi(from_file);
527         string abs_to_file = to_file;
528         if (!AbsolutePath(to_file))
529                 abs_to_file = MakeAbsPath(to_file, OnlyPath(from_file));
530         FileInfo fi2(abs_to_file);
531         if (fi2.exist() && fi.exist() &&
532             difftime(fi2.getModificationTime(),
533                      fi.getModificationTime()) >= 0) {
534         } else {
535                 string const to_filebase = ChangeExtension(to_file, string());
536                 converters.convert(buf, from_file, to_filebase,
537                                    from_format, to_format);
538         }
539 }
540
541
542 namespace {
543
544 /// Substitute meta-variables in this string
545 string const doSubstitution(InsetExternal::Params const & params,
546                             Buffer const * buffer, string const & s)
547 {
548         string result;
549         string const absfilename = params.filename.absFilename();
550         string const basename = ChangeExtension(absfilename, string());
551         string filepath;
552
553         result = subst(s, "$$FName", absfilename);
554         result = subst(result, "$$Basename", basename);
555         result = subst(result, "$$FPath", filepath);
556         result = subst(result, "$$Tempname", params.tempname);
557         result = subst(result, "$$Sysdir", system_lyxdir);
558
559         // Handle the $$Contents(filename) syntax
560         if (contains(result, "$$Contents(\"")) {
561
562                 string::size_type const pos = result.find("$$Contents(\"");
563                 string::size_type const end = result.find("\")", pos);
564                 string const file = result.substr(pos + 12, end - (pos + 12));
565                 string contents;
566                 if (buffer) {
567                         Path p(buffer->filePath());
568                         if (!IsFileReadable(file))
569                                 Path p(buffer->tmppath);
570                         if (IsFileReadable(file))
571                                 contents = GetFileContents(file);
572                 } else {
573                         contents = GetFileContents(file);
574                 }
575                 result = subst(result,
576                                ("$$Contents(\"" + file + "\")").c_str(),
577                                contents);
578         }
579
580         return result;
581 }
582
583
584 void editExternal(InsetExternal::Params const & params, Buffer const * buffer)
585 {
586         if (!buffer)
587                 return;
588
589         ExternalTemplate const * const et_ptr = getTemplatePtr(params);
590         if (!et_ptr)
591                 return;
592         ExternalTemplate const & et = *et_ptr;
593
594         if (et.editCommand.empty())
595                 return;
596
597         string const command = doSubstitution(params, buffer, et.editCommand);
598
599         Path p(buffer->filePath());
600         Forkedcall call;
601         if (lyxerr.debugging()) {
602                 lyxerr << "Executing '" << command << "' in '"
603                        << buffer->filePath() << '\'' << endl;
604         }
605         call.startscript(Forkedcall::DontWait, command);
606 }
607
608 } // namespace anon
609
610 string const InsetExternalMailer::name_("external");
611
612 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
613         : inset_(inset)
614 {}
615
616
617 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
618 {
619         return params2string(inset_.params(), buffer);
620 }
621
622
623 void InsetExternalMailer::string2params(string const & in,
624                                         Buffer const & buffer,
625                                         InsetExternal::Params & params)
626 {
627         params = InsetExternal::Params();
628
629         if (in.empty())
630                 return;
631
632         istringstream data(STRCONV(in));
633         LyXLex lex(0,0);
634         lex.setStream(data);
635
636         if (lex.isOK()) {
637                 lex.next();
638                 string const token = lex.getString();
639                 if (token != name_)
640                         return;
641         }
642
643         // This is part of the inset proper that is usually swallowed
644         // by Buffer::readInset
645         if (lex.isOK()) {
646                 lex.next();
647                 string const token = lex.getString();
648                 if (token != "External")
649                         return;
650         }
651
652         if (lex.isOK()) {
653                 InsetExternal inset;
654                 inset.read(&buffer, lex);
655                 params = inset.params();
656         }
657 }
658
659
660 string const
661 InsetExternalMailer::params2string(InsetExternal::Params const & params,
662                                    Buffer const & buffer)
663 {
664         InsetExternal inset;
665         inset.setParams(params);
666         ostringstream data;
667         data << name_ << ' ';
668         inset.write(&buffer, data);
669         data << "\\end_inset\n";
670         return STRCONV(data.str());
671 }