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