]> git.lyx.org Git - lyx.git/blob - src/insets/insetinclude.C
Enable convertDefault.sh to run even if its executable bit is not set.
[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         write(os);
224 }
225
226
227 void InsetInclude::write(ostream & os) const
228 {
229         os << "Include " << params_.cparams.getCommand() << '\n'
230            << "preview " << tostr(params_.cparams.preview()) << '\n';
231 }
232
233
234 void InsetInclude::read(Buffer const &, LyXLex & lex)
235 {
236         read(lex);
237 }
238
239
240 void InsetInclude::read(LyXLex & lex)
241 {
242         params_.cparams.read(lex);
243
244         if (params_.cparams.getCmdName() == "include")
245                 params_.flag = INCLUDE;
246         else if (params_.cparams.getCmdName() == "input")
247                 params_.flag = INPUT;
248         /* FIXME: is this logic necessary now ? */
249         else if (contains(params_.cparams.getCmdName(), "verbatim")) {
250                 params_.flag = VERB;
251                 if (params_.cparams.getCmdName() == "verbatiminput*")
252                         params_.flag = VERBAST;
253         }
254 }
255
256
257 string const InsetInclude::getScreenLabel(Buffer const &) const
258 {
259         string temp;
260
261         switch (params_.flag) {
262                 case INPUT: temp += _("Input"); break;
263                 case VERB: temp += _("Verbatim Input"); break;
264                 case VERBAST: temp += _("Verbatim Input*"); break;
265                 case INCLUDE: temp += _("Include"); break;
266         }
267
268         temp += ": ";
269
270         if (params_.cparams.getContents().empty())
271                 temp += "???";
272         else
273                 temp += params_.cparams.getContents();
274
275         return temp;
276 }
277
278
279 string const InsetInclude::getFileName() const
280 {
281         return MakeAbsPath(params_.cparams.getContents(),
282                            OnlyPath(getMasterFilename()));
283 }
284
285
286 string const InsetInclude::getMasterFilename() const
287 {
288         return params_.masterFilename_;
289 }
290
291
292 bool InsetInclude::loadIfNeeded() const
293 {
294         if (isVerbatim())
295                 return false;
296
297         if (!IsLyXFilename(getFileName()))
298                 return false;
299
300         if (bufferlist.exists(getFileName()))
301                 return true;
302
303         // the readonly flag can/will be wrong, not anymore I think.
304         FileInfo finfo(getFileName());
305         if (!finfo.isOK())
306                 return false;
307         return loadLyXFile(bufferlist.newBuffer(getFileName()),
308                            getFileName());
309 }
310
311
312 int InsetInclude::latex(Buffer const & buffer, ostream & os,
313                         LatexRunParams const & runparams) const
314 {
315         string incfile(params_.cparams.getContents());
316
317         // Do nothing if no file name has been specified
318         if (incfile.empty())
319                 return 0;
320
321         if (loadIfNeeded()) {
322                 Buffer * tmp = bufferlist.getBuffer(getFileName());
323
324                 // FIXME: this should be a GUI warning
325                 if (tmp->params.textclass != buffer.params.textclass) {
326                         lyxerr << "WARNING: Included file `"
327                                << MakeDisplayPath(getFileName())
328                                << "' has textclass `"
329                                << tmp->params.getLyXTextClass().name()
330                                << "' while parent file has textclass `"
331                                << buffer.params.getLyXTextClass().name()
332                                << "'." << endl;
333                         //return 0;
334                 }
335
336                 // write it to a file (so far the complete file)
337                 string writefile = ChangeExtension(getFileName(), ".tex");
338
339                 if (!buffer.tmppath.empty() && !runparams.nice) {
340                         incfile = subst(incfile, '/','@');
341 #ifdef __EMX__
342                         incfile = subst(incfile, ':', '$');
343 #endif
344                         writefile = AddName(buffer.tmppath, incfile);
345                 } else
346                         writefile = getFileName();
347                 writefile = ChangeExtension(writefile, ".tex");
348                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
349                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
350
351                 tmp->markDepClean(buffer.tmppath);
352
353                 tmp->makeLaTeXFile(writefile, OnlyPath(getMasterFilename()),
354                                    runparams, false);
355         }
356
357         if (isVerbatim()) {
358                 os << '\\' << params_.cparams.getCmdName() << '{' << incfile << '}';
359         } else if (params_.flag == INPUT) {
360                 // \input wants file with extension (default is .tex)
361                 if (!IsLyXFilename(getFileName())) {
362                         os << '\\' << params_.cparams.getCmdName() << '{' << incfile << '}';
363                 } else {
364                         os << '\\' << params_.cparams.getCmdName() << '{'
365                            << ChangeExtension(incfile, ".tex")
366                            <<  '}';
367                 }
368         } else {
369                 // \include don't want extension and demands that the
370                 // file really have .tex
371                 os << '\\' << params_.cparams.getCmdName() << '{'
372                    << ChangeExtension(incfile, string())
373                    << '}';
374         }
375
376         return 0;
377 }
378
379
380 int InsetInclude::ascii(Buffer const &, ostream & os, int) const
381 {
382         if (isVerbatim())
383                 os << GetFileContents(getFileName());
384         return 0;
385 }
386
387
388 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os) const
389 {
390         string incfile(params_.cparams.getContents());
391
392         // Do nothing if no file name has been specified
393         if (incfile.empty())
394                 return 0;
395
396         if (loadIfNeeded()) {
397                 Buffer * tmp = bufferlist.getBuffer(getFileName());
398
399                 // write it to a file (so far the complete file)
400                 string writefile = ChangeExtension(getFileName(), ".sgml");
401                 if (!buffer.tmppath.empty() && !buffer.niceFile) {
402                         incfile = subst(incfile, '/','@');
403                         writefile = AddName(buffer.tmppath, incfile);
404                 } else
405                         writefile = getFileName();
406
407                 if (IsLyXFilename(getFileName()))
408                         writefile = ChangeExtension(writefile, ".sgml");
409
410                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
411                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
412
413                 tmp->makeLinuxDocFile(writefile, buffer.niceFile, true);
414         }
415
416         if (isVerbatim()) {
417                 os << "<![CDATA["
418                    << GetFileContents(getFileName())
419                    << "]]>";
420         } else
421                 os << '&' << include_label << ';';
422
423         return 0;
424 }
425
426
427 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
428                           bool /*mixcont*/) const
429 {
430         string incfile(params_.cparams.getContents());
431
432         // Do nothing if no file name has been specified
433         if (incfile.empty())
434                 return 0;
435
436         if (loadIfNeeded()) {
437                 Buffer * tmp = bufferlist.getBuffer(getFileName());
438
439                 // write it to a file (so far the complete file)
440                 string writefile = ChangeExtension(getFileName(), ".sgml");
441                 if (!buffer.tmppath.empty() && !buffer.niceFile) {
442                         incfile = subst(incfile, '/','@');
443                         writefile = AddName(buffer.tmppath, incfile);
444                 } else
445                         writefile = getFileName();
446                 if (IsLyXFilename(getFileName()))
447                         writefile = ChangeExtension(writefile, ".sgml");
448
449                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
450                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
451
452                 tmp->makeDocBookFile(writefile, buffer.niceFile, true);
453         }
454
455         if (isVerbatim()) {
456                 os << "<inlinegraphic fileref=\""
457                    << '&' << include_label << ';'
458                    << "\" format=\"linespecific\">";
459         } else
460                 os << '&' << include_label << ';';
461
462         return 0;
463 }
464
465
466 void InsetInclude::validate(LaTeXFeatures & features) const
467 {
468
469         string incfile(params_.cparams.getContents());
470         string writefile;
471
472         Buffer const & b = *bufferlist.getBuffer(getMasterFilename());
473
474         if (!b.tmppath.empty() && !b.niceFile && !isVerbatim()) {
475                 incfile = subst(incfile, '/','@');
476                 writefile = AddName(b.tmppath, incfile);
477         } else
478                 writefile = getFileName();
479
480         if (IsLyXFilename(getFileName()))
481                 writefile = ChangeExtension(writefile, ".sgml");
482
483         features.includeFile(include_label, writefile);
484
485         if (isVerbatim())
486                 features.require("verbatim");
487
488         // Here we must do the fun stuff...
489         // Load the file in the include if it needs
490         // to be loaded:
491         if (loadIfNeeded()) {
492                 // a file got loaded
493                 Buffer * const tmp = bufferlist.getBuffer(getFileName());
494                 if (tmp) {
495                         tmp->niceFile = b.niceFile;
496                         tmp->validate(features);
497                 }
498         }
499 }
500
501
502 void InsetInclude::getLabelList(std::vector<string> & list) const
503 {
504         if (loadIfNeeded()) {
505                 Buffer * tmp = bufferlist.getBuffer(getFileName());
506                 tmp->setParentName("");
507                 tmp->getLabelList(list);
508                 tmp->setParentName(getMasterFilename());
509         }
510 }
511
512
513 void InsetInclude::fillWithBibKeys(std::vector<std::pair<string,string> > & keys) const
514 {
515         if (loadIfNeeded()) {
516                 Buffer * tmp = bufferlist.getBuffer(getFileName());
517                 tmp->setParentName("");
518                 tmp->fillWithBibKeys(keys);
519                 tmp->setParentName(getMasterFilename());
520         }
521 }
522
523
524 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
525 {
526         if (preview_->previewReady()) {
527                 dim.asc = preview_->pimage()->ascent();
528                 dim.des = preview_->pimage()->descent();
529                 dim.wid = preview_->pimage()->width();
530         } else {
531                 if (!set_label_) {
532                         set_label_ = true;
533                         button_.update(getScreenLabel(*mi.base.bv->buffer()),
534                                        editable() != NOT_EDITABLE);
535                 }
536                 button_.metrics(mi, dim);
537         }
538         if (params_.flag == INPUT)
539                 center_indent_ = 0;
540         else
541                 center_indent_ = (mi.base.textwidth - dim.wid) / 2;
542         dim.wid = mi.base.textwidth;
543         dim_ = dim;
544 }
545
546
547 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
548 {
549         cache(pi.base.bv);
550         if (!preview_->previewReady()) {
551                 button_.draw(pi, x + center_indent_, y);
552                 return;
553         }
554
555         if (!preview_->monitoring())
556                 preview_->startMonitoring();
557
558         pi.pain.image(x + center_indent_, y - dim_.asc, dim_.wid, dim_.height(),
559                             *(preview_->pimage()->image()));
560 }
561
562
563 BufferView * InsetInclude::view() const
564 {
565         return button_.view();
566 }
567
568
569 //
570 // preview stuff
571 //
572
573 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
574 {
575         preview_->addPreview(ploader);
576 }
577
578
579 bool InsetInclude::PreviewImpl::previewWanted() const
580 {
581         return parent().params_.flag == InsetInclude::INPUT &&
582                 parent().params_.cparams.preview() &&
583                 IsFileReadable(parent().getFileName());
584 }
585
586
587 string const InsetInclude::PreviewImpl::latexString() const
588 {
589         if (!view() || !view()->buffer())
590                 return string();
591
592         ostringstream os;
593         LatexRunParams runparams;
594         runparams.flavor = LatexRunParams::LATEX;
595         parent().latex(*view()->buffer(), os, runparams);
596
597         return STRCONV(os.str());
598 }
599
600
601 void InsetInclude::PreviewImpl::startMonitoring()
602 {
603         monitor_.reset(new FileMonitor(parent().getFileName(), 2000));
604         monitor_->connect(boost::bind(&PreviewImpl::restartLoading, this));
605         monitor_->start();
606 }
607
608
609 void InsetInclude::PreviewImpl::restartLoading()
610 {
611         lyxerr << "restartLoading()" << std::endl;
612         removePreview();
613         if (view())
614                 view()->updateInset(&parent());
615         generatePreview();
616 }
617
618
619 string const InsetIncludeMailer::name_("include");
620
621 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
622         : inset_(inset)
623 {}
624
625
626 string const InsetIncludeMailer::inset2string(Buffer const &) const
627 {
628         return params2string(inset_.params());
629 }
630
631
632 void InsetIncludeMailer::string2params(string const & in,
633                                        InsetInclude::Params & params)
634 {
635         params = InsetInclude::Params();
636
637         if (in.empty())
638                 return;
639
640         istringstream data(STRCONV(in));
641         LyXLex lex(0,0);
642         lex.setStream(data);
643
644         if (lex.isOK()) {
645                 lex.next();
646                 string const token = lex.getString();
647                 if (token != name_)
648                         return;
649         }
650
651         // This is part of the inset proper that is usually swallowed
652         // by Buffer::readInset
653         if (lex.isOK()) {
654                 lex.next();
655                 string const token = lex.getString();
656                 if (token != "Include")
657                         return;
658         }
659
660         if (lex.isOK()) {
661                 InsetInclude inset(params);
662                 inset.read(lex);
663                 params = inset.params();
664         }
665 }
666
667
668 string const
669 InsetIncludeMailer::params2string(InsetInclude::Params const & params)
670 {
671         InsetInclude inset(params);
672         inset.set(params);
673         ostringstream data;
674         data << name_ << ' ';
675         inset.write(data);
676         data << "\\end_inset\n";
677         return STRCONV(data.str());
678 }