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