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