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