]> git.lyx.org Git - lyx.git/blob - src/insets/insetinclude.C
Pass struct LatexRunParams around a bit...
[lyx.git] / src / insets / insetinclude.C
1 /**
2  * \file insetinclude.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "insetinclude.h"
14 #include "buffer.h"
15 #include "bufferlist.h"
16 #include "BufferView.h"
17 #include "debug.h"
18 #include "funcrequest.h"
19 #include "gettext.h"
20 #include "LaTeXFeatures.h"
21 #include "latexrunparams.h"
22 #include "Lsstream.h"
23 #include "lyxlex.h"
24 #include "lyxrc.h"
25 #include "Lsstream.h"
26
27 #include "frontends/Dialogs.h"
28 #include "frontends/LyXView.h"
29 #include "frontends/Painter.h"
30
31 #include "support/filetools.h"
32 #include "support/FileInfo.h"
33 #include "support/FileMonitor.h"
34 #include "support/lstrings.h" // contains
35 #include "support/tostr.h"
36
37 #include "graphics/PreviewedInset.h"
38 #include "graphics/PreviewImage.h"
39
40 #include <boost/bind.hpp>
41
42 #include <cstdlib>
43
44 using std::ostream;
45 using std::endl;
46 using std::vector;
47 using std::pair;
48
49 extern BufferList bufferlist;
50
51
52 class InsetInclude::PreviewImpl : public grfx::PreviewedInset {
53 public:
54         ///
55         PreviewImpl(InsetInclude & p) : PreviewedInset(p) {}
56
57         ///
58         bool previewWanted() const;
59         ///
60         string const latexString() const;
61         ///
62         InsetInclude & parent() const {
63                 return *static_cast<InsetInclude*>(inset());
64         }
65
66         ///
67         bool monitoring() const { return monitor_.get(); }
68         ///
69         void startMonitoring();
70         ///
71         void stopMonitoring() { monitor_.reset(); }
72
73 private:
74         /// Invoked by monitor_ should the parent file change.
75         void restartLoading();
76         ///
77         boost::scoped_ptr<FileMonitor> monitor_;
78 };
79
80
81 namespace {
82
83 string const uniqueID()
84 {
85         static unsigned int seed = 1000;
86         return "file" + tostr(++seed);
87 }
88
89 } // namespace anon
90
91
92 InsetInclude::InsetInclude(Params const & p)
93         : params_(p), include_label(uniqueID()),
94           preview_(new PreviewImpl(*this))
95 {}
96
97
98 InsetInclude::InsetInclude(InsetCommandParams const & p, Buffer const & b)
99         : include_label(uniqueID()),
100           preview_(new PreviewImpl(*this))
101 {
102         params_.cparams = p;
103         params_.masterFilename_ = b.fileName();
104 }
105
106
107 InsetInclude::~InsetInclude()
108 {
109         InsetIncludeMailer mailer(*this);
110         mailer.hideDialog();
111 }
112
113
114 dispatch_result InsetInclude::localDispatch(FuncRequest const & cmd)
115 {
116         switch (cmd.action) {
117
118         case LFUN_INSET_MODIFY: {
119                 InsetInclude::Params p;
120                 InsetIncludeMailer::string2params(cmd.argument, p);
121                 if (!p.cparams.getCmdName().empty()) {
122                         set(p);
123                         params_.masterFilename_ = cmd.view()->buffer()->fileName();
124                         cmd.view()->updateInset(this);
125                 }
126                 return DISPATCHED;
127         }
128
129         case LFUN_INSET_DIALOG_UPDATE: 
130                 InsetIncludeMailer(*this).updateDialog(cmd.view());
131                 return DISPATCHED;
132
133         case LFUN_MOUSE_RELEASE:
134         case LFUN_INSET_EDIT:
135                 InsetIncludeMailer(*this).showDialog(cmd.view());
136                 return DISPATCHED;
137
138         default:
139                 return UNDISPATCHED;
140         }
141 }
142
143
144 InsetInclude::Params const & InsetInclude::params() const
145 {
146         return params_;
147 }
148
149
150 bool InsetInclude::Params::operator==(Params const & o) const
151 {
152         return cparams == o.cparams && flag == o.flag &&
153             masterFilename_ == o.masterFilename_;
154 }
155
156
157 bool InsetInclude::Params::operator!=(Params const & o) const
158 {
159         return !(*this == o);
160 }
161
162
163 void InsetInclude::set(Params const & p)
164 {
165         params_ = p;
166
167         string command;
168
169         switch (params_.flag) {
170                 case INCLUDE:
171                         command="include";
172                         break;
173                 case VERB:
174                         command="verbatiminput";
175                         break;
176                 case INPUT:
177                         command="input";
178                         break;
179                 case VERBAST:
180                         command="verbatiminput*";
181                         break;
182         }
183
184         params_.cparams.setCmdName(command);
185
186         if (preview_->monitoring())
187                 preview_->stopMonitoring();
188
189         if (grfx::PreviewedInset::activated() && params_.flag == INPUT)
190                 preview_->generatePreview();
191 }
192
193
194 Inset * InsetInclude::clone(Buffer const & buffer, bool) const
195 {
196         Params p(params_);
197         p.masterFilename_ = buffer.fileName();
198
199         return new InsetInclude(p);
200 }
201
202
203 void InsetInclude::write(Buffer const *, ostream & os) const
204 {
205         os << "Include " << params_.cparams.getCommand() << '\n'
206            << "preview " << tostr(params_.cparams.preview()) << '\n';
207 }
208
209
210 void InsetInclude::read(Buffer const *, LyXLex & lex)
211 {
212         params_.cparams.read(lex);
213
214         if (params_.cparams.getCmdName() == "include")
215                 params_.flag = INCLUDE;
216         else if (params_.cparams.getCmdName() == "input")
217                 params_.flag = INPUT;
218         /* FIXME: is this logic necessary now ? */
219         else if (contains(params_.cparams.getCmdName(), "verbatim")) {
220                 params_.flag = VERB;
221                 if (params_.cparams.getCmdName() == "verbatiminput*")
222                         params_.flag = VERBAST;
223         }
224 }
225
226
227 bool InsetInclude::display() const
228 {
229         return !(params_.flag == INPUT);
230 }
231
232
233 string const InsetInclude::getScreenLabel(Buffer const *) const
234 {
235         string temp;
236
237         switch (params_.flag) {
238                 case INPUT: temp += _("Input"); break;
239                 case VERB: temp += _("Verbatim Input"); break;
240                 case VERBAST: temp += _("Verbatim Input*"); break;
241                 case INCLUDE: temp += _("Include"); break;
242         }
243
244         temp += ": ";
245
246         if (params_.cparams.getContents().empty())
247                 temp += "???";
248         else
249                 temp += params_.cparams.getContents();
250
251         return temp;
252 }
253
254
255 string const InsetInclude::getFileName() const
256 {
257         return MakeAbsPath(params_.cparams.getContents(),
258                            OnlyPath(getMasterFilename()));
259 }
260
261
262 string const InsetInclude::getMasterFilename() const
263 {
264         return params_.masterFilename_;
265 }
266
267
268 bool InsetInclude::loadIfNeeded() const
269 {
270         if (isVerbatim())
271                 return false;
272
273         if (!IsLyXFilename(getFileName()))
274                 return false;
275
276         if (bufferlist.exists(getFileName()))
277                 return true;
278
279         // the readonly flag can/will be wrong, not anymore I think.
280         FileInfo finfo(getFileName());
281         if (!finfo.isOK())
282                 return false;
283
284         return bufferlist.loadLyXFile(getFileName(), false) != 0;
285 }
286
287
288 int InsetInclude::latex(Buffer const * buffer, ostream & os,
289                         LatexRunParams const & runparams,
290                         bool /*fragile*/, bool /*fs*/) const
291 {
292         string incfile(params_.cparams.getContents());
293
294         // Do nothing if no file name has been specified
295         if (incfile.empty())
296                 return 0;
297
298         if (loadIfNeeded()) {
299                 Buffer * tmp = bufferlist.getBuffer(getFileName());
300
301                 // FIXME: this should be a GUI warning
302                 if (tmp->params.textclass != buffer->params.textclass) {
303                         lyxerr << "WARNING: Included file `"
304                                << MakeDisplayPath(getFileName())
305                                << "' has textclass `"
306                                << tmp->params.getLyXTextClass().name()
307                                << "' while parent file has textclass `"
308                                << buffer->params.getLyXTextClass().name()
309                                << "'." << endl;
310                         //return 0;
311                 }
312
313                 // write it to a file (so far the complete file)
314                 string writefile = ChangeExtension(getFileName(), ".tex");
315
316                 if (!buffer->tmppath.empty()
317                     && !buffer->niceFile) {
318                         incfile = subst(incfile, '/','@');
319 #ifdef __EMX__
320                         incfile = subst(incfile, ':', '$');
321 #endif
322                         writefile = AddName(buffer->tmppath, incfile);
323                 } else
324                         writefile = getFileName();
325                 writefile = ChangeExtension(writefile, ".tex");
326                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
327                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
328
329                 tmp->markDepClean(buffer->tmppath);
330
331                 tmp->makeLaTeXFile(writefile,
332                                    OnlyPath(getMasterFilename()),
333                                    runparams,
334                                    buffer->niceFile, true);
335         }
336
337         if (isVerbatim()) {
338                 os << '\\' << params_.cparams.getCmdName() << '{' << incfile << '}';
339         } else if (params_.flag == INPUT) {
340                 // \input wants file with extension (default is .tex)
341                 if (!IsLyXFilename(getFileName())) {
342                         os << '\\' << params_.cparams.getCmdName() << '{' << incfile << '}';
343                 } else {
344                         os << '\\' << params_.cparams.getCmdName() << '{'
345                            << ChangeExtension(incfile, ".tex")
346                            <<  '}';
347                 }
348         } else {
349                 // \include don't want extension and demands that the
350                 // file really have .tex
351                 os << '\\' << params_.cparams.getCmdName() << '{'
352                    << ChangeExtension(incfile, string())
353                    << '}';
354         }
355
356         return 0;
357 }
358
359
360 int InsetInclude::ascii(Buffer const *, ostream & os, int) const
361 {
362         if (isVerbatim())
363                 os << GetFileContents(getFileName());
364         return 0;
365 }
366
367
368 int InsetInclude::linuxdoc(Buffer const * buffer, ostream & os) const
369 {
370         string incfile(params_.cparams.getContents());
371
372         // Do nothing if no file name has been specified
373         if (incfile.empty())
374                 return 0;
375
376         if (loadIfNeeded()) {
377                 Buffer * tmp = bufferlist.getBuffer(getFileName());
378
379                 // write it to a file (so far the complete file)
380                 string writefile = ChangeExtension(getFileName(), ".sgml");
381                 if (!buffer->tmppath.empty() && !buffer->niceFile) {
382                         incfile = subst(incfile, '/','@');
383                         writefile = AddName(buffer->tmppath, incfile);
384                 } else
385                         writefile = getFileName();
386
387                 if (IsLyXFilename(getFileName()))
388                         writefile = ChangeExtension(writefile, ".sgml");
389
390                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
391                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
392
393                 tmp->makeLinuxDocFile(writefile, buffer->niceFile, true);
394         }
395
396         if (isVerbatim()) {
397                 os << "<![CDATA["
398                    << GetFileContents(getFileName())
399                    << "]]>";
400         } else
401                 os << '&' << include_label << ';';
402
403         return 0;
404 }
405
406
407 int InsetInclude::docbook(Buffer const * buffer, ostream & os,
408                           bool /*mixcont*/) const
409 {
410         string incfile(params_.cparams.getContents());
411
412         // Do nothing if no file name has been specified
413         if (incfile.empty())
414                 return 0;
415
416         if (loadIfNeeded()) {
417                 Buffer * tmp = bufferlist.getBuffer(getFileName());
418
419                 // write it to a file (so far the complete file)
420                 string writefile = ChangeExtension(getFileName(), ".sgml");
421                 if (!buffer->tmppath.empty() && !buffer->niceFile) {
422                         incfile = subst(incfile, '/','@');
423                         writefile = AddName(buffer->tmppath, incfile);
424                 } else
425                         writefile = getFileName();
426                 if (IsLyXFilename(getFileName()))
427                         writefile = ChangeExtension(writefile, ".sgml");
428
429                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
430                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
431
432                 tmp->makeDocBookFile(writefile, buffer->niceFile, true);
433         }
434
435         if (isVerbatim()) {
436                 os << "<inlinegraphic fileref=\""
437                    << '&' << include_label << ';'
438                    << "\" format=\"linespecific\">";
439         } else
440                 os << '&' << include_label << ';';
441
442         return 0;
443 }
444
445
446 void InsetInclude::validate(LaTeXFeatures & features) const
447 {
448
449         string incfile(params_.cparams.getContents());
450         string writefile;
451
452         Buffer const * const b = bufferlist.getBuffer(getMasterFilename());
453
454         if (b && !b->tmppath.empty() && !b->niceFile && !isVerbatim()) {
455                 incfile = subst(incfile, '/','@');
456                 writefile = AddName(b->tmppath, incfile);
457         } else
458                 writefile = getFileName();
459
460         if (IsLyXFilename(getFileName()))
461                 writefile = ChangeExtension(writefile, ".sgml");
462
463         features.includeFile(include_label, writefile);
464
465         if (isVerbatim())
466                 features.require("verbatim");
467
468         // Here we must do the fun stuff...
469         // Load the file in the include if it needs
470         // to be loaded:
471         if (loadIfNeeded()) {
472                 // a file got loaded
473                 Buffer * const tmp = bufferlist.getBuffer(getFileName());
474                 if (tmp) {
475                         if (b)
476                                 tmp->niceFile = b->niceFile;
477                         tmp->validate(features);
478                 }
479         }
480 }
481
482
483 vector<string> const InsetInclude::getLabelList() const
484 {
485         vector<string> l;
486
487         if (loadIfNeeded()) {
488                 Buffer * tmp = bufferlist.getBuffer(getFileName());
489                 tmp->setParentName("");
490                 l = tmp->getLabelList();
491                 tmp->setParentName(getMasterFilename());
492         }
493
494         return l;
495 }
496
497
498 void InsetInclude::fillWithBibKeys(vector<pair<string,string> > & keys) const
499 {
500         if (loadIfNeeded()) {
501                 Buffer * tmp = bufferlist.getBuffer(getFileName());
502                 tmp->setParentName("");
503                 tmp->fillWithBibKeys(keys);
504                 tmp->setParentName(getMasterFilename());
505         }
506 }
507
508
509 int InsetInclude::ascent(BufferView * bv, LyXFont const & font) const
510 {
511         return preview_->previewReady() ?
512                 preview_->pimage()->ascent() : InsetButton::ascent(bv, font);
513 }
514
515
516 int InsetInclude::descent(BufferView * bv, LyXFont const & font) const
517 {
518         return preview_->previewReady() ?
519                 preview_->pimage()->descent() : InsetButton::descent(bv, font);
520 }
521
522
523 int InsetInclude::width(BufferView * bv, LyXFont const & font) const
524 {
525         return preview_->previewReady() ?
526                 preview_->pimage()->width() : InsetButton::width(bv, font);
527 }
528
529
530 void InsetInclude::draw(BufferView * bv, LyXFont const & font, int y,
531                         float & xx) const
532 {
533         cache(bv);
534         if (!preview_->previewReady()) {
535                 InsetButton::draw(bv, font, y, xx);
536                 return;
537         }
538
539         if (!preview_->monitoring())
540                 preview_->startMonitoring();
541
542         int const x = int(xx);
543         int const w = width(bv, font);
544         int const d = descent(bv, font);
545         int const a = ascent(bv, font);
546         int const h = a + d;
547
548         bv->painter().image(x, y - a, w, h,
549                             *(preview_->pimage()->image()));
550
551         xx += w;
552 }
553
554
555 //
556 // preview stuff
557 //
558
559 void InsetInclude::addPreview(grfx::PreviewLoader & ploader) const
560 {
561         preview_->addPreview(ploader);
562 }
563
564
565 bool InsetInclude::PreviewImpl::previewWanted() const
566 {
567         return parent().params_.flag == InsetInclude::INPUT &&
568                 parent().params_.cparams.preview() &&
569                 IsFileReadable(parent().getFileName());
570 }
571
572
573 string const InsetInclude::PreviewImpl::latexString() const
574 {
575         if (!view() || !view()->buffer())
576                 return string();
577
578         ostringstream os;
579         LatexRunParams runparams;
580         runparams.flavor = LatexRunParams::LATEX;
581         parent().latex(view()->buffer(), os, runparams, false, false);
582
583         return STRCONV(os.str());
584 }
585
586
587 void InsetInclude::PreviewImpl::startMonitoring()
588 {
589         monitor_.reset(new FileMonitor(parent().getFileName(), 2000));
590         monitor_->connect(boost::bind(&PreviewImpl::restartLoading, this));
591         monitor_->start();
592 }
593
594
595 void InsetInclude::PreviewImpl::restartLoading()
596 {
597         lyxerr << "restartLoading()" << std::endl;
598         removePreview();
599         if (view())
600                 view()->updateInset(&parent());
601         generatePreview();
602 }
603
604
605 string const InsetIncludeMailer::name_("include");
606
607 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
608         : inset_(inset)
609 {}
610
611
612 string const InsetIncludeMailer::inset2string() const
613 {
614         return params2string(inset_.params());
615 }
616
617
618 void InsetIncludeMailer::string2params(string const & in,
619                                        InsetInclude::Params & params)
620 {
621         params = InsetInclude::Params();
622
623         if (in.empty())
624                 return;
625         
626         istringstream data(STRCONV(in));
627         LyXLex lex(0,0);
628         lex.setStream(data);
629
630         if (lex.isOK()) {
631                 lex.next();
632                 string const token = lex.getString();
633                 if (token != name_)
634                         return;
635         }
636
637         // This is part of the inset proper that is usually swallowed
638         // by Buffer::readInset
639         if (lex.isOK()) {
640                 lex.next();
641                 string const token = lex.getString();
642                 if (token != "Include")
643                         return;
644         }
645
646         if (lex.isOK()) {
647                 InsetInclude inset(params);
648                 inset.read(0, lex);
649                 params = inset.params();
650         }
651 }
652
653
654 string const
655 InsetIncludeMailer::params2string(InsetInclude::Params const & params)
656 {
657         InsetInclude inset(params);
658         inset.set(params);
659         ostringstream data;
660         data << name_ << ' ';
661         inset.write(0, data);
662         data << "\\end_inset\n";
663         return STRCONV(data.str());
664 }