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