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