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