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