]> git.lyx.org Git - features.git/blob - src/insets/InsetInclude.cpp
reduce line noise
[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::find;
79 using std::string;
80 using std::istringstream;
81 using std::ostream;
82 using std::ostringstream;
83 using std::vector;
84
85 namespace Alert = frontend::Alert;
86
87
88 namespace {
89
90 docstring const uniqueID()
91 {
92         static unsigned int seed = 1000;
93         return "file" + convert<docstring>(++seed);
94 }
95
96
97 /// the type of inclusion
98 enum Types {
99         INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
100 };
101
102
103 Types type(std::string const & s)
104 {
105         if (s == "input")
106                 return INPUT;
107         if (s == "verbatiminput")
108                 return VERB;
109         if (s == "verbatiminput*")
110                 return VERBAST;
111         if (s == "lstinputlisting")
112                 return LISTINGS;
113         if (s == "include")
114                 return INCLUDE;
115         return NONE;
116 }
117
118
119 Types type(InsetCommandParams const & params)
120 {
121         return type(params.getCmdName());
122 }
123
124
125 bool isListings(InsetCommandParams const & params)
126 {
127         return type(params) == LISTINGS;
128 }
129
130
131 bool isVerbatim(InsetCommandParams const & params)
132 {
133         Types const t = type(params);
134         return t == VERB || t == VERBAST;
135 }
136
137
138 bool isInputOrInclude(InsetCommandParams const & params)
139 {
140         Types const t = type(params);
141         return t == INPUT || t == INCLUDE;
142 }
143
144 } // namespace anon
145
146
147 InsetInclude::InsetInclude(InsetCommandParams const & p)
148         : InsetCommand(p, "include"), include_label(uniqueID()),
149           preview_(new RenderMonitoredPreview(this)), set_label_(false)
150 {
151         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
152 }
153
154
155 InsetInclude::InsetInclude(InsetInclude const & other)
156         : InsetCommand(other), include_label(other.include_label),
157           preview_(new RenderMonitoredPreview(this)), set_label_(false)
158 {
159         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
160 }
161
162
163 CommandInfo const * InsetInclude::findInfo(std::string const & /* cmdName */)
164 {
165         // This is only correct for the case of listings, but it'll do for now.
166         // In the other cases, this second parameter should just be empty.
167         static const char * const paramnames[] = {"filename", "lstparams", ""};
168         static const bool isoptional[] = {false, true};
169         static const CommandInfo info = {2, paramnames, isoptional};
170         return &info;
171 }
172
173
174 bool InsetInclude::isCompatibleCommand(std::string const & s)
175 {
176         return type(s) != NONE;
177 }
178
179
180 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
181 {
182         switch (cmd.action) {
183
184         case LFUN_INSET_MODIFY: {
185                 InsetCommandParams p(INCLUDE_CODE);
186                 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
187                 if (!p.getCmdName().empty()) {
188                         if (isListings(p)){
189                                 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
190                                 InsetListingsParams par_new(to_utf8(p["lstparams"]));
191                                 if (par_old.getParamValue("label") !=
192                                     par_new.getParamValue("label")
193                                     && !par_new.getParamValue("label").empty())
194                                         cur.bv().buffer().changeRefsIfUnique(
195                                                 from_utf8(par_old.getParamValue("label")),
196                                                 from_utf8(par_new.getParamValue("label")),
197                                                 REF_CODE);
198                         }
199                         set(p, cur.buffer());
200                         cur.buffer().updateBibfilesCache();
201                 } else
202                         cur.noUpdate();
203                 break;
204         }
205
206         //pass everything else up the chain
207         default:
208                 InsetCommand::doDispatch(cur, cmd);
209                 break;
210         }
211 }
212
213
214 namespace {
215
216 FileName const masterFileName(Buffer const & buffer)
217 {
218         return buffer.masterBuffer()->fileName();
219 }
220
221
222 string const parentFilename(Buffer const & buffer)
223 {
224         return buffer.absFileName();
225 }
226
227
228 FileName const includedFilename(Buffer const & buffer,
229                               InsetCommandParams const & params)
230 {
231         return makeAbsPath(to_utf8(params["filename"]),
232                onlyPath(parentFilename(buffer)));
233 }
234
235
236 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
237
238 } // namespace anon
239
240
241 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
242 {
243         setParams(p);
244         set_label_ = false;
245
246         if (preview_->monitoring())
247                 preview_->stopMonitoring();
248
249         if (type(params()) == INPUT)
250                 add_preview(*preview_, *this, buffer);
251 }
252
253
254 Inset * InsetInclude::clone() const
255 {
256         return new InsetInclude(*this);
257 }
258
259
260 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
261 {
262         docstring temp;
263
264         switch (type(params())) {
265                 case INPUT:
266                         temp = buf.B_("Input");
267                         break;
268                 case VERB:
269                         temp = buf.B_("Verbatim Input");
270                         break;
271                 case VERBAST:
272                         temp = buf.B_("Verbatim Input*");
273                         break;
274                 case INCLUDE:
275                         temp = buf.B_("Include");
276                         break;
277                 case LISTINGS:
278                         temp = listings_label_;
279                         break;
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);
400         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
401         LYXERR(Debug::LATEX, "writefile:" << writefile);
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                                 return 0;
477                         }
478                 }
479         }
480
481         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
482                         "latex" : "pdflatex";
483         if (isVerbatim(params())) {
484                 incfile = latex_path(incfile);
485                 // FIXME UNICODE
486                 os << '\\' << from_ascii(params().getCmdName()) << '{'
487                    << from_utf8(incfile) << '}';
488         } else if (type(params()) == INPUT) {
489                 runparams.exportdata->addExternalFile(tex_format, writefile,
490                                                       exportfile);
491
492                 // \input wants file with extension (default is .tex)
493                 if (!isLyXFilename(included_file.absFilename())) {
494                         incfile = latex_path(incfile);
495                         // FIXME UNICODE
496                         os << '\\' << from_ascii(params().getCmdName())
497                            << '{' << from_utf8(incfile) << '}';
498                 } else {
499                 incfile = changeExtension(incfile, ".tex");
500                 incfile = latex_path(incfile);
501                         // FIXME UNICODE
502                         os << '\\' << from_ascii(params().getCmdName())
503                            << '{' << from_utf8(incfile) <<  '}';
504                 }
505         } else if (type(params()) == LISTINGS) {
506                 os << '\\' << from_ascii(params().getCmdName());
507                 string const opt = to_utf8(params()["lstparams"]);
508                 // opt is set in QInclude dialog and should have passed validation.
509                 InsetListingsParams params(opt);
510                 if (!params.params().empty())
511                         os << "[" << from_utf8(params.params()) << "]";
512                 os << '{'  << from_utf8(incfile) << '}';
513         } else {
514                 runparams.exportdata->addExternalFile(tex_format, writefile,
515                                                       exportfile);
516
517                 // \include don't want extension and demands that the
518                 // file really have .tex
519                 incfile = changeExtension(incfile, string());
520                 incfile = latex_path(incfile);
521                 // FIXME UNICODE
522                 os << '\\' << from_ascii(params().getCmdName()) << '{'
523                    << from_utf8(incfile) << '}';
524         }
525
526         return 0;
527 }
528
529
530 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
531                             OutputParams const &) const
532 {
533         if (isVerbatim(params()) || isListings(params())) {
534                 os << '[' << getScreenLabel(buffer) << '\n';
535                 // FIXME: We don't know the encoding of the file
536                 docstring const str =
537                      from_utf8(includedFilename(buffer, params()).fileContents());
538                 os << str;
539                 os << "\n]";
540                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
541         } else {
542                 docstring const str = '[' + getScreenLabel(buffer) + ']';
543                 os << str;
544                 return str.size();
545         }
546 }
547
548
549 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
550                           OutputParams const & runparams) const
551 {
552         string incfile = to_utf8(params()["filename"]);
553
554         // Do nothing if no file name has been specified
555         if (incfile.empty())
556                 return 0;
557
558         string const included_file = includedFilename(buffer, params()).absFilename();
559
560         //Check we're not trying to include ourselves.
561         //FIXME RECURSIVE INCLUDE
562         //This isn't sufficient, as the inclusion could be downstream.
563         //But it'll have to do for now.
564         if (buffer.absFileName() == included_file) {
565                 Alert::error(_("Recursive input"),
566                                bformat(_("Attempted to include file %1$s in itself! "
567                                "Ignoring inclusion."), from_utf8(incfile)));
568                 return 0;
569         }
570
571         // write it to a file (so far the complete file)
572         string const exportfile = changeExtension(incfile, ".sgml");
573         DocFileName writefile(changeExtension(included_file, ".sgml"));
574
575         if (loadIfNeeded(buffer, params())) {
576                 Buffer * tmp = theBufferList().getBuffer(included_file);
577
578                 string const mangled = writefile.mangledFilename();
579                 writefile = makeAbsPath(mangled,
580                                         buffer.masterBuffer()->temppath());
581                 if (!runparams.nice)
582                         incfile = mangled;
583
584                 LYXERR(Debug::LATEX, "incfile:" << incfile);
585                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
586                 LYXERR(Debug::LATEX, "writefile:" << writefile);
587
588                 tmp->makeDocBookFile(writefile, runparams, true);
589         }
590
591         runparams.exportdata->addExternalFile("docbook", writefile,
592                                               exportfile);
593         runparams.exportdata->addExternalFile("docbook-xml", writefile,
594                                               exportfile);
595
596         if (isVerbatim(params()) || isListings(params())) {
597                 os << "<inlinegraphic fileref=\""
598                    << '&' << include_label << ';'
599                    << "\" format=\"linespecific\">";
600         } else
601                 os << '&' << include_label << ';';
602
603         return 0;
604 }
605
606
607 void InsetInclude::validate(LaTeXFeatures & features) const
608 {
609         string incfile = to_utf8(params()["filename"]);
610         string writefile;
611
612         Buffer const & buffer = features.buffer();
613
614         string const included_file = includedFilename(buffer, params()).absFilename();
615
616         if (isLyXFilename(included_file))
617                 writefile = changeExtension(included_file, ".sgml");
618         else
619                 writefile = included_file;
620
621         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
622                 incfile = DocFileName(writefile).mangledFilename();
623                 writefile = makeAbsPath(incfile,
624                                         buffer.masterBuffer()->temppath()).absFilename();
625         }
626
627         features.includeFile(include_label, writefile);
628
629         if (isVerbatim(params()))
630                 features.require("verbatim");
631         else if (isListings(params()))
632                 features.require("listings");
633
634         // Here we must do the fun stuff...
635         // Load the file in the include if it needs
636         // to be loaded:
637         if (loadIfNeeded(buffer, params())) {
638                 // a file got loaded
639                 Buffer * const tmp = theBufferList().getBuffer(included_file);
640                 // make sure the buffer isn't us
641                 // FIXME RECURSIVE INCLUDES
642                 // This is not sufficient, as recursive includes could be
643                 // more than a file away. But it will do for now.
644                 if (tmp && tmp != & buffer) {
645                         // We must temporarily change features.buffer,
646                         // otherwise it would always be the master buffer,
647                         // and nested includes would not work.
648                         features.setBuffer(*tmp);
649                         tmp->validate(features);
650                         features.setBuffer(buffer);
651                 }
652         }
653 }
654
655
656 void InsetInclude::getLabelList(Buffer const & buffer,
657                                 std::vector<docstring> & list) const
658 {
659         if (isListings(params())) {
660                 InsetListingsParams p(to_utf8(params()["lstparams"]));
661                 string label = p.getParamValue("label");
662                 if (!label.empty())
663                         list.push_back(from_utf8(label));
664         }
665         else if (loadIfNeeded(buffer, params())) {
666                 string const included_file = includedFilename(buffer, params()).absFilename();
667                 Buffer * tmp = theBufferList().getBuffer(included_file);
668                 tmp->setParentName("");
669                 tmp->getLabelList(list);
670                 tmp->setParentName(parentFilename(buffer));
671         }
672 }
673
674
675 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
676                 BiblioInfo & keys, InsetIterator const & /*di*/) const
677 {
678         if (loadIfNeeded(buffer, params())) {
679                 string const included_file = includedFilename(buffer, params()).absFilename();
680                 Buffer * tmp = theBufferList().getBuffer(included_file);
681                 //FIXME This is kind of a dirty hack and should be made reasonable.
682                 tmp->setParentName("");
683                 keys.fillWithBibKeys(tmp);
684                 tmp->setParentName(parentFilename(buffer));
685         }
686 }
687
688
689 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
690 {
691         Buffer * const tmp = getChildBuffer(buffer, params());
692         if (tmp) {
693                 tmp->setParentName("");
694                 tmp->updateBibfilesCache();
695                 tmp->setParentName(parentFilename(buffer));
696         }
697 }
698
699
700 std::vector<FileName> const &
701 InsetInclude::getBibfilesCache(Buffer const & buffer) const
702 {
703         Buffer * const tmp = getChildBuffer(buffer, params());
704         if (tmp) {
705                 tmp->setParentName("");
706                 std::vector<FileName> const & cache = tmp->getBibfilesCache();
707                 tmp->setParentName(parentFilename(buffer));
708                 return cache;
709         }
710         static std::vector<FileName> const empty;
711         return empty;
712 }
713
714
715 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
716 {
717         BOOST_ASSERT(mi.base.bv);
718
719         bool use_preview = false;
720         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
721                 graphics::PreviewImage const * pimage =
722                         preview_->getPreviewImage(mi.base.bv->buffer());
723                 use_preview = pimage && pimage->image();
724         }
725
726         if (use_preview) {
727                 preview_->metrics(mi, dim);
728         } else {
729                 if (!set_label_) {
730                         set_label_ = true;
731                         button_.update(getScreenLabel(mi.base.bv->buffer()),
732                                        true);
733                 }
734                 button_.metrics(mi, dim);
735         }
736
737         Box b(0, dim.wid, -dim.asc, dim.des);
738         button_.setBox(b);
739 }
740
741
742 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
743 {
744         BOOST_ASSERT(pi.base.bv);
745
746         bool use_preview = false;
747         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
748                 graphics::PreviewImage const * pimage =
749                         preview_->getPreviewImage(pi.base.bv->buffer());
750                 use_preview = pimage && pimage->image();
751         }
752
753         if (use_preview)
754                 preview_->draw(pi, x, y);
755         else
756                 button_.draw(pi, x, y);
757 }
758
759
760 Inset::DisplayType InsetInclude::display() const
761 {
762         return type(params()) == INPUT ? Inline : AlignCenter;
763 }
764
765
766
767 //
768 // preview stuff
769 //
770
771 void InsetInclude::fileChanged() const
772 {
773         Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
774         if (!buffer_ptr)
775                 return;
776
777         Buffer const & buffer = *buffer_ptr;
778         preview_->removePreview(buffer);
779         add_preview(*preview_.get(), *this, buffer);
780         preview_->startLoading(buffer);
781 }
782
783
784 namespace {
785
786 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
787 {
788         FileName const included_file = includedFilename(buffer, params);
789
790         return type(params) == INPUT && params.preview() &&
791                 included_file.isFileReadable();
792 }
793
794
795 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
796 {
797         odocstringstream os;
798         // We don't need to set runparams.encoding since this will be done
799         // by latex() anyway.
800         OutputParams runparams(0);
801         runparams.flavor = OutputParams::LATEX;
802         inset.latex(buffer, os, runparams);
803
804         return os.str();
805 }
806
807
808 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
809                  Buffer const & buffer)
810 {
811         InsetCommandParams const & params = inset.params();
812         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
813             preview_wanted(params, buffer)) {
814                 renderer.setAbsFile(includedFilename(buffer, params));
815                 docstring const snippet = latex_string(inset, buffer);
816                 renderer.addPreview(snippet, buffer);
817         }
818 }
819
820 } // namespace anon
821
822
823 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
824 {
825         Buffer const & buffer = ploader.buffer();
826         if (preview_wanted(params(), buffer)) {
827                 preview_->setAbsFile(includedFilename(buffer, params()));
828                 docstring const snippet = latex_string(*this, buffer);
829                 preview_->addPreview(snippet, ploader);
830         }
831 }
832
833
834 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
835         ParConstIterator const & pit) const
836 {
837         if (isListings(params())) {
838                 InsetListingsParams p(to_utf8(params()["lstparams"]));
839                 string caption = p.getParamValue("caption");
840                 if (caption.empty())
841                         return;
842                 Toc & toc = toclist["listing"];
843                 docstring const str = convert<docstring>(toc.size() + 1)
844                         + ". " +  from_utf8(caption);
845                 // This inset does not have a valid ParConstIterator
846                 // so it has to use the iterator of its parent paragraph
847                 toc.push_back(TocItem(pit, 0, str));
848                 return;
849         }
850         Buffer const * const childbuffer = getChildBuffer(buffer, params());
851         if (!childbuffer)
852                 return;
853
854         TocList const & childtoclist = childbuffer->tocBackend().tocs();
855         TocList::const_iterator it = childtoclist.begin();
856         TocList::const_iterator const end = childtoclist.end();
857         for(; it != end; ++it)
858                 toclist[it->first].insert(toclist[it->first].end(),
859                                 it->second.begin(), it->second.end());
860 }
861
862
863 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
864 {
865         Buffer const * const childbuffer = getChildBuffer(buffer, params());
866         if (childbuffer)
867                 lyx::updateLabels(*childbuffer, true);
868         else if (isListings(params())) {
869                 InsetListingsParams const par(to_utf8(params()["lstparams"]));
870                 if (par.getParamValue("caption").empty())
871                         listings_label_.clear();
872                 else {
873                         Counters & counters = buffer.params().getTextClass().counters();
874                         docstring const cnt = from_ascii("listing");
875                         if (counters.hasCounter(cnt)) {
876                                 counters.step(cnt);
877                                 listings_label_ = buffer.B_("Program Listing ")
878                                         + convert<docstring>(counters.value(cnt));
879                         } else
880                                 listings_label_ = buffer.B_("Program Listing");
881                 }
882         }
883 }
884
885
886 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
887         EmbeddedFiles & files) const
888 {
889         // include and input are temprarily not considered.
890         if (isVerbatim(params()) || isListings(params()))
891                 files.registerFile(includedFilename(buffer, params()).absFilename(),
892                         false, this);
893 }
894
895 } // namespace lyx