]> git.lyx.org Git - lyx.git/blob - src/insets/insetinclude.C
The markDirty() and fitCursor() changes
[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::getRelFileBaseName() const
281 {
282         return OnlyFilename(ChangeExtension(params_.cparams.getContents(), string()));
283 }
284
285
286 string const InsetInclude::getFileName() const
287 {
288         return MakeAbsPath(params_.cparams.getContents(),
289                            OnlyPath(getMasterFilename()));
290 }
291
292
293 string const InsetInclude::getMasterFilename() const
294 {
295         return params_.masterFilename_;
296 }
297
298
299 bool InsetInclude::loadIfNeeded() const
300 {
301         if (isVerbatim())
302                 return false;
303
304         if (!IsLyXFilename(getFileName()))
305                 return false;
306
307         if (bufferlist.exists(getFileName()))
308                 return true;
309
310         // the readonly flag can/will be wrong, not anymore I think.
311         FileInfo finfo(getFileName());
312         if (!finfo.isOK())
313                 return false;
314
315         return bufferlist.loadLyXFile(getFileName(), false) != 0;
316 }
317
318
319 int InsetInclude::latex(Buffer const * buffer, ostream & os,
320                         bool /*fragile*/, bool /*fs*/) const
321 {
322         string incfile(params_.cparams.getContents());
323
324         // Do nothing if no file name has been specified
325         if (incfile.empty())
326                 return 0;
327
328         if (loadIfNeeded()) {
329                 Buffer * tmp = bufferlist.getBuffer(getFileName());
330
331                 // FIXME: this should be a GUI warning
332                 if (tmp->params.textclass != buffer->params.textclass) {
333                         lyxerr << "WARNING: Included file `"
334                                << MakeDisplayPath(getFileName())
335                                << "' has textclass `"
336                                << tmp->params.getLyXTextClass().name()
337                                << "' while parent file has textclass `"
338                                << buffer->params.getLyXTextClass().name()
339                                << "'." << endl;
340                         //return 0;
341                 }
342
343                 // write it to a file (so far the complete file)
344                 string writefile = ChangeExtension(getFileName(), ".tex");
345
346                 if (!buffer->tmppath.empty()
347                     && !buffer->niceFile) {
348                         incfile = subst(incfile, '/','@');
349 #ifdef __EMX__
350                         incfile = subst(incfile, ':', '$');
351 #endif
352                         writefile = AddName(buffer->tmppath, incfile);
353                 } else
354                         writefile = getFileName();
355                 writefile = ChangeExtension(writefile, ".tex");
356                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
357                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
358
359                 tmp->markDepClean(buffer->tmppath);
360
361                 tmp->makeLaTeXFile(writefile,
362                                    OnlyPath(getMasterFilename()),
363                                    buffer->niceFile, true);
364         }
365
366         if (isVerbatim()) {
367                 os << '\\' << params_.cparams.getCmdName() << '{' << incfile << '}';
368         } else if (params_.flag == INPUT) {
369                 // \input wants file with extension (default is .tex)
370                 if (!IsLyXFilename(getFileName())) {
371                         os << '\\' << params_.cparams.getCmdName() << '{' << incfile << '}';
372                 } else {
373                         os << '\\' << params_.cparams.getCmdName() << '{'
374                            << ChangeExtension(incfile, ".tex")
375                            <<  '}';
376                 }
377         } else {
378                 // \include don't want extension and demands that the
379                 // file really have .tex
380                 os << '\\' << params_.cparams.getCmdName() << '{'
381                    << ChangeExtension(incfile, string())
382                    << '}';
383         }
384
385         return 0;
386 }
387
388
389 int InsetInclude::ascii(Buffer const *, ostream & os, int) const
390 {
391         if (isVerbatim())
392                 os << GetFileContents(getFileName());
393         return 0;
394 }
395
396
397 int InsetInclude::linuxdoc(Buffer const * buffer, ostream & os) const
398 {
399         string incfile(params_.cparams.getContents());
400
401         // Do nothing if no file name has been specified
402         if (incfile.empty())
403                 return 0;
404
405         if (loadIfNeeded()) {
406                 Buffer * tmp = bufferlist.getBuffer(getFileName());
407
408                 // write it to a file (so far the complete file)
409                 string writefile = ChangeExtension(getFileName(), ".sgml");
410                 if (!buffer->tmppath.empty() && !buffer->niceFile) {
411                         incfile = subst(incfile, '/','@');
412                         writefile = AddName(buffer->tmppath, incfile);
413                 } else
414                         writefile = getFileName();
415
416                 if (IsLyXFilename(getFileName()))
417                         writefile = ChangeExtension(writefile, ".sgml");
418
419                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
420                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
421
422                 tmp->makeLinuxDocFile(writefile, buffer->niceFile, true);
423         }
424
425         if (isVerbatim()) {
426                 os << "<![CDATA["
427                    << GetFileContents(getFileName())
428                    << "]]>";
429         } else
430                 os << '&' << include_label << ';';
431
432         return 0;
433 }
434
435
436 int InsetInclude::docbook(Buffer const * buffer, ostream & os,
437                           bool /*mixcont*/) const
438 {
439         string incfile(params_.cparams.getContents());
440
441         // Do nothing if no file name has been specified
442         if (incfile.empty())
443                 return 0;
444
445         if (loadIfNeeded()) {
446                 Buffer * tmp = bufferlist.getBuffer(getFileName());
447
448                 // write it to a file (so far the complete file)
449                 string writefile = ChangeExtension(getFileName(), ".sgml");
450                 if (!buffer->tmppath.empty() && !buffer->niceFile) {
451                         incfile = subst(incfile, '/','@');
452                         writefile = AddName(buffer->tmppath, incfile);
453                 } else
454                         writefile = getFileName();
455                 if (IsLyXFilename(getFileName()))
456                         writefile = ChangeExtension(writefile, ".sgml");
457
458                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
459                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
460
461                 tmp->makeDocBookFile(writefile, buffer->niceFile, true);
462         }
463
464         if (isVerbatim()) {
465                 os << "<inlinegraphic fileref=\""
466                    << '&' << include_label << ';'
467                    << "\" format=\"linespecific\">";
468         } else
469                 os << '&' << include_label << ';';
470
471         return 0;
472 }
473
474
475 void InsetInclude::validate(LaTeXFeatures & features) const
476 {
477
478         string incfile(params_.cparams.getContents());
479         string writefile;
480
481         Buffer const * const b = bufferlist.getBuffer(getMasterFilename());
482
483         if (b && !b->tmppath.empty() && !b->niceFile && !isVerbatim()) {
484                 incfile = subst(incfile, '/','@');
485                 writefile = AddName(b->tmppath, incfile);
486         } else
487                 writefile = getFileName();
488
489         if (IsLyXFilename(getFileName()))
490                 writefile = ChangeExtension(writefile, ".sgml");
491
492         features.includeFile(include_label, writefile);
493
494         if (isVerbatim())
495                 features.require("verbatim");
496
497         // Here we must do the fun stuff...
498         // Load the file in the include if it needs
499         // to be loaded:
500         if (loadIfNeeded()) {
501                 // a file got loaded
502                 Buffer * const tmp = bufferlist.getBuffer(getFileName());
503                 if (tmp) {
504                         if (b)
505                                 tmp->niceFile = b->niceFile;
506                         tmp->validate(features);
507                 }
508         }
509 }
510
511
512 vector<string> const InsetInclude::getLabelList() const
513 {
514         vector<string> l;
515
516         if (loadIfNeeded()) {
517                 Buffer * tmp = bufferlist.getBuffer(getFileName());
518                 tmp->setParentName("");
519                 l = tmp->getLabelList();
520                 tmp->setParentName(getMasterFilename());
521         }
522
523         return l;
524 }
525
526
527 void InsetInclude::fillWithBibKeys(vector<pair<string,string> > & keys) const
528 {
529         if (loadIfNeeded()) {
530                 Buffer * tmp = bufferlist.getBuffer(getFileName());
531                 tmp->setParentName("");
532                 tmp->fillWithBibKeys(keys);
533                 tmp->setParentName(getMasterFilename());
534         }
535 }
536
537
538 int InsetInclude::ascent(BufferView * bv, LyXFont const & font) const
539 {
540         return preview_->previewReady() ?
541                 preview_->pimage()->ascent() : InsetButton::ascent(bv, font);
542 }
543
544
545 int InsetInclude::descent(BufferView * bv, LyXFont const & font) const
546 {
547         return preview_->previewReady() ?
548                 preview_->pimage()->descent() : InsetButton::descent(bv, font);
549 }
550
551
552 int InsetInclude::width(BufferView * bv, LyXFont const & font) const
553 {
554         return preview_->previewReady() ?
555                 preview_->pimage()->width() : InsetButton::width(bv, font);
556 }
557
558
559 void InsetInclude::draw(BufferView * bv, LyXFont const & font, int y,
560                         float & xx) const
561 {
562         cache(bv);
563         if (!preview_->previewReady()) {
564                 InsetButton::draw(bv, font, y, xx);
565                 return;
566         }
567
568         if (!preview_->monitoring())
569                 preview_->startMonitoring();
570
571         int const x = int(xx);
572         int const w = width(bv, font);
573         int const d = descent(bv, font);
574         int const a = ascent(bv, font);
575         int const h = a + d;
576
577         bv->painter().image(x, y - a, w, h,
578                             *(preview_->pimage()->image()));
579
580         xx += w;
581 }
582
583
584 //
585 // preview stuff
586 //
587
588 void InsetInclude::addPreview(grfx::PreviewLoader & ploader) const
589 {
590         preview_->addPreview(ploader);
591 }
592
593
594 bool InsetInclude::PreviewImpl::previewWanted() const
595 {
596         return parent().params_.flag == InsetInclude::INPUT &&
597                 parent().params_.cparams.preview() &&
598                 IsFileReadable(parent().getFileName());
599 }
600
601
602 string const InsetInclude::PreviewImpl::latexString() const
603 {
604         if (!view() || !view()->buffer())
605                 return string();
606
607         ostringstream os;
608         parent().latex(view()->buffer(), os, false, false);
609
610         return STRCONV(os.str());
611 }
612
613
614 void InsetInclude::PreviewImpl::startMonitoring()
615 {
616         monitor_.reset(new FileMonitor(parent().getFileName(), 2000));
617         monitor_->connect(boost::bind(&PreviewImpl::restartLoading, this));
618         monitor_->start();
619 }
620
621
622 void InsetInclude::PreviewImpl::restartLoading()
623 {
624         lyxerr << "restartLoading()" << std::endl;
625         removePreview();
626         if (view())
627                 view()->updateInset(&parent());
628         generatePreview();
629 }
630
631
632 string const InsetIncludeMailer::name_("include");
633
634 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
635         : inset_(inset)
636 {}
637
638
639 string const InsetIncludeMailer::inset2string() const
640 {
641         return params2string(inset_.params());
642 }
643
644
645 void InsetIncludeMailer::string2params(string const & in,
646                                        InsetInclude::Params & params)
647 {
648         params = InsetInclude::Params();
649
650         istringstream data(in);
651         LyXLex lex(0,0);
652         lex.setStream(data);
653
654         if (lex.isOK()) {
655                 lex.next();
656                 string const token = lex.getString();
657                 if (token != name_)
658                         return;
659         }
660
661         // This is part of the inset proper that is usually swallowed
662         // by Buffer::readInset
663         if (lex.isOK()) {
664                 lex.next();
665                 string const token = lex.getString();
666                 if (token != "Include")
667                         return;
668         }
669
670         if (lex.isOK()) {
671                 InsetInclude inset(params);     
672                 inset.read(0, lex);
673                 params = inset.params();
674         }
675 }
676
677
678 string const
679 InsetIncludeMailer::params2string(InsetInclude::Params const & params)
680 {
681         InsetInclude inset(params);
682         inset.set(params);
683         ostringstream data;
684         data << name_ << ' ';
685         inset.write(0, data);
686         data << "\\end_inset\n";
687
688         return data.str();
689 }