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