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