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