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