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