]> git.lyx.org Git - lyx.git/blob - src/insets/insetexternal.C
11c0eaec2ca1ce2acb34cd8f6b0d79cd34b3fc27
[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/lyxlib.h"
40 #include "support/path.h"
41 #include "support/path_defines.h"
42 #include "support/tostr.h"
43 #include "support/LAssert.h"
44 #include "support/translator.h"
45
46 #include <boost/bind.hpp>
47
48 #include <cstdio>
49 #include <utility>
50
51 namespace support = lyx::support;
52
53 using std::ostream;
54 using std::endl;
55 using std::auto_ptr;
56
57 namespace lyx {
58 namespace graphics {
59 /// The translator between the DisplayType and the corresponding lyx string.
60 extern Translator<DisplayType, string> displayTranslator;
61 }
62 }
63
64 namespace {
65
66 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
67
68 unsigned int defaultLyxScale = 100;
69
70 /// Substitute meta-variables in string s, makeing use of params and buffer.
71 string const doSubstitution(InsetExternal::Params const & params,
72                             Buffer const & buffer, string const & s);
73
74 /// Invoke the external editor.
75 void editExternal(InsetExternal::Params const & params, Buffer const & buffer);
76
77 } // namespace anon
78
79
80 InsetExternal::Params::Params()
81         : display(defaultDisplayType),
82           lyxscale(defaultLyxScale)
83 {
84         tempname = support::tempName(string(), "lyxext");
85         support::unlink(tempname);
86         // must have an extension for the converter code to work correctly.
87         tempname += ".tmp";
88 }
89
90
91 InsetExternal::Params::~Params()
92 {
93         support::unlink(tempname);
94 }
95
96
97 InsetExternal::InsetExternal()
98         : renderer_(new ButtonRenderer)
99 {}
100
101
102 InsetExternal::InsetExternal(InsetExternal const & other)
103         : InsetOld(other),
104           boost::signals::trackable(),
105           params_(other.params_),
106           renderer_(other.renderer_->clone())
107 {
108         GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
109         if (ptr) {
110                 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
111         }
112 }
113
114
115 auto_ptr<InsetBase> InsetExternal::clone() const
116 {
117         return auto_ptr<InsetBase>(new InsetExternal(*this));
118 }
119
120
121 InsetExternal::~InsetExternal()
122 {
123         InsetExternalMailer(*this).hideDialog();
124 }
125
126
127 void InsetExternal::statusChanged()
128 {
129         BufferView * bv = renderer_->view();
130         if (bv)
131                 bv->updateInset(this);
132 }
133
134
135 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
136 {
137         switch (cmd.action) {
138
139         case LFUN_EXTERNAL_EDIT: {
140                 support::Assert(cmd.view());
141
142                 Buffer const & buffer = *cmd.view()->buffer();
143                 InsetExternal::Params p;
144                 InsetExternalMailer::string2params(cmd.argument, buffer, p);
145                 editExternal(p, buffer);
146                 return DISPATCHED_NOUPDATE;
147         }
148
149         case LFUN_INSET_MODIFY: {
150                 support::Assert(cmd.view());
151
152                 Buffer const & buffer = *cmd.view()->buffer();
153                 InsetExternal::Params p;
154                 InsetExternalMailer::string2params(cmd.argument, buffer, p);
155                 setParams(p, buffer);
156                 cmd.view()->updateInset(this);
157                 return DISPATCHED;
158         }
159
160         case LFUN_INSET_DIALOG_UPDATE:
161                 InsetExternalMailer(*this).updateDialog(cmd.view());
162                 return DISPATCHED;
163
164         case LFUN_MOUSE_RELEASE:
165         case LFUN_INSET_EDIT:
166                 InsetExternalMailer(*this).showDialog(cmd.view());
167                 return DISPATCHED;
168
169         default:
170                 return UNDISPATCHED;
171         }
172 }
173
174
175 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
176 {
177         renderer_->metrics(mi, dim);
178         dim_ = dim;
179 }
180
181
182 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
183 {
184         renderer_->draw(pi, x, y);
185 }
186
187
188 namespace {
189
190 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
191 {
192         lyx::graphics::Params gparams;
193
194         gparams.filename = eparams.filename.absFilename();
195         gparams.scale = eparams.lyxscale;
196         gparams.display = eparams.display;
197
198         if (gparams.display == lyx::graphics::DefaultDisplay)
199                 gparams.display = lyxrc.display_graphics;
200
201         // Override the above if we're not using a gui
202         if (!lyx_gui::use_gui)
203                 gparams.display = lyx::graphics::NoDisplay;
204
205         return gparams;
206 }
207
208
209 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
210 {
211         ExternalTemplateManager & etm = ExternalTemplateManager::get();
212         ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
213         if (templ.lyxName.empty())
214                 return 0;
215         return &templ;
216 }
217
218
219 string const getScreenLabel(InsetExternal::Params const & params,
220                             Buffer const & buffer)
221 {
222         ExternalTemplate const * const ptr = getTemplatePtr(params);
223         if (!ptr)
224                 return support::bformat(_("External template %1$s is not installed"),
225                                         params.templatename);
226         return doSubstitution(params, buffer, ptr->guiName);
227 }
228
229 } // namespace anon
230
231
232 InsetExternal::Params const & InsetExternal::params() const
233 {
234         return params_;
235 }
236
237
238 void InsetExternal::setParams(Params const & p, Buffer const & buffer)
239 {
240         // The stored params; what we would like to happen in an ideal world.
241         params_.filename = p.filename;
242         params_.templatename = p.templatename;
243         params_.display = p.display;
244         params_.lyxscale = p.lyxscale;
245
246         // We display the inset as a button by default.
247         bool display_button = (!getTemplatePtr(params_) ||
248                                params_.filename.empty() ||
249                                params_.display == lyx::graphics::NoDisplay);
250
251         if (display_button) {
252                 ButtonRenderer * button_ptr =
253                         dynamic_cast<ButtonRenderer *>(renderer_.get());
254                 if (!button_ptr) {
255                         button_ptr = new ButtonRenderer;
256                         renderer_.reset(button_ptr);
257                 }
258
259                 button_ptr->update(getScreenLabel(params_, buffer), true);
260
261         } else {
262                 GraphicRenderer * graphic_ptr =
263                         dynamic_cast<GraphicRenderer *>(renderer_.get());
264                 if (!graphic_ptr) {
265                         graphic_ptr = new GraphicRenderer;
266                         graphic_ptr->connect(
267                                 boost::bind(&InsetExternal::statusChanged, this));
268                         renderer_.reset(graphic_ptr);
269                 }
270
271                 graphic_ptr->update(get_grfx_params(params_));
272         }
273 }
274
275
276 void InsetExternal::write(Buffer const & buffer, ostream & os) const
277 {
278         os << "External\n"
279            << "\ttemplate " << params_.templatename << '\n';
280
281         if (!params_.filename.empty())
282                 os << "\tfilename "
283                    << params_.filename.outputFilename(buffer.filePath())
284                    << '\n';
285
286         if (params_.display != defaultDisplayType)
287                 os << "\tdisplay " << lyx::graphics::displayTranslator.find(params_.display)
288                    << '\n';
289
290         if (params_.lyxscale != defaultLyxScale)
291                 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
292 }
293
294
295 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
296 {
297         enum ExternalTags {
298                 EX_TEMPLATE = 1,
299                 EX_FILENAME,
300                 EX_DISPLAY,
301                 EX_LYXSCALE,
302                 EX_END
303         };
304
305         keyword_item external_tags[] = {
306                 { "\\end_inset", EX_END },
307                 { "display", EX_DISPLAY},
308                 { "filename", EX_FILENAME},
309                 { "lyxscale", EX_LYXSCALE},
310                 { "template", EX_TEMPLATE }
311         };
312
313         pushpophelper pph(lex, external_tags, EX_END);
314
315         bool found_end  = false;
316         bool read_error = false;
317
318         InsetExternal::Params params;
319         while (lex.isOK()) {
320                 switch (lex.lex()) {
321                 case EX_TEMPLATE: {
322                         lex.next();
323                         params.templatename = lex.getString();
324                         break;
325                 }
326
327                 case EX_FILENAME: {
328                         lex.next();
329                         string const name = lex.getString();
330                         params.filename.set(name, buffer.filePath());
331                         break;
332                 }
333
334                 case EX_DISPLAY: {
335                         lex.next();
336                         string const name = lex.getString();
337                         params.display = lyx::graphics::displayTranslator.find(name);
338                         break;
339                 }
340
341                 case EX_LYXSCALE: {
342                         lex.next();
343                         params.lyxscale = lex.getInteger();
344                         break;
345                 }
346
347                 case EX_END:
348                         found_end = true;
349                         break;
350
351                 default:
352                         lex.printError("ExternalInset::read: "
353                                        "Wrong tag: $$Token");
354                         read_error = true;
355                         break;
356                 }
357
358                 if (found_end || read_error)
359                         break;
360         }
361
362         if (!found_end) {
363                 lex.printError("ExternalInset::read: "
364                                "Missing \\end_inset.");
365         }
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);
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 = support::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                 string const temp_file =
523                         support::MakeAbsPath(params_.filename.mangledFilename(),
524                                              buf.tmppath);
525                 unsigned long const from_checksum = support::sum(from_file);
526                 unsigned long const temp_checksum = support::sum(temp_file);
527
528                 // Nothing to do...
529                 if (from_checksum == temp_checksum)
530                         return;
531
532                 // Cannot proceed...
533                 if (!support::copy(from_file, temp_file))
534                         return;
535                 from_file = temp_file;
536         }
537
538         string const to_file = doSubstitution(params_, buf,
539                                               outputFormat.updateResult);
540         string const abs_to_file = support::MakeAbsPath(to_file, buf.filePath());
541
542         // Do we need to perform the conversion?
543         // Yes if to_file does not exist or if from_file is newer than to_file
544         if (support::compare_timestamps(from_file, abs_to_file) < 0)
545                 return;
546         
547         string const to_filebase = support::ChangeExtension(to_file, string());
548         converters.convert(&buf, from_file, to_filebase, from_format, to_format);
549 }
550
551
552 namespace {
553
554 /// Substitute meta-variables in this string
555 string const doSubstitution(InsetExternal::Params const & params,
556                             Buffer const & buffer, string const & s)
557 {
558         string result;
559         string const buffer_path = buffer.filePath();
560         string const filename = params.filename.outputFilename(buffer_path);
561         string const basename = support::ChangeExtension(filename, string());
562         string const filepath = support::OnlyPath(filename);
563
564         result = support::subst(s, "$$FName", filename);
565         result = support::subst(result, "$$Basename", basename);
566         result = support::subst(result, "$$FPath", filepath);
567         result = support::subst(result, "$$Tempname", params.tempname);
568         result = support::subst(result, "$$Sysdir", support::system_lyxdir());
569
570         // Handle the $$Contents(filename) syntax
571         if (support::contains(result, "$$Contents(\"")) {
572
573                 string::size_type const pos = result.find("$$Contents(\"");
574                 string::size_type const end = result.find("\")", pos);
575                 string const file = result.substr(pos + 12, end - (pos + 12));
576                 string contents;
577
578                 string const filepath = support::IsFileReadable(file) ?
579                         buffer.filePath() : buffer.tmppath;
580                 support::Path p(filepath);
581
582                 if (support::IsFileReadable(file))
583                         contents = support::GetFileContents(file);
584
585                 result = support::subst(result,
586                                         ("$$Contents(\"" + file + "\")").c_str(),
587                                         contents);
588         }
589
590         return result;
591 }
592
593
594 void editExternal(InsetExternal::Params const & params, Buffer const & buffer)
595 {
596         ExternalTemplate const * const et_ptr = getTemplatePtr(params);
597         if (!et_ptr)
598                 return;
599         ExternalTemplate const & et = *et_ptr;
600
601         if (et.editCommand.empty())
602                 return;
603
604         string const command = doSubstitution(params, buffer, et.editCommand);
605
606         support::Path p(buffer.filePath());
607         support::Forkedcall call;
608         if (lyxerr.debugging()) {
609                 lyxerr << "Executing '" << command << "' in '"
610                        << buffer.filePath() << '\'' << endl;
611         }
612         call.startscript(support::Forkedcall::DontWait, command);
613 }
614
615 } // namespace anon
616
617 string const InsetExternalMailer::name_("external");
618
619 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
620         : inset_(inset)
621 {}
622
623
624 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
625 {
626         return params2string(inset_.params(), buffer);
627 }
628
629
630 void InsetExternalMailer::string2params(string const & in,
631                                         Buffer const & buffer,
632                                         InsetExternal::Params & params)
633 {
634         params = InsetExternal::Params();
635
636         if (in.empty())
637                 return;
638
639         istringstream data(STRCONV(in));
640         LyXLex lex(0,0);
641         lex.setStream(data);
642
643         if (lex.isOK()) {
644                 lex.next();
645                 string const token = lex.getString();
646                 if (token != name_)
647                         return;
648         }
649
650         // This is part of the inset proper that is usually swallowed
651         // by Buffer::readInset
652         if (lex.isOK()) {
653                 lex.next();
654                 string const token = lex.getString();
655                 if (token != "External")
656                         return;
657         }
658
659         if (lex.isOK()) {
660                 InsetExternal inset;
661                 inset.read(buffer, lex);
662                 params = inset.params();
663         }
664 }
665
666
667 string const
668 InsetExternalMailer::params2string(InsetExternal::Params const & params,
669                                    Buffer const & buffer)
670 {
671         InsetExternal inset;
672         inset.setParams(params, buffer);
673         ostringstream data;
674         data << name_ << ' ';
675         inset.write(buffer, data);
676         data << "\\end_inset\n";
677         return STRCONV(data.str());
678 }