]> git.lyx.org Git - lyx.git/blob - src/insets/insetinclude.C
Enable the InsetInclude dialog to be opened.
[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 "lyx_main.h"
26 #include "lyxlex.h"
27 #include "metricsinfo.h"
28 #include "outputparams.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(*this).hideDialog();
107 }
108
109
110 DispatchResult
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()->update();
121                 }
122                 return DispatchResult(true, true);
123         }
124
125         case LFUN_INSET_DIALOG_UPDATE:
126                 InsetIncludeMailer(*this).updateDialog(cmd.view());
127                 return DispatchResult(true, true);
128
129         case LFUN_MOUSE_RELEASE:
130                 if (button_.box().contains(cmd.x, cmd.y))
131                         InsetIncludeMailer(*this).showDialog(cmd.view());
132                 return DispatchResult(true, true);
133
134         case LFUN_INSET_DIALOG_SHOW:
135                 InsetIncludeMailer(*this).showDialog(cmd.view());
136                 return DispatchResult(true, true);
137
138         default:
139                 return DispatchResult(false);
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 add_preview(RenderMonitoredPreview &, 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                 add_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                         OutputParams 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::plaintext(Buffer const & buffer, ostream & os,
367                         OutputParams const &) const
368 {
369         if (isVerbatim(params_))
370                 os << GetFileContents(includedFilename(buffer, params_));
371         return 0;
372 }
373
374
375 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
376                            OutputParams const & runparams) const
377 {
378         string incfile(params_.getContents());
379
380         // Do nothing if no file name has been specified
381         if (incfile.empty())
382                 return 0;
383
384         string const included_file = includedFilename(buffer, params_);
385
386         if (loadIfNeeded(buffer, params_)) {
387                 Buffer * tmp = bufferlist.getBuffer(included_file);
388
389                 // write it to a file (so far the complete file)
390                 string writefile = ChangeExtension(included_file, ".sgml");
391                 if (!buffer.temppath().empty() && !buffer.niceFile()) {
392                         incfile = subst(incfile, '/','@');
393                         writefile = AddName(buffer.temppath(), incfile);
394                 } else
395                         writefile = included_file;
396
397                 if (IsLyXFilename(included_file))
398                         writefile = ChangeExtension(writefile, ".sgml");
399
400                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
401                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
402
403                 OutputParams runp = runparams;
404                 runp.nice = buffer.niceFile();          
405                 tmp->makeLinuxDocFile(writefile, runp, true);
406         }
407
408         if (isVerbatim(params_)) {
409                 os << "<![CDATA["
410                    << GetFileContents(included_file)
411                    << "]]>";
412         } else
413                 os << '&' << include_label << ';';
414
415         return 0;
416 }
417
418
419 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
420                           OutputParams const & runparams) const
421 {
422         string incfile(params_.getContents());
423
424         // Do nothing if no file name has been specified
425         if (incfile.empty())
426                 return 0;
427
428         string const included_file = includedFilename(buffer, params_);
429
430         if (loadIfNeeded(buffer, params_)) {
431                 Buffer * tmp = bufferlist.getBuffer(included_file);
432
433                 // write it to a file (so far the complete file)
434                 string writefile = ChangeExtension(included_file, ".sgml");
435                 if (!buffer.temppath().empty() && !buffer.niceFile()) {
436                         incfile = subst(incfile, '/','@');
437                         writefile = AddName(buffer.temppath(), incfile);
438                 } else
439                         writefile = included_file;
440                 if (IsLyXFilename(included_file))
441                         writefile = ChangeExtension(writefile, ".sgml");
442
443                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
444                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
445
446                 OutputParams runp = runparams;
447                 runp.nice = buffer.niceFile();
448                 tmp->makeDocBookFile(writefile, runp, true);
449         }
450
451         if (isVerbatim(params_)) {
452                 os << "<inlinegraphic fileref=\""
453                    << '&' << include_label << ';'
454                    << "\" format=\"linespecific\">";
455         } else
456                 os << '&' << include_label << ';';
457
458         return 0;
459 }
460
461
462 void InsetInclude::validate(LaTeXFeatures & features) const
463 {
464         string incfile(params_.getContents());
465         string writefile;
466
467         Buffer const & buffer = features.buffer();
468
469         string const included_file = includedFilename(buffer, params_);
470
471         if (!buffer.temppath().empty() &&
472             !buffer.niceFile() &&
473             !isVerbatim(params_)) {
474                 incfile = subst(incfile, '/','@');
475                 writefile = AddName(buffer.temppath(), incfile);
476         } else
477                 writefile = included_file;
478
479         if (IsLyXFilename(included_file))
480                 writefile = ChangeExtension(writefile, ".sgml");
481
482         features.includeFile(include_label, writefile);
483
484         if (isVerbatim(params_))
485                 features.require("verbatim");
486
487         // Here we must do the fun stuff...
488         // Load the file in the include if it needs
489         // to be loaded:
490         if (loadIfNeeded(buffer, params_)) {
491                 // a file got loaded
492                 Buffer * const tmp = bufferlist.getBuffer(included_file);
493                 if (tmp) {
494                         tmp->niceFile() = buffer.niceFile();
495                         tmp->validate(features);
496                 }
497         }
498 }
499
500
501 void InsetInclude::getLabelList(Buffer const & buffer,
502                                 std::vector<string> & list) const
503 {
504         if (loadIfNeeded(buffer, params_)) {
505                 string const included_file = includedFilename(buffer, params_);
506                 Buffer * tmp = bufferlist.getBuffer(included_file);
507                 tmp->setParentName("");
508                 tmp->getLabelList(list);
509                 tmp->setParentName(masterFilename(buffer));
510         }
511 }
512
513
514 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
515                                    std::vector<std::pair<string,string> > & keys) const
516 {
517         if (loadIfNeeded(buffer, params_)) {
518                 string const included_file = includedFilename(buffer, params_);
519                 Buffer * tmp = bufferlist.getBuffer(included_file);
520                 tmp->setParentName("");
521                 tmp->fillWithBibKeys(keys);
522                 tmp->setParentName(masterFilename(buffer));
523         }
524 }
525
526
527 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
528 {
529         if (RenderPreview::activated() && preview_->previewReady()) {
530                 preview_->metrics(mi, dim);
531         } else {
532                 if (!set_label_) {
533                         set_label_ = true;
534                         button_.update(getScreenLabel(*mi.base.bv->buffer()),
535                                        editable() != NOT_EDITABLE);
536                 }
537                 button_.metrics(mi, dim);
538         }
539         int center_indent = type(params_) == INPUT ?
540                 0 : (mi.base.textwidth - dim.wid) / 2;
541         Box b(center_indent, center_indent + dim.wid, -dim.asc, dim.des);
542         button_.setBox(b);
543
544         dim.wid = mi.base.textwidth;
545         dim_ = dim;
546 }
547
548
549 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
550 {
551         xo_ = x;
552         yo_ = y;
553
554         if (!RenderPreview::activated() || !preview_->previewReady()) {
555                 button_.draw(pi, x + button_.box().x1, y);
556                 return;
557         }
558
559         preview_->draw(pi, x + button_.box().x1, y);
560 }
561
562
563 //
564 // preview stuff
565 //
566
567 void InsetInclude::statusChanged() const
568 {
569         LyX::cref().updateInset(this);
570 }
571
572
573 void InsetInclude::fileChanged() const
574 {
575         Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
576         if (!buffer_ptr)
577                 return;
578
579         Buffer const & buffer = *buffer_ptr;
580         preview_->removePreview(buffer);
581         add_preview(*preview_.get(), *this, buffer);
582         preview_->startLoading(buffer);
583 }
584
585
586 namespace {
587
588 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
589 {
590         string const included_file = includedFilename(buffer, params);
591
592         return type(params) == INPUT && params.preview() &&
593                 IsFileReadable(included_file);
594 }
595
596
597 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
598 {
599         ostringstream os;
600         OutputParams runparams;
601         runparams.flavor = OutputParams::LATEX;
602         inset.latex(buffer, os, runparams);
603
604         return os.str();
605 }
606
607
608 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
609                  Buffer const & buffer)
610 {
611         InsetCommandParams const & params = inset.params();
612         if (RenderPreview::activated() && preview_wanted(params, buffer)) {
613                 renderer.setAbsFile(includedFilename(buffer, params));
614                 string const snippet = latex_string(inset, buffer);
615                 renderer.addPreview(snippet, buffer);
616         }
617 }
618
619 } // namespace anon
620
621
622 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
623 {
624         Buffer const & buffer = ploader.buffer();
625         if (preview_wanted(params(), buffer)) {
626                 preview_->setAbsFile(includedFilename(buffer, params()));
627                 string const snippet = latex_string(*this, buffer);
628                 preview_->addPreview(snippet, ploader);
629         }
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                                        InsetCommandParams & params)
648 {
649         params = InsetCommandParams();
650         if (in.empty())
651                 return;
652
653         istringstream data(in);
654         LyXLex lex(0,0);
655         lex.setStream(data);
656
657         string name;
658         lex >> name;
659         if (!lex || name != name_)
660                 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
661
662         // This is part of the inset proper that is usually swallowed
663         // by LyXText::readInset
664         string id;
665         lex >> id;
666         if (!lex || id != "Include")
667                 return print_mailer_error("InsetBoxMailer", in, 2, "Include");
668
669         InsetInclude inset(params);
670         inset.read(lex);
671         params = inset.params();
672 }
673
674
675 string const
676 InsetIncludeMailer::params2string(InsetCommandParams const & params)
677 {
678         InsetInclude inset(params);
679         ostringstream data;
680         data << name_ << ' ';
681         inset.write(data);
682         data << "\\end_inset\n";
683         return data.str();
684 }