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