]> git.lyx.org Git - lyx.git/blob - src/insets/insetexternal.C
Small clean-ups.
[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/graphicinset.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 std::ostream;
48 using std::endl;
49
50
51 namespace {
52
53 grfx::DisplayType const defaultDisplayType = grfx::NoDisplay;
54
55 unsigned int defaultLyxScale = 100;
56
57 } // namespace anon
58
59
60 InsetExternal::Params::Params()
61         : display(defaultDisplayType),
62           lyxscale(defaultLyxScale)
63 {}
64
65
66 InsetExternal::InsetExternal()
67         : renderer_(new GraphicInset)
68 {
69         renderer_->connect(boost::bind(&InsetExternal::statusChanged, this));
70         params_.templ = ExternalTemplateManager::get().getTemplates().begin()->second;
71 }
72
73
74 InsetExternal::InsetExternal(InsetExternal const & other)
75         : Inset(other),
76           boost::signals::trackable(),
77           params_(other.params_),
78           renderer_(new GraphicInset(*other.renderer_))
79 {
80         renderer_->connect(boost::bind(&InsetExternal::statusChanged, this));
81 }
82
83
84 Inset * InsetExternal::clone() const
85 {
86         InsetExternal * inset = new InsetExternal(*this);
87         return inset;
88 }
89
90
91 InsetExternal::~InsetExternal()
92 {
93         if (!tempname_.empty())
94                 lyx::unlink(tempname_);
95         InsetExternalMailer(*this).hideDialog();
96 }
97
98
99 void InsetExternal::statusChanged()
100 {
101         BufferView * bv = renderer_->view();
102         if (bv)
103                 bv->updateInset(this);
104 }
105         
106
107 InsetExternal::Params const & InsetExternal::params() const
108 {
109         return params_;
110 }
111
112
113 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
114 {
115         switch (cmd.action) {
116
117         case LFUN_INSET_MODIFY: {
118                 InsetExternal::Params p;
119                 InsetExternalMailer::string2params(cmd.argument, p);
120                 setParams(p, cmd.view()->buffer()->filePath());
121                 cmd.view()->updateInset(this);
122                 return DISPATCHED;
123         }
124
125         case LFUN_INSET_DIALOG_UPDATE:
126                 InsetExternalMailer(*this).updateDialog(cmd.view());
127                 return DISPATCHED;
128
129         case LFUN_MOUSE_RELEASE:
130         case LFUN_INSET_EDIT:
131                 InsetExternalMailer(*this).showDialog(cmd.view());
132                 return DISPATCHED;
133
134         default:
135                 return UNDISPATCHED;
136         }
137 }
138
139
140 void InsetExternal::cache(BufferView * bv) const
141 {
142         renderer_->view(bv);
143 }
144
145
146 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
147 {
148         renderer_->metrics(mi, dim);
149 }
150
151
152 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
153 {
154         renderer_->draw(pi, x, y);
155 }
156
157
158 namespace {
159
160 grfx::Params get_grfx_params(InsetExternal::Params const & eparams,
161                              string const & filepath)
162 {
163         grfx::Params gparams;
164
165         if (!eparams.filename.empty()) {
166                 lyx::Assert(AbsolutePath(filepath));
167                 gparams.filename = MakeAbsPath(eparams.filename, filepath);
168         }
169
170         gparams.scale = eparams.lyxscale;
171         gparams.display = eparams.display;
172
173         if (gparams.display == grfx::DefaultDisplay)
174                 gparams.display = lyxrc.display_graphics;
175
176         // Override the above if we're not using a gui
177         if (!lyx_gui::use_gui)
178                 gparams.display = grfx::NoDisplay;
179
180         return gparams;
181 }
182
183 } // namespace anon
184
185
186 void InsetExternal::setParams(Params const & p, string const & filepath)
187 {
188         params_.filename = p.filename;
189         params_.templ = p.templ;
190         params_.display = p.display;
191         params_.lyxscale = p.lyxscale;
192
193         // Update the display using the new parameters.
194         if (params_.filename.empty() || !filepath.empty())
195                 renderer_->update(get_grfx_params(params_, filepath));  
196         string const msg = doSubstitution(0, params_.templ.guiName);
197         renderer_->setNoDisplayMessage(msg);
198 }
199
200
201 string const InsetExternal::editMessage() const
202 {
203         return doSubstitution(0, params_.templ.guiName);
204 }
205
206
207 void InsetExternal::write(Buffer const *, ostream & os) const
208 {
209         os << "External\n"
210            << "\ttemplate " << params_.templ.lyxName << '\n';
211
212         if (!params_.filename.empty())
213                 os << "\tfilename " << params_.filename << '\n';
214
215         if (params_.display != defaultDisplayType)
216                 os << "\tdisplay " << grfx::displayTranslator.find(params_.display)
217                    << '\n';
218
219         if (params_.lyxscale != defaultLyxScale)
220                 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
221 }
222
223
224 void InsetExternal::read(Buffer const * buffer, LyXLex & lex)
225 {
226         enum ExternalTags {
227                 EX_TEMPLATE = 1,
228                 EX_FILENAME,
229                 EX_DISPLAY,
230                 EX_LYXSCALE,
231                 EX_END
232         };
233
234         keyword_item external_tags[] = {
235                 { "\\end_inset", EX_END },
236                 { "display", EX_DISPLAY},
237                 { "filename", EX_FILENAME},
238                 { "lyxscale", EX_LYXSCALE},
239                 { "template", EX_TEMPLATE }
240         };
241
242         lex.pushTable(external_tags, EX_END);
243
244         bool found_end  = false;
245         bool read_error = false;
246
247         InsetExternal::Params params;
248         while (lex.isOK()) {
249                 switch (lex.lex()) {
250                 case EX_TEMPLATE: {
251                         lex.next();
252                         string const name = lex.getString();
253                         ExternalTemplateManager & etm =
254                                 ExternalTemplateManager::get();
255                         params.templ = etm.getTemplateByName(name);
256                         break;
257                 }
258
259                 case EX_FILENAME: {
260                         lex.next();
261                         string const name = lex.getString();
262                         params.filename = name;
263                         break;
264                 }
265
266                 case EX_DISPLAY: {
267                         lex.next();
268                         string const name = lex.getString();
269                         params.display = grfx::displayTranslator.find(name);
270                         break;
271                 }
272
273                 case EX_LYXSCALE: {
274                         lex.next();
275                         params.lyxscale = lex.getInteger();
276                         break;
277                 }
278
279                 case EX_END:
280                         found_end = true;
281                         break;
282
283                 default:
284                         lex.printError("ExternalInset::read: "
285                                        "Wrong tag: $$Token");
286                         read_error = true;
287                         break;
288                 }
289
290                 if (found_end || read_error)
291                         break;
292         }
293
294         if (!found_end) {
295                 lex.printError("ExternalInset::read: "
296                                "Missing \\end_inset.");
297         }
298
299         lex.popTable();
300
301         // Replace the inset's store
302         params_ = params;
303
304         lyxerr[Debug::INFO] << "InsetExternal::Read: "
305                << "template: '" << params_.templ.lyxName
306                << "' filename: '" << params_.filename
307                << "' display: '" << params_.display
308                << "' scale: '" << params_.lyxscale
309                << '\'' << endl;
310
311         // Update the display using the new parameters.
312         if (buffer)
313                 renderer_->update(get_grfx_params(params_, buffer->filePath()));
314         string const msg = doSubstitution(0, params_.templ.guiName);
315         renderer_->setNoDisplayMessage(msg);
316 }
317
318
319 int InsetExternal::write(string const & format,
320                          Buffer const * buf, ostream & os,
321                          bool external_in_tmpdir) const
322 {
323         ExternalTemplate const & et = params_.templ;
324         ExternalTemplate::Formats::const_iterator cit =
325                 et.formats.find(format);
326         if (cit == et.formats.end()) {
327                 lyxerr << "External template format '" << format
328                        << "' not specified in template "
329                        << params_.templ.lyxName << endl;
330                 return 0;
331         }
332
333         updateExternal(format, buf, external_in_tmpdir);
334         string const str = doSubstitution(buf, cit->second.product);
335         os << str;
336         return int(lyx::count(str.begin(), str.end(),'\n') + 1);
337 }
338
339
340 int InsetExternal::latex(Buffer const * buf, ostream & os,
341                          LatexRunParams const & runparams) const
342 {
343         // "nice" means that the buffer is exported to LaTeX format but not
344         // run through the LaTeX compiler.
345         // If we're running through the LaTeX compiler, we should write the
346         // generated files in the bufer's temporary directory.
347         bool const external_in_tmpdir =
348                 lyxrc.use_tempdir && !buf->tmppath.empty() && !runparams.nice;
349
350         // If the template has specified a PDFLaTeX output, then we try and
351         // use that.
352         if (runparams.flavor == LatexRunParams::PDFLATEX) {
353                 ExternalTemplate const & et = params_.templ;
354                 ExternalTemplate::Formats::const_iterator cit =
355                         et.formats.find("PDFLaTeX");
356                 if (cit != et.formats.end())
357                         return write("PDFLaTeX", buf, os, external_in_tmpdir);
358         }
359
360         return write("LaTeX", buf, os, external_in_tmpdir);
361 }
362
363
364 int InsetExternal::ascii(Buffer const * buf, ostream & os, int) const
365 {
366         return write("Ascii", buf, os);
367 }
368
369
370 int InsetExternal::linuxdoc(Buffer const * buf, ostream & os) const
371 {
372         return write("LinuxDoc", buf, os);
373 }
374
375
376 int InsetExternal::docbook(Buffer const * buf, ostream & os, bool) const
377 {
378         return write("DocBook", buf, os);
379 }
380
381
382 void InsetExternal::validate(LaTeXFeatures & features) const
383 {
384         ExternalTemplate const & et = params_.templ;
385         ExternalTemplate::Formats::const_iterator cit =
386                 et.formats.find("LaTeX");
387
388         if (cit == et.formats.end())
389                 return;
390
391         if (!cit->second.requirement.empty()) {
392                 features.require(cit->second.requirement);
393         }
394         if (!cit->second.preamble.empty()) {
395                 features.addExternalPreamble(cit->second.preamble + "\n");
396         }
397 }
398
399
400 string const InsetExternal::doSubstitution(Buffer const * buffer,
401                                            string const & s) const
402 {
403         string result;
404         string const basename = ChangeExtension(params_.filename, string());
405         string filepath;
406         bool external_in_tmpdir = false;
407         if (buffer && !buffer->tmppath.empty() && !buffer->niceFile) {
408                 filepath = buffer->filePath();
409                 if (lyxrc.use_tempdir)
410                         external_in_tmpdir = true;
411         }
412         if (tempname_.empty()) {
413                 string const path = external_in_tmpdir ? buffer->tmppath : string();
414                 tempname_ = lyx::tempName(path, "lyxext");
415                 lyx::unlink(tempname_);
416                 // must have an extension for the converter code to work correctly.
417                 tempname_ += ".tmp";
418         }
419         result = subst(s, "$$FName", params_.filename);
420         result = subst(result, "$$Basename", basename);
421         result = subst(result, "$$FPath", filepath);
422         result = subst(result, "$$Tempname", tempname_);
423         result = subst(result, "$$Sysdir", system_lyxdir);
424
425         // Handle the $$Contents(filename) syntax
426         if (contains(result, "$$Contents(\"")) {
427
428                 string::size_type const pos = result.find("$$Contents(\"");
429                 string::size_type const end = result.find("\")", pos);
430                 string const file = result.substr(pos + 12, end - (pos + 12));
431                 string contents;
432                 if (buffer) {
433                         Path p(buffer->filePath());
434                         if (!IsFileReadable(file))
435                                 Path p(buffer->tmppath);
436                         if (IsFileReadable(file))
437                                 contents = GetFileContents(file);
438                 } else {
439                         contents = GetFileContents(file);
440                 }
441                 result = subst(result,
442                                ("$$Contents(\"" + file + "\")").c_str(),
443                                contents);
444         }
445
446         return result;
447 }
448
449
450 void InsetExternal::updateExternal(string const & format,
451                                    Buffer const * buf,
452                                    bool external_in_tmpdir) const
453 {
454         ExternalTemplate const & et = params_.templ;
455         if (!et.automaticProduction)
456                 return;
457
458         ExternalTemplate::Formats::const_iterator cit =
459                 et.formats.find(format);
460         if (cit == et.formats.end())
461                 return;
462
463         ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
464         if (outputFormat.updateResult.empty())
465                 return;
466
467         string from_format = et.inputFormat;
468         if (from_format.empty())
469                 return;
470
471         string from_file = params_.filename.empty() ?
472                 string() : MakeAbsPath(params_.filename, buf->filePath());
473
474         if (from_format == "*") {
475                 if (from_file.empty())
476                         return;
477
478                 // Try and ascertain the file format from its contents.
479                 from_format = getExtFromContents(from_file);
480                 if (from_format.empty())
481                         return;
482         }
483
484         string const to_format = outputFormat.updateFormat;
485         if (to_format.empty())
486                 return;
487
488         if (!converters.isReachable(from_format, to_format)) {
489                 lyxerr << "InsetExternal::updateExternal. "
490                         "Unable to convert from "
491                        << from_format << " to " << to_format << endl;
492                 return;
493         }
494
495         if (external_in_tmpdir && !from_file.empty()) {
496                 // We are running stuff through LaTeX
497                 from_file = copyFileToDir(buf->tmppath, from_file);
498                 if (from_file.empty())
499                         return;
500         }
501
502         string const to_file = doSubstitution(buf, outputFormat.updateResult);
503
504         FileInfo fi(from_file);
505         string abs_to_file = to_file;
506         if (!AbsolutePath(to_file))
507                 abs_to_file = MakeAbsPath(to_file, OnlyPath(from_file));
508         FileInfo fi2(abs_to_file);
509         if (fi2.exist() && fi.exist() &&
510             difftime(fi2.getModificationTime(),
511                      fi.getModificationTime()) >= 0) {
512         } else {
513                 string const to_filebase = ChangeExtension(to_file, string());
514                 converters.convert(buf, from_file, to_filebase,
515                                    from_format, to_format);
516         }
517 }
518
519
520 void InsetExternal::editExternal() const
521 {
522         ExternalTemplate const & et = params_.templ;
523         if (et.editCommand.empty())
524                 return;
525
526         BufferView const * bv = renderer_->view();
527         Buffer const * buffer = bv ? bv->buffer() : 0;
528         if (!buffer)
529                 return;
530
531         string const command = doSubstitution(buffer, et.editCommand);
532
533         Path p(buffer->filePath());
534         Forkedcall call;
535         if (lyxerr.debugging()) {
536                 lyxerr << "Executing '" << command << "' in '"
537                        << buffer->filePath() << '\'' << endl;
538         }
539         call.startscript(Forkedcall::DontWait, command);
540 }
541
542
543 string const InsetExternalMailer::name_("external");
544
545 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
546         : inset_(inset)
547 {}
548
549
550 string const InsetExternalMailer::inset2string() const
551 {
552         return params2string(inset_.params());
553 }
554
555
556 void InsetExternalMailer::string2params(string const & in,
557                                         InsetExternal::Params & params)
558 {
559         params = InsetExternal::Params();
560
561         if (in.empty())
562                 return;
563
564         istringstream data(STRCONV(in));
565         LyXLex lex(0,0);
566         lex.setStream(data);
567
568         if (lex.isOK()) {
569                 lex.next();
570                 string const token = lex.getString();
571                 if (token != name_)
572                         return;
573         }
574
575         // This is part of the inset proper that is usually swallowed
576         // by Buffer::readInset
577         if (lex.isOK()) {
578                 lex.next();
579                 string const token = lex.getString();
580                 if (token != "External")
581                         return;
582         }
583
584         if (lex.isOK()) {
585                 InsetExternal inset;
586                 inset.read(0, lex);
587                 params = inset.params();
588         }
589 }
590
591
592 string const
593 InsetExternalMailer::params2string(InsetExternal::Params const & params)
594 {
595         InsetExternal inset;
596         inset.setParams(params, string());
597         ostringstream data;
598         data << name_ << ' ';
599         inset.write(0, data);
600         data << "\\end_inset\n";
601         return STRCONV(data.str());
602 }