]> git.lyx.org Git - lyx.git/blob - src/insets/insetinclude.C
Refactoring of renderer code to make inset code simpler.
[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/PreviewLoader.h"
36
37 #include "insets/render_preview.h"
38
39 #include "support/FileInfo.h"
40 #include "support/filename.h"
41 #include "support/filetools.h"
42 #include "support/lstrings.h" // contains
43 #include "support/lyxlib.h"
44 #include "support/tostr.h"
45
46 #include <boost/bind.hpp>
47
48 #include "support/std_ostream.h"
49 #include "support/std_sstream.h"
50
51 using lyx::support::AddName;
52 using lyx::support::AbsolutePath;
53 using lyx::support::bformat;
54 using lyx::support::ChangeExtension;
55 using lyx::support::contains;
56 using lyx::support::copy;
57 using lyx::support::FileInfo;
58 using lyx::support::FileName;
59 using lyx::support::GetFileContents;
60 using lyx::support::IsFileReadable;
61 using lyx::support::IsLyXFilename;
62 using lyx::support::MakeAbsPath;
63 using lyx::support::MakeDisplayPath;
64 using lyx::support::MakeRelPath;
65 using lyx::support::OnlyFilename;
66 using lyx::support::OnlyPath;
67 using lyx::support::subst;
68 using lyx::support::sum;
69
70 using std::endl;
71 using std::string;
72 using std::auto_ptr;
73 using std::istringstream;
74 using std::ostream;
75 using std::ostringstream;
76
77
78 extern BufferList bufferlist;
79
80
81 namespace {
82
83 string const uniqueID()
84 {
85         static unsigned int seed = 1000;
86         return "file" + tostr(++seed);
87 }
88
89 } // namespace anon
90
91
92 InsetInclude::InsetInclude(InsetCommandParams const & p)
93         : params_(p), include_label(uniqueID()),
94           preview_(new RenderMonitoredPreview(this)),
95           set_label_(false)
96 {
97         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
98 }
99
100
101 InsetInclude::InsetInclude(InsetInclude const & other)
102         : InsetOld(other),
103           params_(other.params_),
104           include_label(other.include_label),
105           preview_(new RenderMonitoredPreview(this)),
106           set_label_(other.set_label_)
107 {
108         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
109 }
110
111
112 InsetInclude::~InsetInclude()
113 {
114         InsetIncludeMailer(*this).hideDialog();
115 }
116
117
118 void InsetInclude::priv_dispatch(LCursor & cur, FuncRequest & cmd)
119 {
120         switch (cmd.action) {
121
122         case LFUN_INSET_MODIFY: {
123                 InsetCommandParams p;
124                 InsetIncludeMailer::string2params(cmd.argument, p);
125                 if (!p.getCmdName().empty()) {
126                         set(p, cur.buffer());
127                         cur.bv().update();
128                 }
129                 break;
130         }
131
132         case LFUN_INSET_DIALOG_UPDATE:
133                 InsetIncludeMailer(*this).updateDialog(&cur.bv());
134                 break;
135
136         case LFUN_MOUSE_RELEASE:
137                 if (button_.box().contains(cmd.x, cmd.y))
138                         InsetIncludeMailer(*this).showDialog(&cur.bv());
139                 break;
140
141         case LFUN_INSET_DIALOG_SHOW:
142                 InsetIncludeMailer(*this).showDialog(&cur.bv());
143                 break;
144
145         default:
146                 InsetOld::priv_dispatch(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::clone() 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 " << tostr(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                 FileInfo finfo(included_file);
298                 if (!finfo.isOK())
299                         return false;
300                 buf = bufferlist.newBuffer(included_file);
301                 if (!loadLyXFile(buf, included_file))
302                         return false;
303         }
304         if (buf)
305                 buf->setParentName(parentFilename(buffer));
306         return buf != 0;
307 }
308
309
310 } // namespace anon
311
312
313 int InsetInclude::latex(Buffer const & buffer, ostream & os,
314                         OutputParams const & runparams) const
315 {
316         string incfile(params_.getContents());
317
318         // Do nothing if no file name has been specified
319         if (incfile.empty())
320                 return 0;
321
322         string const included_file = includedFilename(buffer, params_);
323         Buffer const * const m_buffer = buffer.getMasterBuffer();
324
325         // if incfile is relative, make it relative to the master
326         // buffer directory.
327         if (!AbsolutePath(incfile)) {
328                 incfile = MakeRelPath(included_file,
329                                       m_buffer->filePath());
330         }
331
332         // write it to a file (so far the complete file)
333         string writefile = ChangeExtension(included_file, ".tex");
334
335         if (!runparams.nice) {
336                 incfile = FileName(writefile).mangledFilename();
337                 writefile = MakeAbsPath(incfile, m_buffer->temppath());
338         }
339         lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
340         lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
341
342         if (loadIfNeeded(buffer, params_)) {
343                 Buffer * tmp = bufferlist.getBuffer(included_file);
344
345                 if (tmp->params().textclass != m_buffer->params().textclass) {
346                         string text = bformat(_("Included file `%1$s'\n"
347                                                 "has textclass `%2$s'\n"
348                                                 "while parent file has textclass `%3$s'."),
349                                               MakeDisplayPath(included_file),
350                                               tmp->params().getLyXTextClass().name(),
351                                               m_buffer->params().getLyXTextClass().name());
352                         Alert::warning(_("Different textclasses"), text);
353                         //return 0;
354                 }
355
356                 tmp->markDepClean(m_buffer->temppath());
357
358 #ifdef WITH_WARNINGS
359 #warning Second argument is irrelevant!
360 // since only_body is true, makeLaTeXFile will not look at second
361 // argument. Should we set it to string(), or should makeLaTeXFile
362 // make use of it somehow? (JMarc 20031002)
363 #endif
364                 tmp->makeLaTeXFile(writefile,
365                                    OnlyPath(masterFilename(buffer)),
366                                    runparams, false);
367         } else if (!runparams.nice) {
368                 // Copy the file to the temp dir, so that .aux files etc.
369                 // are not created in the original dir. Files included by
370                 // this file will be found via input@path, see ../buffer.C.
371                 unsigned long const checksum_in  = sum(included_file);
372                 unsigned long const checksum_out = sum(writefile);
373
374                 if (checksum_in != checksum_out) {
375                         if (!copy(included_file, writefile)) {
376                                 lyxerr[Debug::LATEX]
377                                         << bformat(_("Could not copy the file\n%1$s\n"
378                                                      "into the temporary directory."),
379                                                    included_file)
380                                         << endl;
381                                 return 0;
382                         }
383                 }
384         }
385
386         if (isVerbatim(params_)) {
387                 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
388         } else if (type(params_) == INPUT) {
389                 // \input wants file with extension (default is .tex)
390                 if (!IsLyXFilename(included_file)) {
391                         os << '\\' << params_.getCmdName() << '{' << incfile << '}';
392                 } else {
393                         os << '\\' << params_.getCmdName() << '{'
394                            << ChangeExtension(incfile, ".tex")
395                            <<  '}';
396                 }
397         } else {
398                 // \include don't want extension and demands that the
399                 // file really have .tex
400                 os << '\\' << params_.getCmdName() << '{'
401                    << ChangeExtension(incfile, string())
402                    << '}';
403         }
404
405         return 0;
406 }
407
408
409 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
410                         OutputParams const &) const
411 {
412         if (isVerbatim(params_))
413                 os << GetFileContents(includedFilename(buffer, params_));
414         return 0;
415 }
416
417
418 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
419                            OutputParams const & runparams) const
420 {
421         string incfile(params_.getContents());
422
423         // Do nothing if no file name has been specified
424         if (incfile.empty())
425                 return 0;
426
427         string const included_file = includedFilename(buffer, params_);
428
429         if (loadIfNeeded(buffer, params_)) {
430                 Buffer * tmp = bufferlist.getBuffer(included_file);
431
432                 // write it to a file (so far the complete file)
433                 string writefile = ChangeExtension(included_file, ".sgml");
434
435                 if (!runparams.nice) {
436                         incfile = FileName(writefile).mangledFilename();
437                         writefile = MakeAbsPath(incfile,
438                                                 buffer.getMasterBuffer()->temppath());
439                 }
440
441                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
442                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
443
444                 OutputParams runp = runparams;
445                 tmp->makeLinuxDocFile(writefile, runp, true);
446         }
447
448         if (isVerbatim(params_)) {
449                 os << "<![CDATA["
450                    << GetFileContents(included_file)
451                    << "]]>";
452         } else
453                 os << '&' << include_label << ';';
454
455         return 0;
456 }
457
458
459 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
460                           OutputParams const & runparams) const
461 {
462         string incfile(params_.getContents());
463
464         // Do nothing if no file name has been specified
465         if (incfile.empty())
466                 return 0;
467
468         string const included_file = includedFilename(buffer, params_);
469
470         if (loadIfNeeded(buffer, params_)) {
471                 Buffer * tmp = bufferlist.getBuffer(included_file);
472
473                 // write it to a file (so far the complete file)
474                 string writefile = ChangeExtension(included_file, ".sgml");
475
476                 if (!runparams.nice) {
477                         incfile = FileName(writefile).mangledFilename();
478                         writefile = MakeAbsPath(incfile,
479                                                 buffer.getMasterBuffer()->temppath());
480                 }
481
482                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
483                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
484
485                 OutputParams runp = runparams;
486                 tmp->makeDocBookFile(writefile, runp, true);
487         }
488
489         if (isVerbatim(params_)) {
490                 os << "<inlinegraphic fileref=\""
491                    << '&' << include_label << ';'
492                    << "\" format=\"linespecific\">";
493         } else
494                 os << '&' << include_label << ';';
495
496         return 0;
497 }
498
499
500 void InsetInclude::validate(LaTeXFeatures & features) const
501 {
502         string incfile(params_.getContents());
503         string writefile;
504
505         Buffer const & buffer = features.buffer();
506
507         string const included_file = includedFilename(buffer, params_);
508
509         if (IsLyXFilename(included_file))
510                 writefile = ChangeExtension(included_file, ".sgml");
511         else
512                 writefile = included_file;
513
514         if (!features.nice() && !isVerbatim(params_)) {
515                 incfile = FileName(writefile).mangledFilename();
516                 writefile = MakeAbsPath(incfile,
517                                         buffer.getMasterBuffer()->temppath());
518         }
519
520         features.includeFile(include_label, writefile);
521
522         if (isVerbatim(params_))
523                 features.require("verbatim");
524
525         // Here we must do the fun stuff...
526         // Load the file in the include if it needs
527         // to be loaded:
528         if (loadIfNeeded(buffer, params_)) {
529                 // a file got loaded
530                 Buffer * const tmp = bufferlist.getBuffer(included_file);
531                 if (tmp) {
532                         // We must temporarily change features.buffer,
533                         // otherwise it would always be the master buffer,
534                         // and nested includes would not work.
535                         features.setBuffer(*tmp);
536                         tmp->validate(features);
537                         features.setBuffer(buffer);
538                 }
539         }
540 }
541
542
543 void InsetInclude::getLabelList(Buffer const & buffer,
544                                 std::vector<string> & list) const
545 {
546         if (loadIfNeeded(buffer, params_)) {
547                 string const included_file = includedFilename(buffer, params_);
548                 Buffer * tmp = bufferlist.getBuffer(included_file);
549                 tmp->setParentName("");
550                 tmp->getLabelList(list);
551                 tmp->setParentName(parentFilename(buffer));
552         }
553 }
554
555
556 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
557                                    std::vector<std::pair<string,string> > & keys) const
558 {
559         if (loadIfNeeded(buffer, params_)) {
560                 string const included_file = includedFilename(buffer, params_);
561                 Buffer * tmp = bufferlist.getBuffer(included_file);
562                 tmp->setParentName("");
563                 tmp->fillWithBibKeys(keys);
564                 tmp->setParentName(parentFilename(buffer));
565         }
566 }
567
568
569 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
570 {
571         if (RenderPreview::activated() && preview_->previewReady()) {
572                 preview_->metrics(mi, dim);
573         } else {
574                 if (!set_label_) {
575                         set_label_ = true;
576                         button_.update(getScreenLabel(*mi.base.bv->buffer()),
577                                        editable() != NOT_EDITABLE);
578                 }
579                 button_.metrics(mi, dim);
580         }
581         int center_indent = type(params_) == INPUT ?
582                 0 : (mi.base.textwidth - dim.wid) / 2;
583         Box b(center_indent, center_indent + dim.wid, -dim.asc, dim.des);
584         button_.setBox(b);
585
586         dim.wid = mi.base.textwidth;
587         dim_ = dim;
588 }
589
590
591 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
592 {
593         setPosCache(pi, x, y);
594
595         if (!RenderPreview::activated() || !preview_->previewReady()) {
596                 button_.draw(pi, x + button_.box().x1, y);
597                 return;
598         }
599
600         preview_->draw(pi, x + button_.box().x1, y);
601 }
602
603
604 //
605 // preview stuff
606 //
607
608 void InsetInclude::fileChanged() const
609 {
610         Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
611         if (!buffer_ptr)
612                 return;
613
614         Buffer const & buffer = *buffer_ptr;
615         preview_->removePreview(buffer);
616         add_preview(*preview_.get(), *this, buffer);
617         preview_->startLoading(buffer);
618 }
619
620
621 namespace {
622
623 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
624 {
625         string const included_file = includedFilename(buffer, params);
626
627         return type(params) == INPUT && params.preview() &&
628                 IsFileReadable(included_file);
629 }
630
631
632 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
633 {
634         ostringstream os;
635         OutputParams runparams;
636         runparams.flavor = OutputParams::LATEX;
637         inset.latex(buffer, os, runparams);
638
639         return os.str();
640 }
641
642
643 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
644                  Buffer const & buffer)
645 {
646         InsetCommandParams const & params = inset.params();
647         if (RenderPreview::activated() && preview_wanted(params, buffer)) {
648                 renderer.setAbsFile(includedFilename(buffer, params));
649                 string const snippet = latex_string(inset, buffer);
650                 renderer.addPreview(snippet, buffer);
651         }
652 }
653
654 } // namespace anon
655
656
657 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
658 {
659         Buffer const & buffer = ploader.buffer();
660         if (preview_wanted(params(), buffer)) {
661                 preview_->setAbsFile(includedFilename(buffer, params()));
662                 string const snippet = latex_string(*this, buffer);
663                 preview_->addPreview(snippet, ploader);
664         }
665 }
666
667
668 string const InsetIncludeMailer::name_("include");
669
670 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
671         : inset_(inset)
672 {}
673
674
675 string const InsetIncludeMailer::inset2string(Buffer const &) const
676 {
677         return params2string(inset_.params());
678 }
679
680
681 void InsetIncludeMailer::string2params(string const & in,
682                                        InsetCommandParams & params)
683 {
684         params = InsetCommandParams();
685         if (in.empty())
686                 return;
687
688         istringstream data(in);
689         LyXLex lex(0,0);
690         lex.setStream(data);
691
692         string name;
693         lex >> name;
694         if (!lex || name != name_)
695                 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
696
697         // This is part of the inset proper that is usually swallowed
698         // by LyXText::readInset
699         string id;
700         lex >> id;
701         if (!lex || id != "Include")
702                 return print_mailer_error("InsetBoxMailer", in, 2, "Include");
703
704         InsetInclude inset(params);
705         inset.read(lex);
706         params = inset.params();
707 }
708
709
710 string const
711 InsetIncludeMailer::params2string(InsetCommandParams const & params)
712 {
713         InsetInclude inset(params);
714         ostringstream data;
715         data << name_ << ' ';
716         inset.write(data);
717         data << "\\end_inset\n";
718         return data.str();
719 }