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