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