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