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