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