]> git.lyx.org Git - lyx.git/blob - src/rowpainter.C
Fix bug 2485 and crash on middle mouse paste on math
[lyx.git] / src / rowpainter.C
1 /**
2  * \file rowpainter.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author various
7  * \author John Levon
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "rowpainter.h"
15
16 #include "buffer.h"
17 #include "coordcache.h"
18 #include "cursor.h"
19 #include "debug.h"
20 #include "bufferparams.h"
21 #include "BufferView.h"
22 #include "encoding.h"
23 #include "gettext.h"
24 #include "language.h"
25 #include "LColor.h"
26 #include "lyxrc.h"
27 #include "lyxrow.h"
28 #include "lyxrow_funcs.h"
29 #include "metricsinfo.h"
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
32 #include "ParagraphParameters.h"
33 #include "vspace.h"
34
35 #include "frontends/font_metrics.h"
36 #include "frontends/nullpainter.h"
37 #include "frontends/Painter.h"
38
39 #include "insets/insettext.h"
40
41 #include "support/textutils.h"
42
43 #include <boost/crc.hpp>
44
45 using lyx::char_type;
46 using lyx::pos_type;
47 using lyx::pit_type;
48
49 using std::endl;
50 using std::max;
51 using std::min;
52 using std::string;
53
54
55 namespace {
56
57 /**
58  * A class used for painting an individual row of text.
59  */
60 class RowPainter {
61 public:
62         /// initialise and run painter
63         RowPainter(PainterInfo & pi, LyXText const & text,
64                 pit_type pit, Row const & row, int x, int y);
65
66         // paint various parts
67         void paintAppendix();
68         void paintDepthBar();
69         void paintChangeBar();
70         void paintFirst();
71         void paintLast();
72         void paintText();
73
74 private:
75         void paintForeignMark(double orig_x, LyXFont const & font, int desc = 0);
76         void paintHebrewComposeChar(lyx::pos_type & vpos, LyXFont const & font);
77         void paintArabicComposeChar(lyx::pos_type & vpos, LyXFont const & font);
78         void paintChars(lyx::pos_type & vpos, LyXFont font,
79                         bool hebrew, bool arabic);
80         int paintAppendixStart(int y);
81         void paintFromPos(lyx::pos_type & vpos);
82         void paintInset(lyx::pos_type const pos, LyXFont const & font);
83
84         /// return left margin
85         int leftMargin() const;
86
87         /// return the label font for this row
88         LyXFont const getLabelFont() const;
89
90         /// bufferview to paint on
91         BufferView const & bv_;
92
93         /// Painter to use
94         Painter & pain_;
95
96         /// LyXText for the row
97         LyXText const & text_;
98         ParagraphList const & pars_;
99
100         /// The row to paint
101         Row const & row_;
102
103         /// Row's paragraph
104         pit_type const pit_;
105         Paragraph const & par_;
106
107         /// is row erased? (change tracking)
108         bool erased_;
109
110         // Looks ugly - is
111         double const xo_;
112         int const yo_;    // current baseline
113         double x_;
114         int width_;
115         double separator_;
116         double hfill_;
117         double label_hfill_;
118 };
119
120
121 RowPainter::RowPainter(PainterInfo & pi,
122         LyXText const & text, pit_type pit, Row const & row, int x, int y)
123         : bv_(*pi.base.bv), pain_(pi.pain), text_(text), pars_(text.paragraphs()),
124           row_(row), pit_(pit), par_(text.paragraphs()[pit]),
125           erased_(pi.erased_),
126           xo_(x), yo_(y), width_(text_.width())
127 {
128         RowMetrics m = text_.computeRowMetrics(pit, row_);
129         x_ = m.x + xo_;
130
131         //lyxerr << "RowPainter: x: " << x_ << " xo: " << xo_ << " yo: " << yo_ << endl;
132         //row_.dump();
133
134         separator_ = m.separator;
135         hfill_ = m.hfill;
136         label_hfill_ = m.label_hfill;
137
138         BOOST_ASSERT(pit >= 0);
139         BOOST_ASSERT(pit < int(text.paragraphs().size()));
140 }
141
142
143 LyXFont const RowPainter::getLabelFont() const
144 {
145         return text_.getLabelFont(par_);
146 }
147
148
149 int RowPainter::leftMargin() const
150 {
151         return text_.leftMargin(pit_, row_.pos());
152 }
153
154
155 void RowPainter::paintInset(pos_type const pos, LyXFont const & font)
156 {
157         InsetBase const * inset = par_.getInset(pos);
158         BOOST_ASSERT(inset);
159         PainterInfo pi(const_cast<BufferView *>(&bv_), pain_);
160         // FIXME: We should always use font, see documentation of
161         // noFontChange() in insetbase.h.
162         pi.base.font = inset->noFontChange() ?
163                 bv_.buffer()->params().getFont() :
164                 font;
165         pi.ltr_pos = (text_.bidi.level(pos) % 2 == 0);
166         pi.erased_ = erased_ || isDeletedText(par_, pos);
167         theCoords.insets().add(inset, int(x_), yo_);
168         InsetText const * const in = inset->asTextInset();
169         // non-wide insets are painted completely. Recursive
170         bool tmp = bv_.repaintAll();
171         if (!in || !in->Wide()) {
172                 bv_.repaintAll(true);
173                 lyxerr[Debug::PAINTING] << endl << "Paint inset fully" << endl;
174         }
175         if (bv_.repaintAll())
176                 inset->drawSelection(pi, int(x_), yo_);
177         inset->draw(pi, int(x_), yo_);
178         bv_.repaintAll(tmp);
179         x_ += inset->width();
180 }
181
182
183 void RowPainter::paintHebrewComposeChar(pos_type & vpos, LyXFont const & font)
184 {
185         pos_type pos = text_.bidi.vis2log(vpos);
186
187         string str;
188
189         // first char
190         char_type c = par_.getChar(pos);
191         str += c;
192         ++vpos;
193
194         int const width = font_metrics::width(c, font);
195         int dx = 0;
196
197         for (pos_type i = pos - 1; i >= 0; --i) {
198                 c = par_.getChar(i);
199                 if (!Encodings::isComposeChar_hebrew(c)) {
200                         if (isPrintableNonspace(c)) {
201                                 int const width2 =
202                                         text_.singleWidth(par_, i, c, text_.getFont(par_, i));
203                                 // dalet / resh
204                                 dx = (c == 'ø' || c == 'ã')
205                                         ? width2 - width
206                                         : (width2 - width) / 2;
207                         }
208                         break;
209                 }
210         }
211
212         // Draw nikud
213         pain_.text(int(x_) + dx, yo_, str, font);
214 }
215
216
217 void RowPainter::paintArabicComposeChar(pos_type & vpos, LyXFont const & font)
218 {
219         pos_type pos = text_.bidi.vis2log(vpos);
220         string str;
221
222         // first char
223         char_type c = par_.getChar(pos);
224         c = par_.transformChar(c, pos);
225         str += c;
226         ++vpos;
227
228         int const width = font_metrics::width(c, font);
229         int dx = 0;
230
231         for (pos_type i = pos - 1; i >= 0; --i) {
232                 c = par_.getChar(i);
233                 if (!Encodings::isComposeChar_arabic(c)) {
234                         if (isPrintableNonspace(c)) {
235                                 int const width2 =
236                                         text_.singleWidth(par_, i, c, text_.getFont(par_, i));
237                                 dx = (width2 - width) / 2;
238                         }
239                         break;
240                 }
241         }
242         // Draw nikud
243         pain_.text(int(x_) + dx, yo_, str, font);
244 }
245
246
247 void RowPainter::paintChars(pos_type & vpos, LyXFont font,
248                             bool hebrew, bool arabic)
249 {
250         pos_type pos = text_.bidi.vis2log(vpos);
251         pos_type const end = row_.endpos();
252         FontSpan const font_span = par_.fontSpan(pos);
253         Change::Type const prev_change = par_.lookupChange(pos);
254
255         // first character
256         string str;
257         str += par_.getChar(pos);
258         if (arabic) {
259                 unsigned char c = str[0];
260                 str[0] = par_.transformChar(c, pos);
261         }
262
263         // collect as much similar chars as we can
264         for (++vpos ; vpos < end ; ++vpos) {
265                 pos = text_.bidi.vis2log(vpos);
266                 if (pos < font_span.first || pos > font_span.last)
267                         break;
268
269                 if (prev_change != par_.lookupChange(pos))
270                         break;
271
272                 char_type c = par_.getChar(pos);
273
274                 if (!isPrintableNonspace(c))
275                         break;
276
277                 if (arabic && Encodings::isComposeChar_arabic(c))
278                         break;
279
280                 if (hebrew && Encodings::isComposeChar_hebrew(c))
281                         break;
282
283                 if (arabic)
284                         c = par_.transformChar(c, pos);
285
286                 str += c;
287         }
288
289         if (prev_change == Change::DELETED)
290                 font.setColor(LColor::strikeout);
291         else if (prev_change == Change::INSERTED)
292                 font.setColor(LColor::newtext);
293
294         // Draw text and set the new x position
295         //lyxerr << "paint row: yo_ " << yo_ << "\n";
296         pain_.text(int(x_), yo_, str, font);
297         x_ += font_metrics::width(str, font);
298 }
299
300
301 void RowPainter::paintForeignMark(double orig_x, LyXFont const & font, int desc)
302 {
303         if (!lyxrc.mark_foreign_language)
304                 return;
305         if (font.language() == latex_language)
306                 return;
307         if (font.language() == bv_.buffer()->params().language)
308                 return;
309
310         int const y = yo_ + 1 + desc;
311         pain_.line(int(orig_x), y, int(x_), y, LColor::language);
312 }
313
314
315 void RowPainter::paintFromPos(pos_type & vpos)
316 {
317         pos_type const pos = text_.bidi.vis2log(vpos);
318         LyXFont orig_font = text_.getFont(par_, pos);
319
320         double const orig_x = x_;
321
322         if (par_.isInset(pos)) {
323                 paintInset(pos, orig_font);
324                 ++vpos;
325                 paintForeignMark(orig_x, orig_font,
326                         par_.getInset(pos)->descent());
327                 return;
328         }
329
330         // usual characters, no insets
331         char_type const c = par_.getChar(pos);
332
333         // special case languages
334         std::string const & lang = orig_font.language()->lang();
335         bool const hebrew = lang == "hebrew";
336         bool const arabic = lang == "arabic" &&
337                 (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
338                 lyxrc.font_norm_type == LyXRC::ISO_10646_1);
339
340         // draw as many chars as we can
341         if ((!hebrew && !arabic)
342                 || (hebrew && !Encodings::isComposeChar_hebrew(c))
343                 || (arabic && !Encodings::isComposeChar_arabic(c))) {
344                 paintChars(vpos, orig_font, hebrew, arabic);
345         } else if (hebrew) {
346                 paintHebrewComposeChar(vpos, orig_font);
347         } else if (arabic) {
348                 paintArabicComposeChar(vpos, orig_font);
349         }
350
351         paintForeignMark(orig_x, orig_font);
352 }
353
354
355 void RowPainter::paintChangeBar()
356 {
357         pos_type const start = row_.pos();
358         pos_type const end = row_.endpos();
359
360         if (start == end || !par_.isChanged(start, end))
361                 return;
362
363         int const height = text_.isLastRow(pit_, row_)
364                 ? row_.ascent()
365                 : row_.height();
366
367         pain_.fillRectangle(4, yo_ - row_.ascent(), 5, height, LColor::changebar);
368 }
369
370
371 void RowPainter::paintAppendix()
372 {
373         if (!par_.params().appendix())
374                 return;
375
376         int y = yo_ - row_.ascent();
377
378         if (par_.params().startOfAppendix())
379                 y += 2 * defaultRowHeight();
380
381         pain_.line(1, y, 1, yo_ + row_.height(), LColor::appendix);
382         pain_.line(width_ - 2, y, width_ - 2, yo_ + row_.height(), LColor::appendix);
383 }
384
385
386 void RowPainter::paintDepthBar()
387 {
388         Paragraph::depth_type const depth = par_.getDepth();
389
390         if (depth <= 0)
391                 return;
392
393         Paragraph::depth_type prev_depth = 0;
394         if (!text_.isFirstRow(pit_, row_)) {
395                 pit_type pit2 = pit_;
396                 if (row_.pos() == 0)
397                         --pit2;
398                 prev_depth = pars_[pit2].getDepth();
399         }
400
401         Paragraph::depth_type next_depth = 0;
402         if (!text_.isLastRow(pit_, row_)) {
403                 pit_type pit2 = pit_;
404                 if (row_.endpos() >= pars_[pit2].size())
405                         ++pit2;
406                 next_depth = pars_[pit2].getDepth();
407         }
408
409         for (Paragraph::depth_type i = 1; i <= depth; ++i) {
410                 int const w = nestMargin() / 5;
411                 int x = int(xo_) + w * i;
412                 // only consider the changebar space if we're drawing outermost text
413                 if (text_.isMainText())
414                         x += changebarMargin();
415
416                 int const starty = yo_ - row_.ascent();
417                 int const h =  row_.height() - 1 - (i - next_depth - 1) * 3;
418
419                 pain_.line(x, starty, x, starty + h, LColor::depthbar);
420
421                 if (i > prev_depth)
422                         pain_.fillRectangle(x, starty, w, 2, LColor::depthbar);
423                 if (i > next_depth)
424                         pain_.fillRectangle(x, starty + h, w, 2, LColor::depthbar);
425         }
426 }
427
428
429 int RowPainter::paintAppendixStart(int y)
430 {
431         LyXFont pb_font;
432         pb_font.setColor(LColor::appendix);
433         pb_font.decSize();
434
435         string const label = _("Appendix");
436         int w = 0;
437         int a = 0;
438         int d = 0;
439         font_metrics::rectText(label, pb_font, w, a, d);
440
441         int const text_start = int(xo_ + (width_ - w) / 2);
442         int const text_end = text_start + w;
443
444         pain_.rectText(text_start, y + d, label, pb_font, LColor::none, LColor::none);
445
446         pain_.line(int(xo_ + 1), y, text_start, y, LColor::appendix);
447         pain_.line(text_end, y, int(xo_ + width_ - 2), y, LColor::appendix);
448
449         return 3 * defaultRowHeight();
450 }
451
452
453 void RowPainter::paintFirst()
454 {
455         ParagraphParameters const & parparams = par_.params();
456
457         int y_top = 0;
458
459         // start of appendix?
460         if (parparams.startOfAppendix())
461                 y_top += paintAppendixStart(yo_ - row_.ascent() + 2 * defaultRowHeight());
462
463         Buffer const & buffer = *bv_.buffer();
464
465         LyXLayout_ptr const & layout = par_.layout();
466
467         if (buffer.params().paragraph_separation == BufferParams::PARSEP_SKIP) {
468                 if (pit_ != 0) {
469                         if (layout->latextype == LATEX_PARAGRAPH
470                                 && !par_.getDepth()) {
471                                 y_top += buffer.params().getDefSkip().inPixels(bv_);
472                         } else {
473                                 LyXLayout_ptr const & playout = pars_[pit_ - 1].layout();
474                                 if (playout->latextype == LATEX_PARAGRAPH
475                                         && !pars_[pit_ - 1].getDepth()) {
476                                         // is it right to use defskip here, too? (AS)
477                                         y_top += buffer.params().getDefSkip().inPixels(bv_);
478                                 }
479                         }
480                 }
481         }
482
483         bool const is_rtl = text_.isRTL(par_);
484         bool const is_seq = isFirstInSequence(pit_, text_.paragraphs());
485         //lyxerr << "paintFirst: " << par_.id() << " is_seq: " << is_seq << std::endl;
486
487         // should we print a label?
488         if (layout->labeltype >= LABEL_STATIC
489             && (layout->labeltype != LABEL_STATIC
490                       || layout->latextype != LATEX_ENVIRONMENT
491                       || is_seq)) {
492
493                 LyXFont const font = getLabelFont();
494                 string const str = par_.getLabelstring();
495                 if (!str.empty()) {
496                         double x = x_;
497
498                         // this is special code for the chapter layout. This is
499                         // printed in an extra row and has a pagebreak at
500                         // the top.
501                         if (layout->counter == "chapter") {
502                                 double spacing_val = 1.0;
503                                 if (!parparams.spacing().isDefault()) {
504                                         spacing_val = parparams.spacing().getValue();
505                                 } else {
506                                         spacing_val = buffer.params().spacing().getValue();
507                                 }
508
509                                 int const labeladdon = int(font_metrics::maxHeight(font) * layout->spacing.getValue() * spacing_val);
510
511                                 int const maxdesc = int(font_metrics::maxDescent(font) * layout->spacing.getValue() * spacing_val)
512                                         + int(layout->parsep) * defaultRowHeight();
513
514                                 if (is_rtl) {
515                                         x = width_ - leftMargin() -
516                                                 font_metrics::width(str, font);
517                                 }
518
519                                 pain_.text(int(x), yo_ - maxdesc - labeladdon, str, font);
520                         } else {
521                                 if (is_rtl) {
522                                         x = width_ - leftMargin()
523                                                 + font_metrics::width(layout->labelsep, font);
524                                 } else {
525                                         x = x_ - font_metrics::width(layout->labelsep, font)
526                                                 - font_metrics::width(str, font);
527                                 }
528
529                                 pain_.text(int(x), yo_, str, font);
530                         }
531                 }
532
533         // the labels at the top of an environment.
534         // More or less for bibliography
535         } else if (is_seq &&
536                 (layout->labeltype == LABEL_TOP_ENVIRONMENT ||
537                 layout->labeltype == LABEL_BIBLIO ||
538                 layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)) {
539                 LyXFont font = getLabelFont();
540                 if (!par_.getLabelstring().empty()) {
541                         string const str = par_.getLabelstring();
542                         double spacing_val = 1.0;
543                         if (!parparams.spacing().isDefault())
544                                 spacing_val = parparams.spacing().getValue();
545                         else
546                                 spacing_val = buffer.params().spacing().getValue();
547
548                         int const labeladdon = int(font_metrics::maxHeight(font) * layout->spacing.getValue() * spacing_val);
549
550                         int maxdesc =
551                                 int(font_metrics::maxDescent(font) * layout->spacing.getValue() * spacing_val
552                                 + (layout->labelbottomsep * defaultRowHeight()));
553
554                         double x = x_;
555                         if (layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
556                                 if (is_rtl)
557                                         x = leftMargin();
558                                 x += (width_ - text_.rightMargin(par_) - leftMargin()) / 2;
559                                 x -= font_metrics::width(str, font) / 2;
560                         } else if (is_rtl) {
561                                 x = width_ - leftMargin() -
562                                         font_metrics::width(str, font);
563                         }
564                         pain_.text(int(x), yo_ - maxdesc - labeladdon, str, font);
565                 }
566         }
567 }
568
569
570 void RowPainter::paintLast()
571 {
572         bool const is_rtl = text_.isRTL(par_);
573         int const endlabel = getEndLabel(pit_, text_.paragraphs());
574
575         // draw an endlabel
576         switch (endlabel) {
577         case END_LABEL_BOX:
578         case END_LABEL_FILLED_BOX: {
579                 LyXFont const font = getLabelFont();
580                 int const size = int(0.75 * font_metrics::maxAscent(font));
581                 int const y = yo_ - size;
582                 int x = is_rtl ? nestMargin() + changebarMargin() : width_ - size;
583
584                 if (width_ - int(row_.width()) <= size)
585                         x += (size - width_ + row_.width() + 1) * (is_rtl ? -1 : 1);
586
587                 if (endlabel == END_LABEL_BOX)
588                         pain_.rectangle(x, y, size, size, LColor::eolmarker);
589                 else
590                         pain_.fillRectangle(x, y, size, size, LColor::eolmarker);
591                 break;
592         }
593
594         case END_LABEL_STATIC: {
595                 LyXFont font = getLabelFont();
596                 string const & str = par_.layout()->endlabelstring();
597                 double const x = is_rtl ?
598                         x_ - font_metrics::width(str, font)
599                         : - text_.rightMargin(par_) - row_.width();
600                 pain_.text(int(x), yo_, str, font);
601                 break;
602         }
603
604         case END_LABEL_NO_LABEL:
605                 break;
606         }
607 }
608
609
610 void RowPainter::paintText()
611 {
612         pos_type const end = row_.endpos();
613         pos_type body_pos = par_.beginOfBody();
614         if (body_pos > 0 &&
615                 (body_pos > end || !par_.isLineSeparator(body_pos - 1))) {
616                 body_pos = 0;
617         }
618
619         LyXLayout_ptr const & layout = par_.layout();
620
621         bool running_strikeout = false;
622         bool is_struckout = false;
623         int last_strikeout_x = 0;
624
625         // Use font span to speed things up, see below
626         FontSpan font_span;
627         LyXFont font;
628
629         for (pos_type vpos = row_.pos(); vpos < end; ) {
630                 if (x_ > bv_.workWidth())
631                         break;
632
633                 pos_type const pos = text_.bidi.vis2log(vpos);
634
635                 if (pos >= par_.size()) {
636                         ++vpos;
637                         continue;
638                 }
639
640                 // Use font span to speed things up, see above
641                 if (vpos < font_span.first || vpos > font_span.last) {
642                         font_span = par_.fontSpan(vpos);
643                         font = text_.getFont(par_, vpos);
644                 }
645
646                 const int width_pos =
647                         text_.singleWidth(par_, pos, par_.getChar(pos), font);
648
649                 if (x_ + width_pos < 0) {
650                         x_ += width_pos;
651                         ++vpos;
652                         continue;
653                 }
654
655                 is_struckout = isDeletedText(par_, pos);
656
657                 if (is_struckout && !running_strikeout) {
658                         running_strikeout = true;
659                         last_strikeout_x = int(x_);
660                 }
661
662                 bool const highly_editable_inset = par_.isInset(pos)
663                         && isHighlyEditableInset(par_.getInset(pos));
664
665                 // If we reach the end of a struck out range, paint it.
666                 // We also don't paint across things like tables
667                 if (running_strikeout && (highly_editable_inset || !is_struckout)) {
668                         // Calculate 1/3 height of the buffer's default font
669                         int const middle =
670                                 yo_ -
671                                 font_metrics::maxAscent(bv_.buffer()->params().getFont()) / 3;
672                         pain_.line(last_strikeout_x, middle, int(x_), middle,
673                                 LColor::strikeout, Painter::line_solid, Painter::line_thin);
674                         running_strikeout = false;
675                 }
676
677                 if (body_pos > 0 && pos == body_pos - 1) {
678                         int const lwidth = font_metrics::width(layout->labelsep,
679                                 getLabelFont());
680
681                         x_ += label_hfill_ + lwidth - width_pos;
682                 }
683
684                 if (par_.isHfill(pos)) {
685                         x_ += 1;
686
687                         int const y0 = yo_;
688                         int const y1 = y0 - defaultRowHeight() / 2;
689
690                         pain_.line(int(x_), y1, int(x_), y0, LColor::added_space);
691
692                         if (hfillExpansion(par_, row_, pos)) {
693                                 int const y2 = (y0 + y1) / 2;
694
695                                 if (pos >= body_pos) {
696                                         pain_.line(int(x_), y2, int(x_ + hfill_), y2,
697                                                   LColor::added_space,
698                                                   Painter::line_onoffdash);
699                                         x_ += hfill_;
700                                 } else {
701                                         pain_.line(int(x_), y2, int(x_ + label_hfill_), y2,
702                                                   LColor::added_space,
703                                                   Painter::line_onoffdash);
704                                         x_ += label_hfill_;
705                                 }
706                                 pain_.line(int(x_), y1, int(x_), y0, LColor::added_space);
707                         }
708                         x_ += 2;
709                         ++vpos;
710                 } else if (par_.isSeparator(pos)) {
711                         x_ += width_pos;
712                         if (pos >= body_pos)
713                                 x_ += separator_;
714                         ++vpos;
715                 } else {
716                         paintFromPos(vpos);
717                 }
718         }
719
720         // if we reach the end of a struck out range, paint it
721         if (running_strikeout) {
722                 // calculate 1/3 height of the buffer's default font
723                 int const middle =
724                         yo_ -
725                         font_metrics::maxAscent(bv_.buffer()->params().getFont()) / 3;
726                 pain_.line(last_strikeout_x, middle, int(x_), middle,
727                         LColor::strikeout, Painter::line_solid, Painter::line_thin);
728                 running_strikeout = false;
729         }
730 }
731
732
733 lyx::size_type calculateRowSignature(Row const & row, Paragraph const & par,
734         int x, int y)
735 {
736         boost::crc_32_type crc;
737         for (lyx::pos_type i = row.pos(); i < row.endpos(); ++i) {
738                 const unsigned char b[] = { par.getChar(i) };
739                 crc.process_bytes(b, 1);
740         }
741         const unsigned char b[] = { x, y, row.width() };
742         crc.process_bytes(b, 3);
743         return crc.checksum();
744 }
745
746
747 bool CursorOnRow(PainterInfo & pi, pit_type const pit,
748         RowList::const_iterator rit, LyXText const & text)
749 {
750         // Is there a cursor on this row (or inside inset on row)
751         LCursor & cur = pi.base.bv->cursor();
752         for (lyx::size_type d = 0; d < cur.depth(); d++) {
753                 CursorSlice const & sl = cur[d];
754                 if (sl.text() == &text
755                     && sl.pit() == pit
756                     && sl.pos() >= rit->pos()
757                     && sl.pos() <= rit->endpos())
758                         return true;
759         }
760         return false;
761 }
762
763
764 bool innerCursorOnRow(PainterInfo & pi, pit_type pit,
765         RowList::const_iterator rit, LyXText const & text)
766 {
767         // Is there a cursor inside an inset on this row, and is this inset
768         // the only "character" on this row
769         LCursor & cur = pi.base.bv->cursor();
770         if (rit->pos() + 1 != rit->endpos())
771                 return false;
772         for (lyx::size_type d = 0; d < cur.depth(); d++) {
773                 CursorSlice const & sl = cur[d];
774                 if (sl.text() == &text
775                     && sl.pit() == pit
776                     && sl.pos() == rit->pos())
777                         return d < cur.depth() - 1;
778         }
779         return false;
780 }
781
782
783 void paintPar
784         (PainterInfo & pi, LyXText const & text, pit_type pit, int x, int y,
785          bool repaintAll)
786 {
787 //      lyxerr << "  paintPar: pit: " << pit << " at y: " << y << endl;
788         static NullPainter nop;
789         static PainterInfo nullpi(pi.base.bv, nop);
790         int const ww = pi.base.bv->workHeight();
791
792         Paragraph const & par = text.paragraphs()[pit];
793
794         RowList::const_iterator const rb = par.rows().begin();
795         RowList::const_iterator const re = par.rows().end();
796         theCoords.parPos()[&text][pit] = Point(x, y);
797
798         y -= rb->ascent();
799         lyx::size_type rowno(0);
800         for (RowList::const_iterator rit = rb; rit != re; ++rit, ++rowno) {
801                 y += rit->ascent();
802                 // Allow setting of bv->repaintAll() for nested insets in
803                 // this row only
804                 bool tmp = pi.base.bv->repaintAll();
805
806                 // Row signature; has row changed since last paint?
807                 lyx::size_type const row_sig = calculateRowSignature(*rit, par, x, y);
808                 bool row_has_changed = par.rowSignature()[rowno] != row_sig;
809
810                 bool cursor_on_row = CursorOnRow(pi, pit, rit, text);
811                 bool in_inset_alone_on_row = innerCursorOnRow(pi, pit, rit,
812                         text);
813
814                 // If this is the only object on the row, we can make it wide
815                 for (pos_type i = rit->pos() ; i != rit->endpos(); ++i) {
816                         InsetBase const * const in = par.getInset(i);
817                         if (in) {
818                                 InsetText const * const t = in->asTextInset();
819                                 if (t)
820                                         t->Wide() = in_inset_alone_on_row &&
821                                                     t->Tall();
822                         }
823                 }
824
825                 // If selection is on, the current row signature differs
826                 // from cache, or cursor is inside an inset _on this row_,
827                 // then paint the row
828                 if (repaintAll || row_has_changed || cursor_on_row) {
829                         // Add to row signature cache
830                         par.rowSignature()[rowno] = row_sig;
831
832                         bool const inside = (y + rit->descent() >= 0
833                                        && y - rit->ascent() < ww);
834                         RowPainter rp(inside ? pi : nullpi, text, pit, *rit, x, y);
835                         // Clear background of this row
836                         // (if paragraph background was not cleared)
837                         if (!repaintAll &&
838                             (!in_inset_alone_on_row || row_has_changed)) {
839                                 pi.pain.fillRectangle(( rowno ? 0 : x - 10 ), y - rit->ascent(),
840                                     pi.base.bv->workWidth(), rit->height(),
841                                     text.backgroundColor());
842                                 // If outer row has changed, force nested
843                                 // insets to repaint completely
844                                 if (row_has_changed)
845                                         pi.base.bv->repaintAll(true);
846                         }
847
848                         // Instrumentation for testing row cache (see also
849                         // 12 lines lower):
850                         if (text.isMainText())
851                                 lyxerr[Debug::PAINTING] << "#";
852                         else
853                                 lyxerr[Debug::PAINTING] << "[" <<
854                                     repaintAll << row_has_changed <<
855                                     cursor_on_row << "]";
856                         rp.paintAppendix();
857                         rp.paintDepthBar();
858                         rp.paintChangeBar();
859                         if (rit == rb)
860                                 rp.paintFirst();
861                         if (rit + 1 == re)
862                                 rp.paintLast();
863                         rp.paintText();
864                 }
865                 y += rit->descent();
866                 // Restore, see above
867                 pi.base.bv->repaintAll(tmp);
868         }
869         lyxerr[Debug::PAINTING] << "." << endl;
870 }
871
872 } // namespace anon
873
874
875 void paintText(BufferView const & bv, ViewMetricsInfo const & vi)
876 {
877         Painter & pain = bv.painter();
878         LyXText * const text = bv.text();
879         bool const select = bv.cursor().selection();
880
881         PainterInfo pi(const_cast<BufferView *>(&bv), pain);
882         // Should the whole screen, including insets, be refreshed?
883         bool repaintAll(select || !vi.singlepar);
884
885         if (repaintAll) {
886                 // Clear background (if not delegated to rows)
887                 pain.fillRectangle(0, vi.y1, bv.workWidth(), vi.y2 - vi.y1,
888                         text->backgroundColor());
889         }
890         if (select) {
891                 text->drawSelection(pi, 0, 0);
892         }
893
894         int yy = vi.y1;
895         // draw contents
896         for (pit_type pit = vi.p1; pit <= vi.p2; ++pit) {
897                 bv.repaintAll(repaintAll);
898                 Paragraph const & par = text->getPar(pit);
899                 yy += par.ascent();
900                 paintPar(pi, *bv.text(), pit, 0, yy, repaintAll);
901                 yy += par.descent();
902         }
903
904         // Cache one paragraph above and one below
905         // Note MV: this cannot be suppressed even for singlepar.
906         // Try viewing the User Guide Mobius figure
907
908         if (vi.p1 > 0) {
909                 text->redoParagraph(vi.p1 - 1);
910                 theCoords.parPos()[bv.text()][vi.p1 - 1] =
911                         Point(0, vi.y1 - text->getPar(vi.p1 - 1).descent());
912         }
913
914         if (vi.p2 < lyx::pit_type(text->paragraphs().size()) - 1) {
915                 text->redoParagraph(vi.p2 + 1);
916                 theCoords.parPos()[bv.text()][vi.p2 + 1] =
917                         Point(0, vi.y2 + text->getPar(vi.p2 + 1).ascent());
918         }
919
920         // and grey out above (should not happen later)
921 //      lyxerr << "par ascent: " << text->getPar(vi.p1).ascent() << endl;
922         if (vi.y1 > 0 && !vi.singlepar)
923                 pain.fillRectangle(0, 0, bv.workWidth(), vi.y1, LColor::bottomarea);
924
925         // and possibly grey out below
926 //      lyxerr << "par descent: " << text->getPar(vi.p1).ascent() << endl;
927         if (vi.y2 < bv.workHeight() && !vi.singlepar)
928                 pain.fillRectangle(0, vi.y2, bv.workWidth(), bv.workHeight() - vi.y2, LColor::bottomarea);
929 }
930
931
932 void paintTextInset(LyXText const & text, PainterInfo & pi, int x, int y)
933 {
934 //      lyxerr << "  paintTextInset: y: " << y << endl;
935
936         y -= text.getPar(0).ascent();
937         // This flag can not be set from within same inset:
938         bool repaintAll = pi.base.bv->repaintAll();
939         for (int pit = 0; pit < int(text.paragraphs().size()); ++pit) {
940                 y += text.getPar(pit).ascent();
941                 paintPar(pi, text, pit, x, y, repaintAll);
942                 y += text.getPar(pit).descent();
943         }
944 }