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