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