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