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