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