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