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