]> git.lyx.org Git - lyx.git/blob - src/insets/insetinclude.C
Move the include dialog to the new scheme
[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 #include <config.h>
11
12
13 #include "insetinclude.h"
14 #include "buffer.h"
15 #include "bufferlist.h"
16 #include "BufferView.h"
17 #include "debug.h"
18 #include "funcrequest.h"
19 #include "gettext.h"
20 #include "LaTeXFeatures.h"
21 #include "lyxlex.h"
22 #include "lyxrc.h"
23
24 #include "frontends/Dialogs.h"
25 #include "frontends/LyXView.h"
26 #include "frontends/Painter.h"
27
28 #include "support/filetools.h"
29 #include "support/FileInfo.h"
30 #include "support/FileMonitor.h"
31 #include "support/lstrings.h"
32
33 #include "graphics/PreviewedInset.h"
34 #include "graphics/PreviewImage.h"
35
36 #include <boost/bind.hpp>
37
38 #include <cstdlib>
39
40
41 using std::ostream;
42 using std::endl;
43 using std::vector;
44 using std::pair;
45
46 extern BufferList bufferlist;
47
48
49 class InsetInclude::PreviewImpl : public grfx::PreviewedInset {
50 public:
51         ///
52         PreviewImpl(InsetInclude & p) : PreviewedInset(p) {}
53
54         ///
55         bool previewWanted() const;
56         ///
57         string const latexString() const;
58         ///
59         InsetInclude & parent() const {
60                 return *static_cast<InsetInclude*>(inset());
61         }
62
63         ///
64         bool monitoring() const { return monitor_.get(); }
65         ///
66         void startMonitoring();
67         ///
68         void stopMonitoring() { monitor_.reset(); }
69
70 private:
71         /// Invoked by monitor_ should the parent file change.
72         void restartLoading();
73         ///
74         boost::scoped_ptr<FileMonitor> monitor_;
75 };
76
77
78 namespace {
79
80 string const uniqueID()
81 {
82         static unsigned int seed = 1000;
83
84         ostringstream ost;
85         ost << "file" << ++seed;
86
87         // Needed if we use lyxstring.
88         return STRCONV(ost.str());
89 }
90
91 } // namespace anon
92
93
94 InsetInclude::InsetInclude(Params const & p)
95         : params_(p), include_label(uniqueID()),
96           preview_(new PreviewImpl(*this))
97 {}
98
99
100 InsetInclude::InsetInclude(InsetCommandParams const & p, Buffer const & b)
101         : include_label(uniqueID()),
102           preview_(new PreviewImpl(*this))
103 {
104         params_.cparams = p;
105         params_.masterFilename_ = b.fileName();
106 }
107
108
109 InsetInclude::~InsetInclude()
110 {
111         InsetIncludeMailer mailer(*this);
112         mailer.hideDialog();
113 }
114
115
116 dispatch_result InsetInclude::localDispatch(FuncRequest const & cmd)
117 {
118         if (cmd.action != LFUN_INSET_MODIFY)
119                 return UNDISPATCHED;
120
121         InsetInclude::Params p;
122         InsetIncludeMailer::string2params(cmd.argument, p);
123         if (p.cparams.getCmdName().empty())
124                 return UNDISPATCHED;
125
126         set(p);
127         params_.masterFilename_ = cmd.view()->buffer()->fileName();
128
129         cmd.view()->updateInset(this, true);
130         return DISPATCHED;
131 }
132
133
134 InsetInclude::Params const & InsetInclude::params() const
135 {
136         return params_;
137 }
138
139
140 bool InsetInclude::Params::operator==(Params const & o) const
141 {
142         if (cparams == o.cparams && flag == o.flag &&
143             masterFilename_ == o.masterFilename_)
144                 return true;
145
146         return false;
147 }
148
149
150 bool InsetInclude::Params::operator!=(Params const & o) const
151 {
152         return !(*this == o);
153 }
154
155
156 void InsetInclude::set(Params const & p)
157 {
158         params_ = p;
159
160         string command;
161  
162         switch (params_.flag) {
163                 case INCLUDE:
164                         command="include";
165                         break;
166                 case VERB:
167                         command="verbatiminput";
168                         break;
169                 case INPUT:
170                         command="input";
171                         break;
172                 case VERBAST:
173                         command="verbatiminput*";
174                         break;
175         }
176  
177         params_.cparams.setCmdName(command); 
178  
179         if (preview_->monitoring())
180                 preview_->stopMonitoring();
181
182         if (grfx::PreviewedInset::activated() && params_.flag == INPUT)
183                 preview_->generatePreview();
184 }
185
186
187 Inset * InsetInclude::clone(Buffer const & buffer, bool) const
188 {
189         Params p(params_);
190         p.masterFilename_ = buffer.fileName();
191
192         return new InsetInclude(p);
193 }
194
195
196 void InsetInclude::edit(BufferView *, int, int, mouse_button::state)
197 {
198         InsetIncludeMailer mailer(*this);
199         mailer.showDialog();
200 }
201
202
203 void InsetInclude::edit(BufferView * bv, bool)
204 {
205         edit(bv, 0, 0, mouse_button::none);
206 }
207
208
209 void InsetInclude::write(Buffer const *, ostream & os) const
210 {
211         os << "Include " << params_.cparams.getCommand() << '\n'
212            << "preview " << tostr(params_.cparams.preview()) << '\n';
213 }
214
215
216 void InsetInclude::read(Buffer const *, LyXLex & lex)
217 {
218         params_.cparams.read(lex);
219
220         if (params_.cparams.getCmdName() == "include")
221                 params_.flag = INCLUDE;
222         else if (params_.cparams.getCmdName() == "input")
223                 params_.flag = INPUT;
224         /* FIXME: is this logic necessary now ? */
225         else if (contains(params_.cparams.getCmdName(), "verbatim")) {
226                 params_.flag = VERB;
227                 if (params_.cparams.getCmdName() == "verbatiminput*")
228                         params_.flag = VERBAST;
229         }
230 }
231
232
233 bool InsetInclude::display() const
234 {
235         return !(params_.flag == INPUT);
236 }
237
238
239 string const InsetInclude::getScreenLabel(Buffer const *) const
240 {
241         string temp;
242
243         switch (params_.flag) {
244                 case INPUT: temp += _("Input"); break;
245                 case VERB: temp += _("Verbatim Input"); break;
246                 case VERBAST: temp += _("Verbatim Input*"); break;
247                 case INCLUDE: temp += _("Include"); break;
248         }
249
250         temp += ": ";
251
252         if (params_.cparams.getContents().empty())
253                 temp += "???";
254         else
255                 temp += params_.cparams.getContents();
256
257         return temp;
258 }
259
260
261 string const InsetInclude::getRelFileBaseName() const
262 {
263         return OnlyFilename(ChangeExtension(params_.cparams.getContents(), string()));
264 }
265
266
267 string const InsetInclude::getFileName() const
268 {
269         return MakeAbsPath(params_.cparams.getContents(),
270                            OnlyPath(getMasterFilename()));
271 }
272
273
274 string const InsetInclude::getMasterFilename() const
275 {
276         return params_.masterFilename_;
277 }
278
279
280 bool InsetInclude::loadIfNeeded() const
281 {
282         if (isVerbatim())
283                 return false;
284
285         if (!IsLyXFilename(getFileName()))
286                 return false;
287
288         if (bufferlist.exists(getFileName()))
289                 return true;
290
291         // the readonly flag can/will be wrong, not anymore I think.
292         FileInfo finfo(getFileName());
293         if (!finfo.isOK())
294                 return false;
295
296         return bufferlist.loadLyXFile(getFileName(), false) != 0;
297 }
298
299
300 int InsetInclude::latex(Buffer const * buffer, ostream & os,
301                         bool /*fragile*/, bool /*fs*/) const
302 {
303         string incfile(params_.cparams.getContents());
304
305         // Do nothing if no file name has been specified
306         if (incfile.empty())
307                 return 0;
308
309         if (loadIfNeeded()) {
310                 Buffer * tmp = bufferlist.getBuffer(getFileName());
311
312                 // FIXME: this should be a GUI warning
313                 if (tmp->params.textclass != buffer->params.textclass) {
314                         lyxerr << "WARNING: Included file `"
315                                << MakeDisplayPath(getFileName())
316                                << "' has textclass `"
317                                << tmp->params.getLyXTextClass().name()
318                                << "' while parent file has textclass `"
319                                << buffer->params.getLyXTextClass().name()
320                                << "'." << endl;
321                         //return 0;
322                 }
323
324                 // write it to a file (so far the complete file)
325                 string writefile = ChangeExtension(getFileName(), ".tex");
326
327                 if (!buffer->tmppath.empty()
328                     && !buffer->niceFile) {
329                         incfile = subst(incfile, '/','@');
330 #ifdef __EMX__
331                         incfile = subst(incfile, ':', '$');
332 #endif
333                         writefile = AddName(buffer->tmppath, incfile);
334                 } else
335                         writefile = getFileName();
336                 writefile = ChangeExtension(writefile, ".tex");
337                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
338                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
339
340                 tmp->markDepClean(buffer->tmppath);
341
342                 tmp->makeLaTeXFile(writefile,
343                                    OnlyPath(getMasterFilename()),
344                                    buffer->niceFile, true);
345         }
346
347         if (isVerbatim()) {
348                 os << '\\' << params_.cparams.getCmdName() << '{' << incfile << '}';
349         } else if (params_.flag == INPUT) {
350                 // \input wants file with extension (default is .tex)
351                 if (!IsLyXFilename(getFileName())) {
352                         os << '\\' << params_.cparams.getCmdName() << '{' << incfile << '}';
353                 } else {
354                         os << '\\' << params_.cparams.getCmdName() << '{'
355                            << ChangeExtension(incfile, ".tex")
356                            <<  '}';
357                 }
358         } else {
359                 // \include don't want extension and demands that the
360                 // file really have .tex
361                 os << '\\' << params_.cparams.getCmdName() << '{'
362                    << ChangeExtension(incfile, string())
363                    << '}';
364         }
365
366         return 0;
367 }
368
369
370 int InsetInclude::ascii(Buffer const *, ostream & os, int) const
371 {
372         if (isVerbatim())
373                 os << GetFileContents(getFileName());
374         return 0;
375 }
376
377
378 int InsetInclude::linuxdoc(Buffer const * buffer, ostream & os) const
379 {
380         string incfile(params_.cparams.getContents());
381
382         // Do nothing if no file name has been specified
383         if (incfile.empty())
384                 return 0;
385
386         if (loadIfNeeded()) {
387                 Buffer * tmp = bufferlist.getBuffer(getFileName());
388
389                 // write it to a file (so far the complete file)
390                 string writefile = ChangeExtension(getFileName(), ".sgml");
391                 if (!buffer->tmppath.empty() && !buffer->niceFile) {
392                         incfile = subst(incfile, '/','@');
393                         writefile = AddName(buffer->tmppath, incfile);
394                 } else
395                         writefile = getFileName();
396
397                 if (IsLyXFilename(getFileName()))
398                         writefile = ChangeExtension(writefile, ".sgml");
399
400                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
401                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
402
403                 tmp->makeLinuxDocFile(writefile, buffer->niceFile, true);
404         }
405
406         if (isVerbatim()) {
407                 os << "<![CDATA["
408                    << GetFileContents(getFileName())
409                    << "]]>";
410         } else
411                 os << '&' << include_label << ';';
412
413         return 0;
414 }
415
416
417 int InsetInclude::docbook(Buffer const * buffer, ostream & os,
418                           bool /*mixcont*/) const
419 {
420         string incfile(params_.cparams.getContents());
421
422         // Do nothing if no file name has been specified
423         if (incfile.empty())
424                 return 0;
425
426         if (loadIfNeeded()) {
427                 Buffer * tmp = bufferlist.getBuffer(getFileName());
428
429                 // write it to a file (so far the complete file)
430                 string writefile = ChangeExtension(getFileName(), ".sgml");
431                 if (!buffer->tmppath.empty() && !buffer->niceFile) {
432                         incfile = subst(incfile, '/','@');
433                         writefile = AddName(buffer->tmppath, incfile);
434                 } else
435                         writefile = getFileName();
436                 if (IsLyXFilename(getFileName()))
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()) {
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
459         string incfile(params_.cparams.getContents());
460         string writefile;
461
462         Buffer const * const b = bufferlist.getBuffer(getMasterFilename());
463
464         if (b && !b->tmppath.empty() && !b->niceFile && !isVerbatim()) {
465                 incfile = subst(incfile, '/','@');
466                 writefile = AddName(b->tmppath, incfile);
467         } else
468                 writefile = getFileName();
469
470         if (IsLyXFilename(getFileName()))
471                 writefile = ChangeExtension(writefile, ".sgml");
472
473         features.includeFile(include_label, writefile);
474
475         if (isVerbatim())
476                 features.require("verbatim");
477
478         // Here we must do the fun stuff...
479         // Load the file in the include if it needs
480         // to be loaded:
481         if (loadIfNeeded()) {
482                 // a file got loaded
483                 Buffer * const tmp = bufferlist.getBuffer(getFileName());
484                 if (tmp) {
485                         if (b)
486                                 tmp->niceFile = b->niceFile;
487                         tmp->validate(features);
488                 }
489         }
490 }
491
492
493 vector<string> const InsetInclude::getLabelList() const
494 {
495         vector<string> l;
496
497         if (loadIfNeeded()) {
498                 Buffer * tmp = bufferlist.getBuffer(getFileName());
499                 tmp->setParentName("");
500                 l = tmp->getLabelList();
501                 tmp->setParentName(getMasterFilename());
502         }
503
504         return l;
505 }
506
507
508 void InsetInclude::fillWithBibKeys(vector<pair<string,string> > & keys) const
509 {
510         if (loadIfNeeded()) {
511                 Buffer * tmp = bufferlist.getBuffer(getFileName());
512                 tmp->setParentName("");
513                 tmp->fillWithBibKeys(keys);
514                 tmp->setParentName(getMasterFilename());
515         }
516 }
517
518
519 int InsetInclude::ascent(BufferView * bv, LyXFont const & font) const
520 {
521         return preview_->previewReady() ?
522                 preview_->pimage()->ascent() : InsetButton::ascent(bv, font);
523 }
524
525
526 int InsetInclude::descent(BufferView * bv, LyXFont const & font) const
527 {
528         return preview_->previewReady() ?
529                 preview_->pimage()->descent() : InsetButton::descent(bv, font);
530 }
531
532
533 int InsetInclude::width(BufferView * bv, LyXFont const & font) const
534 {
535         return preview_->previewReady() ?
536                 preview_->pimage()->width() : InsetButton::width(bv, font);
537 }
538
539
540 void InsetInclude::draw(BufferView * bv, LyXFont const & font, int y,
541                         float & xx, bool b) const
542 {
543         cache(bv);
544         if (!preview_->previewReady()) {
545                 InsetButton::draw(bv, font, y, xx, b);
546                 return;
547         }
548
549         if (!preview_->monitoring())
550                 preview_->startMonitoring();
551
552         int const x = int(xx);
553         int const w = width(bv, font);
554         int const d = descent(bv, font);
555         int const a = ascent(bv, font);
556         int const h = a + d;
557
558         bv->painter().image(x, y - a, w, h,
559                             *(preview_->pimage()->image()));
560
561         xx += w;
562 }
563
564
565 //
566 // preview stuff
567 //
568
569 void InsetInclude::addPreview(grfx::PreviewLoader & ploader) const
570 {
571         preview_->addPreview(ploader);
572 }
573
574
575 bool InsetInclude::PreviewImpl::previewWanted() const
576 {
577         return parent().params_.flag == InsetInclude::INPUT &&
578                 parent().params_.cparams.preview() &&
579                 IsFileReadable(parent().getFileName());
580 }
581
582
583 string const InsetInclude::PreviewImpl::latexString() const
584 {
585         if (!view() || !view()->buffer())
586                 return string();
587
588         ostringstream os;
589         parent().latex(view()->buffer(), os, false, false);
590
591         return STRCONV(os.str());
592 }
593
594
595 void InsetInclude::PreviewImpl::startMonitoring()
596 {
597         monitor_.reset(new FileMonitor(parent().getFileName(), 2000));
598         monitor_->connect(boost::bind(&PreviewImpl::restartLoading, this));
599         monitor_->start();
600 }
601
602
603 void InsetInclude::PreviewImpl::restartLoading()
604 {
605         lyxerr << "restartLoading()" << std::endl;
606         removePreview();
607         if (view())
608                 view()->updateInset(&parent(), false);
609         generatePreview();
610 }
611
612
613 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
614         : name_("include"), inset_(inset)
615 {}
616
617
618 string const InsetIncludeMailer::inset2string() const
619 {
620         return params2string(name(), inset_.params());
621 }
622
623
624 void InsetIncludeMailer::string2params(string const & in,
625                                        InsetInclude::Params & params)
626 {
627         params = InsetInclude::Params();
628
629         string name;
630         string body = split(in, name, ' ');
631
632         if (name != "include" || body.empty())
633                 return;
634
635         // This is part of the inset proper that is usually swallowed
636         // by Buffer::readInset
637         body = split(body, name, ' ');
638         if (name != "Include")
639                 return;
640
641         istringstream data(body);
642         LyXLex lex(0,0);
643         lex.setStream(data);
644
645         InsetInclude inset(params);     
646         inset.read(0, lex);
647         params = inset.params();
648 }
649
650
651 string const
652 InsetIncludeMailer::params2string(string const & name,
653                                   InsetInclude::Params const & params)
654 {
655         InsetInclude inset(params);
656         inset.set(params);
657         ostringstream data;
658         data << name << ' ';
659         inset.write(0, data);
660         data << "\\end_inset\n";
661
662         return data.str();
663 }
664