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