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