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