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