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