]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
Fix GRAPHICS_EDIT of InsetGraphics
[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 "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.setInzipName(to_utf8(params["embed"]));
149         file.enable(buffer.embedded(), &buffer, false);
150         return file;
151 }
152
153 InsetLabel * createLabel(docstring const & label_str)
154 {
155         if (label_str.empty())
156                 return 0;
157         InsetCommandParams icp(LABEL_CODE);
158         icp["name"] = label_str;
159         return new InsetLabel(icp);
160 }
161
162 } // namespace anon
163
164
165 InsetInclude::InsetInclude(InsetCommandParams const & p)
166         : InsetCommand(p, "include"), include_label(uniqueID()),
167           preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
168 {
169         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
170
171         if (isListings(params())) {
172                 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
173                 label_ = createLabel(from_utf8(listing_params.getParamValue("label")));
174         }
175 }
176
177
178 InsetInclude::InsetInclude(InsetInclude const & other)
179         : InsetCommand(other), include_label(other.include_label),
180           preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
181 {
182         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
183
184         if (other.label_)
185                 label_ = new InsetLabel(*other.label_);
186 }
187
188
189 InsetInclude::~InsetInclude()
190 {
191         delete label_;
192         if (isVerbatim(params()) || isListings(params()))
193                 return;
194
195
196         string const parent_filename = buffer().absFileName();
197         FileName const included_file = makeAbsPath(to_utf8(params()["filename"]),
198                            onlyPath(parent_filename));
199
200         if (!isLyXFilename(included_file.absFilename()))
201                 return;
202
203         Buffer * child = theBufferList().getBuffer(included_file.absFilename());
204         // File not opened, nothing to close.
205         if (!child)
206                 return;
207
208         // Child document has a different parent, don't close it.
209         if (child->parent() != &buffer())
210                 return;
211
212         //close the buffer.
213         theBufferList().release(child);
214 }
215
216
217 void InsetInclude::setBuffer(Buffer & buffer)
218 {
219         if (buffer_) {
220                 try {
221                         EmbeddedFile file_from = includedFilename(*buffer_, params());
222                         EmbeddedFile file_to = file_from.copyTo(&buffer);
223                         if (file_to.embedded())
224                                 setParam("embed", from_utf8(file_to.inzipName()));
225                 } catch (ExceptionMessage const & message) {
226                         Alert::error(message.title_, message.details_);
227                         // failed to embed
228                         setParam("embed", docstring());
229                 }
230
231         }
232         buffer_ = &buffer;
233         if (label_)
234                 label_->setBuffer(buffer);
235
236 }
237
238
239 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
240 {
241         // FIXME
242         // This is only correct for the case of listings, but it'll do for now.
243         // In the other cases, this second parameter should just be empty.
244         static ParamInfo param_info_;
245         if (param_info_.empty()) {
246                 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
247                 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
248                 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
249         }
250         return param_info_;
251 }
252
253
254 bool InsetInclude::isCompatibleCommand(string const & s)
255 {
256         return type(s) != NONE;
257 }
258
259
260 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
261 {
262         BOOST_ASSERT(&cur.buffer() == &buffer());
263         switch (cmd.action) {
264
265         case LFUN_INSET_MODIFY: {
266                 InsetCommandParams p(INCLUDE_CODE);
267                 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
268                 if (!p.getCmdName().empty()) {
269                         if (isListings(p)){
270                                 InsetListingsParams new_params(to_utf8(p["lstparams"]));
271                                 docstring const label_str = from_utf8(new_params.getParamValue("label"));
272                                 if (label_str.empty())
273                                         delete label_;
274                                 else if (label_)
275                                         label_->updateCommand(label_str);
276                                 else {
277                                         label_ = createLabel(label_str);
278                                         label_->setBuffer(buffer());
279                                         label_->initView();
280                                 }
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                 }
478
479                 // Make sure modules used in child are all included in master
480                 //FIXME It might be worth loading the children's modules into the master
481                 //over in BufferParams rather than doing this check.
482                 vector<string> const masterModules = masterBuffer->params().getModules();
483                 vector<string> const childModules = tmp->params().getModules();
484                 vector<string>::const_iterator it = childModules.begin();
485                 vector<string>::const_iterator end = childModules.end();
486                 for (; it != end; ++it) {
487                         string const module = *it;
488                         vector<string>::const_iterator found =
489                                 find(masterModules.begin(), masterModules.end(), module);
490                         if (found == masterModules.end()) {
491                                 docstring text = bformat(_("Included file `%1$s'\n"
492                                         "uses module `%2$s'\n"
493                                         "which is not used in parent file."),
494                                         included_file.displayName(), from_utf8(module));
495                                 Alert::warning(_("Module not found"), text);
496                         }
497                 }
498
499                 tmp->markDepClean(masterBuffer->temppath());
500
501 // FIXME: handle non existing files
502 // FIXME: Second argument is irrelevant!
503 // since only_body is true, makeLaTeXFile will not look at second
504 // argument. Should we set it to string(), or should makeLaTeXFile
505 // make use of it somehow? (JMarc 20031002)
506                 // The included file might be written in a different encoding
507                 Encoding const * const oldEnc = runparams.encoding;
508                 runparams.encoding = &tmp->params().encoding();
509                 tmp->makeLaTeXFile(writefile,
510                                    masterFileName(buffer()).onlyPath().absFilename(),
511                                    runparams, false);
512                 runparams.encoding = oldEnc;
513         } else {
514                 // In this case, it's not a LyX file, so we copy the file
515                 // to the temp dir, so that .aux files etc. are not created
516                 // in the original dir. Files included by this file will be
517                 // found via input@path, see ../Buffer.cpp.
518                 unsigned long const checksum_in  = included_file.checksum();
519                 unsigned long const checksum_out = writefile.checksum();
520
521                 if (checksum_in != checksum_out) {
522                         if (!included_file.copyTo(writefile)) {
523                                 // FIXME UNICODE
524                                 LYXERR(Debug::LATEX,
525                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
526                                                                   "into the temporary directory."),
527                                                    from_utf8(included_file.absFilename()))));
528                                 return 0;
529                         }
530                 }
531         }
532
533         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
534                         "latex" : "pdflatex";
535         if (isVerbatim(params())) {
536                 incfile = latex_path(incfile);
537                 // FIXME UNICODE
538                 os << '\\' << from_ascii(params().getCmdName()) << '{'
539                    << from_utf8(incfile) << '}';
540         } else if (type(params()) == INPUT) {
541                 runparams.exportdata->addExternalFile(tex_format, writefile,
542                                                       exportfile);
543
544                 // \input wants file with extension (default is .tex)
545                 if (!isLyXFilename(included_file.absFilename())) {
546                         incfile = latex_path(incfile);
547                         // FIXME UNICODE
548                         os << '\\' << from_ascii(params().getCmdName())
549                            << '{' << from_utf8(incfile) << '}';
550                 } else {
551                 incfile = changeExtension(incfile, ".tex");
552                 incfile = latex_path(incfile);
553                         // FIXME UNICODE
554                         os << '\\' << from_ascii(params().getCmdName())
555                            << '{' << from_utf8(incfile) <<  '}';
556                 }
557         } else if (type(params()) == LISTINGS) {
558                 os << '\\' << from_ascii(params().getCmdName());
559                 string const opt = to_utf8(params()["lstparams"]);
560                 // opt is set in QInclude dialog and should have passed validation.
561                 InsetListingsParams params(opt);
562                 if (!params.params().empty())
563                         os << "[" << from_utf8(params.params()) << "]";
564                 os << '{'  << from_utf8(incfile) << '}';
565         } else {
566                 runparams.exportdata->addExternalFile(tex_format, writefile,
567                                                       exportfile);
568
569                 // \include don't want extension and demands that the
570                 // file really have .tex
571                 incfile = changeExtension(incfile, string());
572                 incfile = latex_path(incfile);
573                 // FIXME UNICODE
574                 os << '\\' << from_ascii(params().getCmdName()) << '{'
575                    << from_utf8(incfile) << '}';
576         }
577
578         return 0;
579 }
580
581
582 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
583 {
584         if (isVerbatim(params()) || isListings(params())) {
585                 os << '[' << screenLabel() << '\n';
586                 // FIXME: We don't know the encoding of the file, default to UTF-8.
587                 os << includedFilename(buffer(), params()).fileContents("UTF-8");
588                 os << "\n]";
589                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
590         } else {
591                 docstring const str = '[' + screenLabel() + ']';
592                 os << str;
593                 return str.size();
594         }
595 }
596
597
598 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
599 {
600         string incfile = to_utf8(params()["filename"]);
601
602         // Do nothing if no file name has been specified
603         if (incfile.empty())
604                 return 0;
605
606         string const included_file = includedFilename(buffer(), params()).absFilename();
607
608         // Check we're not trying to include ourselves.
609         // FIXME RECURSIVE INCLUDE
610         // This isn't sufficient, as the inclusion could be downstream.
611         // But it'll have to do for now.
612         if (buffer().absFileName() == included_file) {
613                 Alert::error(_("Recursive input"),
614                                bformat(_("Attempted to include file %1$s in itself! "
615                                "Ignoring inclusion."), from_utf8(incfile)));
616                 return 0;
617         }
618
619         // write it to a file (so far the complete file)
620         string const exportfile = changeExtension(incfile, ".sgml");
621         DocFileName writefile(changeExtension(included_file, ".sgml"));
622
623         if (loadIfNeeded(buffer(), params())) {
624                 Buffer * tmp = theBufferList().getBuffer(included_file);
625
626                 string const mangled = writefile.mangledFilename();
627                 writefile = makeAbsPath(mangled,
628                                         buffer().masterBuffer()->temppath());
629                 if (!runparams.nice)
630                         incfile = mangled;
631
632                 LYXERR(Debug::LATEX, "incfile:" << incfile);
633                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
634                 LYXERR(Debug::LATEX, "writefile:" << writefile);
635
636                 tmp->makeDocBookFile(writefile, runparams, true);
637         }
638
639         runparams.exportdata->addExternalFile("docbook", writefile,
640                                               exportfile);
641         runparams.exportdata->addExternalFile("docbook-xml", writefile,
642                                               exportfile);
643
644         if (isVerbatim(params()) || isListings(params())) {
645                 os << "<inlinegraphic fileref=\""
646                    << '&' << include_label << ';'
647                    << "\" format=\"linespecific\">";
648         } else
649                 os << '&' << include_label << ';';
650
651         return 0;
652 }
653
654
655 void InsetInclude::validate(LaTeXFeatures & features) const
656 {
657         string incfile = to_utf8(params()["filename"]);
658         string writefile;
659
660         BOOST_ASSERT(&buffer() == &features.buffer());
661
662         string const included_file =
663                 includedFilename(buffer(), params()).availableFile().absFilename();
664
665         if (isLyXFilename(included_file))
666                 writefile = changeExtension(included_file, ".sgml");
667         else
668                 writefile = included_file;
669
670         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
671                 incfile = DocFileName(writefile).mangledFilename();
672                 writefile = makeAbsPath(incfile,
673                                         buffer().masterBuffer()->temppath()).absFilename();
674         }
675
676         features.includeFile(include_label, writefile);
677
678         if (isVerbatim(params()))
679                 features.require("verbatim");
680         else if (isListings(params()))
681                 features.require("listings");
682
683         // Here we must do the fun stuff...
684         // Load the file in the include if it needs
685         // to be loaded:
686         if (loadIfNeeded(buffer(), params())) {
687                 // a file got loaded
688                 Buffer * const tmp = theBufferList().getBuffer(included_file);
689                 // make sure the buffer isn't us
690                 // FIXME RECURSIVE INCLUDES
691                 // This is not sufficient, as recursive includes could be
692                 // more than a file away. But it will do for now.
693                 if (tmp && tmp != &buffer()) {
694                         // We must temporarily change features.buffer,
695                         // otherwise it would always be the master buffer,
696                         // and nested includes would not work.
697                         features.setBuffer(*tmp);
698                         tmp->validate(features);
699                         features.setBuffer(buffer());
700                 }
701         }
702 }
703
704
705 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
706         InsetIterator const & /*di*/) const
707 {
708         if (loadIfNeeded(buffer(), params())) {
709                 string const included_file = includedFilename(buffer(), params()).absFilename();
710                 Buffer * tmp = theBufferList().getBuffer(included_file);
711                 //FIXME This is kind of a dirty hack and should be made reasonable.
712                 tmp->setParent(0);
713                 keys.fillWithBibKeys(tmp);
714                 tmp->setParent(&buffer());
715         }
716 }
717
718
719 void InsetInclude::updateBibfilesCache()
720 {
721         Buffer * const tmp = getChildBuffer(buffer(), params());
722         if (tmp) {
723                 tmp->setParent(0);
724                 tmp->updateBibfilesCache();
725                 tmp->setParent(&buffer());
726         }
727 }
728
729
730 EmbeddedFileList const &
731 InsetInclude::getBibfilesCache(Buffer const & buffer) const
732 {
733         Buffer * const tmp = getChildBuffer(buffer, params());
734         if (tmp) {
735                 tmp->setParent(0);
736                 EmbeddedFileList const & cache = tmp->getBibfilesCache();
737                 tmp->setParent(&buffer);
738                 return cache;
739         }
740         static EmbeddedFileList const empty;
741         return empty;
742 }
743
744
745 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
746 {
747         BOOST_ASSERT(mi.base.bv);
748
749         bool use_preview = false;
750         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
751                 graphics::PreviewImage const * pimage =
752                         preview_->getPreviewImage(mi.base.bv->buffer());
753                 use_preview = pimage && pimage->image();
754         }
755
756         if (use_preview) {
757                 preview_->metrics(mi, dim);
758         } else {
759                 if (!set_label_) {
760                         set_label_ = true;
761                         button_.update(screenLabel(), true);
762                 }
763                 button_.metrics(mi, dim);
764         }
765
766         Box b(0, dim.wid, -dim.asc, dim.des);
767         button_.setBox(b);
768 }
769
770
771 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
772 {
773         BOOST_ASSERT(pi.base.bv);
774
775         bool use_preview = false;
776         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
777                 graphics::PreviewImage const * pimage =
778                         preview_->getPreviewImage(pi.base.bv->buffer());
779                 use_preview = pimage && pimage->image();
780         }
781
782         if (use_preview)
783                 preview_->draw(pi, x, y);
784         else
785                 button_.draw(pi, x, y);
786 }
787
788
789 Inset::DisplayType InsetInclude::display() const
790 {
791         return type(params()) == INPUT ? Inline : AlignCenter;
792 }
793
794
795
796 //
797 // preview stuff
798 //
799
800 void InsetInclude::fileChanged() const
801 {
802         Buffer const * const buffer = updateFrontend();
803         if (!buffer)
804                 return;
805
806         preview_->removePreview(*buffer);
807         add_preview(*preview_.get(), *this, *buffer);
808         preview_->startLoading(*buffer);
809 }
810
811
812 namespace {
813
814 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
815 {
816         FileName const included_file = includedFilename(buffer, params);
817
818         return type(params) == INPUT && params.preview() &&
819                 included_file.isReadableFile();
820 }
821
822
823 docstring latexString(InsetInclude const & inset)
824 {
825         odocstringstream os;
826         // We don't need to set runparams.encoding since this will be done
827         // by latex() anyway.
828         OutputParams runparams(0);
829         runparams.flavor = OutputParams::LATEX;
830         inset.latex(os, runparams);
831
832         return os.str();
833 }
834
835
836 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
837                  Buffer const & buffer)
838 {
839         InsetCommandParams const & params = inset.params();
840         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
841             preview_wanted(params, buffer)) {
842                 renderer.setAbsFile(includedFilename(buffer, params));
843                 docstring const snippet = latexString(inset);
844                 renderer.addPreview(snippet, buffer);
845         }
846 }
847
848 } // namespace anon
849
850
851 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
852 {
853         Buffer const & buffer = ploader.buffer();
854         if (!preview_wanted(params(), buffer))
855                 return;
856         preview_->setAbsFile(includedFilename(buffer, params()));
857         docstring const snippet = latexString(*this);
858         preview_->addPreview(snippet, ploader);
859 }
860
861
862 void InsetInclude::addToToc(ParConstIterator const & cpit) const
863 {
864         bool const embedded_status = !params()["embed"].empty();
865         TocBackend & backend = buffer().tocBackend();
866
867         if (isListings(params())) {
868                 if (label_)
869                         label_->addToToc(cpit);
870
871                 InsetListingsParams p(to_utf8(params()["lstparams"]));
872                 string caption = p.getParamValue("caption");
873                 if (caption.empty())
874                         return;
875                 Toc & toc = backend.toc("listing");
876                 docstring str = convert<docstring>(toc.size() + 1)
877                         + ". " +  from_utf8(caption);
878                 if (embedded_status) {
879                         backend.toc("embedded").push_back(TocItem(cpit, 0, str));
880                         str += _(" (embedded)");
881                 }
882                 ParConstIterator pit = cpit;
883                 pit.push_back(*this);
884                 toc.push_back(TocItem(pit, 0, str));
885                 return;
886         }
887         Buffer const * const childbuffer = getChildBuffer(buffer(), params());
888         if (!childbuffer) {
889                 if (embedded_status) 
890                         // Add it to the embedded list nonetheless.
891                         backend.toc("embedded").push_back(TocItem(cpit, 0,
892                                 params()["filename"]));
893                 return;
894         }
895
896         Toc & toc = backend.toc("child");
897         docstring str = childbuffer->fileName().displayName();
898         if (embedded_status) {
899                 backend.toc("embedded").push_back(TocItem(cpit, 0, str));
900                 str += _(" (embedded)");
901         }
902         toc.push_back(TocItem(cpit, 0, str));
903
904         TocList & toclist = backend.tocs();
905         TocList const & childtoclist = childbuffer->tocBackend().tocs();
906         TocList::const_iterator it = childtoclist.begin();
907         TocList::const_iterator const end = childtoclist.end();
908         for(; it != end; ++it)
909                 toclist[it->first].insert(toclist[it->first].end(),
910                         it->second.begin(), it->second.end());
911 }
912
913
914 void InsetInclude::updateLabels(ParIterator const & it)
915 {
916         Buffer const * const childbuffer = getChildBuffer(buffer(), params());
917         if (childbuffer) {
918                 lyx::updateLabels(*childbuffer, true);
919                 return;
920         }
921         if (!isListings(params()))
922                 return;
923
924         if (label_)
925                 label_->updateLabels(it);
926
927         InsetListingsParams const par(to_utf8(params()["lstparams"]));
928         if (par.getParamValue("caption").empty()) {
929                 listings_label_.clear();
930                 return;
931         }
932         Counters & counters = buffer().params().documentClass().counters();
933         docstring const cnt = from_ascii("listing");
934         listings_label_ = buffer().B_("Program Listing");
935         if (counters.hasCounter(cnt)) {
936                 counters.step(cnt);
937                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
938         }
939 }
940
941
942 void InsetInclude::registerEmbeddedFiles(EmbeddedFileList & files) const
943 {
944         files.registerFile(includedFilename(buffer(), params()), this, buffer());
945 }
946
947
948 void InsetInclude::updateEmbeddedFile(EmbeddedFile const & file)
949 {
950         InsetCommandParams p = params();
951         p["filename"] = from_utf8(file.outputFilename());
952         p["embed"] = file.embedded() ? from_utf8(file.inzipName()) : docstring();
953         setParams(p);
954 }
955
956
957 } // namespace lyx