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