]> git.lyx.org Git - features.git/blob - src/insets/insetexternal.C
7bd70495750288936a99b447316ffe6cb5b6a255
[features.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 std::ostream;
48 using std::endl;
49
50
51 namespace {
52
53 grfx::DisplayType const defaultDisplayType = grfx::NoDisplay;
54
55 unsigned int defaultLyxScale = 100;
56
57 /// Substitute meta-variables in string s, makeing use of params and buffer.
58 string const doSubstitution(InsetExternal::Params const & params,
59                             Buffer const * buffer, string const & s);
60
61 /// Invoke the external editor.
62 void editExternal(InsetExternal::Params const & params, Buffer const * buffer);
63
64 } // namespace anon
65
66
67 InsetExternal::Params::Params()
68         : display(defaultDisplayType),
69           lyxscale(defaultLyxScale)
70 {
71         tempname = lyx::tempName(string(), "lyxext");
72         lyx::unlink(tempname);
73         // must have an extension for the converter code to work correctly.
74         tempname += ".tmp";
75 }
76
77
78 InsetExternal::Params::~Params()
79 {
80         lyx::unlink(tempname);
81 }
82
83
84 InsetExternal::InsetExternal()
85         : renderer_(new ButtonRenderer)
86 {}
87
88
89 InsetExternal::InsetExternal(InsetExternal const & other)
90         : Inset(other),
91           boost::signals::trackable(),
92           params_(other.params_),
93           renderer_(other.renderer_->clone())
94 {
95         GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
96         if (ptr) {
97                 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
98         }
99 }
100
101
102 InsetBase * InsetExternal::clone() const
103 {
104         InsetExternal * inset = new InsetExternal(*this);
105         return inset;
106 }
107
108
109 InsetExternal::~InsetExternal()
110 {
111         InsetExternalMailer(*this).hideDialog();
112 }
113
114
115 void InsetExternal::statusChanged()
116 {
117         BufferView * bv = renderer_->view();
118         if (bv)
119                 bv->updateInset(this);
120 }
121         
122
123 InsetExternal::Params const & InsetExternal::params() const
124 {
125         return params_;
126 }
127
128
129 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
130 {
131         switch (cmd.action) {
132
133         case LFUN_EXTERNAL_EDIT: {
134                 lyx::Assert(cmd.view());
135
136                 InsetExternal::Params p;
137                 InsetExternalMailer::string2params(cmd.argument, p);
138                 editExternal(p, cmd.view()->buffer());
139                 return DISPATCHED_NOUPDATE;
140         }
141         
142         case LFUN_INSET_MODIFY: {
143                 lyx::Assert(cmd.view());
144
145                 InsetExternal::Params p;
146                 InsetExternalMailer::string2params(cmd.argument, p);
147                 setParams(p, cmd.view()->buffer()->filePath());
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 }
171
172
173 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
174 {
175         renderer_->draw(pi, x, y);
176 }
177
178
179 namespace {
180
181 grfx::Params get_grfx_params(InsetExternal::Params const & eparams,
182                              string const & filepath)
183 {
184         grfx::Params gparams;
185
186         if (!eparams.filename.empty()) {
187                 lyx::Assert(AbsolutePath(filepath));
188                 gparams.filename = MakeAbsPath(eparams.filename, filepath);
189         }
190
191         gparams.scale = eparams.lyxscale;
192         gparams.display = eparams.display;
193
194         if (gparams.display == grfx::DefaultDisplay)
195                 gparams.display = lyxrc.display_graphics;
196
197         // Override the above if we're not using a gui
198         if (!lyx_gui::use_gui)
199                 gparams.display = grfx::NoDisplay;
200
201         return gparams;
202 }
203
204
205 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
206 {
207         ExternalTemplateManager & etm = ExternalTemplateManager::get();
208         ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
209         if (templ.lyxName.empty())
210                 return 0;
211         return &templ;
212 }
213
214
215 string const getScreenLabel(InsetExternal::Params const & params)
216 {
217         ExternalTemplate const * const ptr = getTemplatePtr(params);
218         if (!ptr)
219                 return bformat(_("External template %1$s is not installed"),
220                                params.templatename);
221         return doSubstitution(params, 0, ptr->guiName);
222 }
223
224 } // namespace anon
225
226
227 void InsetExternal::setParams(Params const & p, string const & filepath)
228 {
229         // The stored params; what we would like to happen in an ideal world.
230         params_.filename = p.filename;
231         params_.templatename = p.templatename;
232         params_.display = p.display;
233         params_.lyxscale = p.lyxscale;
234
235         // We display the inset as a button by default.
236         bool display_button = (!getTemplatePtr(params_) ||
237                                params_.filename.empty() ||
238                                filepath.empty() ||
239                                params_.display == grfx::NoDisplay);
240
241         if (display_button) {
242                 ButtonRenderer * button_ptr =
243                         dynamic_cast<ButtonRenderer *>(renderer_.get());
244                 if (!button_ptr) {
245                         button_ptr = new ButtonRenderer;
246                         renderer_.reset(button_ptr);
247                 }
248
249                 button_ptr->update(getScreenLabel(params_), true);
250
251         } else {
252                 GraphicRenderer * graphic_ptr =
253                         dynamic_cast<GraphicRenderer *>(renderer_.get());
254                 if (!graphic_ptr) {
255                         graphic_ptr = new GraphicRenderer;
256                         graphic_ptr->connect(
257                                 boost::bind(&InsetExternal::statusChanged, this));
258                         renderer_.reset(graphic_ptr);
259                 }
260
261                 graphic_ptr->update(get_grfx_params(params_, filepath));
262         }
263 }
264
265
266 string const InsetExternal::editMessage() const
267 {
268         return getScreenLabel(params_);
269 }
270
271
272 void InsetExternal::write(Buffer const *, ostream & os) const
273 {
274         os << "External\n"
275            << "\ttemplate " << params_.templatename << '\n';
276
277         if (!params_.filename.empty())
278                 os << "\tfilename " << params_.filename << '\n';
279
280         if (params_.display != defaultDisplayType)
281                 os << "\tdisplay " << grfx::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 = name;
325                         break;
326                 }
327
328                 case EX_DISPLAY: {
329                         lex.next();
330                         string const name = lex.getString();
331                         params.display = grfx::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         string const path = buffer ? buffer->filePath() : string();
365         setParams(params, path);
366
367         lyxerr[Debug::INFO] << "InsetExternal::Read: "
368                << "template: '" << params_.templatename
369                << "' filename: '" << params_.filename
370                << "' display: '" << params_.display
371                << "' scale: '" << params_.lyxscale
372                << '\'' << endl;
373 }
374
375
376 int InsetExternal::write(string const & format,
377                          Buffer const * buf, ostream & os,
378                          bool external_in_tmpdir) const
379 {
380         ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
381         if (!et_ptr)
382                 return 0;
383         ExternalTemplate const & et = *et_ptr;
384
385         ExternalTemplate::Formats::const_iterator cit =
386                 et.formats.find(format);
387         if (cit == et.formats.end()) {
388                 lyxerr << "External template format '" << format
389                        << "' not specified in template "
390                        << params_.templatename << endl;
391                 return 0;
392         }
393
394         updateExternal(format, buf, external_in_tmpdir);
395         string const str = doSubstitution(params_, buf, cit->second.product);
396         os << str;
397         return int(lyx::count(str.begin(), str.end(),'\n') + 1);
398 }
399
400
401 int InsetExternal::latex(Buffer const * buf, ostream & os,
402                          LatexRunParams const & runparams) const
403 {
404         // "nice" means that the buffer is exported to LaTeX format but not
405         // run through the LaTeX compiler.
406         // If we're running through the LaTeX compiler, we should write the
407         // generated files in the bufer's temporary directory.
408         bool const external_in_tmpdir =
409                 lyxrc.use_tempdir && !buf->tmppath.empty() && !runparams.nice;
410
411         // If the template has specified a PDFLaTeX output, then we try and
412         // use that.
413         if (runparams.flavor == LatexRunParams::PDFLATEX) {
414                 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
415                 if (!et_ptr)
416                         return 0;
417                 ExternalTemplate const & et = *et_ptr;
418
419                 ExternalTemplate::Formats::const_iterator cit =
420                         et.formats.find("PDFLaTeX");
421                 if (cit != et.formats.end())
422                         return write("PDFLaTeX", buf, os, external_in_tmpdir);
423         }
424
425         return write("LaTeX", buf, os, external_in_tmpdir);
426 }
427
428
429 int InsetExternal::ascii(Buffer const * buf, ostream & os, int) const
430 {
431         return write("Ascii", buf, os);
432 }
433
434
435 int InsetExternal::linuxdoc(Buffer const * buf, ostream & os) const
436 {
437         return write("LinuxDoc", buf, os);
438 }
439
440
441 int InsetExternal::docbook(Buffer const * buf, ostream & os, bool) const
442 {
443         return write("DocBook", buf, os);
444 }
445
446
447 void InsetExternal::validate(LaTeXFeatures & features) const
448 {
449         ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
450         if (!et_ptr)
451                 return;
452         ExternalTemplate const & et = *et_ptr;
453
454         ExternalTemplate::Formats::const_iterator cit =
455                 et.formats.find("LaTeX");
456
457         if (cit == et.formats.end())
458                 return;
459
460         if (!cit->second.requirement.empty()) {
461                 features.require(cit->second.requirement);
462         }
463         if (!cit->second.preamble.empty()) {
464                 features.addExternalPreamble(cit->second.preamble + "\n");
465         }
466 }
467
468
469 void InsetExternal::updateExternal(string const & format,
470                                    Buffer const * buf,
471                                    bool external_in_tmpdir) const
472 {
473         ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
474         if (!et_ptr)
475                 return;
476         ExternalTemplate const & et = *et_ptr;
477
478         if (!et.automaticProduction)
479                 return;
480
481         ExternalTemplate::Formats::const_iterator cit =
482                 et.formats.find(format);
483         if (cit == et.formats.end())
484                 return;
485
486         ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
487         if (outputFormat.updateResult.empty())
488                 return;
489
490         string from_format = et.inputFormat;
491         if (from_format.empty())
492                 return;
493
494         string from_file = params_.filename.empty() ?
495                 string() : MakeAbsPath(params_.filename, buf->filePath());
496
497         if (from_format == "*") {
498                 if (from_file.empty())
499                         return;
500
501                 // Try and ascertain the file format from its contents.
502                 from_format = getExtFromContents(from_file);
503                 if (from_format.empty())
504                         return;
505         }
506
507         string const to_format = outputFormat.updateFormat;
508         if (to_format.empty())
509                 return;
510
511         if (!converters.isReachable(from_format, to_format)) {
512                 lyxerr << "InsetExternal::updateExternal. "
513                         "Unable to convert from "
514                        << from_format << " to " << to_format << endl;
515                 return;
516         }
517
518         if (external_in_tmpdir && !from_file.empty()) {
519                 // We are running stuff through LaTeX
520                 from_file = copyFileToDir(buf->tmppath, from_file);
521                 if (from_file.empty())
522                         return;
523         }
524
525         string const to_file = doSubstitution(params_, buf,
526                                               outputFormat.updateResult);
527
528         FileInfo fi(from_file);
529         string abs_to_file = to_file;
530         if (!AbsolutePath(to_file))
531                 abs_to_file = MakeAbsPath(to_file, OnlyPath(from_file));
532         FileInfo fi2(abs_to_file);
533         if (fi2.exist() && fi.exist() &&
534             difftime(fi2.getModificationTime(),
535                      fi.getModificationTime()) >= 0) {
536         } else {
537                 string const to_filebase = ChangeExtension(to_file, string());
538                 converters.convert(buf, from_file, to_filebase,
539                                    from_format, to_format);
540         }
541 }
542
543
544 namespace {
545
546 /// Substitute meta-variables in this string
547 string const doSubstitution(InsetExternal::Params const & params,
548                             Buffer const * buffer, string const & s)
549 {
550         string result;
551         string const basename = ChangeExtension(params.filename, string());
552         string filepath;
553
554         result = subst(s, "$$FName", params.filename);
555         result = subst(result, "$$Basename", basename);
556         result = subst(result, "$$FPath", filepath);
557         result = subst(result, "$$Tempname", params.tempname);
558         result = subst(result, "$$Sysdir", system_lyxdir);
559
560         // Handle the $$Contents(filename) syntax
561         if (contains(result, "$$Contents(\"")) {
562
563                 string::size_type const pos = result.find("$$Contents(\"");
564                 string::size_type const end = result.find("\")", pos);
565                 string const file = result.substr(pos + 12, end - (pos + 12));
566                 string contents;
567                 if (buffer) {
568                         Path p(buffer->filePath());
569                         if (!IsFileReadable(file))
570                                 Path p(buffer->tmppath);
571                         if (IsFileReadable(file))
572                                 contents = GetFileContents(file);
573                 } else {
574                         contents = GetFileContents(file);
575                 }
576                 result = subst(result,
577                                ("$$Contents(\"" + file + "\")").c_str(),
578                                contents);
579         }
580
581         return result;
582 }
583
584
585 void editExternal(InsetExternal::Params const & params, Buffer const * buffer)
586 {
587         if (!buffer)
588                 return;
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         Path p(buffer->filePath());
601         Forkedcall call;
602         if (lyxerr.debugging()) {
603                 lyxerr << "Executing '" << command << "' in '"
604                        << buffer->filePath() << '\'' << endl;
605         }
606         call.startscript(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() const
619 {
620         return params2string(inset_.params());
621 }
622
623
624 void InsetExternalMailer::string2params(string const & in,
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(0, lex);
655                 params = inset.params();
656         }
657 }
658
659
660 string const
661 InsetExternalMailer::params2string(InsetExternal::Params const & params)
662 {
663         InsetExternal inset;
664         inset.setParams(params, string());
665         ostringstream data;
666         data << name_ << ' ';
667         inset.write(0, data);
668         data << "\\end_inset\n";
669         return STRCONV(data.str());
670 }