]> git.lyx.org Git - features.git/blob - src/insets/InsetInclude.cpp
a6933444a58eb40073dc2146ff80d9c3a8dbdf4b
[features.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                         break;
281                 case NONE:
282                         BOOST_ASSERT(false);
283         }
284
285         temp += ": ";
286
287         if (params()["filename"].empty())
288                 temp += "???";
289         else
290                 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
291
292         return temp;
293 }
294
295
296 namespace {
297
298 /// return the child buffer if the file is a LyX doc and is loaded
299 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
300 {
301         if (isVerbatim(params) || isListings(params))
302                 return 0;
303
304         string const included_file = includedFilename(buffer, params).absFilename();
305         if (!isLyXFilename(included_file))
306                 return 0;
307
308         Buffer * childBuffer = theBufferList().getBuffer(included_file);
309
310         //FIXME RECURSIVE INCLUDES
311         if (childBuffer == & buffer)
312                 return 0;
313         else
314                 return childBuffer;
315 }
316
317 } // namespace anon
318
319
320 /// return true if the file is or got loaded.
321 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
322 {
323         if (isVerbatim(params) || isListings(params))
324                 return 0;
325
326         string const parent_filename = parent.absFileName();
327         FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
328                            onlyPath(parent_filename));
329
330         if (!isLyXFilename(included_file.absFilename()))
331                 return 0;
332
333         Buffer * child = theBufferList().getBuffer(included_file.absFilename());
334         if (!child) {
335                 // the readonly flag can/will be wrong, not anymore I think.
336                 if (!included_file.exists())
337                         return 0;
338
339                 child = theBufferList().newBuffer(included_file.absFilename());
340                 if (!child->loadLyXFile(included_file)) {
341                         //close the buffer we just opened
342                         theBufferList().close(child, false);
343                         return 0;
344                 }
345         }
346         child->setParentName(parent_filename);
347         return child;
348 }
349
350
351 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
352                         OutputParams const & runparams) const
353 {
354         string incfile(to_utf8(params()["filename"]));
355
356         // Do nothing if no file name has been specified
357         if (incfile.empty())
358                 return 0;
359
360         FileName const included_file = includedFilename(buffer, params());
361
362         //Check we're not trying to include ourselves.
363         //FIXME RECURSIVE INCLUDE
364         //This isn't sufficient, as the inclusion could be downstream.
365         //But it'll have to do for now.
366         if (isInputOrInclude(params()) &&
367                 buffer.absFileName() == included_file.absFilename())
368         {
369                 Alert::error(_("Recursive input"),
370                                bformat(_("Attempted to include file %1$s in itself! "
371                                "Ignoring inclusion."), from_utf8(incfile)));
372                 return 0;
373         }
374
375         Buffer const * const masterBuffer = buffer.masterBuffer();
376
377         // if incfile is relative, make it relative to the master
378         // buffer directory.
379         if (!absolutePath(incfile)) {
380                 // FIXME UNICODE
381                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
382                                               from_utf8(masterBuffer->filePath())));
383         }
384
385         // write it to a file (so far the complete file)
386         string const exportfile = changeExtension(incfile, ".tex");
387         string const mangled =
388                 DocFileName(changeExtension(included_file.absFilename(),".tex")).
389                         mangledFilename();
390         FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
391
392         if (!runparams.nice)
393                 incfile = mangled;
394         else if (!isValidLaTeXFilename(incfile)) {
395                 frontend::Alert::warning(_("Invalid filename"),
396                                          _("The following filename is likely to cause trouble "
397                                            "when running the exported file through LaTeX: ") +
398                                             from_utf8(incfile));
399         }
400         LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
401         LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
402         LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
403
404         if (runparams.inComment || runparams.dryrun) {
405                 //Don't try to load or copy the file if we're
406                 //in a comment or doing a dryrun
407         } else if (isInputOrInclude(params()) &&
408                  isLyXFilename(included_file.absFilename())) {
409                 //if it's a LyX file and we're inputting or including,
410                 //try to load it so we can write the associated latex
411                 if (!loadIfNeeded(buffer, params()))
412                         return false;
413
414                 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
415
416                 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
417                         // FIXME UNICODE
418                         docstring text = bformat(_("Included file `%1$s'\n"
419                                                 "has textclass `%2$s'\n"
420                                                              "while parent file has textclass `%3$s'."),
421                                               included_file.displayName(),
422                                               from_utf8(tmp->params().getTextClass().name()),
423                                               from_utf8(masterBuffer->params().getTextClass().name()));
424                         Alert::warning(_("Different textclasses"), text);
425                         //return 0;
426                 }
427
428                 // Make sure modules used in child are all included in master
429                 //FIXME It might be worth loading the children's modules into the master
430                 //over in BufferParams rather than doing this check.
431                 vector<string> const masterModules = masterBuffer->params().getModules();
432                 vector<string> const childModules = tmp->params().getModules();
433                 vector<string>::const_iterator it = childModules.begin();
434                 vector<string>::const_iterator end = childModules.end();
435                 for (; it != end; ++it) {
436                         string const module = *it;
437                         vector<string>::const_iterator found =
438                                 find(masterModules.begin(), masterModules.end(), module);
439                         if (found != masterModules.end()) {
440                                 docstring text = bformat(_("Included file `%1$s'\n"
441                                                         "uses module `%2$s'\n"
442                                                         "which is not used in parent file."),
443                                        included_file.displayName(), from_utf8(module));
444                                 Alert::warning(_("Module not found"), text);
445                         }
446                 }
447
448                 tmp->markDepClean(masterBuffer->temppath());
449
450 // FIXME: handle non existing files
451 // FIXME: Second argument is irrelevant!
452 // since only_body is true, makeLaTeXFile will not look at second
453 // argument. Should we set it to string(), or should makeLaTeXFile
454 // make use of it somehow? (JMarc 20031002)
455                 // The included file might be written in a different encoding
456                 Encoding const * const oldEnc = runparams.encoding;
457                 runparams.encoding = &tmp->params().encoding();
458                 tmp->makeLaTeXFile(writefile,
459                                    masterFileName(buffer).onlyPath(),
460                                    runparams, false);
461                 runparams.encoding = oldEnc;
462         } else {
463                 // In this case, it's not a LyX file, so we copy the file
464                 // to the temp dir, so that .aux files etc. are not created
465                 // in the original dir. Files included by this file will be
466                 // found via input@path, see ../Buffer.cpp.
467                 unsigned long const checksum_in  = sum(included_file);
468                 unsigned long const checksum_out = sum(writefile);
469
470                 if (checksum_in != checksum_out) {
471                         if (!copy(included_file, writefile)) {
472                                 // FIXME UNICODE
473                                 LYXERR(Debug::LATEX)
474                                         << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
475                                                                   "into the temporary directory."),
476                                                    from_utf8(included_file.absFilename())))
477                                         << endl;
478                                 return 0;
479                         }
480                 }
481         }
482
483         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
484                         "latex" : "pdflatex";
485         if (isVerbatim(params())) {
486                 incfile = latex_path(incfile);
487                 // FIXME UNICODE
488                 os << '\\' << from_ascii(params().getCmdName()) << '{'
489                    << from_utf8(incfile) << '}';
490         } else if (type(params()) == INPUT) {
491                 runparams.exportdata->addExternalFile(tex_format, writefile,
492                                                       exportfile);
493
494                 // \input wants file with extension (default is .tex)
495                 if (!isLyXFilename(included_file.absFilename())) {
496                         incfile = latex_path(incfile);
497                         // FIXME UNICODE
498                         os << '\\' << from_ascii(params().getCmdName())
499                            << '{' << from_utf8(incfile) << '}';
500                 } else {
501                 incfile = changeExtension(incfile, ".tex");
502                 incfile = latex_path(incfile);
503                         // FIXME UNICODE
504                         os << '\\' << from_ascii(params().getCmdName())
505                            << '{' << from_utf8(incfile) <<  '}';
506                 }
507         } else if (type(params()) == LISTINGS) {
508                 os << '\\' << from_ascii(params().getCmdName());
509                 string const opt = to_utf8(params()["lstparams"]);
510                 // opt is set in QInclude dialog and should have passed validation.
511                 InsetListingsParams params(opt);
512                 if (!params.params().empty())
513                         os << "[" << from_utf8(params.params()) << "]";
514                 os << '{'  << from_utf8(incfile) << '}';
515         } else {
516                 runparams.exportdata->addExternalFile(tex_format, writefile,
517                                                       exportfile);
518
519                 // \include don't want extension and demands that the
520                 // file really have .tex
521                 incfile = changeExtension(incfile, string());
522                 incfile = latex_path(incfile);
523                 // FIXME UNICODE
524                 os << '\\' << from_ascii(params().getCmdName()) << '{'
525                    << from_utf8(incfile) << '}';
526         }
527
528         return 0;
529 }
530
531
532 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
533                             OutputParams const &) const
534 {
535         if (isVerbatim(params()) || isListings(params())) {
536                 os << '[' << getScreenLabel(buffer) << '\n';
537                 // FIXME: We don't know the encoding of the file
538                 docstring const str =
539                      from_utf8(includedFilename(buffer, params()).fileContents());
540                 os << str;
541                 os << "\n]";
542                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
543         } else {
544                 docstring const str = '[' + getScreenLabel(buffer) + ']';
545                 os << str;
546                 return str.size();
547         }
548 }
549
550
551 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
552                           OutputParams const & runparams) const
553 {
554         string incfile = to_utf8(params()["filename"]);
555
556         // Do nothing if no file name has been specified
557         if (incfile.empty())
558                 return 0;
559
560         string const included_file = includedFilename(buffer, params()).absFilename();
561
562         //Check we're not trying to include ourselves.
563         //FIXME RECURSIVE INCLUDE
564         //This isn't sufficient, as the inclusion could be downstream.
565         //But it'll have to do for now.
566         if (buffer.absFileName() == included_file) {
567                 Alert::error(_("Recursive input"),
568                                bformat(_("Attempted to include file %1$s in itself! "
569                                "Ignoring inclusion."), from_utf8(incfile)));
570                 return 0;
571         }
572
573         // write it to a file (so far the complete file)
574         string const exportfile = changeExtension(incfile, ".sgml");
575         DocFileName writefile(changeExtension(included_file, ".sgml"));
576
577         if (loadIfNeeded(buffer, params())) {
578                 Buffer * tmp = theBufferList().getBuffer(included_file);
579
580                 string const mangled = writefile.mangledFilename();
581                 writefile = makeAbsPath(mangled,
582                                         buffer.masterBuffer()->temppath());
583                 if (!runparams.nice)
584                         incfile = mangled;
585
586                 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
587                 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
588                 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
589
590                 tmp->makeDocBookFile(writefile, runparams, true);
591         }
592
593         runparams.exportdata->addExternalFile("docbook", writefile,
594                                               exportfile);
595         runparams.exportdata->addExternalFile("docbook-xml", writefile,
596                                               exportfile);
597
598         if (isVerbatim(params()) || isListings(params())) {
599                 os << "<inlinegraphic fileref=\""
600                    << '&' << include_label << ';'
601                    << "\" format=\"linespecific\">";
602         } else
603                 os << '&' << include_label << ';';
604
605         return 0;
606 }
607
608
609 void InsetInclude::validate(LaTeXFeatures & features) const
610 {
611         string incfile = to_utf8(params()["filename"]);
612         string writefile;
613
614         Buffer const & buffer = features.buffer();
615
616         string const included_file = includedFilename(buffer, params()).absFilename();
617
618         if (isLyXFilename(included_file))
619                 writefile = changeExtension(included_file, ".sgml");
620         else
621                 writefile = included_file;
622
623         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
624                 incfile = DocFileName(writefile).mangledFilename();
625                 writefile = makeAbsPath(incfile,
626                                         buffer.masterBuffer()->temppath()).absFilename();
627         }
628
629         features.includeFile(include_label, writefile);
630
631         if (isVerbatim(params()))
632                 features.require("verbatim");
633         else if (isListings(params()))
634                 features.require("listings");
635
636         // Here we must do the fun stuff...
637         // Load the file in the include if it needs
638         // to be loaded:
639         if (loadIfNeeded(buffer, params())) {
640                 // a file got loaded
641                 Buffer * const tmp = theBufferList().getBuffer(included_file);
642                 // make sure the buffer isn't us
643                 // FIXME RECURSIVE INCLUDES
644                 // This is not sufficient, as recursive includes could be
645                 // more than a file away. But it will do for now.
646                 if (tmp && tmp != & buffer) {
647                         // We must temporarily change features.buffer,
648                         // otherwise it would always be the master buffer,
649                         // and nested includes would not work.
650                         features.setBuffer(*tmp);
651                         tmp->validate(features);
652                         features.setBuffer(buffer);
653                 }
654         }
655 }
656
657
658 void InsetInclude::getLabelList(Buffer const & buffer,
659                                 std::vector<docstring> & list) const
660 {
661         if (isListings(params())) {
662                 InsetListingsParams p(to_utf8(params()["lstparams"]));
663                 string label = p.getParamValue("label");
664                 if (!label.empty())
665                         list.push_back(from_utf8(label));
666         }
667         else if (loadIfNeeded(buffer, params())) {
668                 string const included_file = includedFilename(buffer, params()).absFilename();
669                 Buffer * tmp = theBufferList().getBuffer(included_file);
670                 tmp->setParentName("");
671                 tmp->getLabelList(list);
672                 tmp->setParentName(parentFilename(buffer));
673         }
674 }
675
676
677 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
678                 BiblioInfo & keys, InsetIterator const & /*di*/) const
679 {
680         if (loadIfNeeded(buffer, params())) {
681                 string const included_file = includedFilename(buffer, params()).absFilename();
682                 Buffer * tmp = theBufferList().getBuffer(included_file);
683                 //FIXME This is kind of a dirty hack and should be made reasonable.
684                 tmp->setParentName("");
685                 keys.fillWithBibKeys(tmp);
686                 tmp->setParentName(parentFilename(buffer));
687         }
688 }
689
690
691 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
692 {
693         Buffer * const tmp = getChildBuffer(buffer, params());
694         if (tmp) {
695                 tmp->setParentName("");
696                 tmp->updateBibfilesCache();
697                 tmp->setParentName(parentFilename(buffer));
698         }
699 }
700
701
702 std::vector<FileName> const &
703 InsetInclude::getBibfilesCache(Buffer const & buffer) const
704 {
705         Buffer * const tmp = getChildBuffer(buffer, params());
706         if (tmp) {
707                 tmp->setParentName("");
708                 std::vector<FileName> const & cache = tmp->getBibfilesCache();
709                 tmp->setParentName(parentFilename(buffer));
710                 return cache;
711         }
712         static std::vector<FileName> const empty;
713         return empty;
714 }
715
716
717 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
718 {
719         BOOST_ASSERT(mi.base.bv);
720
721         bool use_preview = false;
722         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
723                 graphics::PreviewImage const * pimage =
724                         preview_->getPreviewImage(mi.base.bv->buffer());
725                 use_preview = pimage && pimage->image();
726         }
727
728         if (use_preview) {
729                 preview_->metrics(mi, dim);
730         } else {
731                 if (!set_label_) {
732                         set_label_ = true;
733                         button_.update(getScreenLabel(mi.base.bv->buffer()),
734                                        true);
735                 }
736                 button_.metrics(mi, dim);
737         }
738
739         Box b(0, dim.wid, -dim.asc, dim.des);
740         button_.setBox(b);
741 }
742
743
744 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
745 {
746         BOOST_ASSERT(pi.base.bv);
747
748         bool use_preview = false;
749         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
750                 graphics::PreviewImage const * pimage =
751                         preview_->getPreviewImage(pi.base.bv->buffer());
752                 use_preview = pimage && pimage->image();
753         }
754
755         if (use_preview)
756                 preview_->draw(pi, x, y);
757         else
758                 button_.draw(pi, x, y);
759 }
760
761
762 Inset::DisplayType InsetInclude::display() const
763 {
764         return type(params()) == INPUT ? Inline : AlignCenter;
765 }
766
767
768
769 //
770 // preview stuff
771 //
772
773 void InsetInclude::fileChanged() const
774 {
775         Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
776         if (!buffer_ptr)
777                 return;
778
779         Buffer const & buffer = *buffer_ptr;
780         preview_->removePreview(buffer);
781         add_preview(*preview_.get(), *this, buffer);
782         preview_->startLoading(buffer);
783 }
784
785
786 namespace {
787
788 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
789 {
790         FileName const included_file = includedFilename(buffer, params);
791
792         return type(params) == INPUT && params.preview() &&
793                 included_file.isFileReadable();
794 }
795
796
797 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
798 {
799         odocstringstream os;
800         // We don't need to set runparams.encoding since this will be done
801         // by latex() anyway.
802         OutputParams runparams(0);
803         runparams.flavor = OutputParams::LATEX;
804         inset.latex(buffer, os, runparams);
805
806         return os.str();
807 }
808
809
810 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
811                  Buffer const & buffer)
812 {
813         InsetCommandParams const & params = inset.params();
814         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
815             preview_wanted(params, buffer)) {
816                 renderer.setAbsFile(includedFilename(buffer, params));
817                 docstring const snippet = latex_string(inset, buffer);
818                 renderer.addPreview(snippet, buffer);
819         }
820 }
821
822 } // namespace anon
823
824
825 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
826 {
827         Buffer const & buffer = ploader.buffer();
828         if (preview_wanted(params(), buffer)) {
829                 preview_->setAbsFile(includedFilename(buffer, params()));
830                 docstring const snippet = latex_string(*this, buffer);
831                 preview_->addPreview(snippet, ploader);
832         }
833 }
834
835
836 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
837         ParConstIterator const & pit) const
838 {
839         if (isListings(params())) {
840                 InsetListingsParams p(to_utf8(params()["lstparams"]));
841                 string caption = p.getParamValue("caption");
842                 if (caption.empty())
843                         return;
844                 Toc & toc = toclist["listing"];
845                 docstring const str = convert<docstring>(toc.size() + 1)
846                         + ". " +  from_utf8(caption);
847                 // This inset does not have a valid ParConstIterator
848                 // so it has to use the iterator of its parent paragraph
849                 toc.push_back(TocItem(pit, 0, str));
850                 return;
851         }
852         Buffer const * const childbuffer = getChildBuffer(buffer, params());
853         if (!childbuffer)
854                 return;
855
856         TocList const & childtoclist = childbuffer->tocBackend().tocs();
857         TocList::const_iterator it = childtoclist.begin();
858         TocList::const_iterator const end = childtoclist.end();
859         for(; it != end; ++it)
860                 toclist[it->first].insert(toclist[it->first].end(),
861                                 it->second.begin(), it->second.end());
862 }
863
864
865 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
866 {
867         Buffer const * const childbuffer = getChildBuffer(buffer, params());
868         if (childbuffer)
869                 lyx::updateLabels(*childbuffer, true);
870         else if (isListings(params())) {
871                 InsetListingsParams const par(to_utf8(params()["lstparams"]));
872                 if (par.getParamValue("caption").empty())
873                         listings_label_.clear();
874                 else {
875                         Counters & counters = buffer.params().getTextClass().counters();
876                         docstring const cnt = from_ascii("listing");
877                         if (counters.hasCounter(cnt)) {
878                                 counters.step(cnt);
879                                 listings_label_ = buffer.B_("Program Listing ")
880                                         + convert<docstring>(counters.value(cnt));
881                         } else
882                                 listings_label_ = buffer.B_("Program Listing");
883                 }
884         }
885 }
886
887
888 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
889         EmbeddedFiles & files) const
890 {
891         // include and input are temprarily not considered.
892         if (isVerbatim(params()) || isListings(params()))
893                 files.registerFile(includedFilename(buffer, params()).absFilename(),
894                         false, this);
895 }
896
897 } // namespace lyx