]> git.lyx.org Git - lyx.git/blob - src/insets/insetinclude.C
fix button caching bug with includeinset
[lyx.git] / src / insets / insetinclude.C
1 /**
2  * \file insetinclude.C
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 "gettext.h"
26 #include "LaTeXFeatures.h"
27 #include "lyx_main.h"
28 #include "lyxrc.h"
29 #include "lyxlex.h"
30 #include "metricsinfo.h"
31 #include "outputparams.h"
32
33 #include "frontends/Alert.h"
34 #include "frontends/LyXView.h"
35 #include "frontends/Painter.h"
36
37 #include "graphics/PreviewImage.h"
38 #include "graphics/PreviewLoader.h"
39
40 #include "insets/render_preview.h"
41
42 #include "support/filename.h"
43 #include "support/filetools.h"
44 #include "support/lstrings.h" // contains
45 #include "support/lyxlib.h"
46 #include "support/convert.h"
47
48 #include <boost/bind.hpp>
49 #include <boost/filesystem/operations.hpp>
50
51 #include "support/std_ostream.h"
52
53 #include <sstream>
54
55 using lyx::support::AddName;
56 using lyx::support::AbsolutePath;
57 using lyx::support::bformat;
58 using lyx::support::ChangeExtension;
59 using lyx::support::contains;
60 using lyx::support::copy;
61 using lyx::support::FileName;
62 using lyx::support::GetFileContents;
63 using lyx::support::IsFileReadable;
64 using lyx::support::IsLyXFilename;
65 using lyx::support::MakeAbsPath;
66 using lyx::support::MakeDisplayPath;
67 using lyx::support::MakeRelPath;
68 using lyx::support::OnlyFilename;
69 using lyx::support::OnlyPath;
70 using lyx::support::subst;
71 using lyx::support::sum;
72
73 using std::endl;
74 using std::string;
75 using std::auto_ptr;
76 using std::istringstream;
77 using std::ostream;
78 using std::ostringstream;
79
80 namespace fs = boost::filesystem;
81
82 extern BufferList bufferlist;
83
84
85 namespace {
86
87 string const uniqueID()
88 {
89         static unsigned int seed = 1000;
90         return "file" + convert<string>(++seed);
91 }
92
93 } // namespace anon
94
95
96 InsetInclude::InsetInclude(InsetCommandParams const & p)
97         : params_(p), include_label(uniqueID()),
98           preview_(new RenderMonitoredPreview(this)),
99           set_label_(false)
100 {
101         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
102 }
103
104
105 InsetInclude::InsetInclude(InsetInclude const & other)
106         : InsetOld(other),
107           params_(other.params_),
108           include_label(other.include_label),
109           preview_(new RenderMonitoredPreview(this)),
110           set_label_(false)
111 {
112         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
113 }
114
115
116 InsetInclude::~InsetInclude()
117 {
118         InsetIncludeMailer(*this).hideDialog();
119 }
120
121
122 void InsetInclude::doDispatch(LCursor & cur, FuncRequest & cmd)
123 {
124         switch (cmd.action) {
125
126         case LFUN_INSET_MODIFY: {
127                 InsetCommandParams p;
128                 InsetIncludeMailer::string2params(cmd.argument, p);
129                 if (!p.getCmdName().empty()) {
130                         set(p, cur.buffer());
131                         cur.bv().update();
132                 }
133                 break;
134         }
135
136         case LFUN_INSET_DIALOG_UPDATE:
137                 InsetIncludeMailer(*this).updateDialog(&cur.bv());
138                 break;
139
140         case LFUN_MOUSE_RELEASE:
141         case LFUN_INSET_DIALOG_SHOW:
142                 InsetIncludeMailer(*this).showDialog(&cur.bv());
143                 break;
144
145         default:
146                 InsetBase::doDispatch(cur, cmd);
147                 break;
148         }
149 }
150
151
152 InsetCommandParams const & InsetInclude::params() const
153 {
154         return params_;
155 }
156
157
158 namespace {
159
160 /// the type of inclusion
161 enum Types {
162         INCLUDE = 0,
163         VERB = 1,
164         INPUT = 2,
165         VERBAST = 3
166 };
167
168
169 Types type(InsetCommandParams const & params)
170 {
171         string const command_name = params.getCmdName();
172
173         if (command_name == "input")
174                 return INPUT;
175         if  (command_name == "verbatiminput")
176                 return VERB;
177         if  (command_name == "verbatiminput*")
178                 return VERBAST;
179         return INCLUDE;
180 }
181
182
183 bool isVerbatim(InsetCommandParams const & params)
184 {
185         string const command_name = params.getCmdName();
186         return command_name == "verbatiminput" ||
187                 command_name == "verbatiminput*";
188 }
189
190
191 string const masterFilename(Buffer const & buffer)
192 {
193         return buffer.getMasterBuffer()->fileName();
194 }
195
196
197 string const parentFilename(Buffer const & buffer)
198 {
199         return buffer.fileName();
200 }
201
202
203 string const includedFilename(Buffer const & buffer,
204                               InsetCommandParams const & params)
205 {
206         return MakeAbsPath(params.getContents(),
207                            OnlyPath(parentFilename(buffer)));
208 }
209
210
211 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
212
213 } // namespace anon
214
215
216 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
217 {
218         params_ = p;
219         set_label_ = false;
220
221         if (preview_->monitoring())
222                 preview_->stopMonitoring();
223
224         if (type(params_) == INPUT)
225                 add_preview(*preview_, *this, buffer);
226 }
227
228
229 auto_ptr<InsetBase> InsetInclude::doClone() const
230 {
231         return auto_ptr<InsetBase>(new InsetInclude(*this));
232 }
233
234
235 void InsetInclude::write(Buffer const &, ostream & os) const
236 {
237         write(os);
238 }
239
240
241 void InsetInclude::write(ostream & os) const
242 {
243         os << "Include " << params_.getCommand() << '\n'
244            << "preview " << convert<string>(params_.preview()) << '\n';
245 }
246
247
248 void InsetInclude::read(Buffer const &, LyXLex & lex)
249 {
250         read(lex);
251 }
252
253
254 void InsetInclude::read(LyXLex & lex)
255 {
256         params_.read(lex);
257 }
258
259
260 string const InsetInclude::getScreenLabel(Buffer const &) const
261 {
262         string temp;
263
264         switch (type(params_)) {
265                 case INPUT: temp += _("Input"); break;
266                 case VERB: temp += _("Verbatim Input"); break;
267                 case VERBAST: temp += _("Verbatim Input*"); break;
268                 case INCLUDE: temp += _("Include"); break;
269         }
270
271         temp += ": ";
272
273         if (params_.getContents().empty())
274                 temp += "???";
275         else
276                 temp += OnlyFilename(params_.getContents());
277
278         return temp;
279 }
280
281
282 namespace {
283
284 /// return true if the file is or got loaded.
285 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
286 {
287         if (isVerbatim(params))
288                 return false;
289
290         string const included_file = includedFilename(buffer, params);
291         if (!IsLyXFilename(included_file))
292                 return false;
293
294         Buffer * buf = bufferlist.getBuffer(included_file);
295         if (!buf) {
296                 // the readonly flag can/will be wrong, not anymore I think.
297                 if (!fs::exists(included_file))
298                         return false;
299                 buf = bufferlist.newBuffer(included_file);
300                 if (!loadLyXFile(buf, included_file))
301                         return false;
302         }
303         if (buf)
304                 buf->setParentName(parentFilename(buffer));
305         return buf != 0;
306 }
307
308
309 } // namespace anon
310
311
312 int InsetInclude::latex(Buffer const & buffer, ostream & os,
313                         OutputParams const & runparams) const
314 {
315         string incfile(params_.getContents());
316
317         // Do nothing if no file name has been specified
318         if (incfile.empty())
319                 return 0;
320
321         string const included_file = includedFilename(buffer, params_);
322         Buffer const * const m_buffer = buffer.getMasterBuffer();
323
324         // if incfile is relative, make it relative to the master
325         // buffer directory.
326         if (!AbsolutePath(incfile)) {
327                 incfile = MakeRelPath(included_file,
328                                       m_buffer->filePath());
329         }
330
331         // write it to a file (so far the complete file)
332         string const exportfile = ChangeExtension(incfile, ".tex");
333         string const mangled = FileName(ChangeExtension(included_file,
334                                                         ".tex")).mangledFilename();
335         string const writefile = MakeAbsPath(mangled, m_buffer->temppath());
336
337         if (!runparams.nice)
338                 incfile = mangled;
339         lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
340         lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
341         lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
342
343         if (loadIfNeeded(buffer, params_)) {
344                 Buffer * tmp = bufferlist.getBuffer(included_file);
345
346                 if (tmp->params().textclass != m_buffer->params().textclass) {
347                         string text = bformat(_("Included file `%1$s'\n"
348                                                 "has textclass `%2$s'\n"
349                                                 "while parent file has textclass `%3$s'."),
350                                               MakeDisplayPath(included_file),
351                                               tmp->params().getLyXTextClass().name(),
352                                               m_buffer->params().getLyXTextClass().name());
353                         Alert::warning(_("Different textclasses"), text);
354                         //return 0;
355                 }
356
357                 tmp->markDepClean(m_buffer->temppath());
358
359 #ifdef WITH_WARNINGS
360 #warning Second argument is irrelevant!
361 // since only_body is true, makeLaTeXFile will not look at second
362 // argument. Should we set it to string(), or should makeLaTeXFile
363 // make use of it somehow? (JMarc 20031002)
364 #endif
365                 tmp->makeLaTeXFile(writefile,
366                                    OnlyPath(masterFilename(buffer)),
367                                    runparams, false);
368         } else {
369                 // Copy the file to the temp dir, so that .aux files etc.
370                 // are not created in the original dir. Files included by
371                 // this file will be found via input@path, see ../buffer.C.
372                 unsigned long const checksum_in  = sum(included_file);
373                 unsigned long const checksum_out = sum(writefile);
374
375                 if (checksum_in != checksum_out) {
376                         if (!copy(included_file, writefile)) {
377                                 lyxerr[Debug::LATEX]
378                                         << bformat(_("Could not copy the file\n%1$s\n"
379                                                      "into the temporary directory."),
380                                                    included_file)
381                                         << endl;
382                                 return 0;
383                         }
384                 }
385         }
386
387         if (isVerbatim(params_)) {
388                 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
389         } else if (type(params_) == INPUT) {
390                 runparams.exportdata->addExternalFile("latex", writefile,
391                                                       exportfile);
392
393                 // \input wants file with extension (default is .tex)
394                 if (!IsLyXFilename(included_file)) {
395                         os << '\\' << params_.getCmdName() << '{' << incfile << '}';
396                 } else {
397                         os << '\\' << params_.getCmdName() << '{'
398                            << ChangeExtension(incfile, ".tex")
399                            <<  '}';
400                 }
401         } else {
402                 runparams.exportdata->addExternalFile("latex", writefile,
403                                                       exportfile);
404
405                 // \include don't want extension and demands that the
406                 // file really have .tex
407                 os << '\\' << params_.getCmdName() << '{'
408                    << ChangeExtension(incfile, string())
409                    << '}';
410         }
411
412         return 0;
413 }
414
415
416 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
417                         OutputParams const &) const
418 {
419         if (isVerbatim(params_))
420                 os << GetFileContents(includedFilename(buffer, params_));
421         return 0;
422 }
423
424
425 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
426                            OutputParams const & runparams) const
427 {
428         string incfile(params_.getContents());
429
430         // Do nothing if no file name has been specified
431         if (incfile.empty())
432                 return 0;
433
434         string const included_file = includedFilename(buffer, params_);
435
436         // write it to a file (so far the complete file)
437         string const exportfile = ChangeExtension(incfile, ".sgml");
438         string writefile = ChangeExtension(included_file, ".sgml");
439
440         if (loadIfNeeded(buffer, params_)) {
441                 Buffer * tmp = bufferlist.getBuffer(included_file);
442
443                 writefile = MakeAbsPath(FileName(writefile).mangledFilename(),
444                                         buffer.getMasterBuffer()->temppath());
445                 if (!runparams.nice)
446                         incfile = writefile;
447
448                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
449                 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
450                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
451
452                 tmp->makeLinuxDocFile(writefile, runparams, true);
453         }
454
455         if (isVerbatim(params_)) {
456                 os << "<![CDATA["
457                    << GetFileContents(included_file)
458                    << "]]>";
459         } else {
460                 runparams.exportdata->addExternalFile("linuxdoc", writefile,
461                                                       exportfile);
462                 os << '&' << include_label << ';';
463         }
464
465         return 0;
466 }
467
468
469 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
470                           OutputParams const & runparams) const
471 {
472         string incfile(params_.getContents());
473
474         // Do nothing if no file name has been specified
475         if (incfile.empty())
476                 return 0;
477
478         string const included_file = includedFilename(buffer, params_);
479
480         // write it to a file (so far the complete file)
481         string const exportfile = ChangeExtension(incfile, ".sgml");
482         string writefile = ChangeExtension(included_file, ".sgml");
483
484         if (loadIfNeeded(buffer, params_)) {
485                 Buffer * tmp = bufferlist.getBuffer(included_file);
486
487                 string const mangled = FileName(writefile).mangledFilename();
488                 writefile = MakeAbsPath(mangled,
489                                         buffer.getMasterBuffer()->temppath());
490                 if (!runparams.nice)
491                         incfile = mangled;
492
493                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
494                 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
495                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
496
497                 tmp->makeDocBookFile(writefile, runparams, true);
498         }
499
500         runparams.exportdata->addExternalFile("docbook", writefile,
501                                               exportfile);
502         runparams.exportdata->addExternalFile("docbook-xml", writefile,
503                                               exportfile);
504
505         if (isVerbatim(params_)) {
506                 os << "<inlinegraphic fileref=\""
507                    << '&' << include_label << ';'
508                    << "\" format=\"linespecific\">";
509         } else
510                 os << '&' << include_label << ';';
511
512         return 0;
513 }
514
515
516 void InsetInclude::validate(LaTeXFeatures & features) const
517 {
518         string incfile(params_.getContents());
519         string writefile;
520
521         Buffer const & buffer = features.buffer();
522
523         string const included_file = includedFilename(buffer, params_);
524
525         if (IsLyXFilename(included_file))
526                 writefile = ChangeExtension(included_file, ".sgml");
527         else
528                 writefile = included_file;
529
530         if (!features.nice() && !isVerbatim(params_)) {
531                 incfile = FileName(writefile).mangledFilename();
532                 writefile = MakeAbsPath(incfile,
533                                         buffer.getMasterBuffer()->temppath());
534         }
535
536         features.includeFile(include_label, writefile);
537
538         if (isVerbatim(params_))
539                 features.require("verbatim");
540
541         // Here we must do the fun stuff...
542         // Load the file in the include if it needs
543         // to be loaded:
544         if (loadIfNeeded(buffer, params_)) {
545                 // a file got loaded
546                 Buffer * const tmp = bufferlist.getBuffer(included_file);
547                 if (tmp) {
548                         // We must temporarily change features.buffer,
549                         // otherwise it would always be the master buffer,
550                         // and nested includes would not work.
551                         features.setBuffer(*tmp);
552                         tmp->validate(features);
553                         features.setBuffer(buffer);
554                 }
555         }
556 }
557
558
559 void InsetInclude::getLabelList(Buffer const & buffer,
560                                 std::vector<string> & list) const
561 {
562         if (loadIfNeeded(buffer, params_)) {
563                 string const included_file = includedFilename(buffer, params_);
564                 Buffer * tmp = bufferlist.getBuffer(included_file);
565                 tmp->setParentName("");
566                 tmp->getLabelList(list);
567                 tmp->setParentName(parentFilename(buffer));
568         }
569 }
570
571
572 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
573                                    std::vector<std::pair<string,string> > & keys) const
574 {
575         if (loadIfNeeded(buffer, params_)) {
576                 string const included_file = includedFilename(buffer, params_);
577                 Buffer * tmp = bufferlist.getBuffer(included_file);
578                 tmp->setParentName("");
579                 tmp->fillWithBibKeys(keys);
580                 tmp->setParentName(parentFilename(buffer));
581         }
582 }
583
584
585 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
586 {
587         BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
588
589         bool use_preview = false;
590         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
591                 lyx::graphics::PreviewImage const * pimage =
592                         preview_->getPreviewImage(*mi.base.bv->buffer());
593                 use_preview = pimage && pimage->image();
594         }
595
596         if (use_preview) {
597                 preview_->metrics(mi, dim);
598         } else {
599                 if (!set_label_) {
600                         set_label_ = true;
601                         button_.update(getScreenLabel(*mi.base.bv->buffer()),
602                                        true);
603                 }
604                 button_.metrics(mi, dim);
605         }
606
607         Box b(0, dim.wid, -dim.asc, dim.des);
608         button_.setBox(b);
609
610         dim_ = dim;
611 }
612
613
614 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
615 {
616         setPosCache(pi, x, y);
617
618         BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
619
620         bool use_preview = false;
621         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
622                 lyx::graphics::PreviewImage const * pimage =
623                         preview_->getPreviewImage(*pi.base.bv->buffer());
624                 use_preview = pimage && pimage->image();
625         }
626
627         if (use_preview)
628                 preview_->draw(pi, x, y);
629         else
630                 button_.draw(pi, x, y);
631 }
632
633 bool InsetInclude::display() const
634 {
635         return type(params_) != INPUT;
636 }
637
638
639
640 //
641 // preview stuff
642 //
643
644 void InsetInclude::fileChanged() const
645 {
646         Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
647         if (!buffer_ptr)
648                 return;
649
650         Buffer const & buffer = *buffer_ptr;
651         preview_->removePreview(buffer);
652         add_preview(*preview_.get(), *this, buffer);
653         preview_->startLoading(buffer);
654 }
655
656
657 namespace {
658
659 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
660 {
661         string const included_file = includedFilename(buffer, params);
662
663         return type(params) == INPUT && params.preview() &&
664                 IsFileReadable(included_file);
665 }
666
667
668 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
669 {
670         ostringstream os;
671         OutputParams runparams;
672         runparams.flavor = OutputParams::LATEX;
673         inset.latex(buffer, os, runparams);
674
675         return os.str();
676 }
677
678
679 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
680                  Buffer const & buffer)
681 {
682         InsetCommandParams const & params = inset.params();
683         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
684             preview_wanted(params, buffer)) {
685                 renderer.setAbsFile(includedFilename(buffer, params));
686                 string const snippet = latex_string(inset, buffer);
687                 renderer.addPreview(snippet, buffer);
688         }
689 }
690
691 } // namespace anon
692
693
694 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
695 {
696         Buffer const & buffer = ploader.buffer();
697         if (preview_wanted(params(), buffer)) {
698                 preview_->setAbsFile(includedFilename(buffer, params()));
699                 string const snippet = latex_string(*this, buffer);
700                 preview_->addPreview(snippet, ploader);
701         }
702 }
703
704
705 string const InsetIncludeMailer::name_("include");
706
707 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
708         : inset_(inset)
709 {}
710
711
712 string const InsetIncludeMailer::inset2string(Buffer const &) const
713 {
714         return params2string(inset_.params());
715 }
716
717
718 void InsetIncludeMailer::string2params(string const & in,
719                                        InsetCommandParams & params)
720 {
721         params = InsetCommandParams();
722         if (in.empty())
723                 return;
724
725         istringstream data(in);
726         LyXLex lex(0,0);
727         lex.setStream(data);
728
729         string name;
730         lex >> name;
731         if (!lex || name != name_)
732                 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
733
734         // This is part of the inset proper that is usually swallowed
735         // by LyXText::readInset
736         string id;
737         lex >> id;
738         if (!lex || id != "Include")
739                 return print_mailer_error("InsetBoxMailer", in, 2, "Include");
740
741         InsetInclude inset(params);
742         inset.read(lex);
743         params = inset.params();
744 }
745
746
747 string const
748 InsetIncludeMailer::params2string(InsetCommandParams const & params)
749 {
750         InsetInclude inset(params);
751         ostringstream data;
752         data << name_ << ' ';
753         inset.write(data);
754         data << "\\end_inset\n";
755         return data.str();
756 }