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