]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
ba1207c283177e2a2b723e834223b0782d6804d8
[lyx.git] / src / insets / InsetInclude.cpp
1 /**
2  * \file InsetInclude.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Richard Heck (conversion to InsetCommand)
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetInclude.h"
15
16 #include "Buffer.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "Cursor.h"
22 #include "support/debug.h"
23 #include "DispatchResult.h"
24 #include "Exporter.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.h"
27 #include "support/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
77 using std::find;
78 using std::string;
79 using std::istringstream;
80 using std::ostream;
81 using std::ostringstream;
82 using std::vector;
83
84 namespace Alert = frontend::Alert;
85
86
87 namespace {
88
89 docstring const uniqueID()
90 {
91         static unsigned int seed = 1000;
92         return "file" + convert<docstring>(++seed);
93 }
94
95
96 /// the type of inclusion
97 enum Types {
98         INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
99 };
100
101
102 Types type(std::string const & s)
103 {
104         if (s == "input")
105                 return INPUT;
106         if (s == "verbatiminput")
107                 return VERB;
108         if (s == "verbatiminput*")
109                 return VERBAST;
110         if (s == "lstinputlisting")
111                 return LISTINGS;
112         if (s == "include")
113                 return INCLUDE;
114         return NONE;
115 }
116
117
118 Types type(InsetCommandParams const & params)
119 {
120         return type(params.getCmdName());
121 }
122
123
124 bool isListings(InsetCommandParams const & params)
125 {
126         return type(params) == LISTINGS;
127 }
128
129
130 bool isVerbatim(InsetCommandParams const & params)
131 {
132         Types const t = type(params);
133         return t == VERB || t == VERBAST;
134 }
135
136
137 bool isInputOrInclude(InsetCommandParams const & params)
138 {
139         Types const t = type(params);
140         return t == INPUT || t == INCLUDE;
141 }
142
143 } // namespace anon
144
145
146 InsetInclude::InsetInclude(InsetCommandParams const & p)
147         : InsetCommand(p, "include"), include_label(uniqueID()),
148           preview_(new RenderMonitoredPreview(this)), set_label_(false)
149 {
150         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
151 }
152
153
154 InsetInclude::InsetInclude(InsetInclude const & other)
155         : InsetCommand(other), include_label(other.include_label),
156           preview_(new RenderMonitoredPreview(this)), set_label_(false)
157 {
158         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
159 }
160
161
162 CommandInfo const * InsetInclude::findInfo(std::string const & /* cmdName */)
163 {
164         // FIXME
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().release(child);
342                         return 0;
343                 }
344         }
345         child->setParent(&parent);
346         return child;
347 }
348
349
350 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
351         bool close_it)
352 {
353         if (isVerbatim(params) || isListings(params))
354                 return;
355
356         string const parent_filename = parent->absFileName();
357         FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
358                            onlyPath(parent_filename));
359
360         if (!isLyXFilename(included_file.absFilename()))
361                 return;
362
363         Buffer * child = theBufferList().getBuffer(included_file.absFilename());
364         // File not opened, nothing to close.
365         if (!child)
366                 return;
367
368         // Child document has a different parent, don't close it.
369         if (child->parent() != parent)
370                 return;
371
372         //close the buffer.
373         child->setParent(0);
374         if (close_it)
375                 theBufferList().release(child);
376         else
377                 updateLabels(*child);
378 }
379
380
381 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
382                         OutputParams const & runparams) const
383 {
384         string incfile(to_utf8(params()["filename"]));
385
386         // Do nothing if no file name has been specified
387         if (incfile.empty())
388                 return 0;
389
390         FileName const included_file = includedFilename(buffer, params());
391
392         //Check we're not trying to include ourselves.
393         //FIXME RECURSIVE INCLUDE
394         //This isn't sufficient, as the inclusion could be downstream.
395         //But it'll have to do for now.
396         if (isInputOrInclude(params()) &&
397                 buffer.absFileName() == included_file.absFilename())
398         {
399                 Alert::error(_("Recursive input"),
400                                bformat(_("Attempted to include file %1$s in itself! "
401                                "Ignoring inclusion."), from_utf8(incfile)));
402                 return 0;
403         }
404
405         Buffer const * const masterBuffer = buffer.masterBuffer();
406
407         // if incfile is relative, make it relative to the master
408         // buffer directory.
409         if (!absolutePath(incfile)) {
410                 // FIXME UNICODE
411                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
412                                               from_utf8(masterBuffer->filePath())));
413         }
414
415         // write it to a file (so far the complete file)
416         string const exportfile = changeExtension(incfile, ".tex");
417         string const mangled =
418                 DocFileName(changeExtension(included_file.absFilename(),".tex")).
419                         mangledFilename();
420         FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
421
422         if (!runparams.nice)
423                 incfile = mangled;
424         else if (!isValidLaTeXFilename(incfile)) {
425                 frontend::Alert::warning(_("Invalid filename"),
426                                          _("The following filename is likely to cause trouble "
427                                            "when running the exported file through LaTeX: ") +
428                                             from_utf8(incfile));
429         }
430         LYXERR(Debug::LATEX, "incfile:" << incfile);
431         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
432         LYXERR(Debug::LATEX, "writefile:" << writefile);
433
434         if (runparams.inComment || runparams.dryrun) {
435                 //Don't try to load or copy the file if we're
436                 //in a comment or doing a dryrun
437         } else if (isInputOrInclude(params()) &&
438                  isLyXFilename(included_file.absFilename())) {
439                 //if it's a LyX file and we're inputting or including,
440                 //try to load it so we can write the associated latex
441                 if (!loadIfNeeded(buffer, params()))
442                         return false;
443
444                 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
445
446                 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
447                         // FIXME UNICODE
448                         docstring text = bformat(_("Included file `%1$s'\n"
449                                                 "has textclass `%2$s'\n"
450                                                              "while parent file has textclass `%3$s'."),
451                                               included_file.displayName(),
452                                               from_utf8(tmp->params().getTextClass().name()),
453                                               from_utf8(masterBuffer->params().getTextClass().name()));
454                         Alert::warning(_("Different textclasses"), text);
455                         //return 0;
456                 }
457
458                 // Make sure modules used in child are all included in master
459                 //FIXME It might be worth loading the children's modules into the master
460                 //over in BufferParams rather than doing this check.
461                 vector<string> const masterModules = masterBuffer->params().getModules();
462                 vector<string> const childModules = tmp->params().getModules();
463                 vector<string>::const_iterator it = childModules.begin();
464                 vector<string>::const_iterator end = childModules.end();
465                 for (; it != end; ++it) {
466                         string const module = *it;
467                         vector<string>::const_iterator found =
468                                 find(masterModules.begin(), masterModules.end(), module);
469                         if (found != masterModules.end()) {
470                                 docstring text = bformat(_("Included file `%1$s'\n"
471                                                         "uses module `%2$s'\n"
472                                                         "which is not used in parent file."),
473                                        included_file.displayName(), from_utf8(module));
474                                 Alert::warning(_("Module not found"), text);
475                         }
476                 }
477
478                 tmp->markDepClean(masterBuffer->temppath());
479
480 // FIXME: handle non existing files
481 // FIXME: Second argument is irrelevant!
482 // since only_body is true, makeLaTeXFile will not look at second
483 // argument. Should we set it to string(), or should makeLaTeXFile
484 // make use of it somehow? (JMarc 20031002)
485                 // The included file might be written in a different encoding
486                 Encoding const * const oldEnc = runparams.encoding;
487                 runparams.encoding = &tmp->params().encoding();
488                 tmp->makeLaTeXFile(writefile,
489                                    masterFileName(buffer).onlyPath().absFilename(),
490                                    runparams, false);
491                 runparams.encoding = oldEnc;
492         } else {
493                 // In this case, it's not a LyX file, so we copy the file
494                 // to the temp dir, so that .aux files etc. are not created
495                 // in the original dir. Files included by this file will be
496                 // found via input@path, see ../Buffer.cpp.
497                 unsigned long const checksum_in  = included_file.checksum();
498                 unsigned long const checksum_out = writefile.checksum();
499
500                 if (checksum_in != checksum_out) {
501                         if (!copy(included_file, writefile)) {
502                                 // FIXME UNICODE
503                                 LYXERR(Debug::LATEX,
504                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
505                                                                   "into the temporary directory."),
506                                                    from_utf8(included_file.absFilename()))));
507                                 return 0;
508                         }
509                 }
510         }
511
512         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
513                         "latex" : "pdflatex";
514         if (isVerbatim(params())) {
515                 incfile = latex_path(incfile);
516                 // FIXME UNICODE
517                 os << '\\' << from_ascii(params().getCmdName()) << '{'
518                    << from_utf8(incfile) << '}';
519         } else if (type(params()) == INPUT) {
520                 runparams.exportdata->addExternalFile(tex_format, writefile,
521                                                       exportfile);
522
523                 // \input wants file with extension (default is .tex)
524                 if (!isLyXFilename(included_file.absFilename())) {
525                         incfile = latex_path(incfile);
526                         // FIXME UNICODE
527                         os << '\\' << from_ascii(params().getCmdName())
528                            << '{' << from_utf8(incfile) << '}';
529                 } else {
530                 incfile = changeExtension(incfile, ".tex");
531                 incfile = latex_path(incfile);
532                         // FIXME UNICODE
533                         os << '\\' << from_ascii(params().getCmdName())
534                            << '{' << from_utf8(incfile) <<  '}';
535                 }
536         } else if (type(params()) == LISTINGS) {
537                 os << '\\' << from_ascii(params().getCmdName());
538                 string const opt = to_utf8(params()["lstparams"]);
539                 // opt is set in QInclude dialog and should have passed validation.
540                 InsetListingsParams params(opt);
541                 if (!params.params().empty())
542                         os << "[" << from_utf8(params.params()) << "]";
543                 os << '{'  << from_utf8(incfile) << '}';
544         } else {
545                 runparams.exportdata->addExternalFile(tex_format, writefile,
546                                                       exportfile);
547
548                 // \include don't want extension and demands that the
549                 // file really have .tex
550                 incfile = changeExtension(incfile, string());
551                 incfile = latex_path(incfile);
552                 // FIXME UNICODE
553                 os << '\\' << from_ascii(params().getCmdName()) << '{'
554                    << from_utf8(incfile) << '}';
555         }
556
557         return 0;
558 }
559
560
561 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
562                             OutputParams const &) const
563 {
564         if (isVerbatim(params()) || isListings(params())) {
565                 os << '[' << getScreenLabel(buffer) << '\n';
566                 // FIXME: We don't know the encoding of the file, default to UTF-8.
567                 os << includedFilename(buffer, params()).fileContents("UTF-8");
568                 os << "\n]";
569                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
570         } else {
571                 docstring const str = '[' + getScreenLabel(buffer) + ']';
572                 os << str;
573                 return str.size();
574         }
575 }
576
577
578 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
579                           OutputParams const & runparams) const
580 {
581         string incfile = to_utf8(params()["filename"]);
582
583         // Do nothing if no file name has been specified
584         if (incfile.empty())
585                 return 0;
586
587         string const included_file = includedFilename(buffer, params()).absFilename();
588
589         //Check we're not trying to include ourselves.
590         //FIXME RECURSIVE INCLUDE
591         //This isn't sufficient, as the inclusion could be downstream.
592         //But it'll have to do for now.
593         if (buffer.absFileName() == included_file) {
594                 Alert::error(_("Recursive input"),
595                                bformat(_("Attempted to include file %1$s in itself! "
596                                "Ignoring inclusion."), from_utf8(incfile)));
597                 return 0;
598         }
599
600         // write it to a file (so far the complete file)
601         string const exportfile = changeExtension(incfile, ".sgml");
602         DocFileName writefile(changeExtension(included_file, ".sgml"));
603
604         if (loadIfNeeded(buffer, params())) {
605                 Buffer * tmp = theBufferList().getBuffer(included_file);
606
607                 string const mangled = writefile.mangledFilename();
608                 writefile = makeAbsPath(mangled,
609                                         buffer.masterBuffer()->temppath());
610                 if (!runparams.nice)
611                         incfile = mangled;
612
613                 LYXERR(Debug::LATEX, "incfile:" << incfile);
614                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
615                 LYXERR(Debug::LATEX, "writefile:" << writefile);
616
617                 tmp->makeDocBookFile(writefile, runparams, true);
618         }
619
620         runparams.exportdata->addExternalFile("docbook", writefile,
621                                               exportfile);
622         runparams.exportdata->addExternalFile("docbook-xml", writefile,
623                                               exportfile);
624
625         if (isVerbatim(params()) || isListings(params())) {
626                 os << "<inlinegraphic fileref=\""
627                    << '&' << include_label << ';'
628                    << "\" format=\"linespecific\">";
629         } else
630                 os << '&' << include_label << ';';
631
632         return 0;
633 }
634
635
636 void InsetInclude::validate(LaTeXFeatures & features) const
637 {
638         string incfile = to_utf8(params()["filename"]);
639         string writefile;
640
641         Buffer const & buffer = features.buffer();
642
643         string const included_file = includedFilename(buffer, params()).absFilename();
644
645         if (isLyXFilename(included_file))
646                 writefile = changeExtension(included_file, ".sgml");
647         else
648                 writefile = included_file;
649
650         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
651                 incfile = DocFileName(writefile).mangledFilename();
652                 writefile = makeAbsPath(incfile,
653                                         buffer.masterBuffer()->temppath()).absFilename();
654         }
655
656         features.includeFile(include_label, writefile);
657
658         if (isVerbatim(params()))
659                 features.require("verbatim");
660         else if (isListings(params()))
661                 features.require("listings");
662
663         // Here we must do the fun stuff...
664         // Load the file in the include if it needs
665         // to be loaded:
666         if (loadIfNeeded(buffer, params())) {
667                 // a file got loaded
668                 Buffer * const tmp = theBufferList().getBuffer(included_file);
669                 // make sure the buffer isn't us
670                 // FIXME RECURSIVE INCLUDES
671                 // This is not sufficient, as recursive includes could be
672                 // more than a file away. But it will do for now.
673                 if (tmp && tmp != & buffer) {
674                         // We must temporarily change features.buffer,
675                         // otherwise it would always be the master buffer,
676                         // and nested includes would not work.
677                         features.setBuffer(*tmp);
678                         tmp->validate(features);
679                         features.setBuffer(buffer);
680                 }
681         }
682 }
683
684
685 void InsetInclude::getLabelList(Buffer const & buffer,
686                                 std::vector<docstring> & list) const
687 {
688         if (isListings(params())) {
689                 InsetListingsParams p(to_utf8(params()["lstparams"]));
690                 string label = p.getParamValue("label");
691                 if (!label.empty())
692                         list.push_back(from_utf8(label));
693         }
694         else if (loadIfNeeded(buffer, params())) {
695                 string const included_file = includedFilename(buffer, params()).absFilename();
696                 Buffer * tmp = theBufferList().getBuffer(included_file);
697                 tmp->setParent(0);
698                 tmp->getLabelList(list);
699                 tmp->setParent(const_cast<Buffer *>(&buffer));
700         }
701 }
702
703
704 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
705                 BiblioInfo & keys, InsetIterator const & /*di*/) const
706 {
707         if (loadIfNeeded(buffer, params())) {
708                 string const included_file = includedFilename(buffer, params()).absFilename();
709                 Buffer * tmp = theBufferList().getBuffer(included_file);
710                 //FIXME This is kind of a dirty hack and should be made reasonable.
711                 tmp->setParent(0);
712                 keys.fillWithBibKeys(tmp);
713                 tmp->setParent(&buffer);
714         }
715 }
716
717
718 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
719 {
720         Buffer * const tmp = getChildBuffer(buffer, params());
721         if (tmp) {
722                 tmp->setParent(0);
723                 tmp->updateBibfilesCache();
724                 tmp->setParent(&buffer);
725         }
726 }
727
728
729 std::vector<FileName> const &
730 InsetInclude::getBibfilesCache(Buffer const & buffer) const
731 {
732         Buffer * const tmp = getChildBuffer(buffer, params());
733         if (tmp) {
734                 tmp->setParent(0);
735                 std::vector<FileName> const & cache = tmp->getBibfilesCache();
736                 tmp->setParent(&buffer);
737                 return cache;
738         }
739         static std::vector<FileName> const empty;
740         return empty;
741 }
742
743
744 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
745 {
746         BOOST_ASSERT(mi.base.bv);
747
748         bool use_preview = false;
749         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
750                 graphics::PreviewImage const * pimage =
751                         preview_->getPreviewImage(mi.base.bv->buffer());
752                 use_preview = pimage && pimage->image();
753         }
754
755         if (use_preview) {
756                 preview_->metrics(mi, dim);
757         } else {
758                 if (!set_label_) {
759                         set_label_ = true;
760                         button_.update(getScreenLabel(mi.base.bv->buffer()),
761                                        true);
762                 }
763                 button_.metrics(mi, dim);
764         }
765
766         Box b(0, dim.wid, -dim.asc, dim.des);
767         button_.setBox(b);
768 }
769
770
771 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
772 {
773         BOOST_ASSERT(pi.base.bv);
774
775         bool use_preview = false;
776         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
777                 graphics::PreviewImage const * pimage =
778                         preview_->getPreviewImage(pi.base.bv->buffer());
779                 use_preview = pimage && pimage->image();
780         }
781
782         if (use_preview)
783                 preview_->draw(pi, x, y);
784         else
785                 button_.draw(pi, x, y);
786 }
787
788
789 Inset::DisplayType InsetInclude::display() const
790 {
791         return type(params()) == INPUT ? Inline : AlignCenter;
792 }
793
794
795
796 //
797 // preview stuff
798 //
799
800 void InsetInclude::fileChanged() const
801 {
802         Buffer const * const buffer = updateFrontend();
803         if (!buffer)
804                 return;
805
806         preview_->removePreview(*buffer);
807         add_preview(*preview_.get(), *this, *buffer);
808         preview_->startLoading(*buffer);
809 }
810
811
812 namespace {
813
814 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
815 {
816         FileName const included_file = includedFilename(buffer, params);
817
818         return type(params) == INPUT && params.preview() &&
819                 included_file.isReadableFile();
820 }
821
822
823 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
824 {
825         odocstringstream os;
826         // We don't need to set runparams.encoding since this will be done
827         // by latex() anyway.
828         OutputParams runparams(0);
829         runparams.flavor = OutputParams::LATEX;
830         inset.latex(buffer, os, runparams);
831
832         return os.str();
833 }
834
835
836 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
837                  Buffer const & buffer)
838 {
839         InsetCommandParams const & params = inset.params();
840         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
841             preview_wanted(params, buffer)) {
842                 renderer.setAbsFile(includedFilename(buffer, params));
843                 docstring const snippet = latex_string(inset, buffer);
844                 renderer.addPreview(snippet, buffer);
845         }
846 }
847
848 } // namespace anon
849
850
851 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
852 {
853         Buffer const & buffer = ploader.buffer();
854         if (preview_wanted(params(), buffer)) {
855                 preview_->setAbsFile(includedFilename(buffer, params()));
856                 docstring const snippet = latex_string(*this, buffer);
857                 preview_->addPreview(snippet, ploader);
858         }
859 }
860
861
862 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
863         ParConstIterator const & pit) const
864 {
865         if (isListings(params())) {
866                 InsetListingsParams p(to_utf8(params()["lstparams"]));
867                 string caption = p.getParamValue("caption");
868                 if (caption.empty())
869                         return;
870                 Toc & toc = toclist["listing"];
871                 docstring const str = convert<docstring>(toc.size() + 1)
872                         + ". " +  from_utf8(caption);
873                 // This inset does not have a valid ParConstIterator
874                 // so it has to use the iterator of its parent paragraph
875                 toc.push_back(TocItem(pit, 0, str));
876                 return;
877         }
878         Buffer const * const childbuffer = getChildBuffer(buffer, params());
879         if (!childbuffer)
880                 return;
881
882         TocList const & childtoclist = childbuffer->tocBackend().tocs();
883         TocList::const_iterator it = childtoclist.begin();
884         TocList::const_iterator const end = childtoclist.end();
885         for(; it != end; ++it)
886                 toclist[it->first].insert(toclist[it->first].end(),
887                                 it->second.begin(), it->second.end());
888 }
889
890
891 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
892 {
893         Buffer const * const childbuffer = getChildBuffer(buffer, params());
894         if (childbuffer)
895                 lyx::updateLabels(*childbuffer, true);
896         else if (isListings(params())) {
897                 InsetListingsParams const par(to_utf8(params()["lstparams"]));
898                 if (par.getParamValue("caption").empty())
899                         listings_label_.clear();
900                 else {
901                         Counters & counters = buffer.params().getTextClass().counters();
902                         docstring const cnt = from_ascii("listing");
903                         if (counters.hasCounter(cnt)) {
904                                 counters.step(cnt);
905                                 listings_label_ = buffer.B_("Program Listing ")
906                                         + convert<docstring>(counters.value(cnt));
907                         } else
908                                 listings_label_ = buffer.B_("Program Listing");
909                 }
910         }
911 }
912
913
914 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
915         EmbeddedFiles & files) const
916 {
917         // include and input are temprarily not considered.
918         if (isVerbatim(params()) || isListings(params()))
919                 files.registerFile(includedFilename(buffer, params()).absFilename(),
920                         false, this);
921 }
922
923 } // namespace lyx