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