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