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