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