]> git.lyx.org Git - features.git/blob - src/rowpainter.cpp
dbd9d0f0e3e3ca60e61d4eaf10c3487d8ecb89cf
[features.git] / src / rowpainter.cpp
1 /**
2  * \file rowpainter.cpp
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 "Bidi.h"
17 #include "Buffer.h"
18 #include "CoordCache.h"
19 #include "Cursor.h"
20 #include "debug.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "Encoding.h"
24 #include "gettext.h"
25 #include "Language.h"
26 #include "Color.h"
27 #include "LyXRC.h"
28 #include "Row.h"
29 #include "MetricsInfo.h"
30 #include "Paragraph.h"
31 #include "ParagraphMetrics.h"
32 #include "paragraph_funcs.h"
33 #include "ParagraphParameters.h"
34 #include "TextMetrics.h"
35 #include "VSpace.h"
36
37 #include "frontends/FontMetrics.h"
38 #include "frontends/Painter.h"
39
40 #include "insets/InsetText.h"
41
42 #include "support/textutils.h"
43
44 #include <boost/crc.hpp>
45
46
47 namespace lyx {
48
49 using frontend::Painter;
50 using frontend::FontMetrics;
51
52 using std::endl;
53 using std::max;
54 using std::string;
55
56
57 namespace {
58
59 /**
60  * A class used for painting an individual row of text.
61  */
62 class RowPainter {
63 public:
64         /// initialise and run painter
65         RowPainter(PainterInfo & pi, Text const & text,
66                 pit_type pit, Row const & row, Bidi & bidi, int x, int y);
67
68         // paint various parts
69         void paintAppendix();
70         void paintDepthBar();
71         void paintChangeBar();
72         void paintFirst();
73         void paintLast();
74         void paintText();
75
76 private:
77         void paintForeignMark(double orig_x, Font const & font, int desc = 0);
78         void paintHebrewComposeChar(pos_type & vpos, Font const & font);
79         void paintArabicComposeChar(pos_type & vpos, Font const & font);
80         void paintChars(pos_type & vpos, Font const & font,
81                         bool hebrew, bool arabic);
82         int paintAppendixStart(int y);
83         void paintFromPos(pos_type & vpos);
84         void paintInset(pos_type const pos, Font const & font);
85
86         /// return left margin
87         int leftMargin() const;
88
89         /// return the label font for this row
90         Font const getLabelFont() const;
91
92         /// bufferview to paint on
93         BufferView & bv_;
94
95         /// Painter to use
96         Painter & pain_;
97
98         /// Text for the row
99         Text const & text_;
100         TextMetrics & text_metrics_;
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         ParagraphMetrics const & pm_;
110
111         /// bidi cache, comes from outside the rowpainter because
112         /// rowpainters are normally created in a for loop and there only
113         /// one of them is active at a time.
114         Bidi & bidi_;
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         Text const & text, pit_type pit, Row const & row, Bidi & bidi, 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           bidi_(bidi), erased_(pi.erased_),
138           xo_(x), yo_(y), width_(text_metrics_.width())
139 {
140         RowMetrics m = text_metrics_.computeRowMetrics(pit_, row_);
141         bidi_.computeTables(par_, bv_.buffer(), 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 Font 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(), text_metrics_.width(), pit_,
165                 row_.pos());
166 }
167
168
169 // If you want to debug inset metrics uncomment the following line:
170 // #define DEBUG_METRICS
171 // This draws green lines around each inset.
172
173
174 void RowPainter::paintInset(pos_type const pos, Font const & font)
175 {
176         Inset const * inset = par_.getInset(pos);
177         BOOST_ASSERT(inset);
178         PainterInfo pi(const_cast<BufferView *>(&bv_), pain_);
179         // FIXME: We should always use font, see documentation of
180         // noFontChange() in Inset.h.
181         pi.base.font = inset->noFontChange() ?
182                 bv_.buffer().params().getFont() :
183                 font;
184         pi.ltr_pos = (bidi_.level(pos) % 2 == 0);
185         pi.erased_ = erased_ || par_.isDeleted(pos);
186 #ifdef DEBUG_METRICS
187         int const x1 = int(x_);
188 #endif
189         bv_.coordCache().insets().add(inset, int(x_), yo_);
190         // insets are painted completely. Recursive
191         inset->drawSelection(pi, int(x_), yo_);
192         inset->draw(pi, int(x_), yo_);
193         x_ += inset->width();
194 #ifdef DEBUG_METRICS
195         Dimension dim;
196         BOOST_ASSERT(max_witdh_ > 0);
197         int right_margin = text_metrics_.rightMargin(pm_);
198         int const w = max_witdh_ - leftMargin() - right_margin;
199         MetricsInfo mi(&bv_, font, w);
200         inset->metrics(mi, dim);
201         if (inset->width() > dim.wid)
202                 lyxerr << "Error: inset " << to_ascii(inset->getInsetName())
203                        << " draw width " << inset->width()
204                        << "> metrics width " << dim.wid << "." << std::endl;
205         if (inset->ascent() > dim.asc)
206                 lyxerr << "Error: inset " << to_ascii(inset->getInsetName())
207                        << " draw ascent " << inset->ascent()
208                        << "> metrics ascent " << dim.asc << "." << std::endl;
209         if (inset->descent() > dim.des)
210                 lyxerr << "Error: inset " << to_ascii(inset->getInsetName())
211                        << " draw ascent " << inset->descent()
212                        << "> metrics descent " << dim.des << "." << std::endl;
213         BOOST_ASSERT(inset->width() <= dim.wid);
214         BOOST_ASSERT(inset->ascent() <= dim.asc);
215         BOOST_ASSERT(inset->descent() <= dim.des);
216         int const x2 = x1 + dim.wid;
217         int const y1 = yo_ + dim.des;
218         int const y2 = yo_ - dim.asc;
219         pi.pain.line(x1, y1, x1, y2, Color::green);
220         pi.pain.line(x1, y1, x2, y1, Color::green);
221         pi.pain.line(x2, y1, x2, y2, Color::green);
222         pi.pain.line(x1, y2, x2, y2, Color::green);
223 #endif
224 }
225
226
227 void RowPainter::paintHebrewComposeChar(pos_type & vpos, Font const & font)
228 {
229         pos_type pos = bidi_.vis2log(vpos);
230
231         docstring str;
232
233         // first char
234         char_type c = par_.getChar(pos);
235         str += c;
236         ++vpos;
237
238         int const width = theFontMetrics(font).width(c);
239         int dx = 0;
240
241         for (pos_type i = pos - 1; i >= 0; --i) {
242                 c = par_.getChar(i);
243                 if (!Encodings::isComposeChar_hebrew(c)) {
244                         if (isPrintableNonspace(c)) {
245                                 int const width2 = pm_.singleWidth(i,
246                                         text_.getFont(bv_.buffer(), par_, i));
247                                 dx = (c == 0x05e8 || // resh
248                                       c == 0x05d3)   // dalet
249                                         ? width2 - width
250                                         : (width2 - width) / 2;
251                         }
252                         break;
253                 }
254         }
255
256         // Draw nikud
257         pain_.text(int(x_) + dx, yo_, str, font);
258 }
259
260
261 void RowPainter::paintArabicComposeChar(pos_type & vpos, Font const & font)
262 {
263         pos_type pos = bidi_.vis2log(vpos);
264         docstring str;
265
266         // first char
267         char_type c = par_.getChar(pos);
268         c = par_.transformChar(c, pos);
269         str += c;
270         ++vpos;
271
272         int const width = theFontMetrics(font).width(c);
273         int dx = 0;
274
275         for (pos_type i = pos - 1; i >= 0; --i) {
276                 c = par_.getChar(i);
277                 if (!Encodings::isComposeChar_arabic(c)) {
278                         if (isPrintableNonspace(c)) {
279                                 int const width2 = pm_.singleWidth(i,
280                                                 text_.getFont(bv_.buffer(), par_, i));
281                                 dx = (width2 - width) / 2;
282                         }
283                         break;
284                 }
285         }
286         // Draw nikud
287         pain_.text(int(x_) + dx, yo_, str, font);
288 }
289
290
291 void RowPainter::paintChars(pos_type & vpos, Font const & font,
292                             bool hebrew, bool arabic)
293 {
294         // This method takes up 70% of time when typing
295         pos_type pos = bidi_.vis2log(vpos);
296         pos_type const end = row_.endpos();
297         FontSpan const font_span = par_.fontSpan(pos);
298         Change::Type const prev_change = par_.lookupChange(pos).type;
299
300         // first character
301         std::vector<char_type> str;
302         str.reserve(100);
303         str.push_back(par_.getChar(pos));
304
305         if (arabic) {
306                 char_type c = str[0];
307                 if (c == '(')
308                         c = ')';
309                 else if (c == ')')
310                         c = '(';
311                 str[0] = par_.transformChar(c, pos);
312         }
313
314         // collect as much similar chars as we can
315         for (++vpos ; vpos < end ; ++vpos) {
316                 pos = bidi_.vis2log(vpos);
317                 if (pos < font_span.first || pos > font_span.last)
318                         break;
319
320                 if (prev_change != par_.lookupChange(pos).type)
321                         break;
322
323                 char_type c = par_.getChar(pos);
324
325                 if (!isPrintableNonspace(c))
326                         break;
327
328                 /* Because we do our own bidi, at this point the strings are
329                  * already in visual order. However, Qt also applies its own
330                  * bidi algorithm to strings that it paints to the screen.
331                  * Therefore, if we were to paint Hebrew/Arabic words as a
332                  * single string, the letters in the words would get reversed
333                  * again. In order to avoid that, we don't collect Hebrew/
334                  * Arabic characters, but rather paint them one at a time.
335                  * See also http://thread.gmane.org/gmane.editors.lyx.devel/79740
336                  */
337                 if (hebrew)
338                         break;
339
340                 /* FIXME: these checks are irrelevant, since 'arabic' and
341                  * 'hebrew' alone are already going to trigger a break.
342                  * However, this should not be removed completely, because
343                  * if an alternative solution is found which allows grouping
344                  * of arabic and hebrew characters, then these breaks may have
345                  * to be re-applied.
346
347                 if (arabic && Encodings::isComposeChar_arabic(c))
348                         break;
349
350                 if (hebrew && Encodings::isComposeChar_hebrew(c))
351                         break;
352                 */
353
354                 if (arabic) {
355                         if (c == '(')
356                                 c = ')';
357                         else if (c == ')')
358                                 c = '(';
359                         c = par_.transformChar(c, pos);
360                         /* see comment in hebrew, explaining why we break */
361                         break;
362                 }
363
364                 str.push_back(c);
365         }
366
367         docstring s(&str[0], str.size());
368
369         if (prev_change != Change::UNCHANGED) {
370                 Font copy(font);
371                 if (prev_change == Change::DELETED) {
372                         copy.setColor(Color::deletedtext);
373                 } else if (prev_change == Change::INSERTED) {
374                         copy.setColor(Color::addedtext);
375                 }
376                 x_ += pain_.text(int(x_), yo_, s, copy);
377         } else {
378                 x_ += pain_.text(int(x_), yo_, s, font);
379         }
380 }
381
382
383 void RowPainter::paintForeignMark(double orig_x, Font const & font, int desc)
384 {
385         if (!lyxrc.mark_foreign_language)
386                 return;
387         if (font.language() == latex_language)
388                 return;
389         if (font.language() == bv_.buffer().params().language)
390                 return;
391
392         int const y = yo_ + 1 + desc;
393         pain_.line(int(orig_x), y, int(x_), y, Color::language);
394 }
395
396
397 void RowPainter::paintFromPos(pos_type & vpos)
398 {
399         pos_type const pos = bidi_.vis2log(vpos);
400         Font orig_font = text_.getFont(bv_.buffer(), par_, pos);
401
402         double const orig_x = x_;
403
404         if (par_.isInset(pos)) {
405                 // If outer row has changed, nested insets are repaint completely.
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_arabtex" || lang == "arabic_arabi" || 
420                                                 lang == "farsi";
421
422         // draw as many chars as we can
423         if ((!hebrew && !arabic)
424                 || (hebrew && !Encodings::isComposeChar_hebrew(c))
425                 || (arabic && !Encodings::isComposeChar_arabic(c))) {
426                 paintChars(vpos, orig_font, hebrew, arabic);
427         } else if (hebrew) {
428                 paintHebrewComposeChar(vpos, orig_font);
429         } else if (arabic) {
430                 paintArabicComposeChar(vpos, orig_font);
431         }
432
433         paintForeignMark(orig_x, orig_font);
434 }
435
436
437 void RowPainter::paintChangeBar()
438 {
439         pos_type const start = row_.pos();
440         pos_type end = row_.endpos();
441
442         if (par_.size() == end) {
443                 // this is the last row of the paragraph;
444                 // thus, we must also consider the imaginary end-of-par character
445                 end++;
446         }
447
448         if (start == end || !par_.isChanged(start, end))
449                 return;
450
451         int const height = text_.isLastRow(pit_, row_)
452                 ? row_.ascent()
453                 : row_.height();
454
455         pain_.fillRectangle(5, yo_ - row_.ascent(), 3, height, Color::changebar);
456 }
457
458
459 void RowPainter::paintAppendix()
460 {
461         // only draw the appendix frame once (for the main text)
462         if (!par_.params().appendix() || !text_.isMainText(bv_.buffer()))
463                 return;
464
465         int y = yo_ - row_.ascent();
466
467         if (par_.params().startOfAppendix())
468                 y += 2 * defaultRowHeight();
469
470         pain_.line(1, y, 1, yo_ + row_.height(), Color::appendix);
471         pain_.line(width_ - 2, y, width_ - 2, yo_ + row_.height(), Color::appendix);
472 }
473
474
475 void RowPainter::paintDepthBar()
476 {
477         depth_type const depth = par_.getDepth();
478
479         if (depth <= 0)
480                 return;
481
482         depth_type prev_depth = 0;
483         if (!text_.isFirstRow(pit_, row_)) {
484                 pit_type pit2 = pit_;
485                 if (row_.pos() == 0)
486                         --pit2;
487                 prev_depth = pars_[pit2].getDepth();
488         }
489
490         depth_type next_depth = 0;
491         if (!text_.isLastRow(pit_, row_)) {
492                 pit_type pit2 = pit_;
493                 if (row_.endpos() >= pars_[pit2].size())
494                         ++pit2;
495                 next_depth = pars_[pit2].getDepth();
496         }
497
498         for (depth_type i = 1; i <= depth; ++i) {
499                 int const w = nestMargin() / 5;
500                 int x = int(xo_) + w * i;
501                 // only consider the changebar space if we're drawing outermost text
502                 if (text_.isMainText(bv_.buffer()))
503                         x += changebarMargin();
504
505                 int const starty = yo_ - row_.ascent();
506                 int const h =  row_.height() - 1 - (i - next_depth - 1) * 3;
507
508                 pain_.line(x, starty, x, starty + h, Color::depthbar);
509
510                 if (i > prev_depth)
511                         pain_.fillRectangle(x, starty, w, 2, Color::depthbar);
512                 if (i > next_depth)
513                         pain_.fillRectangle(x, starty + h, w, 2, Color::depthbar);
514         }
515 }
516
517
518 int RowPainter::paintAppendixStart(int y)
519 {
520         Font pb_font;
521         pb_font.setColor(Color::appendix);
522         pb_font.decSize();
523
524         int w = 0;
525         int a = 0;
526         int d = 0;
527
528         docstring const label = _("Appendix");
529         theFontMetrics(pb_font).rectText(label, w, a, d);
530
531         int const text_start = int(xo_ + (width_ - w) / 2);
532         int const text_end = text_start + w;
533
534         pain_.rectText(text_start, y + d, label, pb_font, Color::none, Color::none);
535
536         pain_.line(int(xo_ + 1), y, text_start, y, Color::appendix);
537         pain_.line(text_end, y, int(xo_ + width_ - 2), y, Color::appendix);
538
539         return 3 * defaultRowHeight();
540 }
541
542
543 void RowPainter::paintFirst()
544 {
545         ParagraphParameters const & parparams = par_.params();
546
547         int y_top = 0;
548
549         // start of appendix?
550         if (parparams.startOfAppendix())
551                 y_top += paintAppendixStart(yo_ - row_.ascent() + 2 * defaultRowHeight());
552
553         Buffer const & buffer = bv_.buffer();
554
555         LayoutPtr const & layout = par_.layout();
556
557         if (buffer.params().paragraph_separation == BufferParams::PARSEP_SKIP) {
558                 if (pit_ != 0) {
559                         if (layout->latextype == LATEX_PARAGRAPH
560                                 && !par_.getDepth()) {
561                                 y_top += buffer.params().getDefSkip().inPixels(bv_);
562                         } else {
563                                 LayoutPtr const & playout = pars_[pit_ - 1].layout();
564                                 if (playout->latextype == LATEX_PARAGRAPH
565                                         && !pars_[pit_ - 1].getDepth()) {
566                                         // is it right to use defskip here, too? (AS)
567                                         y_top += buffer.params().getDefSkip().inPixels(bv_);
568                                 }
569                         }
570                 }
571         }
572
573         bool const is_rtl = text_.isRTL(buffer, par_);
574         bool const is_seq = isFirstInSequence(pit_, text_.paragraphs());
575         //lyxerr << "paintFirst: " << par_.id() << " is_seq: " << is_seq << std::endl;
576
577         // should we print a label?
578         if (layout->labeltype >= LABEL_STATIC
579             && (layout->labeltype != LABEL_STATIC
580                       || layout->latextype != LATEX_ENVIRONMENT
581                       || is_seq)) {
582
583                 Font const font = getLabelFont();
584                 FontMetrics const & fm = theFontMetrics(font);
585
586                 docstring const str = par_.getLabelstring();
587                 if (!str.empty()) {
588                         double x = x_;
589
590                         // this is special code for the chapter layout. This is
591                         // printed in an extra row and has a pagebreak at
592                         // the top.
593                         if (layout->counter == "chapter") {
594                                 double spacing_val = 1.0;
595                                 if (!parparams.spacing().isDefault()) {
596                                         spacing_val = parparams.spacing().getValue();
597                                 } else {
598                                         spacing_val = buffer.params().spacing().getValue();
599                                 }
600
601                                 int const labeladdon = int(fm.maxHeight() * layout->spacing.getValue() * spacing_val);
602
603                                 int const maxdesc = int(fm.maxDescent() * layout->spacing.getValue() * spacing_val)
604                                         + int(layout->parsep) * defaultRowHeight();
605
606                                 if (is_rtl) {
607                                         x = width_ - leftMargin() -
608                                                 fm.width(str);
609                                 }
610
611                                 pain_.text(int(x), yo_ - maxdesc - labeladdon, str, font);
612                         } else {
613                                 if (is_rtl) {
614                                         x = width_ - leftMargin()
615                                                 + fm.width(layout->labelsep);
616                                 } else {
617                                         x = x_ - fm.width(layout->labelsep)
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                 Font 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                 Color::color col = par_.isInserted(par_.size()) ? Color::addedtext : Color::deletedtext;
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                 Font 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, Color::eolmarker);
698                 else
699                         pain_.fillRectangle(x, y, size, size, Color::eolmarker);
700                 break;
701         }
702
703         case END_LABEL_STATIC: {
704                 Font 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         // Spaces at logical line breaks in bidi text must be skipped during 
724         // painting. However, they may appear visually in the middle
725         // of a row; they must be skipped, wherever they are...
726         // * logically "abc_[HEBREW_\nHEBREW]"
727         // * visually "abc_[_WERBEH\nWERBEH]"
728         pos_type skipped_sep_vpos = -1;
729         pos_type body_pos = par_.beginOfBody();
730         if (body_pos > 0 &&
731                 (body_pos > end || !par_.isLineSeparator(body_pos - 1))) {
732                 body_pos = 0;
733         }
734
735         LayoutPtr const & layout = par_.layout();
736
737         bool running_strikeout = false;
738         bool is_struckout = false;
739         int last_strikeout_x = 0;
740
741         // Use font span to speed things up, see below
742         FontSpan font_span;
743         Font font;
744         Buffer const & buffer = bv_.buffer();
745
746         // If the last logical character is a separator, don't paint it, unless
747         // it's in the last row of a paragraph; see skipped_sep_vpos declaration
748         if (end > 0 && end < par_.size() && par_.isSeparator(end - 1))
749                 skipped_sep_vpos = bidi_.log2vis(end - 1);
750         
751         for (pos_type vpos = row_.pos(); vpos < end; ) {
752                 if (x_ > bv_.workWidth())
753                         break;
754
755                 // Skip the separator at the logical end of the row
756                 if (vpos == skipped_sep_vpos) {
757                         ++vpos;
758                         continue;
759                 }
760
761                 pos_type const pos = bidi_.vis2log(vpos);
762
763                 if (pos >= par_.size()) {
764                         ++vpos;
765                         continue;
766                 }
767
768                 // Use font span to speed things up, see above
769                 if (vpos < font_span.first || vpos > font_span.last) {
770                         font_span = par_.fontSpan(vpos);
771                         font = text_.getFont(buffer, par_, vpos);
772                 }
773
774                 const int width_pos = pm_.singleWidth(pos, font);
775
776                 if (x_ + width_pos < 0) {
777                         x_ += width_pos;
778                         ++vpos;
779                         continue;
780                 }
781
782                 is_struckout = par_.isDeleted(pos);
783
784                 if (is_struckout && !running_strikeout) {
785                         running_strikeout = true;
786                         last_strikeout_x = int(x_);
787                 }
788
789                 bool const highly_editable_inset = par_.isInset(pos)
790                         && isHighlyEditableInset(par_.getInset(pos));
791
792                 // If we reach the end of a struck out range, paint it.
793                 // We also don't paint across things like tables
794                 if (running_strikeout && (highly_editable_inset || !is_struckout)) {
795                         // Calculate 1/3 height of the buffer's default font
796                         FontMetrics const & fm
797                                 = theFontMetrics(bv_.buffer().params().getFont());
798                         int const middle = yo_ - fm.maxAscent() / 3;
799                         pain_.line(last_strikeout_x, middle, int(x_), middle,
800                                 Color::deletedtext, Painter::line_solid, Painter::line_thin);
801                         running_strikeout = false;
802                 }
803
804                 if (body_pos > 0 && pos == body_pos - 1) {
805                         int const lwidth = theFontMetrics(getLabelFont())
806                                 .width(layout->labelsep);
807
808                         x_ += label_hfill_ + lwidth - width_pos;
809                 }
810
811                 if (par_.isHfill(pos)) {
812                         x_ += 1;
813
814                         int const y0 = yo_;
815                         int const y1 = y0 - defaultRowHeight() / 2;
816
817                         pain_.line(int(x_), y1, int(x_), y0, Color::added_space);
818
819                         if (par_.hfillExpansion(row_, pos)) {
820                                 int const y2 = (y0 + y1) / 2;
821
822                                 if (pos >= body_pos) {
823                                         pain_.line(int(x_), y2, int(x_ + hfill_), y2,
824                                                   Color::added_space,
825                                                   Painter::line_onoffdash);
826                                         x_ += hfill_;
827                                 } else {
828                                         pain_.line(int(x_), y2, int(x_ + label_hfill_), y2,
829                                                   Color::added_space,
830                                                   Painter::line_onoffdash);
831                                         x_ += label_hfill_;
832                                 }
833                                 pain_.line(int(x_), y1, int(x_), y0, Color::added_space);
834                         }
835                         x_ += 2;
836                         ++vpos;
837                 } else if (par_.isSeparator(pos)) {
838                         Font orig_font = text_.getFont(bv_.buffer(), par_, pos);
839                         double const orig_x = x_;
840                         x_ += width_pos;
841                         if (pos >= body_pos)
842                                 x_ += separator_;
843                         ++vpos;
844                         paintForeignMark(orig_x, orig_font);
845                 } else {
846                         paintFromPos(vpos);
847                 }
848         }
849
850         // if we reach the end of a struck out range, paint it
851         if (running_strikeout) {
852                 // calculate 1/3 height of the buffer's default font
853                 FontMetrics const & fm
854                         = theFontMetrics(bv_.buffer().params().getFont());
855                 int const middle = yo_ - fm.maxAscent() / 3;
856                 pain_.line(last_strikeout_x, middle, int(x_), middle,
857                         Color::deletedtext, Painter::line_solid, Painter::line_thin);
858                 running_strikeout = false;
859         }
860 }
861
862
863 bool CursorOnRow(PainterInfo & pi, pit_type const pit,
864         RowList::const_iterator rit, Text const & text)
865 {
866         // Is there a cursor on this row (or inside inset on row)
867         Cursor & cur = pi.base.bv->cursor();
868         for (size_type d = 0; d < cur.depth(); ++d) {
869                 CursorSlice const & sl = cur[d];
870                 if (sl.text() == &text
871                     && sl.pit() == pit
872                     && sl.pos() >= rit->pos()
873                     && sl.pos() <= rit->endpos())
874                         return true;
875         }
876         return false;
877 }
878
879 } // namespace anon
880
881
882 void paintPar
883         (PainterInfo & pi, Text const & text, pit_type pit, int x, int y,
884          bool repaintAll)
885 {
886 //      lyxerr << "  paintPar: pit: " << pit << " at y: " << y << endl;
887         int const ww = pi.base.bv->workHeight();
888
889         pi.base.bv->coordCache().parPos()[&text][pit] = Point(x, y);
890
891         TextMetrics const & tm = pi.base.bv->textMetrics(&text);
892         ParagraphMetrics const & pm = tm.parMetrics(pit);
893         if (pm.rows().empty())
894                 return;
895
896         RowList::const_iterator const rb = pm.rows().begin();
897         RowList::const_iterator const re = pm.rows().end();
898
899         Bidi bidi;
900
901         y -= rb->ascent();
902         size_type rowno = 0;
903         for (RowList::const_iterator rit = rb; rit != re; ++rit, ++rowno) {
904                 y += rit->ascent();
905                 // Row signature; has row changed since last paint?
906                 bool row_has_changed = pm.rowChangeStatus()[rowno];
907
908                 bool cursor_on_row = CursorOnRow(pi, pit, rit, text);
909
910                 // If selection is on, the current row signature differs
911                 // from cache, or cursor is inside an inset _on this row_,
912                 // then paint the row
913                 if (repaintAll || row_has_changed || cursor_on_row) {
914                         bool const inside = (y + rit->descent() >= 0
915                                 && y - rit->ascent() < ww);
916                         // it is not needed to draw on screen if we are not inside.
917                         pi.pain.setDrawingEnabled(inside);
918                         RowPainter rp(pi, text, pit, *rit, bidi, x, y);
919                         // Clear background of this row
920                         // (if paragraph background was not cleared)
921                         if (!repaintAll && row_has_changed)
922                                 pi.pain.fillRectangle(x, y - rit->ascent(),
923                                         tm.width(), rit->height(),
924                                         text.backgroundColor());
925
926                         // Instrumentation for testing row cache (see also
927                         // 12 lines lower):
928                         if (lyxerr.debugging(Debug::PAINTING)) {
929                                 if (text.isMainText(pi.base.bv->buffer()))
930                                         LYXERR(Debug::PAINTING) << "#";
931                                 else
932                                         LYXERR(Debug::PAINTING) << "[" <<
933                                                 repaintAll << row_has_changed <<
934                                                 cursor_on_row << "]";
935                         }
936                         rp.paintAppendix();
937                         rp.paintDepthBar();
938                         rp.paintChangeBar();
939                         if (rit == rb)
940                                 rp.paintFirst();
941                         rp.paintText();
942                         if (rit + 1 == re)
943                                 rp.paintLast();
944                 }
945                 y += rit->descent();
946         }
947         // Re-enable screen drawing for future use of the painter.
948         pi.pain.setDrawingEnabled(true);
949
950         LYXERR(Debug::PAINTING) << "." << endl;
951 }
952
953 } // namespace lyx