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