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