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