]> git.lyx.org Git - lyx.git/blob - src/rowpainter.cpp
Speed-up drawing when text is not justified.
[lyx.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 #include <algorithm>
14
15 #include "rowpainter.h"
16
17 #include "Buffer.h"
18 #include "CoordCache.h"
19 #include "Cursor.h"
20 #include "BufferParams.h"
21 #include "BufferView.h"
22 #include "Changes.h"
23 #include "Language.h"
24 #include "Layout.h"
25 #include "LyXRC.h"
26 #include "Row.h"
27 #include "MetricsInfo.h"
28 #include "Paragraph.h"
29 #include "ParagraphMetrics.h"
30 #include "ParagraphParameters.h"
31 #include "TextMetrics.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 "mathed/InsetMath.h"
40
41 #include "support/debug.h"
42 #include "support/gettext.h"
43 #include "support/textutils.h"
44
45 #include "support/lassert.h"
46 #include <boost/crc.hpp>
47
48 using namespace std;
49
50 namespace lyx {
51
52 using frontend::Painter;
53 using frontend::FontMetrics;
54
55
56 RowPainter::RowPainter(PainterInfo & pi,
57         Text const & text, pit_type pit, Row const & row, int x, int y)
58         : pi_(pi), text_(text),
59           text_metrics_(pi_.base.bv->textMetrics(&text)),
60           pars_(text.paragraphs()),
61           row_(row), pit_(pit), par_(text.paragraphs()[pit]),
62           pm_(text_metrics_.parMetrics(pit)), change_(pi_.change_),
63           xo_(x), yo_(y), width_(text_metrics_.width()),
64           solid_line_thickness_(1.0), solid_line_offset_(1),
65           dotted_line_thickness_(1.0), dotted_line_offset_(2)
66 {
67         bidi_.computeTables(par_, pi_.base.bv->buffer(), row_);
68
69         if (lyxrc.zoom >= 200) {
70                 // derive the line thickness from zoom factor
71                 // the zoom is given in percent
72                 // (increase thickness at 250%, 450% etc.)
73                 solid_line_thickness_ = (float)(int((lyxrc.zoom + 50) / 200.0));
74                 // adjust line_offset_ too
75                 solid_line_offset_ = 1 + int(0.5 * solid_line_thickness_);
76         }
77         if (lyxrc.zoom >= 100) {
78                 // derive the line thickness from zoom factor
79                 // the zoom is given in percent
80                 // (increase thickness at 150%, 250% etc.)
81                 dotted_line_thickness_ = (float)(int((lyxrc.zoom + 50) / 100.0));
82                 // adjust line_offset_ too
83                 dotted_line_offset_ = int(0.5 * dotted_line_thickness_) + 1;
84         }
85
86         x_ = row_.x + xo_;
87
88         //lyxerr << "RowPainter: x: " << x_ << " xo: " << xo_ << " yo: " << yo_ << endl;
89         //row_.dump();
90
91         LBUFERR(pit >= 0);
92         LBUFERR(pit < int(text.paragraphs().size()));
93 }
94
95
96 FontInfo RowPainter::labelFont() const
97 {
98         FontInfo f = text_.labelFont(par_);
99         // selected text?
100         if (row_.begin_margin_sel || pi_.selected)
101                 f.setPaintColor(Color_selectiontext);
102         return f;
103 }
104
105
106 int RowPainter::leftMargin() const
107 {
108         return text_metrics_.leftMargin(text_metrics_.width(), pit_,
109                 row_.pos());
110 }
111
112 // If you want to debug inset metrics uncomment the following line:
113 //#define DEBUG_METRICS
114 // This draws green lines around each inset.
115
116
117 void RowPainter::paintInset(Inset const * inset, pos_type const pos)
118 {
119         Font const font = text_metrics_.displayFont(pit_, pos);
120
121         LASSERT(inset, return);
122         // Backup full_repaint status because some insets (InsetTabular)
123         // requires a full repaint
124         bool pi_full_repaint = pi_.full_repaint;
125
126         pi_.base.font = inset->inheritFont() ? font.fontInfo() :
127                 pi_.base.bv->buffer().params().getFont().fontInfo();
128         pi_.ltr_pos = (bidi_.level(pos) % 2 == 0);
129         Change prev_change = change_;
130         pi_.change_ = change_.changed() ? change_ : par_.lookupChange(pos);
131
132         int const x1 = int(x_);
133         pi_.base.bv->coordCache().insets().add(inset, x1, yo_);
134         // insets are painted completely. Recursive
135         // FIXME: it is wrong to completely paint the background
136         // if we want to do single row painting.
137         inset->drawBackground(pi_, x1, yo_);
138         inset->drawSelection(pi_, x1, yo_);
139         inset->draw(pi_, x1, yo_);
140
141         Dimension const & dim = pm_.insetDimension(inset);
142
143         paintForeignMark(x_, font.language(), dim.descent());
144
145         x_ += dim.width();
146
147         // Restore full_repaint status.
148         pi_.full_repaint = pi_full_repaint;
149         pi_.change_ = prev_change;
150
151 #ifdef DEBUG_METRICS
152         int const x2 = x1 + dim.wid;
153         int const y1 = yo_ + dim.des;
154         int const y2 = yo_ - dim.asc;
155         pi_.pain.line(x1, y1, x1, y2, Color_green);
156         pi_.pain.line(x1, y1, x2, y1, Color_green);
157         pi_.pain.line(x2, y1, x2, y2, Color_green);
158         pi_.pain.line(x1, y2, x2, y2, Color_green);
159 #endif
160 }
161
162
163 void RowPainter::paintChars(pos_type & vpos, Font const & font)
164 {
165         // This method takes up 70% of time when typing
166         pos_type pos = bidi_.vis2log(vpos);
167         // first character
168         char_type c = par_.getChar(pos);
169         docstring str;
170         str.reserve(100);
171
172         // special case for arabic
173         string const & lang = font.language()->lang();
174         bool const swap_paren = lang == "arabic_arabtex"
175                 || lang == "arabic_arabi"
176                 || lang == "farsi";
177
178         // FIXME: Why only round brackets and why the difference to
179         // Hebrew? See also Paragraph::getUChar
180         if (swap_paren) {
181                 if (c == '(')
182                         c = ')';
183                 else if (c == ')')
184                         c = '(';
185         }
186         str.push_back(c);
187
188         pos_type const end = row_.endpos();
189         FontSpan const font_span = par_.fontSpan(pos);
190         // Track-change status.
191         Change const & change_running = par_.lookupChange(pos);
192
193         // selected text?
194         bool const selection = (pos >= row_.sel_beg && pos < row_.sel_end)
195                 || pi_.selected;
196
197         // spelling correct?
198         bool const spell_state =
199                 lyxrc.spellcheck_continuously && par_.isMisspelled(pos);
200
201         // collect as much similar chars as we can
202         for (++vpos ; vpos < end ; ++vpos) {
203                 if (lyxrc.force_paint_single_char)
204                         break;
205
206                 pos = bidi_.vis2log(vpos);
207                 if (pos < font_span.first || pos > font_span.last)
208                         break;
209
210                 bool const new_selection = pos >= row_.sel_beg && pos < row_.sel_end;
211                 if (new_selection != selection)
212                         // Selection ends or starts here.
213                         break;
214
215                 bool const new_spell_state =
216                         lyxrc.spellcheck_continuously && par_.isMisspelled(pos);
217                 if (new_spell_state != spell_state)
218                         // Spell checker state changed here.
219                         break;
220
221                 Change const & change = par_.lookupChange(pos);
222                 if (!change_running.isSimilarTo(change))
223                         // Track change type or author has changed.
224                         break;
225
226                 char_type c = par_.getChar(pos);
227
228                 if (c == '\t')
229                         break;
230
231                 if (!isPrintableNonspace(c)
232                     && (c != ' ' || row_.separator > 0))
233                         break;
234
235                 // FIXME: Why only round brackets and why the difference to
236                 // Hebrew? See also Paragraph::getUChar
237                 if (swap_paren) {
238                         if (c == '(')
239                                 c = ')';
240                         else if (c == ')')
241                                 c = '(';
242                 }
243
244                 str.push_back(c);
245         }
246
247         if (str[0] == '\t')
248                 str.replace(0,1,from_ascii("    "));
249
250         /* Because we do our own bidi, at this point the strings are
251          * already in visual order. However, Qt also applies its own
252          * bidi algorithm to strings that it paints to the screen.
253          * Therefore, if we were to paint Hebrew/Arabic words as a
254          * single string, the letters in the words would get reversed
255          * again. In order to avoid that, we force LTR drawing.
256          * See also http://thread.gmane.org/gmane.editors.lyx.devel/79740
257          * for an earlier thread on the subject
258          */
259         // Left-to-right override: forces to draw text left-to-right
260         char_type const LRO = 0x202D;
261         // Right-to-left override: forces to draw text right-to-left
262         char_type const RLO = 0x202E;
263         // Pop directional formatting: return to previous state
264         char_type const PDF = 0x202C;
265         if (font.isVisibleRightToLeft()) {
266                 reverse(str.begin(), str.end());
267                 str = RLO + str + PDF;
268         } else
269                 str = LRO + str + PDF;
270
271         if (!selection && !change_running.changed()) {
272                 x_ += pi_.pain.text(int(x_), yo_, str, font.fontInfo());
273                 return;
274         }
275
276         FontInfo copy = font.fontInfo();
277         if (change_running.changed())
278                 copy.setPaintColor(change_running.color());
279         else if (selection)
280                 copy.setPaintColor(Color_selectiontext);
281
282         x_ += pi_.pain.text(int(x_), yo_, str, copy);
283 }
284
285
286 void RowPainter::paintSeparator(double orig_x, double width,
287         FontInfo const & font)
288 {
289         pi_.pain.textDecoration(font, int(orig_x), yo_, int(width));
290         x_ += width;
291 }
292
293
294 void RowPainter::paintForeignMark(double orig_x, Language const * lang,
295                 int desc)
296 {
297         if (!lyxrc.mark_foreign_language)
298                 return;
299         if (lang == latex_language)
300                 return;
301         if (lang == pi_.base.bv->buffer().params().language)
302                 return;
303
304         int const y = yo_ + solid_line_offset_ + desc + int(solid_line_thickness_/2);
305         pi_.pain.line(int(orig_x), y, int(x_), y, Color_language,
306                 Painter::line_solid, solid_line_thickness_);
307 }
308
309
310 void RowPainter::paintMisspelledMark(double orig_x, bool changed)
311 {
312         // if changed the misspelled marker gets placed slightly lower than normal
313         // to avoid drawing at the same vertical offset
314         float const y = yo_ + solid_line_offset_ + solid_line_thickness_
315                 + (changed ? solid_line_thickness_ + 1 : 0)
316                 + dotted_line_offset_;
317         pi_.pain.line(int(orig_x), int(y), int(x_), int(y), Color_error,
318                 Painter::line_onoffdash, dotted_line_thickness_);
319 }
320
321
322 void RowPainter::paintFromPos(pos_type & vpos, bool changed)
323 {
324         pos_type const pos = bidi_.vis2log(vpos);
325         Font const font = text_metrics_.displayFont(pit_, pos);
326         double const orig_x = x_;
327
328         paintChars(vpos, font);
329         paintForeignMark(orig_x, font.language());
330
331         // Paint the spelling mark if needed.
332         if (lyxrc.spellcheck_continuously && par_.isMisspelled(pos)) {
333                 // check for cursor position
334                 // don't draw misspelled marker for words at cursor position
335                 // we don't want to disturb the process of text editing
336                 BufferView const * bv = pi_.base.bv;
337                 DocIterator const nw = bv->cursor().newWord();
338                 bool new_word = false;
339                 if (!nw.empty() && par_.id() == nw.paragraph().id()) {
340                         pos_type cpos = nw.pos();
341                         if (cpos > 0 && cpos == par_.size() && !par_.isWordSeparator(cpos-1))
342                                 --cpos;
343                         else if (cpos > 0 && par_.isWordSeparator(cpos))
344                                 --cpos;
345                         new_word = par_.isSameSpellRange(pos, cpos) ;
346                 }
347                 if (!new_word)
348                         paintMisspelledMark(orig_x, changed);
349         }
350 }
351
352
353 void RowPainter::paintChangeBar()
354 {
355         pos_type const start = row_.pos();
356         pos_type end = row_.endpos();
357
358         if (par_.size() == end) {
359                 // this is the last row of the paragraph;
360                 // thus, we must also consider the imaginary end-of-par character
361                 end++;
362         }
363
364         if (start == end || !par_.isChanged(start, end))
365                 return;
366
367         int const height = text_metrics_.isLastRow(pit_, row_)
368                 ? row_.ascent()
369                 : row_.height();
370
371         pi_.pain.fillRectangle(5, yo_ - row_.ascent(), 3, height, Color_changebar);
372 }
373
374
375 void RowPainter::paintAppendix()
376 {
377         // only draw the appendix frame once (for the main text)
378         if (!par_.params().appendix() || !text_.isMainText())
379                 return;
380
381         int y = yo_ - row_.ascent();
382
383         if (par_.params().startOfAppendix())
384                 y += 2 * defaultRowHeight();
385
386         pi_.pain.line(1, y, 1, yo_ + row_.height(), Color_appendix);
387         pi_.pain.line(width_ - 2, y, width_ - 2, yo_ + row_.height(), Color_appendix);
388 }
389
390
391 void RowPainter::paintDepthBar()
392 {
393         depth_type const depth = par_.getDepth();
394
395         if (depth <= 0)
396                 return;
397
398         depth_type prev_depth = 0;
399         if (!text_metrics_.isFirstRow(pit_, row_)) {
400                 pit_type pit2 = pit_;
401                 if (row_.pos() == 0)
402                         --pit2;
403                 prev_depth = pars_[pit2].getDepth();
404         }
405
406         depth_type next_depth = 0;
407         if (!text_metrics_.isLastRow(pit_, row_)) {
408                 pit_type pit2 = pit_;
409                 if (row_.endpos() >= pars_[pit2].size())
410                         ++pit2;
411                 next_depth = pars_[pit2].getDepth();
412         }
413
414         for (depth_type i = 1; i <= depth; ++i) {
415                 int const w = nestMargin() / 5;
416                 int x = int(xo_) + w * i;
417                 // only consider the changebar space if we're drawing outermost text
418                 if (text_.isMainText())
419                         x += changebarMargin();
420
421                 int const starty = yo_ - row_.ascent();
422                 int const h =  row_.height() - 1 - (i - next_depth - 1) * 3;
423
424                 pi_.pain.line(x, starty, x, starty + h, Color_depthbar);
425
426                 if (i > prev_depth)
427                         pi_.pain.fillRectangle(x, starty, w, 2, Color_depthbar);
428                 if (i > next_depth)
429                         pi_.pain.fillRectangle(x, starty + h, w, 2, Color_depthbar);
430         }
431 }
432
433
434 int RowPainter::paintAppendixStart(int y)
435 {
436         FontInfo pb_font = sane_font;
437         pb_font.setColor(Color_appendix);
438         pb_font.decSize();
439
440         int w = 0;
441         int a = 0;
442         int d = 0;
443
444         docstring const label = _("Appendix");
445         theFontMetrics(pb_font).rectText(label, w, a, d);
446
447         int const text_start = int(xo_ + (width_ - w) / 2);
448         int const text_end = text_start + w;
449
450         pi_.pain.rectText(text_start, y + d, label, pb_font, Color_none, Color_none);
451
452         pi_.pain.line(int(xo_ + 1), y, text_start, y, Color_appendix);
453         pi_.pain.line(text_end, y, int(xo_ + width_ - 2), y, Color_appendix);
454
455         return 3 * defaultRowHeight();
456 }
457
458
459 void RowPainter::paintFirst()
460 {
461         BufferParams const & bparams = pi_.base.bv->buffer().params();
462         Layout const & layout = par_.layout();
463
464         int y_top = 0;
465
466         // start of appendix?
467         if (par_.params().startOfAppendix())
468                 y_top += paintAppendixStart(yo_ - row_.ascent() + 2 * defaultRowHeight());
469
470         if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
471                 && pit_ != 0) {
472                 if (layout.latextype == LATEX_PARAGRAPH
473                     && !par_.getDepth()) {
474                         y_top += bparams.getDefSkip().inPixels(*pi_.base.bv);
475                 } else {
476                         Layout const & playout = pars_[pit_ - 1].layout();
477                         if (playout.latextype == LATEX_PARAGRAPH
478                             && !pars_[pit_ - 1].getDepth()) {
479                                 // is it right to use defskip here, too? (AS)
480                                 y_top += bparams.getDefSkip().inPixels(*pi_.base.bv);
481                         }
482                 }
483         }
484
485         bool const is_first =
486                 text_.isFirstInSequence(pit_) || !layout.isParagraphGroup();
487         //lyxerr << "paintFirst: " << par_.id() << " is_seq: " << is_seq << endl;
488
489         if (layout.labelIsInline()
490                         && (layout.labeltype != LABEL_STATIC || is_first)) {
491                 paintLabel();
492         } else if (is_first && layout.labelIsAbove()) {
493                 paintTopLevelLabel();
494         }
495 }
496
497
498 void RowPainter::paintLabel()
499 {
500         docstring const str = par_.labelString();
501         if (str.empty())
502                 return;
503
504         bool const is_rtl = text_.isRTL(par_);
505         Layout const & layout = par_.layout();
506         FontInfo const font = labelFont();
507         FontMetrics const & fm = theFontMetrics(font);
508         double x = x_;
509
510         if (is_rtl) {
511                 x = width_ - leftMargin()
512                         + fm.width(layout.labelsep);
513         } else {
514                 x = x_ - fm.width(layout.labelsep)
515                         - fm.width(str);
516         }
517
518         pi_.pain.text(int(x), yo_, str, font);
519 }
520
521
522 void RowPainter::paintTopLevelLabel()
523 {
524         BufferParams const & bparams = pi_.base.bv->buffer().params();
525         bool const is_rtl = text_.isRTL(par_);
526         ParagraphParameters const & pparams = par_.params();
527         Layout const & layout = par_.layout();
528         FontInfo const font = labelFont();
529         docstring const str = par_.labelString();
530         if (str.empty())
531                 return;
532
533         double spacing_val = 1.0;
534         if (!pparams.spacing().isDefault())
535                 spacing_val = pparams.spacing().getValue();
536         else
537                 spacing_val = bparams.spacing().getValue();
538
539         FontMetrics const & fm = theFontMetrics(font);
540
541         int const labeladdon = int(fm.maxHeight()
542                 * layout.spacing.getValue() * spacing_val);
543
544         int maxdesc =
545                 int(fm.maxDescent() * layout.spacing.getValue() * spacing_val
546                 + (layout.labelbottomsep * defaultRowHeight()));
547
548         double x = x_;
549         if (layout.labeltype == LABEL_CENTERED) {
550                 if (is_rtl)
551                         x = leftMargin();
552                 x += (width_ - text_metrics_.rightMargin(pm_) - leftMargin()) / 2;
553                 x -= fm.width(str) / 2;
554         } else if (is_rtl) {
555                 x = width_ - leftMargin() -     fm.width(str);
556         }
557         pi_.pain.text(int(x), yo_ - maxdesc - labeladdon, str, font);
558 }
559
560
561 /** Check if the current paragraph is the last paragraph in a
562     proof environment */
563 static int getEndLabel(pit_type p, Text const & text)
564 {
565         ParagraphList const & pars = text.paragraphs();
566         pit_type pit = p;
567         depth_type par_depth = pars[p].getDepth();
568         while (pit != pit_type(pars.size())) {
569                 Layout const & layout = pars[pit].layout();
570                 int const endlabeltype = layout.endlabeltype;
571
572                 if (endlabeltype != END_LABEL_NO_LABEL) {
573                         if (p + 1 == pit_type(pars.size()))
574                                 return endlabeltype;
575
576                         depth_type const next_depth =
577                                 pars[p + 1].getDepth();
578                         if (par_depth > next_depth ||
579                             (par_depth == next_depth && layout != pars[p + 1].layout()))
580                                 return endlabeltype;
581                         break;
582                 }
583                 if (par_depth == 0)
584                         break;
585                 pit = text.outerHook(pit);
586                 if (pit != pit_type(pars.size()))
587                         par_depth = pars[pit].getDepth();
588         }
589         return END_LABEL_NO_LABEL;
590 }
591
592
593 void RowPainter::paintLast()
594 {
595         bool const is_rtl = text_.isRTL(par_);
596         int const endlabel = getEndLabel(pit_, text_);
597
598         // paint imaginary end-of-paragraph character
599
600         Change const & change = par_.lookupChange(par_.size());
601         if (change.changed()) {
602                 FontMetrics const & fm =
603                         theFontMetrics(pi_.base.bv->buffer().params().getFont());
604                 int const length = fm.maxAscent() / 2;
605                 Color col = change.color();
606
607                 pi_.pain.line(int(x_) + 1, yo_ + 2, int(x_) + 1, yo_ + 2 - length, col,
608                            Painter::line_solid, 3);
609
610                 if (change.deleted()) {
611                         pi_.pain.line(int(x_) + 1 - length, yo_ + 2, int(x_) + 1 + length,
612                                 yo_ + 2, col, Painter::line_solid, 3);
613                 } else {
614                         pi_.pain.line(int(x_) + 1 - length, yo_ + 2, int(x_) + 1,
615                                 yo_ + 2, col, Painter::line_solid, 3);
616                 }
617         }
618
619         // draw an endlabel
620
621         switch (endlabel) {
622         case END_LABEL_BOX:
623         case END_LABEL_FILLED_BOX: {
624                 FontInfo const font = labelFont();
625                 FontMetrics const & fm = theFontMetrics(font);
626                 int const size = int(0.75 * fm.maxAscent());
627                 int const y = yo_ - size;
628                 int const max_row_width = width_ - size - Inset::TEXT_TO_INSET_OFFSET;
629                 int x = is_rtl ? nestMargin() + changebarMargin()
630                         : max_row_width - text_metrics_.rightMargin(pm_);
631
632                 // If needed, move the box a bit to avoid overlapping with text.
633                 int const rem = max_row_width - row_.width();
634                 if (rem <= 0)
635                         x += is_rtl ? rem : - rem;
636
637                 if (endlabel == END_LABEL_BOX)
638                         pi_.pain.rectangle(x, y, size, size, Color_eolmarker);
639                 else
640                         pi_.pain.fillRectangle(x, y, size, size, Color_eolmarker);
641                 break;
642         }
643
644         case END_LABEL_STATIC: {
645                 FontInfo const font = labelFont();
646                 FontMetrics const & fm = theFontMetrics(font);
647                 docstring const & str = par_.layout().endlabelstring();
648                 double const x = is_rtl ? x_ - fm.width(str) : x_;
649                 pi_.pain.text(int(x), yo_, str, font);
650                 break;
651         }
652
653         case END_LABEL_NO_LABEL:
654                 if (lyxrc.paragraph_markers && size_type(pit_ + 1) < pars_.size()) {
655                         docstring const s = docstring(1, char_type(0x00B6));
656                         FontInfo f = FontInfo(text_.layoutFont(pit_));
657                         f.setColor(Color_paragraphmarker);
658                         pi_.pain.text(int(x_), yo_, s, f);
659                         x_ += theFontMetrics(f).width(s);
660                 }
661                 break;
662         }
663 }
664
665
666 void RowPainter::paintOnlyInsets()
667 {
668         CoordCache const & cache = pi_.base.bv->coordCache();
669         pos_type const end = row_.endpos();
670         for (pos_type pos = row_.pos(); pos != end; ++pos) {
671                 // If outer row has changed, nested insets are repaint completely.
672                 Inset const * inset = par_.getInset(pos);
673                 bool const nested_inset = inset &&
674                                 ((inset->asInsetMath() &&
675                                   !inset->asInsetMath()->asMacroTemplate())
676                                  || inset->asInsetText()
677                                  || inset->asInsetTabular());
678                 if (!nested_inset)
679                         continue;
680                 if (x_ > pi_.base.bv->workWidth()
681                     || !cache.getInsets().has(inset))
682                         continue;
683                 x_ = cache.getInsets().x(inset);
684
685                 bool const pi_selected = pi_.selected;
686                 Cursor const & cur = pi_.base.bv->cursor();
687                 if (cur.selection() && cur.text() == &text_
688                           && cur.normalAnchor().text() == &text_)
689                         pi_.selected = row_.sel_beg <= pos && row_.sel_end > pos;
690                 paintInset(inset, pos);
691                 pi_.selected = pi_selected;
692         }
693 }
694
695
696 void RowPainter::paintText()
697 {
698         pos_type const end = row_.endpos();
699         // Spaces at logical line breaks in bidi text must be skipped during
700         // painting. However, they may appear visually in the middle
701         // of a row; they must be skipped, wherever they are...
702         // * logically "abc_[HEBREW_\nHEBREW]"
703         // * visually "abc_[_WERBEH\nWERBEH]"
704         pos_type skipped_sep_vpos = -1;
705         pos_type body_pos = par_.beginOfBody();
706         if (body_pos > 0 &&
707                 (body_pos > end || !par_.isLineSeparator(body_pos - 1))) {
708                 body_pos = 0;
709         }
710
711         Layout const & layout = par_.layout();
712
713         Change change_running;
714         int change_last_x = 0;
715
716         // check for possible inline completion
717         DocIterator const & inlineCompletionPos = pi_.base.bv->inlineCompletionPos();
718         pos_type inlineCompletionVPos = -1;
719         if (inlineCompletionPos.inTexted()
720             && inlineCompletionPos.text() == &text_
721             && inlineCompletionPos.pit() == pit_
722             && inlineCompletionPos.pos() - 1 >= row_.pos()
723             && inlineCompletionPos.pos() - 1 < row_.endpos()) {
724                 // draw logically behind the previous character
725                 inlineCompletionVPos = bidi_.log2vis(inlineCompletionPos.pos() - 1);
726         }
727
728         // Use font span to speed things up, see below
729         FontSpan font_span;
730         Font font;
731
732         // If the last logical character is a separator, don't paint it, unless
733         // it's in the last row of a paragraph; see skipped_sep_vpos declaration
734         if (end > 0 && end < par_.size() && par_.isSeparator(end - 1))
735                 skipped_sep_vpos = bidi_.log2vis(end - 1);
736
737         for (pos_type vpos = row_.pos(); vpos < end; ) {
738                 if (x_ > pi_.base.bv->workWidth())
739                         break;
740
741                 // Skip the separator at the logical end of the row
742                 if (vpos == skipped_sep_vpos) {
743                         ++vpos;
744                         continue;
745                 }
746
747                 pos_type const pos = bidi_.vis2log(vpos);
748
749                 if (pos >= par_.size()) {
750                         ++vpos;
751                         continue;
752                 }
753
754                 // Use font span to speed things up, see above
755                 if (vpos < font_span.first || vpos > font_span.last) {
756                         font_span = par_.fontSpan(vpos);
757                         font = text_metrics_.displayFont(pit_, vpos);
758
759                         // split font span if inline completion is inside
760                         if (font_span.first <= inlineCompletionVPos
761                             && font_span.last > inlineCompletionVPos)
762                                 font_span.last = inlineCompletionVPos;
763                 }
764
765                 const int width_pos = pm_.singleWidth(pos, font);
766
767                 if (x_ + width_pos < 0) {
768                         x_ += width_pos;
769                         ++vpos;
770                         continue;
771                 }
772                 Change const & change = par_.lookupChange(pos);
773                 if (change.changed() && !change_running.changed()) {
774                         change_running = change;
775                         change_last_x = int(x_);
776                 }
777
778                 Inset const * inset = par_.getInset(pos);
779                 bool const highly_editable_inset = inset
780                         && inset->editable();
781
782                 // If we reach the end of a change or if the author changes, paint it.
783                 // We also don't paint across things like tables
784                 if (change_running.changed() && (highly_editable_inset
785                         || !change.changed() || !change_running.isSimilarTo(change))) {
786                         // Calculate 1/3 height of the buffer's default font
787                         FontMetrics const & fm
788                                 = theFontMetrics(pi_.base.bv->buffer().params().getFont());
789                         float const y_bar = change_running.deleted() ?
790                                 yo_ - fm.maxAscent() / 3 : yo_ + 2 * solid_line_offset_ + solid_line_thickness_;
791                         pi_.pain.line(change_last_x, int(y_bar), int(x_), int(y_bar),
792                                 change_running.color(), Painter::line_solid, solid_line_thickness_);
793
794                         // Change might continue with a different author or type
795                         if (change.changed() && !highly_editable_inset) {
796                                 change_running = change;
797                                 change_last_x = int(x_);
798                         } else
799                                 change_running.setUnchanged();
800                 }
801
802                 if (body_pos > 0 && pos == body_pos - 1) {
803                         int const lwidth = theFontMetrics(labelFont())
804                                 .width(layout.labelsep);
805
806                         x_ += row_.label_hfill + lwidth - width_pos;
807                 }
808
809                 // Is the inline completion in front of character?
810                 if (font.isRightToLeft() && vpos == inlineCompletionVPos)
811                         paintInlineCompletion(font);
812
813                 if (par_.isSeparator(pos)) {
814                         Font const orig_font = text_metrics_.displayFont(pit_, pos);
815                         double const orig_x = x_;
816                         double separator_width = width_pos;
817                         if (pos >= body_pos)
818                                 separator_width += row_.separator;
819                         paintSeparator(orig_x, separator_width, orig_font.fontInfo());
820                         paintForeignMark(orig_x, orig_font.language());
821                         ++vpos;
822
823                 } else if (inset) {
824                         // If outer row has changed, nested insets are repaint completely.
825                         pi_.base.bv->coordCache().insets().add(inset, int(x_), yo_);
826
827                         bool const pi_selected = pi_.selected;
828                         Cursor const & cur = pi_.base.bv->cursor();
829                         if (cur.selection() && cur.text() == &text_
830                                   && cur.normalAnchor().text() == &text_)
831                                 pi_.selected = row_.sel_beg <= pos && row_.sel_end > pos;
832                         paintInset(inset, pos);
833                         pi_.selected = pi_selected;
834                         ++vpos;
835
836                 } else {
837                         // paint as many characters as possible.
838                         paintFromPos(vpos, change_running.changed());
839                 }
840
841                 // Is the inline completion after character?
842                 if (!font.isRightToLeft() && vpos - 1 == inlineCompletionVPos)
843                         paintInlineCompletion(font);
844         }
845
846         // if we reach the end of a struck out range, paint it
847         if (change_running.changed()) {
848                 FontMetrics const & fm
849                         = theFontMetrics(pi_.base.bv->buffer().params().getFont());
850                 float const y_bar = change_running.deleted() ?
851                                 yo_ - fm.maxAscent() / 3 : yo_ + 2 * solid_line_offset_ + solid_line_thickness_;
852                 pi_.pain.line(change_last_x, int(y_bar), int(x_), int(y_bar),
853                         change_running.color(), Painter::line_solid, solid_line_thickness_);
854                 change_running.setUnchanged();
855         }
856 }
857
858
859 void RowPainter::paintSelection()
860 {
861         if (!row_.selection())
862                 return;
863         Cursor const & curs = pi_.base.bv->cursor();
864         DocIterator beg = curs.selectionBegin();
865         beg.pit() = pit_;
866         beg.pos() = row_.sel_beg;
867
868         DocIterator end = curs.selectionEnd();
869         end.pit() = pit_;
870         end.pos() = row_.sel_end;
871
872         bool const begin_boundary = beg.pos() >= row_.endpos();
873         bool const end_boundary = row_.sel_end == row_.endpos();
874
875         DocIterator cur = beg;
876         cur.boundary(begin_boundary);
877         int x1 = text_metrics_.cursorX(beg.top(), begin_boundary);
878         int x2 = text_metrics_.cursorX(end.top(), end_boundary);
879         int const y1 = yo_ - row_.ascent();
880         int const y2 = y1 + row_.height();
881
882         int const rm = text_.isMainText() ? pi_.base.bv->rightMargin() : 0;
883         int const lm = text_.isMainText() ? pi_.base.bv->leftMargin() : 0;
884
885         // draw the margins
886         if (row_.begin_margin_sel) {
887                 if (text_.isRTL(beg.paragraph())) {
888                         pi_.pain.fillRectangle(int(xo_ + x1), y1,
889                                 text_metrics_.width() - rm - x1, y2 - y1, Color_selection);
890                 } else {
891                         pi_.pain.fillRectangle(int(xo_ + lm), y1, x1 - lm, y2 - y1,
892                                 Color_selection);
893                 }
894         }
895
896         if (row_.end_margin_sel) {
897                 if (text_.isRTL(beg.paragraph())) {
898                         pi_.pain.fillRectangle(int(xo_ + lm), y1, x2 - lm, y2 - y1,
899                                 Color_selection);
900                 } else {
901                         pi_.pain.fillRectangle(int(xo_ + x2), y1, text_metrics_.width() - rm - x2,
902                                 y2 - y1, Color_selection);
903                 }
904         }
905
906         // if we are on a boundary from the beginning, it's probably
907         // a RTL boundary and we jump to the other side directly as this
908         // segement is 0-size and confuses the logic below
909         if (cur.boundary())
910                 cur.boundary(false);
911
912         // go through row and draw from RTL boundary to RTL boundary
913         while (cur < end) {
914                 bool draw_now = false;
915
916                 // simplified cursorForward code below which does not
917                 // descend into insets and which does not go into the
918                 // next line. Compare the logic with the original cursorForward
919
920                 // if left of boundary -> just jump to right side, but
921                 // for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
922                 if (cur.boundary()) {
923                         cur.boundary(false);
924                 }       else if (text_metrics_.isRTLBoundary(cur.pit(), cur.pos() + 1)) {
925                         // in front of RTL boundary -> Stay on this side of the boundary
926                         // because:  ab|cDDEEFFghi -> abc|DDEEFFghi
927                         ++cur.pos();
928                         cur.boundary(true);
929                         draw_now = true;
930                 } else {
931                         // move right
932                         ++cur.pos();
933
934                         // line end?
935                         if (cur.pos() == row_.endpos())
936                                 cur.boundary(true);
937                 }
938
939                 if (x1 == -1) {
940                         // the previous segment was just drawn, now the next starts
941                         x1 = text_metrics_.cursorX(cur.top(), cur.boundary());
942                 }
943
944                 if (!(cur < end) || draw_now) {
945                         x2 = text_metrics_.cursorX(cur.top(), cur.boundary());
946                         pi_.pain.fillRectangle(int(xo_ + min(x1, x2)), y1, abs(x2 - x1),
947                                 y2 - y1, Color_selection);
948
949                         // reset x1, so it is set again next round (which will be on the
950                         // right side of a boundary or at the selection end)
951                         x1 = -1;
952                 }
953         }
954 }
955
956
957 void RowPainter::paintInlineCompletion(Font const & font)
958 {
959         docstring completion = pi_.base.bv->inlineCompletion();
960         FontInfo f = font.fontInfo();
961         bool rtl = font.isRightToLeft();
962
963         // draw the unique and the non-unique completion part
964         // Note: this is not time-critical as it is
965         // only done once per screen.
966         size_t uniqueTo = pi_.base.bv->inlineCompletionUniqueChars();
967         docstring s1 = completion.substr(0, uniqueTo);
968         docstring s2 = completion.substr(uniqueTo);
969         ColorCode c1 = Color_inlinecompletion;
970         ColorCode c2 = Color_nonunique_inlinecompletion;
971
972         // right to left?
973         if (rtl) {
974                 swap(s1, s2);
975                 swap(c1, c2);
976         }
977
978         if (!s1.empty()) {
979                 f.setColor(c1);
980                 pi_.pain.text(int(x_), yo_, s1, f);
981                 x_ += theFontMetrics(font).width(s1);
982         }
983
984         if (!s2.empty()) {
985                 f.setColor(c2);
986                 pi_.pain.text(int(x_), yo_, s2, f);
987                 x_ += theFontMetrics(font).width(s2);
988         }
989 }
990
991 } // namespace lyx