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