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