]> git.lyx.org Git - lyx.git/blob - src/insets/insetinclude.C
Alfredo's second patch
[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);
131                 result = DISPATCHED;
132         }
133         break;
134
135         case LFUN_INSET_DIALOG_UPDATE: {
136                 InsetIncludeMailer mailer(*this);
137                 mailer.updateDialog(cmd.view());
138         }
139         break;
140
141         case LFUN_MOUSE_RELEASE:
142                 edit(cmd.view(), cmd.x, cmd.y, cmd.button());
143                 break;
144
145         default:
146                 break;
147         }
148
149         return result;
150 }
151
152
153 InsetInclude::Params const & InsetInclude::params() const
154 {
155         return params_;
156 }
157
158
159 bool InsetInclude::Params::operator==(Params const & o) const
160 {
161         if (cparams == o.cparams && flag == o.flag &&
162             masterFilename_ == o.masterFilename_)
163                 return true;
164
165         return false;
166 }
167
168
169 bool InsetInclude::Params::operator!=(Params const & o) const
170 {
171         return !(*this == o);
172 }
173
174
175 void InsetInclude::set(Params const & p)
176 {
177         params_ = p;
178
179         string command;
180
181         switch (params_.flag) {
182                 case INCLUDE:
183                         command="include";
184                         break;
185                 case VERB:
186                         command="verbatiminput";
187                         break;
188                 case INPUT:
189                         command="input";
190                         break;
191                 case VERBAST:
192                         command="verbatiminput*";
193                         break;
194         }
195
196         params_.cparams.setCmdName(command);
197
198         if (preview_->monitoring())
199                 preview_->stopMonitoring();
200
201         if (grfx::PreviewedInset::activated() && params_.flag == INPUT)
202                 preview_->generatePreview();
203 }
204
205
206 Inset * InsetInclude::clone(Buffer const & buffer, bool) const
207 {
208         Params p(params_);
209         p.masterFilename_ = buffer.fileName();
210
211         return new InsetInclude(p);
212 }
213
214
215 void InsetInclude::edit(BufferView * bv, int, int, mouse_button::state)
216 {
217         InsetIncludeMailer mailer(*this);
218         mailer.showDialog(bv);
219 }
220
221
222 void InsetInclude::edit(BufferView * bv, bool)
223 {
224         edit(bv, 0, 0, mouse_button::none);
225 }
226
227
228 void InsetInclude::write(Buffer const *, 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         params_.cparams.read(lex);
238
239         if (params_.cparams.getCmdName() == "include")
240                 params_.flag = INCLUDE;
241         else if (params_.cparams.getCmdName() == "input")
242                 params_.flag = INPUT;
243         /* FIXME: is this logic necessary now ? */
244         else if (contains(params_.cparams.getCmdName(), "verbatim")) {
245                 params_.flag = VERB;
246                 if (params_.cparams.getCmdName() == "verbatiminput*")
247                         params_.flag = VERBAST;
248         }
249 }
250
251
252 bool InsetInclude::display() const
253 {
254         return !(params_.flag == INPUT);
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
309         return bufferlist.loadLyXFile(getFileName(), false) != 0;
310 }
311
312
313 int InsetInclude::latex(Buffer const * buffer, ostream & os,
314                         bool /*fragile*/, bool /*fs*/) 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->tmppath.empty()
341                     && !buffer->niceFile) {
342                         incfile = subst(incfile, '/','@');
343 #ifdef __EMX__
344                         incfile = subst(incfile, ':', '$');
345 #endif
346                         writefile = AddName(buffer->tmppath, incfile);
347                 } else
348                         writefile = getFileName();
349                 writefile = ChangeExtension(writefile, ".tex");
350                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
351                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
352
353                 tmp->markDepClean(buffer->tmppath);
354
355                 tmp->makeLaTeXFile(writefile,
356                                    OnlyPath(getMasterFilename()),
357                                    buffer->niceFile, true);
358         }
359
360         if (isVerbatim()) {
361                 os << '\\' << params_.cparams.getCmdName() << '{' << incfile << '}';
362         } else if (params_.flag == INPUT) {
363                 // \input wants file with extension (default is .tex)
364                 if (!IsLyXFilename(getFileName())) {
365                         os << '\\' << params_.cparams.getCmdName() << '{' << incfile << '}';
366                 } else {
367                         os << '\\' << params_.cparams.getCmdName() << '{'
368                            << ChangeExtension(incfile, ".tex")
369                            <<  '}';
370                 }
371         } else {
372                 // \include don't want extension and demands that the
373                 // file really have .tex
374                 os << '\\' << params_.cparams.getCmdName() << '{'
375                    << ChangeExtension(incfile, string())
376                    << '}';
377         }
378
379         return 0;
380 }
381
382
383 int InsetInclude::ascii(Buffer const *, ostream & os, int) const
384 {
385         if (isVerbatim())
386                 os << GetFileContents(getFileName());
387         return 0;
388 }
389
390
391 int InsetInclude::linuxdoc(Buffer const * buffer, ostream & os) const
392 {
393         string incfile(params_.cparams.getContents());
394
395         // Do nothing if no file name has been specified
396         if (incfile.empty())
397                 return 0;
398
399         if (loadIfNeeded()) {
400                 Buffer * tmp = bufferlist.getBuffer(getFileName());
401
402                 // write it to a file (so far the complete file)
403                 string writefile = ChangeExtension(getFileName(), ".sgml");
404                 if (!buffer->tmppath.empty() && !buffer->niceFile) {
405                         incfile = subst(incfile, '/','@');
406                         writefile = AddName(buffer->tmppath, incfile);
407                 } else
408                         writefile = getFileName();
409
410                 if (IsLyXFilename(getFileName()))
411                         writefile = ChangeExtension(writefile, ".sgml");
412
413                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
414                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
415
416                 tmp->makeLinuxDocFile(writefile, buffer->niceFile, true);
417         }
418
419         if (isVerbatim()) {
420                 os << "<![CDATA["
421                    << GetFileContents(getFileName())
422                    << "]]>";
423         } else
424                 os << '&' << include_label << ';';
425
426         return 0;
427 }
428
429
430 int InsetInclude::docbook(Buffer const * buffer, ostream & os,
431                           bool /*mixcont*/) const
432 {
433         string incfile(params_.cparams.getContents());
434
435         // Do nothing if no file name has been specified
436         if (incfile.empty())
437                 return 0;
438
439         if (loadIfNeeded()) {
440                 Buffer * tmp = bufferlist.getBuffer(getFileName());
441
442                 // write it to a file (so far the complete file)
443                 string writefile = ChangeExtension(getFileName(), ".sgml");
444                 if (!buffer->tmppath.empty() && !buffer->niceFile) {
445                         incfile = subst(incfile, '/','@');
446                         writefile = AddName(buffer->tmppath, incfile);
447                 } else
448                         writefile = getFileName();
449                 if (IsLyXFilename(getFileName()))
450                         writefile = ChangeExtension(writefile, ".sgml");
451
452                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
453                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
454
455                 tmp->makeDocBookFile(writefile, buffer->niceFile, true);
456         }
457
458         if (isVerbatim()) {
459                 os << "<inlinegraphic fileref=\""
460                    << '&' << include_label << ';'
461                    << "\" format=\"linespecific\">";
462         } else
463                 os << '&' << include_label << ';';
464
465         return 0;
466 }
467
468
469 void InsetInclude::validate(LaTeXFeatures & features) const
470 {
471
472         string incfile(params_.cparams.getContents());
473         string writefile;
474
475         Buffer const * const b = bufferlist.getBuffer(getMasterFilename());
476
477         if (b && !b->tmppath.empty() && !b->niceFile && !isVerbatim()) {
478                 incfile = subst(incfile, '/','@');
479                 writefile = AddName(b->tmppath, incfile);
480         } else
481                 writefile = getFileName();
482
483         if (IsLyXFilename(getFileName()))
484                 writefile = ChangeExtension(writefile, ".sgml");
485
486         features.includeFile(include_label, writefile);
487
488         if (isVerbatim())
489                 features.require("verbatim");
490
491         // Here we must do the fun stuff...
492         // Load the file in the include if it needs
493         // to be loaded:
494         if (loadIfNeeded()) {
495                 // a file got loaded
496                 Buffer * const tmp = bufferlist.getBuffer(getFileName());
497                 if (tmp) {
498                         if (b)
499                                 tmp->niceFile = b->niceFile;
500                         tmp->validate(features);
501                 }
502         }
503 }
504
505
506 vector<string> const InsetInclude::getLabelList() const
507 {
508         vector<string> l;
509
510         if (loadIfNeeded()) {
511                 Buffer * tmp = bufferlist.getBuffer(getFileName());
512                 tmp->setParentName("");
513                 l = tmp->getLabelList();
514                 tmp->setParentName(getMasterFilename());
515         }
516
517         return l;
518 }
519
520
521 void InsetInclude::fillWithBibKeys(vector<pair<string,string> > & keys) const
522 {
523         if (loadIfNeeded()) {
524                 Buffer * tmp = bufferlist.getBuffer(getFileName());
525                 tmp->setParentName("");
526                 tmp->fillWithBibKeys(keys);
527                 tmp->setParentName(getMasterFilename());
528         }
529 }
530
531
532 int InsetInclude::ascent(BufferView * bv, LyXFont const & font) const
533 {
534         return preview_->previewReady() ?
535                 preview_->pimage()->ascent() : InsetButton::ascent(bv, font);
536 }
537
538
539 int InsetInclude::descent(BufferView * bv, LyXFont const & font) const
540 {
541         return preview_->previewReady() ?
542                 preview_->pimage()->descent() : InsetButton::descent(bv, font);
543 }
544
545
546 int InsetInclude::width(BufferView * bv, LyXFont const & font) const
547 {
548         return preview_->previewReady() ?
549                 preview_->pimage()->width() : InsetButton::width(bv, font);
550 }
551
552
553 void InsetInclude::draw(BufferView * bv, LyXFont const & font, int y,
554                         float & xx) const
555 {
556         cache(bv);
557         if (!preview_->previewReady()) {
558                 InsetButton::draw(bv, font, y, xx);
559                 return;
560         }
561
562         if (!preview_->monitoring())
563                 preview_->startMonitoring();
564
565         int const x = int(xx);
566         int const w = width(bv, font);
567         int const d = descent(bv, font);
568         int const a = ascent(bv, font);
569         int const h = a + d;
570
571         bv->painter().image(x, y - a, w, h,
572                             *(preview_->pimage()->image()));
573
574         xx += w;
575 }
576
577
578 //
579 // preview stuff
580 //
581
582 void InsetInclude::addPreview(grfx::PreviewLoader & ploader) const
583 {
584         preview_->addPreview(ploader);
585 }
586
587
588 bool InsetInclude::PreviewImpl::previewWanted() const
589 {
590         return parent().params_.flag == InsetInclude::INPUT &&
591                 parent().params_.cparams.preview() &&
592                 IsFileReadable(parent().getFileName());
593 }
594
595
596 string const InsetInclude::PreviewImpl::latexString() const
597 {
598         if (!view() || !view()->buffer())
599                 return string();
600
601         ostringstream os;
602         parent().latex(view()->buffer(), os, false, false);
603
604         return STRCONV(os.str());
605 }
606
607
608 void InsetInclude::PreviewImpl::startMonitoring()
609 {
610         monitor_.reset(new FileMonitor(parent().getFileName(), 2000));
611         monitor_->connect(boost::bind(&PreviewImpl::restartLoading, this));
612         monitor_->start();
613 }
614
615
616 void InsetInclude::PreviewImpl::restartLoading()
617 {
618         lyxerr << "restartLoading()" << std::endl;
619         removePreview();
620         if (view())
621                 view()->updateInset(&parent());
622         generatePreview();
623 }
624
625
626 string const InsetIncludeMailer::name_("include");
627
628 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
629         : inset_(inset)
630 {}
631
632
633 string const InsetIncludeMailer::inset2string() const
634 {
635         return params2string(inset_.params());
636 }
637
638
639 void InsetIncludeMailer::string2params(string const & in,
640                                        InsetInclude::Params & params)
641 {
642         params = InsetInclude::Params();
643
644         if (in.empty())
645                 return;
646         
647         istringstream data(in);
648         LyXLex lex(0,0);
649         lex.setStream(data);
650
651         if (lex.isOK()) {
652                 lex.next();
653                 string const token = lex.getString();
654                 if (token != name_)
655                         return;
656         }
657
658         // This is part of the inset proper that is usually swallowed
659         // by Buffer::readInset
660         if (lex.isOK()) {
661                 lex.next();
662                 string const token = lex.getString();
663                 if (token != "Include")
664                         return;
665         }
666
667         if (lex.isOK()) {
668                 InsetInclude inset(params);
669                 inset.read(0, lex);
670                 params = inset.params();
671         }
672 }
673
674
675 string const
676 InsetIncludeMailer::params2string(InsetInclude::Params const & params)
677 {
678         InsetInclude inset(params);
679         inset.set(params);
680         ostringstream data;
681         data << name_ << ' ';
682         inset.write(0, data);
683         data << "\\end_inset\n";
684
685         return data.str();
686 }