]> git.lyx.org Git - lyx.git/blob - src/rowpainter.cpp
experiment in spell checker mark appearance (see bug #7112)
[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) + 1;
364         pi_.pain.line(int(orig_x), y, int(x_), y, Color_misspelled,
365                 Painter::line_onoffdash, 2.0);
366 }
367
368
369 void RowPainter::paintFromPos(pos_type & vpos, bool changed)
370 {
371         pos_type const pos = bidi_.vis2log(vpos);
372         Font const orig_font = text_metrics_.displayFont(pit_, pos);
373         double const orig_x = x_;
374
375         // usual characters, no insets
376         char_type const c = par_.getChar(pos);
377
378         // special case languages
379         string const & lang = orig_font.language()->lang();
380         bool const hebrew = lang == "hebrew";
381         bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi" ||
382                                                 lang == "farsi";
383
384         // spelling correct?
385         bool const misspelled_ =
386                 lyxrc.spellcheck_continuously && par_.isMisspelled(pos);
387
388         // draw as many chars as we can
389         if ((!hebrew && !arabic)
390                 || (hebrew && !Encodings::isHebrewComposeChar(c))
391                 || (arabic && !Encodings::isArabicComposeChar(c))) {
392                 paintChars(vpos, orig_font.fontInfo(), hebrew, arabic);
393         } else if (hebrew) {
394                 paintHebrewComposeChar(vpos, orig_font.fontInfo());
395         } else if (arabic) {
396                 paintArabicComposeChar(vpos, orig_font.fontInfo());
397         }
398
399         paintForeignMark(orig_x, orig_font.language());
400
401         if (lyxrc.spellcheck_continuously && misspelled_) {
402                 paintMisspelledMark(orig_x, 2, changed);
403         }
404 }
405
406
407 void RowPainter::paintChangeBar()
408 {
409         pos_type const start = row_.pos();
410         pos_type end = row_.endpos();
411
412         if (par_.size() == end) {
413                 // this is the last row of the paragraph;
414                 // thus, we must also consider the imaginary end-of-par character
415                 end++;
416         }
417
418         if (start == end || !par_.isChanged(start, end))
419                 return;
420
421         int const height = text_metrics_.isLastRow(pit_, row_)
422                 ? row_.ascent()
423                 : row_.height();
424
425         pi_.pain.fillRectangle(5, yo_ - row_.ascent(), 3, height, Color_changebar);
426 }
427
428
429 void RowPainter::paintAppendix()
430 {
431         // only draw the appendix frame once (for the main text)
432         if (!par_.params().appendix() || !text_.isMainText())
433                 return;
434
435         int y = yo_ - row_.ascent();
436
437         if (par_.params().startOfAppendix())
438                 y += 2 * defaultRowHeight();
439
440         pi_.pain.line(1, y, 1, yo_ + row_.height(), Color_appendix);
441         pi_.pain.line(width_ - 2, y, width_ - 2, yo_ + row_.height(), Color_appendix);
442 }
443
444
445 void RowPainter::paintDepthBar()
446 {
447         depth_type const depth = par_.getDepth();
448
449         if (depth <= 0)
450                 return;
451
452         depth_type prev_depth = 0;
453         if (!text_metrics_.isFirstRow(pit_, row_)) {
454                 pit_type pit2 = pit_;
455                 if (row_.pos() == 0)
456                         --pit2;
457                 prev_depth = pars_[pit2].getDepth();
458         }
459
460         depth_type next_depth = 0;
461         if (!text_metrics_.isLastRow(pit_, row_)) {
462                 pit_type pit2 = pit_;
463                 if (row_.endpos() >= pars_[pit2].size())
464                         ++pit2;
465                 next_depth = pars_[pit2].getDepth();
466         }
467
468         for (depth_type i = 1; i <= depth; ++i) {
469                 int const w = nestMargin() / 5;
470                 int x = int(xo_) + w * i;
471                 // only consider the changebar space if we're drawing outermost text
472                 if (text_.isMainText())
473                         x += changebarMargin();
474
475                 int const starty = yo_ - row_.ascent();
476                 int const h =  row_.height() - 1 - (i - next_depth - 1) * 3;
477
478                 pi_.pain.line(x, starty, x, starty + h, Color_depthbar);
479
480                 if (i > prev_depth)
481                         pi_.pain.fillRectangle(x, starty, w, 2, Color_depthbar);
482                 if (i > next_depth)
483                         pi_.pain.fillRectangle(x, starty + h, w, 2, Color_depthbar);
484         }
485 }
486
487
488 int RowPainter::paintAppendixStart(int y)
489 {
490         FontInfo pb_font = sane_font;
491         pb_font.setColor(Color_appendix);
492         pb_font.decSize();
493
494         int w = 0;
495         int a = 0;
496         int d = 0;
497
498         docstring const label = _("Appendix");
499         theFontMetrics(pb_font).rectText(label, w, a, d);
500
501         int const text_start = int(xo_ + (width_ - w) / 2);
502         int const text_end = text_start + w;
503
504         pi_.pain.rectText(text_start, y + d, label, pb_font, Color_none, Color_none);
505
506         pi_.pain.line(int(xo_ + 1), y, text_start, y, Color_appendix);
507         pi_.pain.line(text_end, y, int(xo_ + width_ - 2), y, Color_appendix);
508
509         return 3 * defaultRowHeight();
510 }
511
512
513 void RowPainter::paintFirst()
514 {
515         ParagraphParameters const & pparams = par_.params();
516         Buffer const & buffer = pi_.base.bv->buffer();
517         BufferParams const & bparams = buffer.params();
518         Layout const & layout = par_.layout();
519
520         int y_top = 0;
521
522         // start of appendix?
523         if (pparams.startOfAppendix())
524                 y_top += paintAppendixStart(yo_ - row_.ascent() + 2 * defaultRowHeight());
525
526         if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
527                 && pit_ != 0) {
528                 if (layout.latextype == LATEX_PARAGRAPH
529                     && !par_.getDepth()) {
530                         y_top += bparams.getDefSkip().inPixels(*pi_.base.bv);
531                 } else {
532                         Layout const & playout = pars_[pit_ - 1].layout();
533                         if (playout.latextype == LATEX_PARAGRAPH
534                             && !pars_[pit_ - 1].getDepth()) {
535                                 // is it right to use defskip here, too? (AS)
536                                 y_top += bparams.getDefSkip().inPixels(*pi_.base.bv);
537                         }
538                 }
539         }
540
541         bool const is_rtl = text_.isRTL(par_);
542         bool const is_seq = text_.isFirstInSequence(pit_);
543         //lyxerr << "paintFirst: " << par_.id() << " is_seq: " << is_seq << endl;
544
545         // should we print a label?
546         if (layout.labeltype >= LABEL_STATIC
547             && (layout.labeltype != LABEL_STATIC
548                       || layout.latextype != LATEX_ENVIRONMENT
549                       || is_seq)) {
550
551                 FontInfo const font = labelFont();
552                 FontMetrics const & fm = theFontMetrics(font);
553
554                 docstring const str = par_.labelString();
555                 if (!str.empty()) {
556                         double x = x_;
557
558                         // this is special code for the chapter layout. This is
559                         // printed in an extra row and has a pagebreak at
560                         // the top.
561                         if (layout.counter == "chapter") {
562                                 double spacing_val = 1.0;
563                                 if (!pparams.spacing().isDefault()) {
564                                         spacing_val = pparams.spacing().getValue();
565                                 } else {
566                                         spacing_val = bparams.spacing().getValue();
567                                 }
568
569                                 int const labeladdon = int(fm.maxHeight() * layout.spacing.getValue() * spacing_val);
570
571                                 int const maxdesc = int(fm.maxDescent() * layout.spacing.getValue() * spacing_val)
572                                         + int(layout.parsep) * defaultRowHeight();
573
574                                 if (is_rtl) {
575                                         x = width_ - leftMargin() -
576                                                 fm.width(str);
577                                 }
578
579                                 pi_.pain.text(int(x), yo_ - maxdesc - labeladdon, str, font);
580                         } else {
581                                 if (is_rtl) {
582                                         x = width_ - leftMargin()
583                                                 + fm.width(layout.labelsep);
584                                 } else {
585                                         x = x_ - fm.width(layout.labelsep)
586                                                 - fm.width(str);
587                                 }
588
589                                 pi_.pain.text(int(x), yo_, str, font);
590                         }
591                 }
592
593         // the labels at the top of an environment.
594         // More or less for bibliography
595         } else if (is_seq &&
596                 (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
597                 layout.labeltype == LABEL_BIBLIO ||
598                 layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)) {
599                 FontInfo const font = labelFont();
600                 docstring const str = par_.labelString();
601                 if (!str.empty()) {
602                         double spacing_val = 1.0;
603                         if (!pparams.spacing().isDefault())
604                                 spacing_val = pparams.spacing().getValue();
605                         else
606                                 spacing_val = bparams.spacing().getValue();
607
608                         FontMetrics const & fm = theFontMetrics(font);
609
610                         int const labeladdon = int(fm.maxHeight()
611                                 * layout.spacing.getValue() * spacing_val);
612
613                         int maxdesc =
614                                 int(fm.maxDescent() * layout.spacing.getValue() * spacing_val
615                                 + (layout.labelbottomsep * defaultRowHeight()));
616
617                         double x = x_;
618                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
619                                 if (is_rtl)
620                                         x = leftMargin();
621                                 x += (width_ - text_metrics_.rightMargin(pm_) - leftMargin()) / 2;
622                                 x -= fm.width(str) / 2;
623                         } else if (is_rtl) {
624                                 x = width_ - leftMargin() -     fm.width(str);
625                         }
626                         pi_.pain.text(int(x), yo_ - maxdesc - labeladdon, str, font);
627                 }
628         }
629 }
630
631
632 /** Check if the current paragraph is the last paragraph in a
633     proof environment */
634 static int getEndLabel(pit_type p, Text const & text)
635 {
636         ParagraphList const & pars = text.paragraphs();
637         pit_type pit = p;
638         depth_type par_depth = pars[p].getDepth();
639         while (pit != pit_type(pars.size())) {
640                 Layout const & layout = pars[pit].layout();
641                 int const endlabeltype = layout.endlabeltype;
642
643                 if (endlabeltype != END_LABEL_NO_LABEL) {
644                         if (p + 1 == pit_type(pars.size()))
645                                 return endlabeltype;
646
647                         depth_type const next_depth =
648                                 pars[p + 1].getDepth();
649                         if (par_depth > next_depth ||
650                             (par_depth == next_depth && layout != pars[p + 1].layout()))
651                                 return endlabeltype;
652                         break;
653                 }
654                 if (par_depth == 0)
655                         break;
656                 pit = text.outerHook(pit);
657                 if (pit != pit_type(pars.size()))
658                         par_depth = pars[pit].getDepth();
659         }
660         return END_LABEL_NO_LABEL;
661 }
662
663
664 void RowPainter::paintLast()
665 {
666         bool const is_rtl = text_.isRTL(par_);
667         int const endlabel = getEndLabel(pit_, text_);
668
669         // paint imaginary end-of-paragraph character
670
671         Change const & change = par_.lookupChange(par_.size());
672         if (change.changed()) {
673                 FontMetrics const & fm =
674                         theFontMetrics(pi_.base.bv->buffer().params().getFont());
675                 int const length = fm.maxAscent() / 2;
676                 Color col = change.color();
677
678                 pi_.pain.line(int(x_) + 1, yo_ + 2, int(x_) + 1, yo_ + 2 - length, col,
679                            Painter::line_solid, 3);
680
681                 if (change.deleted()) {
682                         pi_.pain.line(int(x_) + 1 - length, yo_ + 2, int(x_) + 1 + length,
683                                 yo_ + 2, col, Painter::line_solid, 3);
684                 } else {
685                         pi_.pain.line(int(x_) + 1 - length, yo_ + 2, int(x_) + 1,
686                                 yo_ + 2, col, Painter::line_solid, 3);
687                 }
688         }
689
690         // draw an endlabel
691
692         switch (endlabel) {
693         case END_LABEL_BOX:
694         case END_LABEL_FILLED_BOX: {
695                 FontInfo const font = labelFont();
696                 FontMetrics const & fm = theFontMetrics(font);
697                 int const size = int(0.75 * fm.maxAscent());
698                 int const y = yo_ - size;
699                 int const max_row_width = width_ - size - Inset::TEXT_TO_INSET_OFFSET;
700                 int x = is_rtl ? nestMargin() + changebarMargin()
701                         : max_row_width - text_metrics_.rightMargin(pm_);
702
703                 // If needed, move the box a bit to avoid overlapping with text.
704                 int const rem = max_row_width - row_.width();
705                 if (rem <= 0)
706                         x += is_rtl ? rem : - rem;
707
708                 if (endlabel == END_LABEL_BOX)
709                         pi_.pain.rectangle(x, y, size, size, Color_eolmarker);
710                 else
711                         pi_.pain.fillRectangle(x, y, size, size, Color_eolmarker);
712                 break;
713         }
714
715         case END_LABEL_STATIC: {
716                 FontInfo const font = labelFont();
717                 FontMetrics const & fm = theFontMetrics(font);
718                 docstring const & str = par_.layout().endlabelstring();
719                 double const x = is_rtl ? x_ - fm.width(str) : x_;
720                 pi_.pain.text(int(x), yo_, str, font);
721                 break;
722         }
723
724         case END_LABEL_NO_LABEL:
725                 if (lyxrc.paragraph_markers && size_type(pit_ + 1) < pars_.size()) {
726                         docstring const s = docstring(1, char_type(0x00B6));
727                         FontInfo f = FontInfo();
728                         FontMetrics const & fm = theFontMetrics(f);
729                         f.setColor(Color_paragraphmarker);
730                         pi_.pain.text(int(x_), yo_, s, f);
731                         x_ += fm.width(s);
732                 }
733                 break;
734         }
735 }
736
737
738 void RowPainter::paintOnlyInsets()
739 {
740         CoordCache const & cache = pi_.base.bv->coordCache();
741         pos_type const end = row_.endpos();
742         for (pos_type pos = row_.pos(); pos != end; ++pos) {
743                 // If outer row has changed, nested insets are repaint completely.
744                 Inset const * inset = par_.getInset(pos);
745                 if (!inset)
746                         continue;
747                 if (x_ > pi_.base.bv->workWidth()
748                     || !cache.getInsets().has(inset))
749                         continue;
750                 x_ = cache.getInsets().x(inset);
751
752                 bool const pi_selected = pi_.selected;
753                 Cursor const & cur = pi_.base.bv->cursor();
754                 if (cur.selection() && cur.text() == &text_
755                           && cur.normalAnchor().text() == &text_)
756                         pi_.selected = row_.sel_beg <= pos && row_.sel_end > pos;
757                 paintInset(inset, pos);
758                 pi_.selected = pi_selected;
759         }
760 }
761
762
763 void RowPainter::paintText()
764 {
765         pos_type const end = row_.endpos();
766         // Spaces at logical line breaks in bidi text must be skipped during
767         // painting. However, they may appear visually in the middle
768         // of a row; they must be skipped, wherever they are...
769         // * logically "abc_[HEBREW_\nHEBREW]"
770         // * visually "abc_[_WERBEH\nWERBEH]"
771         pos_type skipped_sep_vpos = -1;
772         pos_type body_pos = par_.beginOfBody();
773         if (body_pos > 0 &&
774                 (body_pos > end || !par_.isLineSeparator(body_pos - 1))) {
775                 body_pos = 0;
776         }
777
778         Layout const & layout = par_.layout();
779
780         Change change_running;
781         int change_last_x = 0;
782
783         // check for possible inline completion
784         DocIterator const & inlineCompletionPos = pi_.base.bv->inlineCompletionPos();
785         pos_type inlineCompletionVPos = -1;
786         if (inlineCompletionPos.inTexted()
787             && inlineCompletionPos.text() == &text_
788             && inlineCompletionPos.pit() == pit_
789             && inlineCompletionPos.pos() - 1 >= row_.pos()
790             && inlineCompletionPos.pos() - 1 < row_.endpos()) {
791                 // draw logically behind the previous character
792                 inlineCompletionVPos = bidi_.log2vis(inlineCompletionPos.pos() - 1);
793         }
794
795         // Use font span to speed things up, see below
796         FontSpan font_span;
797         Font font;
798
799         // If the last logical character is a separator, don't paint it, unless
800         // it's in the last row of a paragraph; see skipped_sep_vpos declaration
801         if (end > 0 && end < par_.size() && par_.isSeparator(end - 1))
802                 skipped_sep_vpos = bidi_.log2vis(end - 1);
803
804         for (pos_type vpos = row_.pos(); vpos < end; ) {
805                 if (x_ > pi_.base.bv->workWidth())
806                         break;
807
808                 // Skip the separator at the logical end of the row
809                 if (vpos == skipped_sep_vpos) {
810                         ++vpos;
811                         continue;
812                 }
813
814                 pos_type const pos = bidi_.vis2log(vpos);
815
816                 if (pos >= par_.size()) {
817                         ++vpos;
818                         continue;
819                 }
820
821                 // Use font span to speed things up, see above
822                 if (vpos < font_span.first || vpos > font_span.last) {
823                         font_span = par_.fontSpan(vpos);
824                         font = text_metrics_.displayFont(pit_, vpos);
825
826                         // split font span if inline completion is inside
827                         if (font_span.first <= inlineCompletionVPos
828                             && font_span.last > inlineCompletionVPos)
829                                 font_span.last = inlineCompletionVPos;
830                 }
831
832                 const int width_pos = pm_.singleWidth(pos, font);
833
834                 if (x_ + width_pos < 0) {
835                         x_ += width_pos;
836                         ++vpos;
837                         continue;
838                 }
839                 Change const & change = par_.lookupChange(pos);
840                 if (change.changed() && !change_running.changed()) {
841                         change_running = change;
842                         change_last_x = int(x_);
843                 }
844
845                 Inset const * inset = par_.getInset(pos);
846                 bool const highly_editable_inset = inset
847                         && inset->editable();
848
849                 // If we reach the end of a change or if the author changes, paint it.
850                 // We also don't paint across things like tables
851                 if (change_running.changed() && (highly_editable_inset
852                         || !change.changed() || !change_running.isSimilarTo(change))) {
853                         // Calculate 1/3 height of the buffer's default font
854                         FontMetrics const & fm
855                                 = theFontMetrics(pi_.base.bv->buffer().params().getFont());
856                         int const y_bar = change_running.deleted() ?
857                                 yo_ - fm.maxAscent() / 3 : yo_ + fm.maxAscent() / 6;
858                         pi_.pain.line(change_last_x, y_bar, int(x_), y_bar,
859                                 change_running.color(), Painter::line_solid, 0.5);
860
861                         // Change might continue with a different author or type
862                         if (change.changed() && !highly_editable_inset) {
863                                 change_running = change;
864                                 change_last_x = int(x_);
865                         } else
866                                 change_running.setUnchanged();
867                 }
868
869                 if (body_pos > 0 && pos == body_pos - 1) {
870                         int const lwidth = theFontMetrics(labelFont())
871                                 .width(layout.labelsep);
872
873                         x_ += row_.label_hfill + lwidth - width_pos;
874                 }
875
876                 // Is the inline completion in front of character?
877                 if (font.isRightToLeft() && vpos == inlineCompletionVPos)
878                         paintInlineCompletion(font);
879
880                 if (par_.isSeparator(pos)) {
881                         Font const orig_font = text_metrics_.displayFont(pit_, pos);
882                         double const orig_x = x_;
883                         x_ += width_pos;
884                         if (pos >= body_pos)
885                                 x_ += row_.separator;
886                         paintForeignMark(orig_x, orig_font.language());
887                         ++vpos;
888
889                 } else if (inset) {
890                         // If outer row has changed, nested insets are repaint completely.
891                         pi_.base.bv->coordCache().insets().add(inset, int(x_), yo_);
892
893                         bool const pi_selected = pi_.selected;
894                         Cursor const & cur = pi_.base.bv->cursor();
895                         if (cur.selection() && cur.text() == &text_
896                                   && cur.normalAnchor().text() == &text_)
897                                 pi_.selected = row_.sel_beg <= pos && row_.sel_end > pos;
898                         paintInset(inset, pos);
899                         pi_.selected = pi_selected;
900                         ++vpos;
901
902                 } else {
903                         // paint as many characters as possible.
904                         paintFromPos(vpos, change_running.changed());
905                 }
906
907                 // Is the inline completion after character?
908                 if (!font.isRightToLeft() && vpos - 1 == inlineCompletionVPos)
909                         paintInlineCompletion(font);
910         }
911
912         // if we reach the end of a struck out range, paint it
913         if (change_running.changed()) {
914                 FontMetrics const & fm
915                         = theFontMetrics(pi_.base.bv->buffer().params().getFont());
916                 int const y_bar = change_running.deleted() ?
917                                 yo_ - fm.maxAscent() / 3 : yo_ + fm.maxAscent() / 6;
918                 pi_.pain.line(change_last_x, y_bar, int(x_), y_bar,
919                         change_running.color(), Painter::line_solid, 0.5);
920                 change_running.setUnchanged();
921         }
922 }
923
924
925 void RowPainter::paintSelection()
926 {
927         if (!row_.selection())
928                 return;
929         Cursor const & curs = pi_.base.bv->cursor();
930         DocIterator beg = curs.selectionBegin();
931         beg.pit() = pit_;
932         beg.pos() = row_.sel_beg;
933
934         DocIterator end = curs.selectionEnd();
935         end.pit() = pit_;
936         end.pos() = row_.sel_end;
937
938         bool const begin_boundary = beg.pos() >= row_.endpos();
939         bool const end_boundary = row_.sel_end == row_.endpos();
940
941         DocIterator cur = beg;
942         cur.boundary(begin_boundary);
943         int x1 = text_metrics_.cursorX(beg.top(), begin_boundary);
944         int x2 = text_metrics_.cursorX(end.top(), end_boundary);
945         int const y1 = yo_ - row_.ascent();
946         int const y2 = y1 + row_.height();
947
948         int const rm = text_.isMainText() ? pi_.base.bv->rightMargin() : 0;
949         int const lm = text_.isMainText() ? pi_.base.bv->leftMargin() : 0;
950
951         // draw the margins
952         if (row_.begin_margin_sel) {
953                 if (text_.isRTL(beg.paragraph())) {
954                         pi_.pain.fillRectangle(xo_ + x1, y1, text_metrics_.width() - rm - x1, y2 - y1,
955                                 Color_selection);
956                 } else {
957                         pi_.pain.fillRectangle(xo_ + lm, y1, x1 - lm, y2 - y1,
958                                 Color_selection);
959                 }
960         }
961
962         if (row_.end_margin_sel) {
963                 if (text_.isRTL(beg.paragraph())) {
964                         pi_.pain.fillRectangle(xo_ + lm, y1, x2 - lm, y2 - y1,
965                                 Color_selection);
966                 } else {
967                         pi_.pain.fillRectangle(xo_ + x2, y1, text_metrics_.width() - rm - x2, y2 - y1,
968                                 Color_selection);
969                 }
970         }
971
972         // if we are on a boundary from the beginning, it's probably
973         // a RTL boundary and we jump to the other side directly as this
974         // segement is 0-size and confuses the logic below
975         if (cur.boundary())
976                 cur.boundary(false);
977
978         // go through row and draw from RTL boundary to RTL boundary
979         while (cur < end) {
980                 bool draw_now = false;
981
982                 // simplified cursorForward code below which does not
983                 // descend into insets and which does not go into the
984                 // next line. Compare the logic with the original cursorForward
985
986                 // if left of boundary -> just jump to right side, but
987                 // for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
988                 if (cur.boundary()) {
989                         cur.boundary(false);
990                 }       else if (text_metrics_.isRTLBoundary(cur.pit(), cur.pos() + 1)) {
991                         // in front of RTL boundary -> Stay on this side of the boundary
992                         // because:  ab|cDDEEFFghi -> abc|DDEEFFghi
993                         ++cur.pos();
994                         cur.boundary(true);
995                         draw_now = true;
996                 } else {
997                         // move right
998                         ++cur.pos();
999
1000                         // line end?
1001                         if (cur.pos() == row_.endpos())
1002                                 cur.boundary(true);
1003                 }
1004
1005                 if (x1 == -1) {
1006                         // the previous segment was just drawn, now the next starts
1007                         x1 = text_metrics_.cursorX(cur.top(), cur.boundary());
1008                 }
1009
1010                 if (!(cur < end) || draw_now) {
1011                         x2 = text_metrics_.cursorX(cur.top(), cur.boundary());
1012                         pi_.pain.fillRectangle(xo_ + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
1013                                 Color_selection);
1014
1015                         // reset x1, so it is set again next round (which will be on the
1016                         // right side of a boundary or at the selection end)
1017                         x1 = -1;
1018                 }
1019         }
1020 }
1021
1022
1023 void RowPainter::paintInlineCompletion(Font const & font)
1024 {
1025         docstring completion = pi_.base.bv->inlineCompletion();
1026         FontInfo f = font.fontInfo();
1027         bool rtl = font.isRightToLeft();
1028
1029         // draw the unique and the non-unique completion part
1030         // Note: this is not time-critical as it is
1031         // only done once per screen.
1032         size_t uniqueTo = pi_.base.bv->inlineCompletionUniqueChars();
1033         docstring s1 = completion.substr(0, uniqueTo);
1034         docstring s2 = completion.substr(uniqueTo);
1035         ColorCode c1 = Color_inlinecompletion;
1036         ColorCode c2 = Color_nonunique_inlinecompletion;
1037
1038         // right to left?
1039         if (rtl) {
1040                 swap(s1, s2);
1041                 swap(c1, c2);
1042         }
1043
1044         if (s1.size() > 0) {
1045                 f.setColor(c1);
1046                 pi_.pain.text(int(x_), yo_, s1, f);
1047                 x_ += theFontMetrics(font).width(s1);
1048         }
1049
1050         if (s2.size() > 0) {
1051                 f.setColor(c2);
1052                 pi_.pain.text(int(x_), yo_, s2, f);
1053                 x_ += theFontMetrics(font).width(s2);
1054         }
1055 }
1056
1057 } // namespace lyx