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