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