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