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