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