]> git.lyx.org Git - features.git/blob - src/insets/insetexternal.C
namespace grfx -> lyx::graphics
[features.git] / src / insets / insetexternal.C
1 /**
2  * \file insetexternal.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup Nielsen
7  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "insetexternal.h"
14 #include "insets/renderers.h"
15
16 #include "buffer.h"
17 #include "BufferView.h"
18 #include "converter.h"
19 #include "debug.h"
20 #include "ExternalTemplate.h"
21 #include "funcrequest.h"
22 #include "gettext.h"
23 #include "LaTeXFeatures.h"
24 #include "latexrunparams.h"
25 #include "lyx_main.h"
26 #include "lyxlex.h"
27 #include "lyxrc.h"
28 #include "Lsstream.h"
29
30 #include "frontends/lyx_gui.h"
31 #include "frontends/LyXView.h"
32 #include "frontends/Dialogs.h"
33
34 #include "support/FileInfo.h"
35 #include "support/filetools.h"
36 #include "support/forkedcall.h"
37 #include "support/lstrings.h"
38 #include "support/lyxalgo.h"
39 #include "support/path.h"
40 #include "support/tostr.h"
41
42 #include <boost/bind.hpp>
43
44 #include <cstdio>
45 #include <utility>
46
47 using namespace lyx::support;
48
49 using std::ostream;
50 using std::endl;
51
52 namespace grfx = lyx::graphics;
53
54 namespace {
55
56 grfx::DisplayType const defaultDisplayType = grfx::NoDisplay;
57
58 unsigned int defaultLyxScale = 100;
59
60 /// Substitute meta-variables in string s, makeing use of params and buffer.
61 string const doSubstitution(InsetExternal::Params const & params,
62                             Buffer const * buffer, string const & s);
63
64 /// Invoke the external editor.
65 void editExternal(InsetExternal::Params const & params, Buffer const * buffer);
66
67 } // namespace anon
68
69
70 InsetExternal::Params::Params()
71         : display(defaultDisplayType),
72           lyxscale(defaultLyxScale)
73 {
74         tempname = tempName(string(), "lyxext");
75         unlink(tempname);
76         // must have an extension for the converter code to work correctly.
77         tempname += ".tmp";
78 }
79
80
81 InsetExternal::Params::~Params()
82 {
83         unlink(tempname);
84 }
85
86
87 InsetExternal::InsetExternal()
88         : renderer_(new ButtonRenderer)
89 {}
90
91
92 InsetExternal::InsetExternal(InsetExternal const & other)
93         : Inset(other),
94           boost::signals::trackable(),
95           params_(other.params_),
96           renderer_(other.renderer_->clone())
97 {
98         GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
99         if (ptr) {
100                 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
101         }
102 }
103
104
105 InsetBase * InsetExternal::clone() const
106 {
107         InsetExternal * inset = new InsetExternal(*this);
108         return inset;
109 }
110
111
112 InsetExternal::~InsetExternal()
113 {
114         InsetExternalMailer(*this).hideDialog();
115 }
116
117
118 void InsetExternal::statusChanged()
119 {
120         BufferView * bv = renderer_->view();
121         if (bv)
122                 bv->updateInset(this);
123 }
124
125
126 InsetExternal::Params const & InsetExternal::params() const
127 {
128         return params_;
129 }
130
131
132 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
133 {
134         switch (cmd.action) {
135
136         case LFUN_EXTERNAL_EDIT: {
137                 Assert(cmd.view());
138
139                 InsetExternal::Params p;
140                 InsetExternalMailer::string2params(cmd.argument, p);
141                 editExternal(p, cmd.view()->buffer());
142                 return DISPATCHED_NOUPDATE;
143         }
144
145         case LFUN_INSET_MODIFY: {
146                 Assert(cmd.view());
147
148                 InsetExternal::Params p;
149                 InsetExternalMailer::string2params(cmd.argument, p);
150                 setParams(p, cmd.view()->buffer()->filePath());
151                 cmd.view()->updateInset(this);
152                 return DISPATCHED;
153         }
154
155         case LFUN_INSET_DIALOG_UPDATE:
156                 InsetExternalMailer(*this).updateDialog(cmd.view());
157                 return DISPATCHED;
158
159         case LFUN_MOUSE_RELEASE:
160         case LFUN_INSET_EDIT:
161                 InsetExternalMailer(*this).showDialog(cmd.view());
162                 return DISPATCHED;
163
164         default:
165                 return UNDISPATCHED;
166         }
167 }
168
169
170 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
171 {
172         renderer_->metrics(mi, 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 grfx::Params get_grfx_params(InsetExternal::Params const & eparams,
185                              string const & filepath)
186 {
187         grfx::Params gparams;
188
189         if (!eparams.filename.empty()) {
190                 Assert(AbsolutePath(filepath));
191                 gparams.filename = MakeAbsPath(eparams.filename, filepath);
192         }
193
194         gparams.scale = eparams.lyxscale;
195         gparams.display = eparams.display;
196
197         if (gparams.display == grfx::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 = grfx::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 {
220         ExternalTemplate const * const ptr = getTemplatePtr(params);
221         if (!ptr)
222                 return bformat(_("External template %1$s is not installed"),
223                                params.templatename);
224         return doSubstitution(params, 0, ptr->guiName);
225 }
226
227 } // namespace anon
228
229
230 void InsetExternal::setParams(Params const & p, string const & filepath)
231 {
232         // The stored params; what we would like to happen in an ideal world.
233         params_.filename = p.filename;
234         params_.templatename = p.templatename;
235         params_.display = p.display;
236         params_.lyxscale = p.lyxscale;
237
238         // We display the inset as a button by default.
239         bool display_button = (!getTemplatePtr(params_) ||
240                                params_.filename.empty() ||
241                                filepath.empty() ||
242                                params_.display == grfx::NoDisplay);
243
244         if (display_button) {
245                 ButtonRenderer * button_ptr =
246                         dynamic_cast<ButtonRenderer *>(renderer_.get());
247                 if (!button_ptr) {
248                         button_ptr = new ButtonRenderer;
249                         renderer_.reset(button_ptr);
250                 }
251
252                 button_ptr->update(getScreenLabel(params_), true);
253
254         } else {
255                 GraphicRenderer * graphic_ptr =
256                         dynamic_cast<GraphicRenderer *>(renderer_.get());
257                 if (!graphic_ptr) {
258                         graphic_ptr = new GraphicRenderer;
259                         graphic_ptr->connect(
260                                 boost::bind(&InsetExternal::statusChanged, this));
261                         renderer_.reset(graphic_ptr);
262                 }
263
264                 graphic_ptr->update(get_grfx_params(params_, filepath));
265         }
266 }
267
268
269 string const InsetExternal::editMessage() const
270 {
271         return getScreenLabel(params_);
272 }
273
274
275 void InsetExternal::write(Buffer const *, ostream & os) const
276 {
277         os << "External\n"
278            << "\ttemplate " << params_.templatename << '\n';
279
280         if (!params_.filename.empty())
281                 os << "\tfilename " << params_.filename << '\n';
282
283         if (params_.display != defaultDisplayType)
284                 os << "\tdisplay " << grfx::displayTranslator.find(params_.display)
285                    << '\n';
286
287         if (params_.lyxscale != defaultLyxScale)
288                 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
289 }
290
291
292 void InsetExternal::read(Buffer const * buffer, LyXLex & lex)
293 {
294         enum ExternalTags {
295                 EX_TEMPLATE = 1,
296                 EX_FILENAME,
297                 EX_DISPLAY,
298                 EX_LYXSCALE,
299                 EX_END
300         };
301
302         keyword_item external_tags[] = {
303                 { "\\end_inset", EX_END },
304                 { "display", EX_DISPLAY},
305                 { "filename", EX_FILENAME},
306                 { "lyxscale", EX_LYXSCALE},
307                 { "template", EX_TEMPLATE }
308         };
309
310         lex.pushTable(external_tags, EX_END);
311
312         bool found_end  = false;
313         bool read_error = false;
314
315         InsetExternal::Params params;
316         while (lex.isOK()) {
317                 switch (lex.lex()) {
318                 case EX_TEMPLATE: {
319                         lex.next();
320                         params.templatename = lex.getString();
321                         break;
322                 }
323
324                 case EX_FILENAME: {
325                         lex.next();
326                         string const name = lex.getString();
327                         params.filename = name;
328                         break;
329                 }
330
331                 case EX_DISPLAY: {
332                         lex.next();
333                         string const name = lex.getString();
334                         params.display = grfx::displayTranslator.find(name);
335                         break;
336                 }
337
338                 case EX_LYXSCALE: {
339                         lex.next();
340                         params.lyxscale = lex.getInteger();
341                         break;
342                 }
343
344                 case EX_END:
345                         found_end = true;
346                         break;
347
348                 default:
349                         lex.printError("ExternalInset::read: "
350                                        "Wrong tag: $$Token");
351                         read_error = true;
352                         break;
353                 }
354
355                 if (found_end || read_error)
356                         break;
357         }
358
359         if (!found_end) {
360                 lex.printError("ExternalInset::read: "
361                                "Missing \\end_inset.");
362         }
363
364         lex.popTable();
365
366         // Replace the inset's store
367         string const path = buffer ? buffer->filePath() : string();
368         setParams(params, path);
369
370         lyxerr[Debug::INFO] << "InsetExternal::Read: "
371                << "template: '" << params_.templatename
372                << "' filename: '" << params_.filename
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 + "\n");
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.empty() ?
498                 string() : MakeAbsPath(params_.filename, buf->filePath());
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 basename = ChangeExtension(params.filename, string());
555         string filepath;
556
557         result = subst(s, "$$FName", params.filename);
558         result = subst(result, "$$Basename", basename);
559         result = subst(result, "$$FPath", filepath);
560         result = subst(result, "$$Tempname", params.tempname);
561         result = subst(result, "$$Sysdir", system_lyxdir);
562
563         // Handle the $$Contents(filename) syntax
564         if (contains(result, "$$Contents(\"")) {
565
566                 string::size_type const pos = result.find("$$Contents(\"");
567                 string::size_type const end = result.find("\")", pos);
568                 string const file = result.substr(pos + 12, end - (pos + 12));
569                 string contents;
570                 if (buffer) {
571                         Path p(buffer->filePath());
572                         if (!IsFileReadable(file))
573                                 Path p(buffer->tmppath);
574                         if (IsFileReadable(file))
575                                 contents = GetFileContents(file);
576                 } else {
577                         contents = GetFileContents(file);
578                 }
579                 result = subst(result,
580                                ("$$Contents(\"" + file + "\")").c_str(),
581                                contents);
582         }
583
584         return result;
585 }
586
587
588 void editExternal(InsetExternal::Params const & params, Buffer const * buffer)
589 {
590         if (!buffer)
591                 return;
592
593         ExternalTemplate const * const et_ptr = getTemplatePtr(params);
594         if (!et_ptr)
595                 return;
596         ExternalTemplate const & et = *et_ptr;
597
598         if (et.editCommand.empty())
599                 return;
600
601         string const command = doSubstitution(params, buffer, et.editCommand);
602
603         Path p(buffer->filePath());
604         Forkedcall call;
605         if (lyxerr.debugging()) {
606                 lyxerr << "Executing '" << command << "' in '"
607                        << buffer->filePath() << '\'' << endl;
608         }
609         call.startscript(Forkedcall::DontWait, command);
610 }
611
612 } // namespace anon
613
614 string const InsetExternalMailer::name_("external");
615
616 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
617         : inset_(inset)
618 {}
619
620
621 string const InsetExternalMailer::inset2string() const
622 {
623         return params2string(inset_.params());
624 }
625
626
627 void InsetExternalMailer::string2params(string const & in,
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(0, lex);
658                 params = inset.params();
659         }
660 }
661
662
663 string const
664 InsetExternalMailer::params2string(InsetExternal::Params const & params)
665 {
666         InsetExternal inset;
667         inset.setParams(params, string());
668         ostringstream data;
669         data << name_ << ' ';
670         inset.write(0, data);
671         data << "\\end_inset\n";
672         return STRCONV(data.str());
673 }