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