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