]> git.lyx.org Git - lyx.git/blob - src/insets/insetinclude.C
Fix InsetInclude properly. Data is now stored in an InsetCommandParams
[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 "debug.h"
21 #include "funcrequest.h"
22 #include "gettext.h"
23 #include "LaTeXFeatures.h"
24 #include "latexrunparams.h"
25 #include "lyxlex.h"
26 #include "metricsinfo.h"
27
28 #include "frontends/Painter.h"
29
30 #include "graphics/PreviewedInset.h"
31 #include "graphics/PreviewImage.h"
32
33 #include "support/FileInfo.h"
34 #include "support/FileMonitor.h"
35 #include "support/filetools.h"
36 #include "support/lstrings.h" // contains
37 #include "support/tostr.h"
38
39 #include <boost/bind.hpp>
40
41 #include "support/std_sstream.h"
42
43 using lyx::support::AddName;
44 using lyx::support::ChangeExtension;
45 using lyx::support::contains;
46 using lyx::support::FileInfo;
47 using lyx::support::FileMonitor;
48 using lyx::support::GetFileContents;
49 using lyx::support::IsFileReadable;
50 using lyx::support::IsLyXFilename;
51 using lyx::support::MakeAbsPath;
52 using lyx::support::MakeDisplayPath;
53 using lyx::support::OnlyFilename;
54 using lyx::support::OnlyPath;
55 using lyx::support::subst;
56
57 using std::endl;
58
59 using std::auto_ptr;
60 using std::istringstream;
61 using std::ostream;
62 using std::ostringstream;
63
64
65 extern BufferList bufferlist;
66
67
68 class InsetInclude::PreviewImpl : public lyx::graphics::PreviewedInset {
69 public:
70         ///
71         PreviewImpl(InsetInclude & p) : PreviewedInset(p) {}
72
73         ///
74         bool previewWanted(Buffer const &) const;
75         ///
76         string const latexString(Buffer const &) const;
77         ///
78         InsetInclude const & parent() const {
79                 return dynamic_cast<InsetInclude const &>(inset());
80         }
81
82         ///
83         bool monitoring() const { return monitor_.get(); }
84         ///
85         void startMonitoring(string const & file);
86         ///
87         void stopMonitoring() { monitor_.reset(); }
88
89 private:
90         /// Invoked by monitor_ should the parent file change.
91         void restartLoading();
92         ///
93         boost::scoped_ptr<FileMonitor> monitor_;
94 };
95
96
97 namespace {
98
99 string const uniqueID()
100 {
101         static unsigned int seed = 1000;
102         return "file" + tostr(++seed);
103 }
104
105 } // namespace anon
106
107
108 InsetInclude::InsetInclude(InsetCommandParams const & p)
109         : params_(p), include_label(uniqueID()),
110           preview_(new PreviewImpl(*this)),
111           set_label_(false)
112 {}
113
114
115 InsetInclude::InsetInclude(InsetInclude const & other)
116         : InsetOld(other),
117           params_(other.params_),
118           include_label(other.include_label),
119           preview_(new PreviewImpl(*this)),
120           set_label_(other.set_label_)
121 {}
122
123
124 InsetInclude::~InsetInclude()
125 {
126         InsetIncludeMailer mailer(*this);
127         mailer.hideDialog();
128 }
129
130
131 dispatch_result InsetInclude::localDispatch(FuncRequest const & cmd)
132 {
133         switch (cmd.action) {
134
135         case LFUN_INSET_MODIFY: {
136                 InsetCommandParams p;
137                 InsetIncludeMailer::string2params(cmd.argument, p);
138                 if (!p.getCmdName().empty()) {
139                         set(p, *cmd.view()->buffer());
140                         cmd.view()->updateInset(this);
141                 }
142                 return DISPATCHED;
143         }
144
145         case LFUN_INSET_DIALOG_UPDATE:
146                 InsetIncludeMailer(*this).updateDialog(cmd.view());
147                 return DISPATCHED;
148
149         case LFUN_MOUSE_RELEASE:
150                 if (button_.box().contains(cmd.x, cmd.y))
151                         InsetIncludeMailer(*this).showDialog(cmd.view());
152                 return DISPATCHED;
153
154         case LFUN_INSET_DIALOG_SHOW:
155                 InsetIncludeMailer(*this).showDialog(cmd.view());
156                 return DISPATCHED;
157
158         default:
159                 return InsetOld::localDispatch(cmd);
160         }
161 }
162
163
164 InsetCommandParams const & InsetInclude::params() const
165 {
166         return params_;
167 }
168
169
170 namespace {
171
172 /// the type of inclusion
173 enum Types {
174         INCLUDE = 0,
175         VERB = 1,
176         INPUT = 2,
177         VERBAST = 3
178 };
179
180
181 Types type(InsetCommandParams const & params)
182 {
183         string const command_name = params.getCmdName();
184
185         if (command_name == "input")
186                 return INPUT;
187         if  (command_name == "verbatiminput")
188                 return VERB;
189         if  (command_name == "verbatiminput*")
190                 return VERBAST;
191         return INCLUDE;
192 }
193  
194
195 bool isVerbatim(InsetCommandParams const & params)
196 {
197         string const command_name = params.getCmdName();
198         return command_name == "verbatiminput" ||
199                 command_name == "verbatiminput*";
200 }
201
202 } // namespace anon
203
204
205 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
206 {
207         params_ = p;
208         set_label_ = false;
209
210         if (preview_->monitoring())
211                 preview_->stopMonitoring();
212
213         if (lyx::graphics::PreviewedInset::activated() &&
214             type(params_) == INPUT)
215                 preview_->generatePreview(buffer);
216 }
217
218
219 auto_ptr<InsetBase> InsetInclude::clone() const
220 {
221         return auto_ptr<InsetBase>(new InsetInclude(*this));
222 }
223
224
225 void InsetInclude::write(Buffer const &, ostream & os) const
226 {
227         write(os);
228 }
229
230
231 void InsetInclude::write(ostream & os) const
232 {
233         os << "Include " << params_.getCommand() << '\n'
234            << "preview " << tostr(params_.preview()) << '\n';
235 }
236
237
238 void InsetInclude::read(Buffer const &, LyXLex & lex)
239 {
240         read(lex);
241 }
242
243
244 void InsetInclude::read(LyXLex & lex)
245 {
246         params_.read(lex);
247 }
248
249
250 string const InsetInclude::getScreenLabel(Buffer const &) const
251 {
252         string temp;
253
254         switch (type(params_)) {
255                 case INPUT: temp += _("Input"); break;
256                 case VERB: temp += _("Verbatim Input"); break;
257                 case VERBAST: temp += _("Verbatim Input*"); break;
258                 case INCLUDE: temp += _("Include"); break;
259         }
260
261         temp += ": ";
262
263         if (params_.getContents().empty())
264                 temp += "???";
265         else
266                 temp += OnlyFilename(params_.getContents());
267
268         return temp;
269 }
270
271
272 namespace {
273
274 string const masterFilename(Buffer const & buffer)
275 {
276         return buffer.fileName();
277 }
278
279
280 string const includedFilename(Buffer const & buffer,
281                               InsetCommandParams const & params)
282 {
283         return MakeAbsPath(params.getContents(),
284                            OnlyPath(masterFilename(buffer)));
285 }
286
287
288 /// return true if the file is or got loaded.
289 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
290 {
291         if (isVerbatim(params))
292                 return false;
293
294         string const included_file = includedFilename(buffer, params);
295         if (!IsLyXFilename(included_file))
296                 return false;
297
298         if (bufferlist.exists(included_file))
299                 return true;
300
301         // the readonly flag can/will be wrong, not anymore I think.
302         FileInfo finfo(included_file);
303         if (!finfo.isOK())
304                 return false;
305         return loadLyXFile(bufferlist.newBuffer(included_file),
306                            included_file);
307 }
308
309
310 } // namespace anon
311
312
313 int InsetInclude::latex(Buffer const & buffer, ostream & os,
314                         LatexRunParams 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
324         if (loadIfNeeded(buffer, params_)) {
325                 Buffer * tmp = bufferlist.getBuffer(included_file);
326
327                 // FIXME: this should be a GUI warning
328                 if (tmp->params().textclass != buffer.params().textclass) {
329                         lyxerr << "WARNING: Included file `"
330                                << MakeDisplayPath(included_file)
331                                << "' has textclass `"
332                                << tmp->params().getLyXTextClass().name()
333                                << "' while parent file has textclass `"
334                                << buffer.params().getLyXTextClass().name()
335                                << "'." << endl;
336                         //return 0;
337                 }
338
339                 // write it to a file (so far the complete file)
340                 string writefile = ChangeExtension(included_file, ".tex");
341
342                 if (!buffer.temppath().empty() && !runparams.nice) {
343                         incfile = subst(incfile, '/','@');
344 #ifdef __EMX__
345                         incfile = subst(incfile, ':', '$');
346 #endif
347                         writefile = AddName(buffer.temppath(), incfile);
348                 } else
349                         writefile = included_file;
350                 writefile = ChangeExtension(writefile, ".tex");
351                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
352                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
353
354                 tmp->markDepClean(buffer.temppath());
355
356                 tmp->makeLaTeXFile(writefile,
357                                    OnlyPath(masterFilename(buffer)),
358                                    runparams, false);
359         }
360
361         if (isVerbatim(params_)) {
362                 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
363         } else if (type(params_) == INPUT) {
364                 // \input wants file with extension (default is .tex)
365                 if (!IsLyXFilename(included_file)) {
366                         os << '\\' << params_.getCmdName() << '{' << incfile << '}';
367                 } else {
368                         os << '\\' << params_.getCmdName() << '{'
369                            << ChangeExtension(incfile, ".tex")
370                            <<  '}';
371                 }
372         } else {
373                 // \include don't want extension and demands that the
374                 // file really have .tex
375                 os << '\\' << params_.getCmdName() << '{'
376                    << ChangeExtension(incfile, string())
377                    << '}';
378         }
379
380         return 0;
381 }
382
383
384 int InsetInclude::ascii(Buffer const & buffer, ostream & os, int) const
385 {
386         if (isVerbatim(params_))
387                 os << GetFileContents(includedFilename(buffer, params_));
388         return 0;
389 }
390
391
392 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os) const
393 {
394         string incfile(params_.getContents());
395
396         // Do nothing if no file name has been specified
397         if (incfile.empty())
398                 return 0;
399
400         string const included_file = includedFilename(buffer, params_);
401
402         if (loadIfNeeded(buffer, params_)) {
403                 Buffer * tmp = bufferlist.getBuffer(included_file);
404
405                 // write it to a file (so far the complete file)
406                 string writefile = ChangeExtension(included_file, ".sgml");
407                 if (!buffer.temppath().empty() && !buffer.niceFile()) {
408                         incfile = subst(incfile, '/','@');
409                         writefile = AddName(buffer.temppath(), incfile);
410                 } else
411                         writefile = included_file;
412
413                 if (IsLyXFilename(included_file))
414                         writefile = ChangeExtension(writefile, ".sgml");
415
416                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
417                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
418
419                 tmp->makeLinuxDocFile(writefile, buffer.niceFile(), true);
420         }
421
422         if (isVerbatim(params_)) {
423                 os << "<![CDATA["
424                    << GetFileContents(included_file)
425                    << "]]>";
426         } else
427                 os << '&' << include_label << ';';
428
429         return 0;
430 }
431
432
433 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
434                           bool /*mixcont*/) const
435 {
436         string incfile(params_.getContents());
437
438         // Do nothing if no file name has been specified
439         if (incfile.empty())
440                 return 0;
441
442         string const included_file = includedFilename(buffer, params_);
443
444         if (loadIfNeeded(buffer, params_)) {
445                 Buffer * tmp = bufferlist.getBuffer(included_file);
446
447                 // write it to a file (so far the complete file)
448                 string writefile = ChangeExtension(included_file, ".sgml");
449                 if (!buffer.temppath().empty() && !buffer.niceFile()) {
450                         incfile = subst(incfile, '/','@');
451                         writefile = AddName(buffer.temppath(), incfile);
452                 } else
453                         writefile = included_file;
454                 if (IsLyXFilename(included_file))
455                         writefile = ChangeExtension(writefile, ".sgml");
456
457                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
458                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
459
460                 tmp->makeDocBookFile(writefile, buffer.niceFile(), true);
461         }
462
463         if (isVerbatim(params_)) {
464                 os << "<inlinegraphic fileref=\""
465                    << '&' << include_label << ';'
466                    << "\" format=\"linespecific\">";
467         } else
468                 os << '&' << include_label << ';';
469
470         return 0;
471 }
472
473
474 void InsetInclude::validate(LaTeXFeatures & features) const
475 {
476         string incfile(params_.getContents());
477         string writefile;
478
479         Buffer const & buffer = features.buffer();
480
481         string const included_file = includedFilename(buffer, params_);
482
483         if (!buffer.temppath().empty() &&
484             !buffer.niceFile() &&
485             !isVerbatim(params_)) {
486                 incfile = subst(incfile, '/','@');
487                 writefile = AddName(buffer.temppath(), incfile);
488         } else
489                 writefile = included_file;
490
491         if (IsLyXFilename(included_file))
492                 writefile = ChangeExtension(writefile, ".sgml");
493
494         features.includeFile(include_label, writefile);
495
496         if (isVerbatim(params_))
497                 features.require("verbatim");
498
499         // Here we must do the fun stuff...
500         // Load the file in the include if it needs
501         // to be loaded:
502         if (loadIfNeeded(buffer, params_)) {
503                 // a file got loaded
504                 Buffer * const tmp = bufferlist.getBuffer(included_file);
505                 if (tmp) {
506                         tmp->niceFile() = buffer.niceFile();
507                         tmp->validate(features);
508                 }
509         }
510 }
511
512
513 void InsetInclude::getLabelList(Buffer const & buffer,
514                                 std::vector<string> & list) const
515 {
516         if (loadIfNeeded(buffer, params_)) {
517                 string const included_file = includedFilename(buffer, params_);
518                 Buffer * tmp = bufferlist.getBuffer(included_file);
519                 tmp->setParentName("");
520                 tmp->getLabelList(list);
521                 tmp->setParentName(masterFilename(buffer));
522         }
523 }
524
525
526 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
527                                    std::vector<std::pair<string,string> > & keys) const
528 {
529         if (loadIfNeeded(buffer, params_)) {
530                 string const included_file = includedFilename(buffer, params_);
531                 Buffer * tmp = bufferlist.getBuffer(included_file);
532                 tmp->setParentName("");
533                 tmp->fillWithBibKeys(keys);
534                 tmp->setParentName(masterFilename(buffer));
535         }
536 }
537
538
539 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
540 {
541         if (preview_->previewReady()) {
542                 dim.asc = preview_->pimage()->ascent();
543                 dim.des = preview_->pimage()->descent();
544                 dim.wid = preview_->pimage()->width();
545         } else {
546                 if (!set_label_) {
547                         set_label_ = true;
548                         button_.update(getScreenLabel(*mi.base.bv->buffer()),
549                                        editable() != NOT_EDITABLE);
550                 }
551                 button_.metrics(mi, dim);
552         }
553         int center_indent = type(params_) == INPUT ?
554                 0 : (mi.base.textwidth - dim.wid) / 2;
555         Box b(center_indent, center_indent + dim.wid, -dim.asc, dim.des);
556         button_.setBox(b);
557
558         dim.wid = mi.base.textwidth;
559         dim_ = dim;
560 }
561
562
563 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
564 {
565         cache(pi.base.bv);
566         if (!preview_->previewReady()) {
567                 button_.draw(pi, x + button_.box().x1, y);
568                 return;
569         }
570
571         if (!preview_->monitoring()) {
572                 string const included_file =
573                         includedFilename(*view()->buffer(), params_);
574                 preview_->startMonitoring(included_file);
575         }
576
577         pi.pain.image(x + button_.box().x1, y - dim_.asc, dim_.wid, dim_.height(),
578                             *(preview_->pimage()->image()));
579 }
580
581
582 BufferView * InsetInclude::view() const
583 {
584         return button_.view();
585 }
586
587
588 //
589 // preview stuff
590 //
591
592 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
593 {
594         preview_->addPreview(ploader);
595 }
596
597
598 bool InsetInclude::PreviewImpl::previewWanted(Buffer const & buffer) const
599 {
600         string const included_file = includedFilename(buffer, parent().params());
601
602         return type(parent().params_) == INPUT &&
603                 parent().params_.preview() &&
604                 IsFileReadable(included_file);
605 }
606
607
608 string const InsetInclude::PreviewImpl::latexString(Buffer const & buffer) const
609 {
610         ostringstream os;
611         LatexRunParams runparams;
612         runparams.flavor = LatexRunParams::LATEX;
613         parent().latex(buffer, os, runparams);
614
615         return os.str();
616 }
617
618
619 void InsetInclude::PreviewImpl::startMonitoring(string const & file)
620 {
621         monitor_.reset(new FileMonitor(file, 2000));
622         monitor_->connect(boost::bind(&PreviewImpl::restartLoading, this));
623         monitor_->start();
624 }
625
626
627 void InsetInclude::PreviewImpl::restartLoading()
628 {
629         removePreview();
630         if (!view())
631                 return;
632         view()->updateInset(&parent());
633         if (view()->buffer())
634                 generatePreview(*view()->buffer());
635 }
636
637
638 string const InsetIncludeMailer::name_("include");
639
640 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
641         : inset_(inset)
642 {}
643
644
645 string const InsetIncludeMailer::inset2string(Buffer const &) const
646 {
647         return params2string(inset_.params());
648 }
649
650
651 void InsetIncludeMailer::string2params(string const & in,
652                                        InsetCommandParams & params)
653 {
654         params = InsetCommandParams();
655
656         if (in.empty())
657                 return;
658
659         istringstream data(in);
660         LyXLex lex(0,0);
661         lex.setStream(data);
662
663         if (lex.isOK()) {
664                 lex.next();
665                 string const token = lex.getString();
666                 if (token != name_)
667                         return;
668         }
669
670         // This is part of the inset proper that is usually swallowed
671         // by Buffer::readInset
672         if (lex.isOK()) {
673                 lex.next();
674                 string const token = lex.getString();
675                 if (token != "Include")
676                         return;
677         }
678
679         if (lex.isOK()) {
680                 InsetInclude inset(params);
681                 inset.read(lex);
682                 params = inset.params();
683         }
684 }
685
686
687 string const
688 InsetIncludeMailer::params2string(InsetCommandParams const & params)
689 {
690         InsetInclude inset(params);
691         ostringstream data;
692         data << name_ << ' ';
693         inset.write(data);
694         data << "\\end_inset\n";
695         return data.str();
696 }