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