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