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