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