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