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