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