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