]> git.lyx.org Git - lyx.git/blob - src/insets/insetexternal.C
fix #832
[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 "ExternalTemplate.h"
15 #include "BufferView.h"
16 #include "buffer.h"
17 #include "funcrequest.h"
18 #include "lyx_main.h"
19 #include "LaTeXFeatures.h"
20 #include "gettext.h"
21 #include "debug.h"
22 #include "lyxlex.h"
23 #include "Lsstream.h"
24
25 #include "frontends/LyXView.h"
26 #include "frontends/Dialogs.h"
27
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
30 #include "support/path.h"
31 #include "support/systemcall.h"
32 #include "support/FileInfo.h"
33
34 #include <cstdio>
35 #include <utility>
36
37 using std::ostream;
38 using std::endl;
39
40
41 InsetExternal::InsetExternal()
42         : view_(0)
43 {
44         tempname_ = lyx::tempName(string(), "lyxext");
45         //ExternalTemplateManager::Templates::const_iterator i1;
46         params_.templ = ExternalTemplateManager::get().getTemplates().begin()->second;
47 }
48
49
50 InsetExternal::~InsetExternal()
51 {
52         lyx::unlink(tempname_);
53         InsetExternalMailer mailer(*this);
54         mailer.hideDialog();
55 }
56
57
58 InsetExternal::Params const & InsetExternal::params() const
59 {
60         return params_;
61 }
62
63
64 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
65 {
66         switch (cmd.action) {
67
68         case LFUN_INSET_MODIFY: {
69                 InsetExternal::Params p;
70                 InsetExternalMailer::string2params(cmd.argument, p);
71                 if (!p.filename.empty()) {
72                         setFromParams(p);
73                         cmd.view()->updateInset(this);
74                 }
75                 return DISPATCHED;
76         }
77
78         case LFUN_INSET_DIALOG_UPDATE:
79                 InsetExternalMailer(*this).updateDialog(cmd.view());
80                 return DISPATCHED;
81
82         case LFUN_MOUSE_RELEASE:
83         case LFUN_INSET_EDIT:
84                 InsetExternalMailer(*this).showDialog(cmd.view());
85                 return DISPATCHED;
86
87         default:
88                 return UNDISPATCHED;
89         }
90 }
91
92
93 void InsetExternal::setFromParams(Params const & p)
94 {
95         params_.filename = p.filename;
96         params_.parameters = p.parameters;
97         params_.templ = p.templ;
98 }
99
100
101 string const InsetExternal::editMessage() const
102 {
103         return doSubstitution(0, params_.templ.guiName);
104 }
105
106
107 void InsetExternal::write(Buffer const *, ostream & os) const
108 {
109         os << "External " << params_.templ.lyxName << ",\""
110            << params_.filename << "\",\"" << params_.parameters << "\"\n";
111 }
112
113
114 void InsetExternal::read(Buffer const *, LyXLex & lex)
115 {
116         string format;
117         string token;
118
119         // Read inset data from lex and store in format
120         if (lex.eatLine()) {
121                 format = lex.getString();
122         } else {
123                 lex.printError("InsetExternal: Parse error: `$$Token'");
124         }
125
126         while (lex.isOK()) {
127                 lex.nextToken();
128                 token = lex.getString();
129                 if (token == "\\end_inset")
130                         break;
131         }
132         if (token != "\\end_inset") {
133                 lex.printError("Missing \\end_inset at this point. "
134                                "Read: `$$Token'");
135         }
136
137         // Parse string format...
138         string::size_type const pos1 = format.find(',');
139         params_.templ = ExternalTemplateManager::get().getTemplateByName(format.substr(0, pos1));
140         string::size_type const pos2 = format.find("\",\"", pos1);
141         params_.filename = format.substr(pos1 + 2, pos2 - (pos1 + 2));
142         params_.parameters = format.substr(pos2 + 3, format.length() - (pos2 + 4));
143
144         lyxerr[Debug::INFO] << "InsetExternal::Read: " << params_.templ.lyxName
145                             << ' ' << params_.filename
146                             << ' ' << params_.parameters << endl;
147 }
148
149
150 int InsetExternal::write(string const & format,
151                          Buffer const * buf, ostream & os) const
152 {
153         ExternalTemplate const & et = params_.templ;
154         ExternalTemplate::Formats::const_iterator cit =
155                 et.formats.find(format);
156         if (cit == et.formats.end()) {
157                 lyxerr << "External template format '" << format
158                        << "' not specified in template "
159                        << params_.templ.lyxName << endl;
160                 return 0;
161         }
162
163         updateExternal(format, buf);
164         os << doSubstitution(buf, cit->second.product);
165         return 0; // CHECK  (FIXME check what ? - jbl)
166 }
167
168
169 int InsetExternal::latex(Buffer const * buf,
170                          ostream & os, bool, bool) const
171 {
172         return write("LaTeX", buf, os);
173 }
174
175
176 int InsetExternal::ascii(Buffer const * buf, ostream & os, int) const
177 {
178         return write("Ascii", buf, os);
179 }
180
181
182 int InsetExternal::linuxdoc(Buffer const * buf, ostream & os) const
183 {
184         return write("LinuxDoc", buf, os);
185 }
186
187
188 int InsetExternal::docbook(Buffer const * buf, ostream & os, bool) const
189 {
190         return write("DocBook", buf, os);
191 }
192
193
194 void InsetExternal::validate(LaTeXFeatures & features) const
195 {
196         ExternalTemplate const & et = params_.templ;
197         ExternalTemplate::Formats::const_iterator cit =
198                 et.formats.find("LaTeX");
199
200         if (cit == et.formats.end())
201                 return;
202
203         if (!cit->second.requirement.empty()) {
204                 features.require(cit->second.requirement);
205         }
206         if (!cit->second.preamble.empty()) {
207                 features.addExternalPreamble(cit->second.preamble + "\n");
208         }
209 }
210
211
212 Inset * InsetExternal::clone(Buffer const &, bool same_id) const
213 {
214         InsetExternal * inset = new InsetExternal;
215         inset->params_ = params_;
216         inset->view_ = view_;
217         if (same_id)
218                 inset->id_ = id_;
219         return inset;
220 }
221
222
223 string const InsetExternal::getScreenLabel(Buffer const *) const
224 {
225         ExternalTemplate const & et = params_.templ;
226         if (et.guiName.empty())
227                 return _("External");
228         else
229                 return doSubstitution(0, et.guiName);
230 }
231
232
233 void InsetExternal::executeCommand(string const & s,
234                                    Buffer const * buffer) const
235 {
236         Path p(buffer->filePath());
237         Systemcall one;
238         if (lyxerr.debugging()) {
239                 lyxerr << "Executing '" << s << "' in '"
240                        << buffer->filePath() << '\'' << endl;
241         }
242         one.startscript(Systemcall::Wait, s);
243 }
244
245
246 string const InsetExternal::doSubstitution(Buffer const * buffer,
247                                            string const & s) const
248 {
249         string result;
250         string const basename = ChangeExtension(params_.filename, string());
251         string filepath;
252         if (buffer && !buffer->tmppath.empty() && !buffer->niceFile) {
253                 filepath = buffer->filePath();
254         }
255         result = subst(s, "$$FName", params_.filename);
256         result = subst(result, "$$Basename", basename);
257         result = subst(result, "$$Parameters", params_.parameters);
258         result = subst(result, "$$FPath", filepath);
259         result = subst(result, "$$Tempname", tempname_);
260         result = subst(result, "$$Sysdir", system_lyxdir);
261
262         // Handle the $$Contents(filename) syntax
263         if (contains(result, "$$Contents(\"")) {
264
265                 string::size_type const pos = result.find("$$Contents(\"");
266                 string::size_type const end = result.find("\")", pos);
267                 string const file = result.substr(pos + 12, end - (pos + 12));
268                 string contents;
269                 if (buffer) {
270                         // Make sure we are in the directory of the buffer
271                         Path p(buffer->filePath());
272                         contents = GetFileContents(file);
273                 } else {
274                         contents = GetFileContents(file);
275                 }
276                 result = subst(result,
277                                ("$$Contents(\"" + file + "\")").c_str(),
278                                contents);
279         }
280
281         return result;
282 }
283
284
285 void InsetExternal::updateExternal() const
286 {
287         updateExternal("LaTeX", view_->buffer());
288 }
289
290 void InsetExternal::updateExternal(string const & format,
291                                    Buffer const * buf) const
292 {
293         ExternalTemplate const & et = params_.templ;
294         ExternalTemplate::Formats::const_iterator cit =
295                 et.formats.find(format);
296
297         if (cit == et.formats.end() ||
298             cit->second.updateCommand.empty() ||
299             !et.automaticProduction)
300                 return;
301
302         if (!cit->second.updateResult.empty()) {
303                 string const resultfile = doSubstitution(buf,
304                                                          cit->second.updateResult);
305                 FileInfo fi(params_.filename);
306                 FileInfo fi2(resultfile);
307                 if (fi2.exist() && fi.exist() &&
308                     difftime(fi2.getModificationTime(),
309                              fi.getModificationTime()) >= 0) {
310                         lyxerr[Debug::FILES] << resultfile
311                                              << " is up to date" << endl;
312                         return;
313                 }
314         }
315
316         executeCommand(doSubstitution(buf, cit->second.updateCommand), buf);
317 }
318
319
320 void InsetExternal::viewExternal() const
321 {
322         ExternalTemplate const & et = params_.templ;
323         if (et.viewCommand.empty())
324                 return;
325
326         updateExternal();
327         executeCommand(doSubstitution(view_->buffer(),
328                                       et.viewCommand),
329                        view_->buffer());
330 }
331
332
333 void InsetExternal::editExternal() const
334 {
335         ExternalTemplate const & et = params_.templ;
336         if (et.editCommand.empty())
337                 return;
338
339         updateExternal();
340         executeCommand(doSubstitution(view_->buffer(),
341                                       et.editCommand),
342                        view_->buffer());
343 }
344
345
346 string const InsetExternalMailer::name_("external");
347
348 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
349         : inset_(inset)
350 {}
351
352
353 string const InsetExternalMailer::inset2string() const
354 {
355         return params2string(inset_.params());
356 }
357
358
359 void InsetExternalMailer::string2params(string const & in,
360                                         InsetExternal::Params & params)
361 {
362         params = InsetExternal::Params();
363
364         if (in.empty())
365                 return;
366
367         istringstream data(STRCONV(in));
368         LyXLex lex(0,0);
369         lex.setStream(data);
370
371         if (lex.isOK()) {
372                 lex.next();
373                 string const token = lex.getString();
374                 if (token != name_)
375                         return;
376         }
377
378         // This is part of the inset proper that is usually swallowed
379         // by Buffer::readInset
380         if (lex.isOK()) {
381                 lex.next();
382                 string const token = lex.getString();
383                 if (token != "External")
384                         return;
385         }
386
387         if (lex.isOK()) {
388                 InsetExternal inset;
389                 inset.read(0, lex);
390                 params = inset.params();
391         }
392 }
393
394
395 string const
396 InsetExternalMailer::params2string(InsetExternal::Params const & params)
397 {
398         InsetExternal inset;
399         inset.setFromParams(params);
400         ostringstream data;
401         data << name_ << ' ';
402         inset.write(0, data);
403         data << "\\end_inset\n";
404         return STRCONV(data.str());
405 }