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