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