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