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