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