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