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