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