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