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