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