]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
cosmetics
[lyx.git] / src / insets / InsetInclude.cpp
1 /**
2  * \file InsetInclude.cpp
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  * \author Richard Heck (conversion to InsetCommand)
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetInclude.h"
15
16 #include "Buffer.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "Cursor.h"
22 #include "debug.h"
23 #include "DispatchResult.h"
24 #include "Exporter.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.h"
27 #include "gettext.h"
28 #include "LaTeXFeatures.h"
29 #include "LyX.h"
30 #include "LyXRC.h"
31 #include "Lexer.h"
32 #include "MetricsInfo.h"
33 #include "OutputParams.h"
34 #include "TocBackend.h"
35 #include "TextClass.h"
36
37 #include "frontends/alert.h"
38 #include "frontends/Painter.h"
39
40 #include "graphics/PreviewImage.h"
41 #include "graphics/PreviewLoader.h"
42
43 #include "insets/RenderPreview.h"
44 #include "insets/InsetListingsParams.h"
45
46 #include "support/docstream.h"
47 #include "support/filetools.h"
48 #include "support/lstrings.h" // contains
49 #include "support/lyxalgo.h"
50 #include "support/lyxlib.h"
51 #include "support/convert.h"
52
53 #include <boost/bind.hpp>
54
55
56 namespace lyx {
57
58 using support::addName;
59 using support::absolutePath;
60 using support::bformat;
61 using support::changeExtension;
62 using support::contains;
63 using support::copy;
64 using support::DocFileName;
65 using support::FileName;
66 using support::getVectorFromString;
67 using support::isLyXFilename;
68 using support::isValidLaTeXFilename;
69 using support::latex_path;
70 using support::makeAbsPath;
71 using support::makeRelPath;
72 using support::onlyFilename;
73 using support::onlyPath;
74 using support::prefixIs;
75 using support::subst;
76 using support::sum;
77
78 using std::endl;
79 using std::find;
80 using std::string;
81 using std::istringstream;
82 using std::ostream;
83 using std::ostringstream;
84 using std::vector;
85
86 namespace Alert = frontend::Alert;
87
88
89 namespace {
90
91 docstring const uniqueID()
92 {
93         static unsigned int seed = 1000;
94         return "file" + convert<docstring>(++seed);
95 }
96
97
98 /// the type of inclusion
99 enum Types {
100         INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
101 };
102
103
104 Types type(std::string const & s)
105 {
106         if (s == "input")
107                 return INPUT;
108         if (s == "verbatiminput")
109                 return VERB;
110         if (s == "verbatiminput*")
111                 return VERBAST;
112         if (s == "lstinputlisting")
113                 return LISTINGS;
114         if (s == "include")
115                 return INCLUDE;
116         return NONE;
117 }
118
119
120 Types type(InsetCommandParams const & params)
121 {
122         return type(params.getCmdName());
123 }
124
125
126 bool isListings(InsetCommandParams const & params)
127 {
128         return type(params) == LISTINGS;
129 }
130
131
132 bool isVerbatim(InsetCommandParams const & params)
133 {
134         Types const t = type(params);
135         return t == VERB || t == VERBAST;
136 }
137
138
139 bool isInputOrInclude(InsetCommandParams const & params)
140 {
141         Types const t = type(params);
142         return t == INPUT || t == INCLUDE;
143 }
144
145 } // namespace anon
146
147
148 InsetInclude::InsetInclude(InsetCommandParams const & p)
149         : InsetCommand(p, "include"), include_label(uniqueID()),
150           preview_(new RenderMonitoredPreview(this)), set_label_(false)
151 {
152         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
153 }
154
155
156 InsetInclude::InsetInclude(InsetInclude const & other)
157         : InsetCommand(other), include_label(other.include_label),
158           preview_(new RenderMonitoredPreview(this)), set_label_(false)
159 {
160         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
161 }
162
163
164 CommandInfo const * InsetInclude::findInfo(std::string const & /* cmdName */)
165 {
166         // This is only correct for the case of listings, but it'll do for now.
167         // In the other cases, this second parameter should just be empty.
168         static const char * const paramnames[] = {"filename", "lstparams", ""};
169         static const bool isoptional[] = {false, true};
170         static const CommandInfo info = {2, paramnames, isoptional};
171         return &info;
172 }
173
174
175 bool InsetInclude::isCompatibleCommand(std::string const & s)
176 {
177         return type(s) != NONE;
178 }
179
180
181 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
182 {
183         switch (cmd.action) {
184
185         case LFUN_INSET_MODIFY: {
186                 InsetCommandParams p(INCLUDE_CODE);
187                 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
188                 if (!p.getCmdName().empty()) {
189                         if (isListings(p)){
190                                 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
191                                 InsetListingsParams par_new(to_utf8(p["lstparams"]));
192                                 if (par_old.getParamValue("label") !=
193                                     par_new.getParamValue("label")
194                                     && !par_new.getParamValue("label").empty())
195                                         cur.bv().buffer().changeRefsIfUnique(
196                                                 from_utf8(par_old.getParamValue("label")),
197                                                 from_utf8(par_new.getParamValue("label")),
198                                                 REF_CODE);
199                         }
200                         set(p, cur.buffer());
201                         cur.buffer().updateBibfilesCache();
202                 } else
203                         cur.noUpdate();
204                 break;
205         }
206
207         //pass everything else up the chain
208         default:
209                 InsetCommand::doDispatch(cur, cmd);
210                 break;
211         }
212 }
213
214
215 namespace {
216
217 FileName const masterFileName(Buffer const & buffer)
218 {
219         return buffer.masterBuffer()->fileName();
220 }
221
222
223 string const parentFilename(Buffer const & buffer)
224 {
225         return buffer.absFileName();
226 }
227
228
229 FileName const includedFilename(Buffer const & buffer,
230                               InsetCommandParams const & params)
231 {
232         return makeAbsPath(to_utf8(params["filename"]),
233                onlyPath(parentFilename(buffer)));
234 }
235
236
237 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
238
239 } // namespace anon
240
241
242 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
243 {
244         setParams(p);
245         set_label_ = false;
246
247         if (preview_->monitoring())
248                 preview_->stopMonitoring();
249
250         if (type(params()) == INPUT)
251                 add_preview(*preview_, *this, buffer);
252 }
253
254
255 Inset * InsetInclude::clone() const
256 {
257         return new InsetInclude(*this);
258 }
259
260
261 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
262 {
263         docstring temp;
264
265         switch (type(params())) {
266                 case INPUT:
267                         temp = buf.B_("Input");
268                         break;
269                 case VERB:
270                         temp = buf.B_("Verbatim Input");
271                         break;
272                 case VERBAST:
273                         temp = buf.B_("Verbatim Input*");
274                         break;
275                 case INCLUDE:
276                         temp = buf.B_("Include");
277                         break;
278                 case LISTINGS:
279                         temp = listings_label_;
280                 case NONE:
281                         BOOST_ASSERT(false);
282         }
283
284         temp += ": ";
285
286         if (params()["filename"].empty())
287                 temp += "???";
288         else
289                 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
290
291         return temp;
292 }
293
294
295 namespace {
296
297 /// return the child buffer if the file is a LyX doc and is loaded
298 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
299 {
300         if (isVerbatim(params) || isListings(params))
301                 return 0;
302
303         string const included_file = includedFilename(buffer, params).absFilename();
304         if (!isLyXFilename(included_file))
305                 return 0;
306
307         Buffer * childBuffer = theBufferList().getBuffer(included_file);
308
309         //FIXME RECURSIVE INCLUDES
310         if (childBuffer == & buffer)
311                 return 0;
312         else
313                 return childBuffer;
314 }
315
316 } // namespace anon
317
318
319 /// return true if the file is or got loaded.
320 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
321 {
322         if (isVerbatim(params) || isListings(params))
323                 return 0;
324
325         string const parent_filename = parent.absFileName();
326         FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
327                            onlyPath(parent_filename));
328
329         if (!isLyXFilename(included_file.absFilename()))
330                 return 0;
331
332         Buffer * child = theBufferList().getBuffer(included_file.absFilename());
333         if (!child) {
334                 // the readonly flag can/will be wrong, not anymore I think.
335                 if (!included_file.exists())
336                         return 0;
337
338                 child = theBufferList().newBuffer(included_file.absFilename());
339                 if (!child->loadLyXFile(included_file)) {
340                         //close the buffer we just opened
341                         theBufferList().close(child, false);
342                         return 0;
343                 }
344         }
345         child->setParentName(parent_filename);
346         return child;
347 }
348
349
350 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
351                         OutputParams const & runparams) const
352 {
353         string incfile(to_utf8(params()["filename"]));
354
355         // Do nothing if no file name has been specified
356         if (incfile.empty())
357                 return 0;
358
359         FileName const included_file = includedFilename(buffer, params());
360
361         //Check we're not trying to include ourselves.
362         //FIXME RECURSIVE INCLUDE
363         //This isn't sufficient, as the inclusion could be downstream.
364         //But it'll have to do for now.
365         if (isInputOrInclude(params()) &&
366                 buffer.absFileName() == included_file.absFilename())
367         {
368                 Alert::error(_("Recursive input"),
369                                bformat(_("Attempted to include file %1$s in itself! "
370                                "Ignoring inclusion."), from_utf8(incfile)));
371                 return 0;
372         }
373
374         Buffer const * const masterBuffer = buffer.masterBuffer();
375
376         // if incfile is relative, make it relative to the master
377         // buffer directory.
378         if (!absolutePath(incfile)) {
379                 // FIXME UNICODE
380                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
381                                               from_utf8(masterBuffer->filePath())));
382         }
383
384         // write it to a file (so far the complete file)
385         string const exportfile = changeExtension(incfile, ".tex");
386         string const mangled =
387                 DocFileName(changeExtension(included_file.absFilename(),".tex")).
388                         mangledFilename();
389         FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
390
391         if (!runparams.nice)
392                 incfile = mangled;
393         else if (!isValidLaTeXFilename(incfile)) {
394                 frontend::Alert::warning(_("Invalid filename"),
395                                          _("The following filename is likely to cause trouble "
396                                            "when running the exported file through LaTeX: ") +
397                                             from_utf8(incfile));
398         }
399         LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
400         LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
401         LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
402
403         if (runparams.inComment || runparams.dryrun) {
404                 //Don't try to load or copy the file if we're
405                 //in a comment or doing a dryrun
406         } else if (isInputOrInclude(params()) &&
407                  isLyXFilename(included_file.absFilename())) {
408                 //if it's a LyX file and we're inputting or including,
409                 //try to load it so we can write the associated latex
410                 if (!loadIfNeeded(buffer, params()))
411                         return false;
412
413                 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
414
415                 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
416                         // FIXME UNICODE
417                         docstring text = bformat(_("Included file `%1$s'\n"
418                                                 "has textclass `%2$s'\n"
419                                                              "while parent file has textclass `%3$s'."),
420                                               included_file.displayName(),
421                                               from_utf8(tmp->params().getTextClass().name()),
422                                               from_utf8(masterBuffer->params().getTextClass().name()));
423                         Alert::warning(_("Different textclasses"), text);
424                         //return 0;
425                 }
426
427                 // Make sure modules used in child are all included in master
428                 //FIXME It might be worth loading the children's modules into the master
429                 //over in BufferParams rather than doing this check.
430                 vector<string> const masterModules = masterBuffer->params().getModules();
431                 vector<string> const childModules = tmp->params().getModules();
432                 vector<string>::const_iterator it = childModules.begin();
433                 vector<string>::const_iterator end = childModules.end();
434                 for (; it != end; ++it) {
435                         string const module = *it;
436                         vector<string>::const_iterator found =
437                                 find(masterModules.begin(), masterModules.end(), module);
438                         if (found != masterModules.end()) {
439                                 docstring text = bformat(_("Included file `%1$s'\n"
440                                                         "uses module `%2$s'\n"
441                                                         "which is not used in parent file."),
442                                        included_file.displayName(), from_utf8(module));
443                                 Alert::warning(_("Module not found"), text);
444                         }
445                 }
446
447                 tmp->markDepClean(masterBuffer->temppath());
448
449 // FIXME: handle non existing files
450 // FIXME: Second argument is irrelevant!
451 // since only_body is true, makeLaTeXFile will not look at second
452 // argument. Should we set it to string(), or should makeLaTeXFile
453 // make use of it somehow? (JMarc 20031002)
454                 // The included file might be written in a different encoding
455                 Encoding const * const oldEnc = runparams.encoding;
456                 runparams.encoding = &tmp->params().encoding();
457                 tmp->makeLaTeXFile(writefile,
458                                    masterFileName(buffer).onlyPath(),
459                                    runparams, false);
460                 runparams.encoding = oldEnc;
461         } else {
462                 // In this case, it's not a LyX file, so we copy the file
463                 // to the temp dir, so that .aux files etc. are not created
464                 // in the original dir. Files included by this file will be
465                 // found via input@path, see ../Buffer.cpp.
466                 unsigned long const checksum_in  = sum(included_file);
467                 unsigned long const checksum_out = sum(writefile);
468
469                 if (checksum_in != checksum_out) {
470                         if (!copy(included_file, writefile)) {
471                                 // FIXME UNICODE
472                                 LYXERR(Debug::LATEX)
473                                         << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
474                                                                   "into the temporary directory."),
475                                                    from_utf8(included_file.absFilename())))
476                                         << endl;
477                                 return 0;
478                         }
479                 }
480         }
481
482         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
483                         "latex" : "pdflatex";
484         if (isVerbatim(params())) {
485                 incfile = latex_path(incfile);
486                 // FIXME UNICODE
487                 os << '\\' << from_ascii(params().getCmdName()) << '{'
488                    << from_utf8(incfile) << '}';
489         } else if (type(params()) == INPUT) {
490                 runparams.exportdata->addExternalFile(tex_format, writefile,
491                                                       exportfile);
492
493                 // \input wants file with extension (default is .tex)
494                 if (!isLyXFilename(included_file.absFilename())) {
495                         incfile = latex_path(incfile);
496                         // FIXME UNICODE
497                         os << '\\' << from_ascii(params().getCmdName())
498                            << '{' << from_utf8(incfile) << '}';
499                 } else {
500                 incfile = changeExtension(incfile, ".tex");
501                 incfile = latex_path(incfile);
502                         // FIXME UNICODE
503                         os << '\\' << from_ascii(params().getCmdName())
504                            << '{' << from_utf8(incfile) <<  '}';
505                 }
506         } else if (type(params()) == LISTINGS) {
507                 os << '\\' << from_ascii(params().getCmdName());
508                 string const opt = to_utf8(params()["lstparams"]);
509                 // opt is set in QInclude dialog and should have passed validation.
510                 InsetListingsParams params(opt);
511                 if (!params.params().empty())
512                         os << "[" << from_utf8(params.params()) << "]";
513                 os << '{'  << from_utf8(incfile) << '}';
514         } else {
515                 runparams.exportdata->addExternalFile(tex_format, writefile,
516                                                       exportfile);
517
518                 // \include don't want extension and demands that the
519                 // file really have .tex
520                 incfile = changeExtension(incfile, string());
521                 incfile = latex_path(incfile);
522                 // FIXME UNICODE
523                 os << '\\' << from_ascii(params().getCmdName()) << '{'
524                    << from_utf8(incfile) << '}';
525         }
526
527         return 0;
528 }
529
530
531 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
532                             OutputParams const &) const
533 {
534         if (isVerbatim(params()) || isListings(params())) {
535                 os << '[' << getScreenLabel(buffer) << '\n';
536                 // FIXME: We don't know the encoding of the file
537                 docstring const str =
538                      from_utf8(includedFilename(buffer, params()).fileContents());
539                 os << str;
540                 os << "\n]";
541                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
542         } else {
543                 docstring const str = '[' + getScreenLabel(buffer) + ']';
544                 os << str;
545                 return str.size();
546         }
547 }
548
549
550 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
551                           OutputParams const & runparams) const
552 {
553         string incfile = to_utf8(params()["filename"]);
554
555         // Do nothing if no file name has been specified
556         if (incfile.empty())
557                 return 0;
558
559         string const included_file = includedFilename(buffer, params()).absFilename();
560
561         //Check we're not trying to include ourselves.
562         //FIXME RECURSIVE INCLUDE
563         //This isn't sufficient, as the inclusion could be downstream.
564         //But it'll have to do for now.
565         if (buffer.absFileName() == included_file) {
566                 Alert::error(_("Recursive input"),
567                                bformat(_("Attempted to include file %1$s in itself! "
568                                "Ignoring inclusion."), from_utf8(incfile)));
569                 return 0;
570         }
571
572         // write it to a file (so far the complete file)
573         string const exportfile = changeExtension(incfile, ".sgml");
574         DocFileName writefile(changeExtension(included_file, ".sgml"));
575
576         if (loadIfNeeded(buffer, params())) {
577                 Buffer * tmp = theBufferList().getBuffer(included_file);
578
579                 string const mangled = writefile.mangledFilename();
580                 writefile = makeAbsPath(mangled,
581                                         buffer.masterBuffer()->temppath());
582                 if (!runparams.nice)
583                         incfile = mangled;
584
585                 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
586                 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
587                 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
588
589                 tmp->makeDocBookFile(writefile, runparams, true);
590         }
591
592         runparams.exportdata->addExternalFile("docbook", writefile,
593                                               exportfile);
594         runparams.exportdata->addExternalFile("docbook-xml", writefile,
595                                               exportfile);
596
597         if (isVerbatim(params()) || isListings(params())) {
598                 os << "<inlinegraphic fileref=\""
599                    << '&' << include_label << ';'
600                    << "\" format=\"linespecific\">";
601         } else
602                 os << '&' << include_label << ';';
603
604         return 0;
605 }
606
607
608 void InsetInclude::validate(LaTeXFeatures & features) const
609 {
610         string incfile = to_utf8(params()["filename"]);
611         string writefile;
612
613         Buffer const & buffer = features.buffer();
614
615         string const included_file = includedFilename(buffer, params()).absFilename();
616
617         if (isLyXFilename(included_file))
618                 writefile = changeExtension(included_file, ".sgml");
619         else
620                 writefile = included_file;
621
622         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
623                 incfile = DocFileName(writefile).mangledFilename();
624                 writefile = makeAbsPath(incfile,
625                                         buffer.masterBuffer()->temppath()).absFilename();
626         }
627
628         features.includeFile(include_label, writefile);
629
630         if (isVerbatim(params()))
631                 features.require("verbatim");
632         else if (isListings(params()))
633                 features.require("listings");
634
635         // Here we must do the fun stuff...
636         // Load the file in the include if it needs
637         // to be loaded:
638         if (loadIfNeeded(buffer, params())) {
639                 // a file got loaded
640                 Buffer * const tmp = theBufferList().getBuffer(included_file);
641                 // make sure the buffer isn't us
642                 // FIXME RECURSIVE INCLUDES
643                 // This is not sufficient, as recursive includes could be
644                 // more than a file away. But it will do for now.
645                 if (tmp && tmp != & buffer) {
646                         // We must temporarily change features.buffer,
647                         // otherwise it would always be the master buffer,
648                         // and nested includes would not work.
649                         features.setBuffer(*tmp);
650                         tmp->validate(features);
651                         features.setBuffer(buffer);
652                 }
653         }
654 }
655
656
657 void InsetInclude::getLabelList(Buffer const & buffer,
658                                 std::vector<docstring> & list) const
659 {
660         if (isListings(params())) {
661                 InsetListingsParams p(to_utf8(params()["lstparams"]));
662                 string label = p.getParamValue("label");
663                 if (!label.empty())
664                         list.push_back(from_utf8(label));
665         }
666         else if (loadIfNeeded(buffer, params())) {
667                 string const included_file = includedFilename(buffer, params()).absFilename();
668                 Buffer * tmp = theBufferList().getBuffer(included_file);
669                 tmp->setParentName("");
670                 tmp->getLabelList(list);
671                 tmp->setParentName(parentFilename(buffer));
672         }
673 }
674
675
676 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
677                 BiblioInfo & keys, InsetIterator const & /*di*/) const
678 {
679         if (loadIfNeeded(buffer, params())) {
680                 string const included_file = includedFilename(buffer, params()).absFilename();
681                 Buffer * tmp = theBufferList().getBuffer(included_file);
682                 //FIXME This is kind of a dirty hack and should be made reasonable.
683                 tmp->setParentName("");
684                 keys.fillWithBibKeys(tmp);
685                 tmp->setParentName(parentFilename(buffer));
686         }
687 }
688
689
690 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
691 {
692         Buffer * const tmp = getChildBuffer(buffer, params());
693         if (tmp) {
694                 tmp->setParentName("");
695                 tmp->updateBibfilesCache();
696                 tmp->setParentName(parentFilename(buffer));
697         }
698 }
699
700
701 std::vector<FileName> const &
702 InsetInclude::getBibfilesCache(Buffer const & buffer) const
703 {
704         Buffer * const tmp = getChildBuffer(buffer, params());
705         if (tmp) {
706                 tmp->setParentName("");
707                 std::vector<FileName> const & cache = tmp->getBibfilesCache();
708                 tmp->setParentName(parentFilename(buffer));
709                 return cache;
710         }
711         static std::vector<FileName> const empty;
712         return empty;
713 }
714
715
716 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
717 {
718         BOOST_ASSERT(mi.base.bv);
719
720         bool use_preview = false;
721         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
722                 graphics::PreviewImage const * pimage =
723                         preview_->getPreviewImage(mi.base.bv->buffer());
724                 use_preview = pimage && pimage->image();
725         }
726
727         if (use_preview) {
728                 preview_->metrics(mi, dim);
729         } else {
730                 if (!set_label_) {
731                         set_label_ = true;
732                         button_.update(getScreenLabel(mi.base.bv->buffer()),
733                                        true);
734                 }
735                 button_.metrics(mi, dim);
736         }
737
738         Box b(0, dim.wid, -dim.asc, dim.des);
739         button_.setBox(b);
740 }
741
742
743 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
744 {
745         BOOST_ASSERT(pi.base.bv);
746
747         bool use_preview = false;
748         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
749                 graphics::PreviewImage const * pimage =
750                         preview_->getPreviewImage(pi.base.bv->buffer());
751                 use_preview = pimage && pimage->image();
752         }
753
754         if (use_preview)
755                 preview_->draw(pi, x, y);
756         else
757                 button_.draw(pi, x, y);
758 }
759
760
761 Inset::DisplayType InsetInclude::display() const
762 {
763         return type(params()) == INPUT ? Inline : AlignCenter;
764 }
765
766
767
768 //
769 // preview stuff
770 //
771
772 void InsetInclude::fileChanged() const
773 {
774         Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
775         if (!buffer_ptr)
776                 return;
777
778         Buffer const & buffer = *buffer_ptr;
779         preview_->removePreview(buffer);
780         add_preview(*preview_.get(), *this, buffer);
781         preview_->startLoading(buffer);
782 }
783
784
785 namespace {
786
787 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
788 {
789         FileName const included_file = includedFilename(buffer, params);
790
791         return type(params) == INPUT && params.preview() &&
792                 included_file.isFileReadable();
793 }
794
795
796 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
797 {
798         odocstringstream os;
799         // We don't need to set runparams.encoding since this will be done
800         // by latex() anyway.
801         OutputParams runparams(0);
802         runparams.flavor = OutputParams::LATEX;
803         inset.latex(buffer, os, runparams);
804
805         return os.str();
806 }
807
808
809 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
810                  Buffer const & buffer)
811 {
812         InsetCommandParams const & params = inset.params();
813         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
814             preview_wanted(params, buffer)) {
815                 renderer.setAbsFile(includedFilename(buffer, params));
816                 docstring const snippet = latex_string(inset, buffer);
817                 renderer.addPreview(snippet, buffer);
818         }
819 }
820
821 } // namespace anon
822
823
824 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
825 {
826         Buffer const & buffer = ploader.buffer();
827         if (preview_wanted(params(), buffer)) {
828                 preview_->setAbsFile(includedFilename(buffer, params()));
829                 docstring const snippet = latex_string(*this, buffer);
830                 preview_->addPreview(snippet, ploader);
831         }
832 }
833
834
835 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
836         ParConstIterator const & pit) const
837 {
838         if (isListings(params())) {
839                 InsetListingsParams p(to_utf8(params()["lstparams"]));
840                 string caption = p.getParamValue("caption");
841                 if (caption.empty())
842                         return;
843                 Toc & toc = toclist["listing"];
844                 docstring const str = convert<docstring>(toc.size() + 1)
845                         + ". " +  from_utf8(caption);
846                 // This inset does not have a valid ParConstIterator
847                 // so it has to use the iterator of its parent paragraph
848                 toc.push_back(TocItem(pit, 0, str));
849                 return;
850         }
851         Buffer const * const childbuffer = getChildBuffer(buffer, params());
852         if (!childbuffer)
853                 return;
854
855         TocList const & childtoclist = childbuffer->tocBackend().tocs();
856         TocList::const_iterator it = childtoclist.begin();
857         TocList::const_iterator const end = childtoclist.end();
858         for(; it != end; ++it)
859                 toclist[it->first].insert(toclist[it->first].end(),
860                                 it->second.begin(), it->second.end());
861 }
862
863
864 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
865 {
866         Buffer const * const childbuffer = getChildBuffer(buffer, params());
867         if (childbuffer)
868                 lyx::updateLabels(*childbuffer, true);
869         else if (isListings(params())) {
870                 InsetListingsParams const par(to_utf8(params()["lstparams"]));
871                 if (par.getParamValue("caption").empty())
872                         listings_label_.clear();
873                 else {
874                         Counters & counters = buffer.params().getTextClass().counters();
875                         docstring const cnt = from_ascii("listing");
876                         if (counters.hasCounter(cnt)) {
877                                 counters.step(cnt);
878                                 listings_label_ = buffer.B_("Program Listing ")
879                                         + convert<docstring>(counters.value(cnt));
880                         } else
881                                 listings_label_ = buffer.B_("Program Listing");
882                 }
883         }
884 }
885
886
887 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
888         EmbeddedFiles & files) const
889 {
890         // include and input are temprarily not considered.
891         if (isVerbatim(params()) || isListings(params()))
892                 files.registerFile(includedFilename(buffer, params()).absFilename(),
893                         false, this);
894 }
895
896 } // namespace lyx