]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
handle most of InsetText::dispatch() to LyXText::dispatch
[lyx.git] / src / insets / insettext.C
1 /**
2  * \file insettext.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "insettext.h"
14 #include "insetnewline.h"
15
16 #include "buffer.h"
17 #include "bufferparams.h"
18 #include "BufferView.h"
19 #include "CutAndPaste.h"
20 #include "cursor.h"
21 #include "debug.h"
22 #include "dispatchresult.h"
23 #include "errorlist.h"
24 #include "funcrequest.h"
25 #include "gettext.h"
26 #include "intl.h"
27 #include "LColor.h"
28 #include "lyxfind.h"
29 #include "lyxlex.h"
30 #include "lyxrc.h"
31 #include "lyxtext.h"
32 #include "metricsinfo.h"
33 #include "output_docbook.h"
34 #include "output_latex.h"
35 #include "output_linuxdoc.h"
36 #include "output_plaintext.h"
37 #include "paragraph.h"
38 #include "paragraph_funcs.h"
39 #include "ParagraphParameters.h"
40 #include "rowpainter.h"
41 #include "sgml.h"
42 #include "texrow.h"
43 #include "undo.h"
44
45 #include "frontends/Alert.h"
46 #include "frontends/font_metrics.h"
47 #include "frontends/LyXView.h"
48 #include "frontends/Painter.h"
49
50 #include "support/lyxalgo.h" // lyx::count
51
52 #include <boost/bind.hpp>
53
54 using bv_funcs::replaceSelection;
55
56 using lyx::pos_type;
57
58 using lyx::graphics::PreviewLoader;
59
60 using lyx::support::isStrUnsignedInt;
61 using lyx::support::strToUnsignedInt;
62
63 using std::endl;
64 using std::for_each;
65 using std::max;
66 using std::string;
67 using std::auto_ptr;
68 using std::ostream;
69 using std::vector;
70
71
72 InsetText::InsetText(BufferParams const & bp)
73         : UpdatableInset(),
74           paragraphs(1),
75           autoBreakRows_(false),
76           drawFrame_(NEVER),
77           frame_color_(LColor::insetframe),
78           text_(0, this, true, paragraphs)
79 {
80         textwidth_ = 0; // broken
81         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
82         if (bp.tracking_changes)
83                 paragraphs.begin()->trackChanges();
84         init();
85 }
86
87
88 InsetText::InsetText(InsetText const & in)
89         : UpdatableInset(in),
90           text_(in.text_.bv_owner, this, true, paragraphs)
91 {
92         // this is ugly...
93         operator=(in);
94 }
95
96
97 void InsetText::operator=(InsetText const & in)
98 {
99         UpdatableInset::operator=(in);
100         paragraphs = in.paragraphs;
101         autoBreakRows_ = in.autoBreakRows_;
102         drawFrame_ = in.drawFrame_;
103         frame_color_ = in.frame_color_;
104         textwidth_ = in.textwidth_;
105         text_ = LyXText(in.text_.bv_owner, this, true, paragraphs);
106         init();
107 }
108
109
110 void InsetText::init()
111 {
112         ParagraphList::iterator pit = paragraphs.begin();
113         ParagraphList::iterator end = paragraphs.end();
114         for (; pit != end; ++pit)
115                 pit->setInsetOwner(this);
116         text_.paragraphs_ = &paragraphs;
117         no_selection = true;
118         old_par = -1;
119         in_insetAllowed = false;
120         mouse_x = 0;
121         mouse_y = 0;
122 }
123
124
125 void InsetText::clear(bool just_mark_erased)
126 {
127         if (just_mark_erased) {
128                 ParagraphList::iterator it = paragraphs.begin();
129                 ParagraphList::iterator end = paragraphs.end();
130                 for (; it != end; ++it)
131                         it->markErased();
132                 return;
133         }
134
135         // This is a gross hack...
136         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
137
138         paragraphs.clear();
139         paragraphs.push_back(Paragraph());
140         paragraphs.begin()->setInsetOwner(this);
141         paragraphs.begin()->layout(old_layout);
142 }
143
144
145 auto_ptr<InsetBase> InsetText::clone() const
146 {
147         return auto_ptr<InsetBase>(new InsetText(*this));
148 }
149
150
151 void InsetText::write(Buffer const & buf, ostream & os) const
152 {
153         os << "Text\n";
154         writeParagraphData(buf, os);
155 }
156
157
158 void InsetText::writeParagraphData(Buffer const & buf, ostream & os) const
159 {
160         ParagraphList::const_iterator it = paragraphs.begin();
161         ParagraphList::const_iterator end = paragraphs.end();
162         Paragraph::depth_type dth = 0;
163         for (; it != end; ++it) {
164                 it->write(buf, os, buf.params(), dth);
165         }
166 }
167
168
169 void InsetText::read(Buffer const & buf, LyXLex & lex)
170 {
171         string token;
172         Paragraph::depth_type depth = 0;
173
174         clear(false);
175
176 #warning John, look here. Doesnt make much sense.
177         if (buf.params().tracking_changes)
178                 paragraphs.begin()->trackChanges();
179
180         // delete the initial paragraph
181         Paragraph oldpar = *paragraphs.begin();
182         paragraphs.clear();
183         ParagraphList::iterator pit = paragraphs.begin();
184
185         while (lex.isOK()) {
186                 lex.nextToken();
187                 token = lex.getString();
188                 if (token.empty())
189                         continue;
190                 if (token == "\\end_inset") {
191                         break;
192                 }
193
194                 if (token == "\\end_document") {
195                         lex.printError("\\end_document read in inset! Error in document!");
196                         return;
197                 }
198
199                 // FIXME: ugly.
200                 const_cast<Buffer&>(buf).readParagraph(lex, token, paragraphs, pit, depth);
201         }
202
203         pit = paragraphs.begin();
204         ParagraphList::iterator const end = paragraphs.end();
205         for (; pit != end; ++pit)
206                 pit->setInsetOwner(this);
207
208         if (token != "\\end_inset") {
209                 lex.printError("Missing \\end_inset at this point. "
210                                            "Read: `$$Token'");
211         }
212
213         // sanity check
214         // ensure we have at least one par.
215         if (paragraphs.empty())
216                 paragraphs.push_back(oldpar);
217 }
218
219
220 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
221 {
222         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
223         textwidth_ = max(40, mi.base.textwidth - 30);
224         BufferView * bv = mi.base.bv;
225         setViewCache(bv);
226         text_.metrics(mi, dim);
227         dim.asc += TEXT_TO_INSET_OFFSET;
228         dim.des += TEXT_TO_INSET_OFFSET;
229         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
230         dim_ = dim;
231 }
232
233
234 int InsetText::textWidth() const
235 {
236         return textwidth_;
237 }
238
239
240 void InsetText::draw(PainterInfo & pi, int x, int y) const
241 {
242         // update our idea of where we are. Clearly, we should
243         // not have to know this information.
244         xo_ = x;
245         yo_ = y;
246
247         int const start_x = x;
248
249         BufferView * bv = pi.base.bv;
250         Painter & pain = pi.pain;
251
252         // repaint the background if needed
253         if (backgroundColor() != LColor::background)
254                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, y);
255
256         bv->hideCursor();
257
258         if (!owner())
259                 x += scroll();
260
261         x += TEXT_TO_INSET_OFFSET;
262
263         paintTextInset(*bv, text_, x, y);
264
265         if (drawFrame_ == ALWAYS || drawFrame_ == LOCKED)
266                 drawFrame(pain, start_x);
267 }
268
269
270 void InsetText::drawFrame(Painter & pain, int x) const
271 {
272         int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
273         int const frame_x = x + ttoD2;
274         int const frame_y = yo_ - dim_.asc + ttoD2;
275         int const frame_w = dim_.wid - TEXT_TO_INSET_OFFSET;
276         int const frame_h = dim_.asc + dim_.des - TEXT_TO_INSET_OFFSET;
277         pain.rectangle(frame_x, frame_y, frame_w, frame_h, frameColor());
278 }
279
280
281 void InsetText::updateLocal(BufferView * bv, bool /*mark_dirty*/)
282 {
283         if (!bv)
284                 return;
285
286         if (!autoBreakRows_ && paragraphs.size() > 1)
287                 collapseParagraphs(bv);
288
289         if (!text_.selection.set())
290                 text_.selection.cursor = text_.cursor;
291
292 //      bv->fitCursor();
293         bv->owner()->view_state_changed();
294         bv->owner()->updateMenubar();
295         bv->owner()->updateToolbar();
296         if (old_par != text_.cursor.par()) {
297                 bv->owner()->setLayout(cpar()->layout()->name());
298                 old_par = text_.cursor.par();
299         }
300 }
301
302
303 string const InsetText::editMessage() const
304 {
305         return _("Opened Text Inset");
306 }
307
308
309 void InsetText::sanitizeEmptyText(BufferView * bv)
310 {
311         if (paragraphs.size() == 1
312                         && paragraphs.begin()->empty() 
313                         && bv->getParentLanguage(this) != text_.current_font.language()) {
314                 LyXFont font(LyXFont::ALL_IGNORE);
315                 font.setLanguage(bv->getParentLanguage(this));
316                 setFont(bv, font, false);
317         }
318 }
319
320
321 extern LCursor theTempCursor;
322
323 void InsetText::lfunMousePress(FuncRequest const & cmd)
324 {
325         lyxerr << "InsetText::lfunMousePress, inset: " << this << endl;
326         no_selection = true;
327
328         // use this to check mouse motion for selection
329         mouse_x = cmd.x;
330         mouse_y = cmd.y;
331
332         BufferView * bv = cmd.view();
333         no_selection = false;
334         text_.clearSelection();
335
336         // set global cursor
337         bv->cursor() = theTempCursor;
338         lyxerr << "new global cursor: \n" << bv->cursor() << endl;
339         text_.setCursorFromCoordinates(cmd.x, cmd.y);
340 }
341
342
343 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
344 {
345         lyxerr << "InsetText::lfunMouseMotion, inset: " << this << endl;
346         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
347                 return;
348
349         BufferView * bv = cmd.view();
350         LyXCursor cur = text_.cursor;
351         text_.setCursorFromCoordinates(cmd.x, cmd.y + dim_.asc);
352         bv->x_target(text_.cursor.x());
353         if (cur != text_.cursor) {
354                 text_.setSelection();
355                 updateLocal(bv, false);
356         }
357 }
358
359
360 void InsetText::lfunMouseRelease(FuncRequest const &)
361 {
362         lyxerr << "InsetText::lfunMouseRelease, inset: " << this << endl;
363         no_selection = true;
364 }
365
366
367 void InsetText::edit(BufferView * bv, bool left)
368 {
369         lyxerr << "InsetText: edit left/right" << endl;
370         setViewCache(bv);
371
372         old_par = -1;
373
374         if (left)
375                 text_.setCursorIntern(0, 0);
376         else
377                 text_.setCursor(paragraphs.size() - 1, paragraphs.back().size());
378
379         sanitizeEmptyText(bv);
380         updateLocal(bv, false);
381         bv->updateParagraphDialog();
382 }
383
384
385 void InsetText::edit(BufferView * bv, int x, int y)
386 {
387         lyxerr << "InsetText::edit xy" << endl;
388         old_par = -1;
389         sanitizeEmptyText(bv);
390         text_.setCursorFromCoordinates(x, y + dim_.asc);
391         text_.cursor.x(text_.cursor.x());
392         bv->x_target(text_.cursor.x());
393
394         text_.clearSelection();
395         finishUndo();
396
397         updateLocal(bv, false);
398         bv->updateParagraphDialog();
399 }
400
401
402 DispatchResult InsetText::priv_dispatch(FuncRequest const & cmd,
403         idx_type &, pos_type &)
404 {
405         lyxerr << "InsetText::priv_dispatch (begin), act: "
406                 << cmd.action << " " << endl;
407         BufferView * bv = cmd.view();
408         setViewCache(bv);
409         DispatchResult result;
410         result.dispatched(true);
411
412         bool was_empty = paragraphs.begin()->empty() && paragraphs.size() == 1;
413         if (cmd.action != LFUN_MOUSE_PRESS
414                         && cmd.action != LFUN_MOUSE_MOTION
415                         && cmd.action != LFUN_MOUSE_RELEASE)
416                 no_selection = false;
417
418         switch (cmd.action) {
419         case LFUN_MOUSE_PRESS:
420                 lfunMousePress(cmd);
421                 result = DispatchResult(true, true);    
422                 break;
423
424         case LFUN_MOUSE_MOTION:
425                 lfunMouseMotion(cmd);
426                 result = DispatchResult(true, true);
427                 break;
428
429         case LFUN_MOUSE_RELEASE:
430                 lfunMouseRelease(cmd);
431                 result = DispatchResult(true, true);
432                 break;
433
434         default:
435                 result = text_.dispatch(cmd);
436                 break;
437         }
438
439         /// If the action has deleted all text in the inset, we need to change the
440         // language to the language of the surronding text.
441         if (!was_empty && paragraphs.begin()->empty() &&
442             paragraphs.size() == 1) {
443                 LyXFont font(LyXFont::ALL_IGNORE);
444                 font.setLanguage(bv->getParentLanguage(this));
445                 setFont(bv, font, false);
446         }
447
448         lyxerr << "InsetText::priv_dispatch (end)" << endl;
449         return result;
450 }
451
452
453 int InsetText::latex(Buffer const & buf, ostream & os,
454                      OutputParams const & runparams) const
455 {
456         TexRow texrow;
457         latexParagraphs(buf, paragraphs, os, texrow, runparams);
458         return texrow.rows();
459 }
460
461
462 int InsetText::plaintext(Buffer const & buf, ostream & os,
463                      OutputParams const & runparams) const
464 {
465         ParagraphList::const_iterator beg = paragraphs.begin();
466         ParagraphList::const_iterator end = paragraphs.end();
467         ParagraphList::const_iterator it = beg;
468         for (; it != end; ++it)
469                 asciiParagraph(buf, *it, os, runparams, it == beg);
470
471         //FIXME: Give the total numbers of lines
472         return 0;
473 }
474
475
476 int InsetText::linuxdoc(Buffer const & buf, ostream & os,
477                         OutputParams const & runparams) const
478 {
479         linuxdocParagraphs(buf, paragraphs, os, runparams);
480         return 0;
481 }
482
483
484 int InsetText::docbook(Buffer const & buf, ostream & os,
485                        OutputParams const & runparams) const
486 {
487         docbookParagraphs(buf, paragraphs, os, runparams);
488         return 0;
489 }
490
491
492 void InsetText::validate(LaTeXFeatures & features) const
493 {
494         for_each(paragraphs.begin(), paragraphs.end(),
495                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
496 }
497
498
499 void InsetText::getCursorPos(BufferView *, int & x, int & y) const
500 {
501         x = text_.cursor.x() + TEXT_TO_INSET_OFFSET;
502         y = text_.cursor.y() - dim_.asc + TEXT_TO_INSET_OFFSET;
503 }
504
505
506 int InsetText::insetInInsetY() const
507 {
508         return 0;
509 }
510
511
512 bool InsetText::insertInset(BufferView * bv, InsetOld * inset)
513 {
514         inset->setOwner(this);
515         text_.insertInset(inset);
516 //      bv->fitCursor();
517         updateLocal(bv, true);
518         return true;
519 }
520
521
522 bool InsetText::insetAllowed(InsetOld::Code code) const
523 {
524         // in_insetAllowed is a really gross hack,
525         // to allow us to call the owner's insetAllowed
526         // without stack overflow, which can happen
527         // when the owner uses InsetCollapsable::insetAllowed()
528         bool ret = true;
529         if (in_insetAllowed)
530                 return ret;
531         in_insetAllowed = true;
532         if (owner())
533                 ret = owner()->insetAllowed(code);
534         in_insetAllowed = false;
535         return ret;
536 }
537
538
539 bool InsetText::showInsetDialog(BufferView *) const
540 {
541         return false;
542 }
543
544
545 void InsetText::getLabelList(Buffer const & buffer,
546                              std::vector<string> & list) const
547 {
548         ParagraphList::const_iterator pit = paragraphs.begin();
549         ParagraphList::const_iterator pend = paragraphs.end();
550         for (; pit != pend; ++pit) {
551                 InsetList::const_iterator beg = pit->insetlist.begin();
552                 InsetList::const_iterator end = pit->insetlist.end();
553                 for (; beg != end; ++beg)
554                         beg->inset->getLabelList(buffer, list);
555         }
556 }
557
558
559 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
560                         bool selectall)
561 {
562         if ((paragraphs.size() == 1 && paragraphs.begin()->empty())
563             || cpar()->empty()) {
564                 text_.setFont(font, toggleall);
565                 return;
566         }
567
568         if (text_.selection.set())
569                 text_.recUndo(text_.cursor.par());
570
571         if (selectall) {
572                 text_.cursorTop();
573                 text_.selection.cursor = text_.cursor;
574                 text_.cursorBottom();
575                 text_.setSelection();
576         }
577
578         text_.toggleFree(font, toggleall);
579
580         if (selectall)
581                 text_.clearSelection();
582
583 //      bv->fitCursor();
584         updateLocal(bv, true);
585 }
586
587
588 void InsetText::markNew(bool track_changes)
589 {
590         ParagraphList::iterator pit = paragraphs.begin();
591         ParagraphList::iterator end = paragraphs.end();
592         for (; pit != end; ++pit) {
593                 if (track_changes) {
594                         pit->trackChanges();
595                 } else {
596                         // no-op when not tracking
597                         pit->cleanChanges();
598                 }
599         }
600 }
601
602
603 void InsetText::setText(string const & data, LyXFont const & font)
604 {
605         clear(false);
606         for (unsigned int i = 0; i < data.length(); ++i)
607                 paragraphs.begin()->insertChar(i, data[i], font);
608 }
609
610
611 void InsetText::setAutoBreakRows(bool flag)
612 {
613         if (flag != autoBreakRows_) {
614                 autoBreakRows_ = flag;
615                 if (!flag)
616                         removeNewlines();
617         }
618 }
619
620
621 void InsetText::setDrawFrame(DrawFrame how)
622 {
623         drawFrame_ = how;
624 }
625
626
627 LColor_color InsetText::frameColor() const
628 {
629         return LColor::color(frame_color_);
630 }
631
632
633 void InsetText::setFrameColor(LColor_color col)
634 {
635         frame_color_ = col;
636 }
637
638
639 pos_type InsetText::cpos() const
640 {
641         return text_.cursor.pos();
642 }
643
644
645 ParagraphList::iterator InsetText::cpar() const
646 {
647         return text_.cursorPar();
648 }
649
650
651 RowList::iterator InsetText::crow() const
652 {
653         return cpar()->getRow(cpos());
654 }
655
656
657 void InsetText::setViewCache(BufferView const * bv) const
658 {
659         if (bv) {
660                 if (bv != text_.bv_owner) {
661                         //lyxerr << "setting view cache from "
662                         //      << text_.bv_owner << " to " << bv << "\n";
663                         text_.init(const_cast<BufferView *>(bv));
664                 }
665                 text_.bv_owner = const_cast<BufferView *>(bv);
666         }
667 }
668
669
670 void InsetText::removeNewlines()
671 {
672         ParagraphList::iterator it = paragraphs.begin();
673         ParagraphList::iterator end = paragraphs.end();
674         for (; it != end; ++it)
675                 for (int i = 0; i < it->size(); ++i)
676                         if (it->isNewline(i))
677                                 it->erase(i);
678 }
679
680
681 int InsetText::scroll(bool /*recursive*/) const
682 {
683         return UpdatableInset::scroll(false);
684 }
685
686
687 void InsetText::clearSelection(BufferView *)
688 {
689         text_.clearSelection();
690 }
691
692
693 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
694 {
695         Painter & pain = bv->painter();
696         int w = dim_.wid;
697         int h = dim_.asc + dim_.des;
698         int ty = baseline - dim_.asc;
699
700         if (ty < 0) {
701                 h += ty;
702                 ty = 0;
703         }
704         if (ty + h > pain.paperHeight())
705                 h = pain.paperHeight();
706         if (xo_ + w > pain.paperWidth())
707                 w = pain.paperWidth();
708         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
709 }
710
711
712 ParagraphList * InsetText::getParagraphs(int i) const
713 {
714         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
715 }
716
717
718 LyXText * InsetText::getText(int i) const
719 {
720         return (i == 0) ? const_cast<LyXText*>(&text_) : 0;
721 }
722
723
724 bool InsetText::checkInsertChar(LyXFont & font)
725 {
726         return owner() ? owner()->checkInsertChar(font) : true;
727 }
728
729
730 void InsetText::collapseParagraphs(BufferView * bv)
731 {
732         while (paragraphs.size() > 1) {
733                 ParagraphList::iterator const first = paragraphs.begin();
734                 ParagraphList::iterator second = first;
735                 ++second;
736                 size_t const first_par_size = first->size();
737
738                 if (!first->empty() &&
739                     !second->empty() &&
740                     !first->isSeparator(first_par_size - 1)) {
741                         first->insertChar(first_par_size, ' ');
742                 }
743
744 #warning probably broken
745                 if (text_.selection.set()) {
746                         if (text_.selection.start.par() == 1) {
747                                 text_.selection.start.par(1);
748                                 text_.selection.start.pos(text_.selection.start.pos() + first_par_size);
749                         }
750                         if (text_.selection.end.par() == 2) {
751                                 text_.selection.end.par(1);
752                                 text_.selection.end.pos(text_.selection.end.pos() + first_par_size);
753                         }
754                 }
755
756                 mergeParagraph(bv->buffer()->params(), paragraphs, first);
757         }
758 }
759
760
761 void InsetText::getDrawFont(LyXFont & font) const
762 {
763         if (owner())
764                 owner()->getDrawFont(font);
765 }
766
767
768 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
769 {
770 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
771 // And it probably does. You have to take a look at this John. (Lgb)
772 #warning John, have a look here. (Lgb)
773         ParagraphList::iterator pit = plist.begin();
774         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
775         ++pit;
776         mergeParagraph(buffer->params(), paragraphs, boost::prior(ins));
777
778         ParagraphList::iterator pend = plist.end();
779         for (; pit != pend; ++pit)
780                 paragraphs.push_back(*pit);
781 }
782
783
784 void InsetText::addPreview(PreviewLoader & loader) const
785 {
786         ParagraphList::const_iterator pit = paragraphs.begin();
787         ParagraphList::const_iterator pend = paragraphs.end();
788
789         for (; pit != pend; ++pit) {
790                 InsetList::const_iterator it  = pit->insetlist.begin();
791                 InsetList::const_iterator end = pit->insetlist.end();
792                 for (; it != end; ++it)
793                         it->inset->addPreview(loader);
794         }
795 }