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