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