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