]> git.lyx.org Git - features.git/blob - src/RowPainter.cpp
#9514 contents inside of LyX insets with spell check disabled should be ignored by...
[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_.left_margin + 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 const pi_full_repaint = pi_.full_repaint;
125         bool const pi_do_spellcheck = pi_.do_spellcheck;
126
127         pi_.base.font = inset->inheritFont() ? font.fontInfo() :
128                 pi_.base.bv->buffer().params().getFont().fontInfo();
129         pi_.ltr_pos = (bidi_.level(pos) % 2 == 0);
130         Change prev_change = change_;
131         pi_.change_ = change_.changed() ? change_ : par_.lookupChange(pos);
132         pi_.do_spellcheck &= inset->allowSpellCheck();
133
134         int const x1 = int(x_);
135         pi_.base.bv->coordCache().insets().add(inset, x1, yo_);
136         // insets are painted completely. Recursive
137         // FIXME: it is wrong to completely paint the background
138         // if we want to do single row painting.
139         inset->drawBackground(pi_, x1, yo_);
140         inset->drawSelection(pi_, x1, yo_);
141         inset->draw(pi_, x1, yo_);
142
143         Dimension const & dim = pm_.insetDimension(inset);
144
145         paintForeignMark(x_, font.language(), dim.descent());
146
147         x_ += dim.width();
148
149         // Restore full_repaint status.
150         pi_.full_repaint = pi_full_repaint;
151         pi_.change_ = prev_change;
152         pi_.do_spellcheck = pi_do_spellcheck;
153
154 #ifdef DEBUG_METRICS
155         int const x2 = x1 + dim.wid;
156         int const y1 = yo_ + dim.des;
157         int const y2 = yo_ - dim.asc;
158         pi_.pain.line(x1, y1, x1, y2, Color_green);
159         pi_.pain.line(x1, y1, x2, y1, Color_green);
160         pi_.pain.line(x2, y1, x2, y2, Color_green);
161         pi_.pain.line(x1, y2, x2, y2, Color_green);
162 #endif
163 }
164
165
166 void RowPainter::paintChars(pos_type & vpos, Font const & font)
167 {
168         // This method takes up 70% of time when typing
169         pos_type pos = bidi_.vis2log(vpos);
170         pos_type start_pos = pos;
171         // first character
172         docstring str;
173         str.reserve(100);
174         char_type const c = par_.getChar(pos);
175         str.push_back(c);
176
177         FontSpan const font_span = par_.fontSpan(pos);
178         // Track-change status.
179         Change const & change_running = par_.lookupChange(pos);
180         // spelling correct?
181         bool const spell_state =
182                 lyxrc.spellcheck_continuously && par_.isMisspelled(pos);
183
184         // collect as much similar chars as we can
185         pos_type const end = row_.endpos();
186         for (++vpos ; vpos < end ; ++vpos) {
187                 pos = bidi_.vis2log(vpos);
188
189                 if (!font_span.contains(pos))
190                         break;
191
192                 bool const new_spell_state =
193                         lyxrc.spellcheck_continuously && par_.isMisspelled(pos);
194                 if (new_spell_state != spell_state)
195                         // Spell checker state changed here.
196                         break;
197
198                 Change const & change = par_.lookupChange(pos);
199                 if (!change_running.isSimilarTo(change))
200                         // Track change type or author has changed.
201                         break;
202
203                 char_type const c = par_.getChar(pos);
204
205                 if (c == '\t')
206                         break;
207
208                 if (!isPrintableNonspace(c))
209                         break;
210
211                 str.push_back(c);
212         }
213
214         // Make pos point to the last character in the string.
215         // Using "pos = bidi_.vis2log(vpos)" does not work for some reason.
216         if (vpos < end)
217                 pos = bidi_.vis2log(vpos - 1);
218
219         // Now make pos point to the position _after_ the string.
220         // Using vis2log for that is not a good idea in general, we
221         // want logical ordering.
222         if (font.isVisibleRightToLeft())
223                 --pos;
224         else
225                 ++pos;
226
227         if (str[0] == '\t')
228                 str.replace(0,1,from_ascii("    "));
229
230         /* Because we do our own bidi, at this point the strings are
231          * already in visual order. However, Qt also applies its own
232          * bidi algorithm to strings that it paints to the screen.
233          * Therefore, if we were to paint Hebrew/Arabic words as a
234          * single string, the letters in the words would get reversed
235          * again. In order to avoid that, we force LTR drawing.
236          * See also http://thread.gmane.org/gmane.editors.lyx.devel/79740
237          * for an earlier thread on the subject
238          */
239         if (font.isVisibleRightToLeft()) {
240                 reverse(str.begin(), str.end());
241                 // If the string is reversed, the positions need to be adjusted
242                 ++pos;
243                 ++start_pos;
244                 swap(start_pos, pos);
245         }
246
247         // at least part of text selected?
248         bool const some_sel = (pos >= row_.sel_beg && start_pos < row_.sel_end)
249                 || pi_.selected;
250         // all the text selected?
251         bool const all_sel = (start_pos >= row_.sel_beg && pos < row_.sel_end)
252                 || pi_.selected;
253
254         if (all_sel) {
255                 Font copy = font;
256                 copy.fontInfo().setPaintColor(Color_selectiontext);
257                 x_ += pi_.pain.text(int(x_), yo_, str, copy);
258         } else if (change_running.changed()) {
259                 Font copy = font;
260                 copy.fontInfo().setPaintColor(change_running.color());
261                 x_ += pi_.pain.text(int(x_), yo_, str, copy);
262         } else if (!some_sel) {
263                 x_ += pi_.pain.text(int(x_), yo_, str, font);
264         } else {
265                 x_ += pi_.pain.text(int(x_), yo_, str, font, Color_selectiontext,
266                                     max(row_.sel_beg, start_pos) - start_pos,
267                                     min(row_.sel_end, pos) - start_pos);
268         }
269 }
270
271
272 void RowPainter::paintSeparator(double orig_x, double width,
273         FontInfo const & font)
274 {
275         pi_.pain.textDecoration(font, int(orig_x), yo_, int(width));
276         x_ += width;
277 }
278
279
280 void RowPainter::paintForeignMark(double orig_x, Language const * lang,
281                 int desc)
282 {
283         if (!lyxrc.mark_foreign_language)
284                 return;
285         if (lang == latex_language)
286                 return;
287         if (lang == pi_.base.bv->buffer().params().language)
288                 return;
289
290         int const y = yo_ + solid_line_offset_ + desc + int(solid_line_thickness_/2);
291         pi_.pain.line(int(orig_x), y, int(x_), y, Color_language,
292                 Painter::line_solid, solid_line_thickness_);
293 }
294
295
296 void RowPainter::paintMisspelledMark(double orig_x, bool changed)
297 {
298         // if changed the misspelled marker gets placed slightly lower than normal
299         // to avoid drawing at the same vertical offset
300         float const y = yo_ + solid_line_offset_ + solid_line_thickness_
301                 + (changed ? solid_line_thickness_ + 1 : 0)
302                 + dotted_line_offset_;
303         pi_.pain.line(int(orig_x), int(y), int(x_), int(y), Color_error,
304                 Painter::line_onoffdash, dotted_line_thickness_);
305 }
306
307
308 void RowPainter::paintFromPos(pos_type & vpos, bool changed)
309 {
310         pos_type const pos = bidi_.vis2log(vpos);
311         Font const font = text_metrics_.displayFont(pit_, pos);
312         double const orig_x = x_;
313
314         paintChars(vpos, font);
315         paintForeignMark(orig_x, font.language());
316
317         // Paint the spelling mark if needed.
318         if (lyxrc.spellcheck_continuously && par_.isMisspelled(pos)) {
319                 // check for cursor position
320                 // don't draw misspelled marker for words at cursor position
321                 // we don't want to disturb the process of text editing
322                 BufferView const * bv = pi_.base.bv;
323                 DocIterator const nw = bv->cursor().newWord();
324                 bool new_word = false;
325                 if (!nw.empty() && par_.id() == nw.paragraph().id()) {
326                         pos_type cpos = nw.pos();
327                         if (cpos > 0 && cpos == par_.size() && !par_.isWordSeparator(cpos-1))
328                                 --cpos;
329                         else if (cpos > 0 && par_.isWordSeparator(cpos))
330                                 --cpos;
331                         new_word = par_.isSameSpellRange(pos, cpos) ;
332                 }
333                 if (!new_word)
334                         paintMisspelledMark(orig_x, changed);
335         }
336 }
337
338
339 void RowPainter::paintChangeBar()
340 {
341         pos_type const start = row_.pos();
342         pos_type end = row_.endpos();
343
344         if (par_.size() == end) {
345                 // this is the last row of the paragraph;
346                 // thus, we must also consider the imaginary end-of-par character
347                 end++;
348         }
349
350         if (start == end || !par_.isChanged(start, end))
351                 return;
352
353         int const height = text_metrics_.isLastRow(pit_, row_)
354                 ? row_.ascent()
355                 : row_.height();
356
357         pi_.pain.fillRectangle(5, yo_ - row_.ascent(), 3, height, Color_changebar);
358 }
359
360
361 void RowPainter::paintAppendix()
362 {
363         // only draw the appendix frame once (for the main text)
364         if (!par_.params().appendix() || !text_.isMainText())
365                 return;
366
367         int y = yo_ - row_.ascent();
368
369         if (par_.params().startOfAppendix())
370                 y += 2 * defaultRowHeight();
371
372         pi_.pain.line(1, y, 1, yo_ + row_.height(), Color_appendix);
373         pi_.pain.line(width_ - 2, y, width_ - 2, yo_ + row_.height(), Color_appendix);
374 }
375
376
377 void RowPainter::paintDepthBar()
378 {
379         depth_type const depth = par_.getDepth();
380
381         if (depth <= 0)
382                 return;
383
384         depth_type prev_depth = 0;
385         if (!text_metrics_.isFirstRow(pit_, row_)) {
386                 pit_type pit2 = pit_;
387                 if (row_.pos() == 0)
388                         --pit2;
389                 prev_depth = pars_[pit2].getDepth();
390         }
391
392         depth_type next_depth = 0;
393         if (!text_metrics_.isLastRow(pit_, row_)) {
394                 pit_type pit2 = pit_;
395                 if (row_.endpos() >= pars_[pit2].size())
396                         ++pit2;
397                 next_depth = pars_[pit2].getDepth();
398         }
399
400         for (depth_type i = 1; i <= depth; ++i) {
401                 int const w = nestMargin() / 5;
402                 int x = int(xo_) + w * i;
403                 // only consider the changebar space if we're drawing outermost text
404                 if (text_.isMainText())
405                         x += changebarMargin();
406
407                 int const starty = yo_ - row_.ascent();
408                 int const h =  row_.height() - 1 - (i - next_depth - 1) * 3;
409
410                 pi_.pain.line(x, starty, x, starty + h, Color_depthbar);
411
412                 if (i > prev_depth)
413                         pi_.pain.fillRectangle(x, starty, w, 2, Color_depthbar);
414                 if (i > next_depth)
415                         pi_.pain.fillRectangle(x, starty + h, w, 2, Color_depthbar);
416         }
417 }
418
419
420 int RowPainter::paintAppendixStart(int y)
421 {
422         FontInfo pb_font = sane_font;
423         pb_font.setColor(Color_appendix);
424         pb_font.decSize();
425
426         int w = 0;
427         int a = 0;
428         int d = 0;
429
430         docstring const label = _("Appendix");
431         theFontMetrics(pb_font).rectText(label, w, a, d);
432
433         int const text_start = int(xo_ + (width_ - w) / 2);
434         int const text_end = text_start + w;
435
436         pi_.pain.rectText(text_start, y + d, label, pb_font, Color_none, Color_none);
437
438         pi_.pain.line(int(xo_ + 1), y, text_start, y, Color_appendix);
439         pi_.pain.line(text_end, y, int(xo_ + width_ - 2), y, Color_appendix);
440
441         return 3 * defaultRowHeight();
442 }
443
444
445 void RowPainter::paintTooLargeMarks(bool const left, bool const right)
446 {
447         if (left)
448                 pi_.pain.line(int(dotted_line_thickness_), yo_ - row_.ascent(),
449                                           int(dotted_line_thickness_), yo_ + row_.descent(),
450                                           Color_scroll,
451                                           Painter::line_onoffdash, dotted_line_thickness_);
452         if (right) {
453                 int const wwidth = pi_.base.bv->workWidth() - int(dotted_line_thickness_);
454                 pi_.pain.line(wwidth, yo_ - row_.ascent(),
455                                           wwidth, yo_ + row_.descent(),
456                                           Color_scroll,
457                                           Painter::line_onoffdash, dotted_line_thickness_);
458         }
459 }
460
461
462 void RowPainter::paintFirst()
463 {
464         BufferParams const & bparams = pi_.base.bv->buffer().params();
465         Layout const & layout = par_.layout();
466
467         int y_top = 0;
468
469         // start of appendix?
470         if (par_.params().startOfAppendix())
471                 y_top += paintAppendixStart(yo_ - row_.ascent() + 2 * defaultRowHeight());
472
473         if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
474                 && pit_ != 0) {
475                 if (layout.latextype == LATEX_PARAGRAPH
476                     && !par_.getDepth()) {
477                         y_top += bparams.getDefSkip().inPixels(*pi_.base.bv);
478                 } else {
479                         Layout const & playout = pars_[pit_ - 1].layout();
480                         if (playout.latextype == LATEX_PARAGRAPH
481                             && !pars_[pit_ - 1].getDepth()) {
482                                 // is it right to use defskip here, too? (AS)
483                                 y_top += bparams.getDefSkip().inPixels(*pi_.base.bv);
484                         }
485                 }
486         }
487
488         bool const is_first =
489                 text_.isFirstInSequence(pit_) || !layout.isParagraphGroup();
490         //lyxerr << "paintFirst: " << par_.id() << " is_seq: " << is_seq << endl;
491
492         if (layout.labelIsInline()
493                         && (layout.labeltype != LABEL_STATIC || is_first)) {
494                 paintLabel();
495         } else if (is_first && layout.labelIsAbove()) {
496                 paintTopLevelLabel();
497         }
498 }
499
500
501 void RowPainter::paintLabel()
502 {
503         docstring const str = par_.labelString();
504         if (str.empty())
505                 return;
506
507         bool const is_rtl = text_.isRTL(par_);
508         Layout const & layout = par_.layout();
509         FontInfo const font = labelFont();
510         FontMetrics const & fm = theFontMetrics(font);
511         double x = x_;
512
513         if (is_rtl) {
514                 x = width_ - leftMargin()
515                         + fm.width(layout.labelsep);
516         } else {
517                 x = x_ - fm.width(layout.labelsep)
518                         - fm.width(str);
519         }
520
521         pi_.pain.text(int(x), yo_, str, font);
522 }
523
524
525 void RowPainter::paintTopLevelLabel()
526 {
527         BufferParams const & bparams = pi_.base.bv->buffer().params();
528         bool const is_rtl = text_.isRTL(par_);
529         ParagraphParameters const & pparams = par_.params();
530         Layout const & layout = par_.layout();
531         FontInfo const font = labelFont();
532         docstring const str = par_.labelString();
533         if (str.empty())
534                 return;
535
536         double spacing_val = 1.0;
537         if (!pparams.spacing().isDefault())
538                 spacing_val = pparams.spacing().getValue();
539         else
540                 spacing_val = bparams.spacing().getValue();
541
542         FontMetrics const & fm = theFontMetrics(font);
543
544         int const labeladdon = int(fm.maxHeight()
545                 * layout.spacing.getValue() * spacing_val);
546
547         int maxdesc =
548                 int(fm.maxDescent() * layout.spacing.getValue() * spacing_val
549                 + (layout.labelbottomsep * defaultRowHeight()));
550
551         double x = x_;
552         if (layout.labeltype == LABEL_CENTERED) {
553                 if (is_rtl)
554                         x = leftMargin();
555                 x += (width_ - text_metrics_.rightMargin(pm_) - leftMargin()) / 2;
556                 x -= fm.width(str) / 2;
557         } else if (is_rtl) {
558                 x = width_ - leftMargin() -     fm.width(str);
559         }
560         pi_.pain.text(int(x), yo_ - maxdesc - labeladdon, str, font);
561 }
562
563
564 /** Check if the current paragraph is the last paragraph in a
565     proof environment */
566 static int getEndLabel(pit_type p, Text const & text)
567 {
568         ParagraphList const & pars = text.paragraphs();
569         pit_type pit = p;
570         depth_type par_depth = pars[p].getDepth();
571         while (pit != pit_type(pars.size())) {
572                 Layout const & layout = pars[pit].layout();
573                 int const endlabeltype = layout.endlabeltype;
574
575                 if (endlabeltype != END_LABEL_NO_LABEL) {
576                         if (p + 1 == pit_type(pars.size()))
577                                 return endlabeltype;
578
579                         depth_type const next_depth =
580                                 pars[p + 1].getDepth();
581                         if (par_depth > next_depth ||
582                             (par_depth == next_depth && layout != pars[p + 1].layout()))
583                                 return endlabeltype;
584                         break;
585                 }
586                 if (par_depth == 0)
587                         break;
588                 pit = text.outerHook(pit);
589                 if (pit != pit_type(pars.size()))
590                         par_depth = pars[pit].getDepth();
591         }
592         return END_LABEL_NO_LABEL;
593 }
594
595
596 void RowPainter::paintLast()
597 {
598         bool const is_rtl = text_.isRTL(par_);
599         int const endlabel = getEndLabel(pit_, text_);
600
601         // paint imaginary end-of-paragraph character
602
603         Change const & change = par_.lookupChange(par_.size());
604         if (change.changed()) {
605                 FontMetrics const & fm =
606                         theFontMetrics(pi_.base.bv->buffer().params().getFont());
607                 int const length = fm.maxAscent() / 2;
608                 Color col = change.color();
609
610                 pi_.pain.line(int(x_) + 1, yo_ + 2, int(x_) + 1, yo_ + 2 - length, col,
611                            Painter::line_solid, 3);
612
613                 if (change.deleted()) {
614                         pi_.pain.line(int(x_) + 1 - length, yo_ + 2, int(x_) + 1 + length,
615                                 yo_ + 2, col, Painter::line_solid, 3);
616                 } else {
617                         pi_.pain.line(int(x_) + 1 - length, yo_ + 2, int(x_) + 1,
618                                 yo_ + 2, col, Painter::line_solid, 3);
619                 }
620         }
621
622         // draw an endlabel
623
624         switch (endlabel) {
625         case END_LABEL_BOX:
626         case END_LABEL_FILLED_BOX: {
627                 FontInfo const font = labelFont();
628                 FontMetrics const & fm = theFontMetrics(font);
629                 int const size = int(0.75 * fm.maxAscent());
630                 int const y = yo_ - size;
631                 int const max_row_width = width_ - size - Inset::TEXT_TO_INSET_OFFSET;
632                 int x = is_rtl ? nestMargin() + changebarMargin()
633                         : max_row_width - text_metrics_.rightMargin(pm_);
634
635                 // If needed, move the box a bit to avoid overlapping with text.
636                 int const rem = max_row_width - row_.width();
637                 if (rem <= 0)
638                         x += is_rtl ? rem : - rem;
639
640                 if (endlabel == END_LABEL_BOX)
641                         pi_.pain.rectangle(x, y, size, size, Color_eolmarker);
642                 else
643                         pi_.pain.fillRectangle(x, y, size, size, Color_eolmarker);
644                 break;
645         }
646
647         case END_LABEL_STATIC: {
648                 FontInfo const font = labelFont();
649                 FontMetrics const & fm = theFontMetrics(font);
650                 docstring const & str = par_.layout().endlabelstring();
651                 double const x = is_rtl ? x_ - fm.width(str) : x_;
652                 pi_.pain.text(int(x), yo_, str, font);
653                 break;
654         }
655
656         case END_LABEL_NO_LABEL:
657                 if (lyxrc.paragraph_markers && size_type(pit_ + 1) < pars_.size()) {
658                         docstring const s = docstring(1, char_type(0x00B6));
659                         FontInfo f = FontInfo(text_.layoutFont(pit_));
660                         f.setColor(Color_paragraphmarker);
661                         pi_.pain.text(int(x_), yo_, s, f);
662                         x_ += theFontMetrics(f).width(s);
663                 }
664                 break;
665         }
666 }
667
668
669 void RowPainter::paintOnlyInsets()
670 {
671         CoordCache const & cache = pi_.base.bv->coordCache();
672         pos_type const end = row_.endpos();
673         for (pos_type pos = row_.pos(); pos != end; ++pos) {
674                 // If outer row has changed, nested insets are repaint completely.
675                 Inset const * inset = par_.getInset(pos);
676                 bool const nested_inset = inset &&
677                                 ((inset->asInsetMath() &&
678                                   !inset->asInsetMath()->asMacroTemplate())
679                                  || inset->asInsetText()
680                                  || inset->asInsetTabular());
681                 if (!nested_inset)
682                         continue;
683                 if (x_ > pi_.base.bv->workWidth()
684                     || !cache.getInsets().has(inset))
685                         continue;
686                 x_ = cache.getInsets().x(inset);
687
688                 bool const pi_selected = pi_.selected;
689                 Cursor const & cur = pi_.base.bv->cursor();
690                 if (cur.selection() && cur.text() == &text_
691                           && cur.normalAnchor().text() == &text_)
692                         pi_.selected = row_.sel_beg <= pos && row_.sel_end > pos;
693                 paintInset(inset, pos);
694                 pi_.selected = pi_selected;
695         }
696 }
697
698
699 void RowPainter::paintText()
700 {
701         //LYXERR0("-------------------------------------------------------");
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 (!font_span.contains(pos)) {
760                         font_span = par_.fontSpan(pos);
761                         font = text_metrics_.displayFont(pit_, pos);
762
763                         // split font span if inline completion is inside
764                         if (inlineCompletionVPos != -1
765                             && font_span.contains(inlineCompletionPos.pos()))
766                                 font_span.last = inlineCompletionPos.pos();
767                 }
768
769                 // Note that this value will only be used in
770                 // situations where no ligature of composition of
771                 // characters is needed. (see comments in uses of width_pos).
772                 const int width_pos = pm_.singleWidth(pos, font);
773
774                 Change const & change = par_.lookupChange(pos);
775                 if (change.changed() && !change_running.changed()) {
776                         change_running = change;
777                         change_last_x = int(x_);
778                 }
779
780                 Inset const * inset = par_.getInset(pos);
781                 bool const highly_editable_inset = inset
782                         && inset->editable();
783
784                 // If we reach the end of a change or if the author changes, paint it.
785                 // We also don't paint across things like tables
786                 if (change_running.changed() && (highly_editable_inset
787                         || !change.changed() || !change_running.isSimilarTo(change))) {
788                         // Calculate 1/3 height of the buffer's default font
789                         FontMetrics const & fm
790                                 = theFontMetrics(pi_.base.bv->buffer().params().getFont());
791                         float const y_bar = change_running.deleted() ?
792                                 yo_ - fm.maxAscent() / 3 : yo_ + 2 * solid_line_offset_ + solid_line_thickness_;
793                         pi_.pain.line(change_last_x, int(y_bar), int(x_), int(y_bar),
794                                 change_running.color(), Painter::line_solid, solid_line_thickness_);
795
796                         // Change might continue with a different author or type
797                         if (change.changed() && !highly_editable_inset) {
798                                 change_running = change;
799                                 change_last_x = int(x_);
800                         } else
801                                 change_running.setUnchanged();
802                 }
803
804                 if (body_pos > 0 && pos == body_pos - 1) {
805                         int const lwidth = theFontMetrics(labelFont())
806                                 .width(layout.labelsep);
807
808                         // width_pos is either the width of a space or an inset
809                         x_ += row_.label_hfill + lwidth - width_pos;
810                 }
811
812                 // Is the inline completion in front of character?
813                 if (font.isRightToLeft() && vpos == inlineCompletionVPos)
814                         paintInlineCompletion(font);
815
816                 if (par_.isSeparator(pos)) {
817                         Font const orig_font = text_metrics_.displayFont(pit_, pos);
818                         double const orig_x = x_;
819                         // width_pos is the width of a space
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