]> git.lyx.org Git - lyx.git/blob - src/rowpainter.cpp
* src/frontends/controllers/Dialog.{cpp,h}:
[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
14 #include "rowpainter.h"
15
16 #include "Bidi.h"
17 #include "Buffer.h"
18 #include "CoordCache.h"
19 #include "Cursor.h"
20 #include "debug.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "Encoding.h"
24 #include "gettext.h"
25 #include "Language.h"
26 #include "Color.h"
27 #include "LyXRC.h"
28 #include "Row.h"
29 #include "MetricsInfo.h"
30 #include "Paragraph.h"
31 #include "ParagraphMetrics.h"
32 #include "paragraph_funcs.h"
33 #include "ParagraphParameters.h"
34 #include "TextMetrics.h"
35 #include "VSpace.h"
36
37 #include "frontends/FontMetrics.h"
38 #include "frontends/Painter.h"
39
40 #include "insets/InsetText.h"
41
42 #include "support/textutils.h"
43
44 #include <boost/crc.hpp>
45
46
47 namespace lyx {
48
49 using frontend::Painter;
50 using frontend::FontMetrics;
51
52 using std::endl;
53 using std::max;
54 using std::string;
55
56
57 namespace {
58
59 /// Flag: do a full redraw of inside text of inset
60 /// Working variable indicating a full screen refresh
61 bool refreshInside;
62
63 /**
64  * A class used for painting an individual row of text.
65  */
66 class RowPainter {
67 public:
68         /// initialise and run painter
69         RowPainter(PainterInfo & pi, Text const & text,
70                 pit_type pit, Row const & row, Bidi & bidi, int x, int y);
71
72         // paint various parts
73         void paintAppendix();
74         void paintDepthBar();
75         void paintChangeBar();
76         void paintFirst();
77         void paintLast();
78         void paintText();
79         int maxWidth() { return max_width_; }
80
81 private:
82         void paintForeignMark(double orig_x, Font const & font, int desc = 0);
83         void paintHebrewComposeChar(pos_type & vpos, Font const & font);
84         void paintArabicComposeChar(pos_type & vpos, Font const & font);
85         void paintChars(pos_type & vpos, Font const & font,
86                         bool hebrew, bool arabic);
87         int paintAppendixStart(int y);
88         void paintFromPos(pos_type & vpos);
89         void paintInset(pos_type const pos, Font const & font);
90
91         /// return left margin
92         int leftMargin() const;
93
94         /// return the label font for this row
95         Font const getLabelFont() const;
96
97         /// bufferview to paint on
98         BufferView & bv_;
99
100         /// Painter to use
101         Painter & pain_;
102
103         /// Text for the row
104         Text const & text_;
105         TextMetrics & text_metrics_;
106         ParagraphList const & pars_;
107
108         /// The row to paint
109         Row const & row_;
110
111         /// Row's paragraph
112         pit_type const pit_;
113         Paragraph const & par_;
114         ParagraphMetrics const & pm_;
115         int max_width_;
116
117         /// bidi cache, comes from outside the rowpainter because
118         /// rowpainters are normally created in a for loop and there only
119         /// one of them is active at a time.
120         Bidi & bidi_;
121
122         /// is row erased? (change tracking)
123         bool erased_;
124
125         // Looks ugly - is
126         double const xo_;
127         int const yo_;    // current baseline
128         double x_;
129         int width_;
130         double separator_;
131         double hfill_;
132         double label_hfill_;
133 };
134
135
136 RowPainter::RowPainter(PainterInfo & pi,
137         Text const & text, pit_type pit, Row const & row, Bidi & bidi, int x, int y)
138         : bv_(*pi.base.bv), pain_(pi.pain), text_(text),
139           text_metrics_(pi.base.bv->textMetrics(&text)),
140           pars_(text.paragraphs()),
141           row_(row), pit_(pit), par_(text.paragraphs()[pit]),
142           pm_(text_metrics_.parMetrics(pit)),
143           max_width_(bv_.workWidth()),
144                 bidi_(bidi), erased_(pi.erased_),
145           xo_(x), yo_(y), width_(text_metrics_.width())
146 {
147         RowMetrics m = text_metrics_.computeRowMetrics(pit_, row_);
148         bidi_.computeTables(par_, *bv_.buffer(), row_);
149         x_ = m.x + xo_;
150
151         //lyxerr << "RowPainter: x: " << x_ << " xo: " << xo_ << " yo: " << yo_ << endl;
152         //row_.dump();
153
154         separator_ = m.separator;
155         hfill_ = m.hfill;
156         label_hfill_ = m.label_hfill;
157
158         BOOST_ASSERT(pit >= 0);
159         BOOST_ASSERT(pit < int(text.paragraphs().size()));
160 }
161
162
163 Font const RowPainter::getLabelFont() const
164 {
165         return text_.getLabelFont(*bv_.buffer(), par_);
166 }
167
168
169 int RowPainter::leftMargin() const
170 {
171         return text_.leftMargin(*bv_.buffer(), max_width_, pit_, row_.pos());
172 }
173
174
175 // If you want to debug inset metrics uncomment the following line:
176 // #define DEBUG_METRICS
177 // This draws green lines around each inset.
178
179
180 void RowPainter::paintInset(pos_type const pos, Font const & font)
181 {
182         Inset const * inset = par_.getInset(pos);
183         BOOST_ASSERT(inset);
184         PainterInfo pi(const_cast<BufferView *>(&bv_), pain_);
185         // FIXME: We should always use font, see documentation of
186         // noFontChange() in Inset.h.
187         pi.base.font = inset->noFontChange() ?
188                 bv_.buffer()->params().getFont() :
189                 font;
190         pi.ltr_pos = (bidi_.level(pos) % 2 == 0);
191         pi.erased_ = erased_ || par_.isDeleted(pos);
192 #ifdef DEBUG_METRICS
193         int const x1 = int(x_);
194 #endif
195         bv_.coordCache().insets().add(inset, int(x_), yo_);
196         InsetText const * const in = inset->asTextInset();
197         // non-wide insets are painted completely. Recursive
198         bool tmp = refreshInside;
199         if (!in || !in->wide()) {
200                 refreshInside = true;
201                 LYXERR(Debug::PAINTING) << endl << "Paint inset fully" << endl;
202         }
203         if (refreshInside)
204                 inset->drawSelection(pi, int(x_), yo_);
205         inset->draw(pi, int(x_), yo_);
206         refreshInside = tmp;
207         x_ += inset->width();
208 #ifdef DEBUG_METRICS
209         Dimension dim;
210         BOOST_ASSERT(max_witdh_ > 0);
211         int right_margin = text_metrics_.rightMargin(pm_);
212         int const w = max_witdh_ - leftMargin() - right_margin;
213         MetricsInfo mi(&bv_, font, w);
214         inset->metrics(mi, dim);
215         if (inset->width() > dim.wid)
216                 lyxerr << "Error: inset " << to_ascii(inset->getInsetName())
217                        << " draw width " << inset->width()
218                        << "> metrics width " << dim.wid << "." << std::endl;
219         if (inset->ascent() > dim.asc)
220                 lyxerr << "Error: inset " << to_ascii(inset->getInsetName())
221                        << " draw ascent " << inset->ascent()
222                        << "> metrics ascent " << dim.asc << "." << std::endl;
223         if (inset->descent() > dim.des)
224                 lyxerr << "Error: inset " << to_ascii(inset->getInsetName())
225                        << " draw ascent " << inset->descent()
226                        << "> metrics descent " << dim.des << "." << std::endl;
227         BOOST_ASSERT(inset->width() <= dim.wid);
228         BOOST_ASSERT(inset->ascent() <= dim.asc);
229         BOOST_ASSERT(inset->descent() <= dim.des);
230         int const x2 = x1 + dim.wid;
231         int const y1 = yo_ + dim.des;
232         int const y2 = yo_ - dim.asc;
233         pi.pain.line(x1, y1, x1, y2, Color::green);
234         pi.pain.line(x1, y1, x2, y1, Color::green);
235         pi.pain.line(x2, y1, x2, y2, Color::green);
236         pi.pain.line(x1, y2, x2, y2, Color::green);
237 #endif
238 }
239
240
241 void RowPainter::paintHebrewComposeChar(pos_type & vpos, Font const & font)
242 {
243         pos_type pos = bidi_.vis2log(vpos);
244
245         docstring str;
246
247         // first char
248         char_type c = par_.getChar(pos);
249         str += c;
250         ++vpos;
251
252         int const width = theFontMetrics(font).width(c);
253         int dx = 0;
254
255         for (pos_type i = pos - 1; i >= 0; --i) {
256                 c = par_.getChar(i);
257                 if (!Encodings::isComposeChar_hebrew(c)) {
258                         if (isPrintableNonspace(c)) {
259                                 int const width2 = text_.singleWidth(par_, i, c,
260                                         text_.getFont(*bv_.buffer(), par_, i));
261                                 dx = (c == 0x05e8 || // resh
262                                       c == 0x05d3)   // dalet
263                                         ? width2 - width
264                                         : (width2 - width) / 2;
265                         }
266                         break;
267                 }
268         }
269
270         // Draw nikud
271         pain_.text(int(x_) + dx, yo_, str, font);
272 }
273
274
275 void RowPainter::paintArabicComposeChar(pos_type & vpos, Font const & font)
276 {
277         pos_type pos = bidi_.vis2log(vpos);
278         docstring str;
279
280         // first char
281         char_type c = par_.getChar(pos);
282         c = par_.transformChar(c, pos);
283         str += c;
284         ++vpos;
285
286         int const width = theFontMetrics(font).width(c);
287         int dx = 0;
288
289         for (pos_type i = pos - 1; i >= 0; --i) {
290                 c = par_.getChar(i);
291                 if (!Encodings::isComposeChar_arabic(c)) {
292                         if (isPrintableNonspace(c)) {
293                                 int const width2 = text_.singleWidth(par_, i, c,
294                                                 text_.getFont(*bv_.buffer(), par_, i));
295                                 dx = (width2 - width) / 2;
296                         }
297                         break;
298                 }
299         }
300         // Draw nikud
301         pain_.text(int(x_) + dx, yo_, str, font);
302 }
303
304
305 void RowPainter::paintChars(pos_type & vpos, Font const & font,
306                             bool hebrew, bool arabic)
307 {
308         // This method takes up 70% of time when typing
309         pos_type pos = bidi_.vis2log(vpos);
310         pos_type const end = row_.endpos();
311         FontSpan const font_span = par_.fontSpan(pos);
312         Change::Type const prev_change = par_.lookupChange(pos).type;
313
314         // first character
315         std::vector<char_type> str;
316         str.reserve(100);
317         str.push_back(par_.getChar(pos));
318
319         if (arabic) {
320                 char_type c = str[0];
321                 if (c == '(')
322                         c = ')';
323                 else if (c == ')')
324                         c = '(';
325                 str[0] = par_.transformChar(c, pos);
326         }
327
328         // collect as much similar chars as we can
329         for (++vpos ; vpos < end ; ++vpos) {
330                 pos = bidi_.vis2log(vpos);
331                 if (pos < font_span.first || pos > font_span.last)
332                         break;
333
334                 if (prev_change != par_.lookupChange(pos).type)
335                         break;
336
337                 char_type c = par_.getChar(pos);
338
339                 if (!isPrintableNonspace(c))
340                         break;
341
342                 /* Because we do our own bidi, at this point the strings are
343                  * already in visual order. However, Qt also applies its own
344                  * bidi algorithm to strings that it paints to the screen.
345                  * Therefore, if we were to paint Hebrew/Arabic words as a
346                  * single string, the letters in the words would get reversed
347                  * again. In order to avoid that, we don't collect Hebrew/
348                  * Arabic characters, but rather paint them one at a time.
349                  * See also http://thread.gmane.org/gmane.editors.lyx.devel/79740
350                  */
351                 if (hebrew)
352                         break;
353
354                 /* FIXME: these checks are irrelevant, since 'arabic' and
355                  * 'hebrew' alone are already going to trigger a break.
356                  * However, this should not be removed completely, because
357                  * if an alternative solution is found which allows grouping
358                  * of arabic and hebrew characters, then these breaks may have
359                  * to be re-applied.
360
361                 if (arabic && Encodings::isComposeChar_arabic(c))
362                         break;
363
364                 if (hebrew && Encodings::isComposeChar_hebrew(c))
365                         break;
366                 */
367
368                 if (arabic) {
369                         if (c == '(')
370                                 c = ')';
371                         else if (c == ')')
372                                 c = '(';
373                         c = par_.transformChar(c, pos);
374                         /* see comment in hebrew, explaining why we break */
375                         break;
376                 }
377
378                 str.push_back(c);
379         }
380
381         docstring s(&str[0], str.size());
382
383         if (prev_change != Change::UNCHANGED) {
384                 Font copy(font);
385                 if (prev_change == Change::DELETED) {
386                         copy.setColor(Color::deletedtext);
387                 } else if (prev_change == Change::INSERTED) {
388                         copy.setColor(Color::addedtext);
389                 }
390                 x_ += pain_.text(int(x_), yo_, s, copy);
391         } else {
392                 x_ += pain_.text(int(x_), yo_, s, font);
393         }
394 }
395
396
397 void RowPainter::paintForeignMark(double orig_x, Font const & font, int desc)
398 {
399         if (!lyxrc.mark_foreign_language)
400                 return;
401         if (font.language() == latex_language)
402                 return;
403         if (font.language() == bv_.buffer()->params().language)
404                 return;
405
406         int const y = yo_ + 1 + desc;
407         pain_.line(int(orig_x), y, int(x_), y, Color::language);
408 }
409
410
411 void RowPainter::paintFromPos(pos_type & vpos)
412 {
413         pos_type const pos = bidi_.vis2log(vpos);
414         Font orig_font = text_.getFont(*bv_.buffer(), par_, pos);
415
416         double const orig_x = x_;
417
418         if (par_.isInset(pos)) {
419                 paintInset(pos, orig_font);
420                 ++vpos;
421                 paintForeignMark(orig_x, orig_font,
422                         par_.getInset(pos)->descent());
423                 return;
424         }
425
426         // usual characters, no insets
427         char_type const c = par_.getChar(pos);
428
429         // special case languages
430         std::string const & lang = orig_font.language()->lang();
431         bool const hebrew = lang == "hebrew";
432         bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi" || 
433                                                 lang == "farsi";
434
435         // draw as many chars as we can
436         if ((!hebrew && !arabic)
437                 || (hebrew && !Encodings::isComposeChar_hebrew(c))
438                 || (arabic && !Encodings::isComposeChar_arabic(c))) {
439                 paintChars(vpos, orig_font, hebrew, arabic);
440         } else if (hebrew) {
441                 paintHebrewComposeChar(vpos, orig_font);
442         } else if (arabic) {
443                 paintArabicComposeChar(vpos, orig_font);
444         }
445
446         paintForeignMark(orig_x, orig_font);
447 }
448
449
450 void RowPainter::paintChangeBar()
451 {
452         pos_type const start = row_.pos();
453         pos_type end = row_.endpos();
454
455         if (par_.size() == end) {
456                 // this is the last row of the paragraph;
457                 // thus, we must also consider the imaginary end-of-par character
458                 end++;
459         }
460
461         if (start == end || !par_.isChanged(start, end))
462                 return;
463
464         int const height = text_.isLastRow(pit_, row_)
465                 ? row_.ascent()
466                 : row_.height();
467
468         pain_.fillRectangle(5, yo_ - row_.ascent(), 3, height, Color::changebar);
469 }
470
471
472 void RowPainter::paintAppendix()
473 {
474         if (!par_.params().appendix())
475                 return;
476
477         int y = yo_ - row_.ascent();
478
479         if (par_.params().startOfAppendix())
480                 y += 2 * defaultRowHeight();
481
482         pain_.line(1, y, 1, yo_ + row_.height(), Color::appendix);
483         pain_.line(width_ - 2, y, width_ - 2, yo_ + row_.height(), Color::appendix);
484 }
485
486
487 void RowPainter::paintDepthBar()
488 {
489         depth_type const depth = par_.getDepth();
490
491         if (depth <= 0)
492                 return;
493
494         depth_type prev_depth = 0;
495         if (!text_.isFirstRow(pit_, row_)) {
496                 pit_type pit2 = pit_;
497                 if (row_.pos() == 0)
498                         --pit2;
499                 prev_depth = pars_[pit2].getDepth();
500         }
501
502         depth_type next_depth = 0;
503         if (!text_.isLastRow(pit_, row_)) {
504                 pit_type pit2 = pit_;
505                 if (row_.endpos() >= pars_[pit2].size())
506                         ++pit2;
507                 next_depth = pars_[pit2].getDepth();
508         }
509
510         for (depth_type i = 1; i <= depth; ++i) {
511                 int const w = nestMargin() / 5;
512                 int x = int(xo_) + w * i;
513                 // only consider the changebar space if we're drawing outermost text
514                 if (text_.isMainText(*bv_.buffer()))
515                         x += changebarMargin();
516
517                 int const starty = yo_ - row_.ascent();
518                 int const h =  row_.height() - 1 - (i - next_depth - 1) * 3;
519
520                 pain_.line(x, starty, x, starty + h, Color::depthbar);
521
522                 if (i > prev_depth)
523                         pain_.fillRectangle(x, starty, w, 2, Color::depthbar);
524                 if (i > next_depth)
525                         pain_.fillRectangle(x, starty + h, w, 2, Color::depthbar);
526         }
527 }
528
529
530 int RowPainter::paintAppendixStart(int y)
531 {
532         Font pb_font;
533         pb_font.setColor(Color::appendix);
534         pb_font.decSize();
535
536         int w = 0;
537         int a = 0;
538         int d = 0;
539
540         docstring const label = _("Appendix");
541         theFontMetrics(pb_font).rectText(label, w, a, d);
542
543         int const text_start = int(xo_ + (width_ - w) / 2);
544         int const text_end = text_start + w;
545
546         pain_.rectText(text_start, y + d, label, pb_font, Color::none, Color::none);
547
548         pain_.line(int(xo_ + 1), y, text_start, y, Color::appendix);
549         pain_.line(text_end, y, int(xo_ + width_ - 2), y, Color::appendix);
550
551         return 3 * defaultRowHeight();
552 }
553
554
555 void RowPainter::paintFirst()
556 {
557         ParagraphParameters const & parparams = par_.params();
558
559         int y_top = 0;
560
561         // start of appendix?
562         if (parparams.startOfAppendix())
563                 y_top += paintAppendixStart(yo_ - row_.ascent() + 2 * defaultRowHeight());
564
565         Buffer const & buffer = *bv_.buffer();
566
567         Layout_ptr const & layout = par_.layout();
568
569         if (buffer.params().paragraph_separation == BufferParams::PARSEP_SKIP) {
570                 if (pit_ != 0) {
571                         if (layout->latextype == LATEX_PARAGRAPH
572                                 && !par_.getDepth()) {
573                                 y_top += buffer.params().getDefSkip().inPixels(bv_);
574                         } else {
575                                 Layout_ptr const & playout = pars_[pit_ - 1].layout();
576                                 if (playout->latextype == LATEX_PARAGRAPH
577                                         && !pars_[pit_ - 1].getDepth()) {
578                                         // is it right to use defskip here, too? (AS)
579                                         y_top += buffer.params().getDefSkip().inPixels(bv_);
580                                 }
581                         }
582                 }
583         }
584
585         bool const is_rtl = text_.isRTL(buffer, par_);
586         bool const is_seq = isFirstInSequence(pit_, text_.paragraphs());
587         //lyxerr << "paintFirst: " << par_.id() << " is_seq: " << is_seq << std::endl;
588
589         // should we print a label?
590         if (layout->labeltype >= LABEL_STATIC
591             && (layout->labeltype != LABEL_STATIC
592                       || layout->latextype != LATEX_ENVIRONMENT
593                       || is_seq)) {
594
595                 Font const font = getLabelFont();
596                 FontMetrics const & fm = theFontMetrics(font);
597
598                 docstring const str = par_.getLabelstring();
599                 if (!str.empty()) {
600                         double x = x_;
601
602                         // this is special code for the chapter layout. This is
603                         // printed in an extra row and has a pagebreak at
604                         // the top.
605                         if (layout->counter == "chapter") {
606                                 double spacing_val = 1.0;
607                                 if (!parparams.spacing().isDefault()) {
608                                         spacing_val = parparams.spacing().getValue();
609                                 } else {
610                                         spacing_val = buffer.params().spacing().getValue();
611                                 }
612
613                                 int const labeladdon = int(fm.maxHeight() * layout->spacing.getValue() * spacing_val);
614
615                                 int const maxdesc = int(fm.maxDescent() * layout->spacing.getValue() * spacing_val)
616                                         + int(layout->parsep) * defaultRowHeight();
617
618                                 if (is_rtl) {
619                                         x = width_ - leftMargin() -
620                                                 fm.width(str);
621                                 }
622
623                                 pain_.text(int(x), yo_ - maxdesc - labeladdon, str, font);
624                         } else {
625                                 // FIXME UNICODE
626                                 docstring lab = from_utf8(layout->labelsep);
627                                 if (is_rtl) {
628                                         x = width_ - leftMargin()
629                                                 + fm.width(lab);
630                                 } else {
631                                         x = x_ - fm.width(lab)
632                                                 - fm.width(str);
633                                 }
634
635                                 pain_.text(int(x), yo_, str, font);
636                         }
637                 }
638
639         // the labels at the top of an environment.
640         // More or less for bibliography
641         } else if (is_seq &&
642                 (layout->labeltype == LABEL_TOP_ENVIRONMENT ||
643                 layout->labeltype == LABEL_BIBLIO ||
644                 layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)) {
645                 Font font = getLabelFont();
646                 if (!par_.getLabelstring().empty()) {
647                         docstring const str = par_.getLabelstring();
648                         double spacing_val = 1.0;
649                         if (!parparams.spacing().isDefault())
650                                 spacing_val = parparams.spacing().getValue();
651                         else
652                                 spacing_val = buffer.params().spacing().getValue();
653
654                         FontMetrics const & fm = theFontMetrics(font);
655
656                         int const labeladdon = int(fm.maxHeight()
657                                 * layout->spacing.getValue() * spacing_val);
658
659                         int maxdesc =
660                                 int(fm.maxDescent() * layout->spacing.getValue() * spacing_val
661                                 + (layout->labelbottomsep * defaultRowHeight()));
662
663                         double x = x_;
664                         if (layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
665                                 if (is_rtl)
666                                         x = leftMargin();
667                                 x += (width_ - text_metrics_.rightMargin(pm_) - leftMargin()) / 2;
668                                 x -= fm.width(str) / 2;
669                         } else if (is_rtl) {
670                                 x = width_ - leftMargin() -     fm.width(str);
671                         }
672                         pain_.text(int(x), yo_ - maxdesc - labeladdon, str, font);
673                 }
674         }
675 }
676
677
678 void RowPainter::paintLast()
679 {
680         bool const is_rtl = text_.isRTL(*bv_.buffer(), par_);
681         int const endlabel = getEndLabel(pit_, text_.paragraphs());
682
683         // paint imaginary end-of-paragraph character
684
685         if (par_.isInserted(par_.size()) || par_.isDeleted(par_.size())) {
686                 FontMetrics const & fm = theFontMetrics(bv_.buffer()->params().getFont());
687                 int const length = fm.maxAscent() / 2;
688                 Color::color col = par_.isInserted(par_.size()) ? Color::addedtext : Color::deletedtext;
689
690                 pain_.line(int(x_) + 1, yo_ + 2, int(x_) + 1, yo_ + 2 - length, col,
691                            Painter::line_solid, Painter::line_thick);
692                 pain_.line(int(x_) + 1 - length, yo_ + 2, int(x_) + 1, yo_ + 2, col,
693                            Painter::line_solid, Painter::line_thick);
694         }
695
696         // draw an endlabel
697
698         switch (endlabel) {
699         case END_LABEL_BOX:
700         case END_LABEL_FILLED_BOX: {
701                 Font const font = getLabelFont();
702                 FontMetrics const & fm = theFontMetrics(font);
703                 int const size = int(0.75 * fm.maxAscent());
704                 int const y = yo_ - size;
705                 int x = is_rtl ? nestMargin() + changebarMargin() : width_ - size;
706
707                 if (width_ - int(row_.width()) <= size)
708                         x += (size - width_ + row_.width() + 1) * (is_rtl ? -1 : 1);
709
710                 if (endlabel == END_LABEL_BOX)
711                         pain_.rectangle(x, y, size, size, Color::eolmarker);
712                 else
713                         pain_.fillRectangle(x, y, size, size, Color::eolmarker);
714                 break;
715         }
716
717         case END_LABEL_STATIC: {
718                 Font font = getLabelFont();
719                 FontMetrics const & fm = theFontMetrics(font);
720                 docstring const & str = par_.layout()->endlabelstring();
721                 double const x = is_rtl ?
722                         x_ - fm.width(str)
723                         : - text_metrics_.rightMargin(pm_) - row_.width();
724                 pain_.text(int(x), yo_, str, font);
725                 break;
726         }
727
728         case END_LABEL_NO_LABEL:
729                 break;
730         }
731 }
732
733
734 void RowPainter::paintText()
735 {
736         pos_type const end = row_.endpos();
737         pos_type body_pos = par_.beginOfBody();
738         if (body_pos > 0 &&
739                 (body_pos > end || !par_.isLineSeparator(body_pos - 1))) {
740                 body_pos = 0;
741         }
742
743         Layout_ptr const & layout = par_.layout();
744
745         bool running_strikeout = false;
746         bool is_struckout = false;
747         int last_strikeout_x = 0;
748
749         // Use font span to speed things up, see below
750         FontSpan font_span;
751         Font font;
752         Buffer const & buffer = *bv_.buffer();
753
754         for (pos_type vpos = row_.pos(); vpos < end; ) {
755                 if (x_ > bv_.workWidth())
756                         break;
757
758                 pos_type const pos = bidi_.vis2log(vpos);
759
760                 if (pos >= par_.size()) {
761                         ++vpos;
762                         continue;
763                 }
764
765                 // Use font span to speed things up, see above
766                 if (vpos < font_span.first || vpos > font_span.last) {
767                         font_span = par_.fontSpan(vpos);
768                         font = text_.getFont(buffer, par_, vpos);
769                 }
770
771                 const int width_pos =
772                         text_.singleWidth(par_, pos, par_.getChar(pos), font);
773
774                 if (x_ + width_pos < 0) {
775                         x_ += width_pos;
776                         ++vpos;
777                         continue;
778                 }
779
780                 is_struckout = par_.isDeleted(pos);
781
782                 if (is_struckout && !running_strikeout) {
783                         running_strikeout = true;
784                         last_strikeout_x = int(x_);
785                 }
786
787                 bool const highly_editable_inset = par_.isInset(pos)
788                         && isHighlyEditableInset(par_.getInset(pos));
789
790                 // If we reach the end of a struck out range, paint it.
791                 // We also don't paint across things like tables
792                 if (running_strikeout && (highly_editable_inset || !is_struckout)) {
793                         // Calculate 1/3 height of the buffer's default font
794                         FontMetrics const & fm
795                                 = theFontMetrics(bv_.buffer()->params().getFont());
796                         int const middle = yo_ - fm.maxAscent() / 3;
797                         pain_.line(last_strikeout_x, middle, int(x_), middle,
798                                 Color::deletedtext, Painter::line_solid, Painter::line_thin);
799                         running_strikeout = false;
800                 }
801
802                 if (body_pos > 0 && pos == body_pos - 1) {
803                         // FIXME UNICODE
804                         int const lwidth = theFontMetrics(getLabelFont())
805                                 .width(from_utf8(layout->labelsep));
806
807                         x_ += label_hfill_ + lwidth - width_pos;
808                 }
809
810                 if (par_.isHfill(pos)) {
811                         x_ += 1;
812
813                         int const y0 = yo_;
814                         int const y1 = y0 - defaultRowHeight() / 2;
815
816                         pain_.line(int(x_), y1, int(x_), y0, Color::added_space);
817
818                         if (par_.hfillExpansion(row_, pos)) {
819                                 int const y2 = (y0 + y1) / 2;
820
821                                 if (pos >= body_pos) {
822                                         pain_.line(int(x_), y2, int(x_ + hfill_), y2,
823                                                   Color::added_space,
824                                                   Painter::line_onoffdash);
825                                         x_ += hfill_;
826                                 } else {
827                                         pain_.line(int(x_), y2, int(x_ + label_hfill_), y2,
828                                                   Color::added_space,
829                                                   Painter::line_onoffdash);
830                                         x_ += label_hfill_;
831                                 }
832                                 pain_.line(int(x_), y1, int(x_), y0, Color::added_space);
833                         }
834                         x_ += 2;
835                         ++vpos;
836                 } else if (par_.isSeparator(pos)) {
837                         Font orig_font = text_.getFont(*bv_.buffer(), par_, pos);
838                         double const orig_x = x_;
839                         x_ += width_pos;
840                         if (pos >= body_pos)
841                                 x_ += separator_;
842                         ++vpos;
843                         paintForeignMark(orig_x, orig_font);
844                 } else {
845                         paintFromPos(vpos);
846                 }
847         }
848
849         // if we reach the end of a struck out range, paint it
850         if (running_strikeout) {
851                 // calculate 1/3 height of the buffer's default font
852                 FontMetrics const & fm
853                         = theFontMetrics(bv_.buffer()->params().getFont());
854                 int const middle = yo_ - fm.maxAscent() / 3;
855                 pain_.line(last_strikeout_x, middle, int(x_), middle,
856                         Color::deletedtext, Painter::line_solid, Painter::line_thin);
857                 running_strikeout = false;
858         }
859 }
860
861
862 bool CursorOnRow(PainterInfo & pi, pit_type const pit,
863         RowList::const_iterator rit, Text const & text)
864 {
865         // Is there a cursor on this row (or inside inset on row)
866         Cursor & cur = pi.base.bv->cursor();
867         for (size_type d = 0; d < cur.depth(); ++d) {
868                 CursorSlice const & sl = cur[d];
869                 if (sl.text() == &text
870                     && sl.pit() == pit
871                     && sl.pos() >= rit->pos()
872                     && sl.pos() <= rit->endpos())
873                         return true;
874         }
875         return false;
876 }
877
878
879 bool innerCursorOnRow(PainterInfo & pi, pit_type pit,
880         RowList::const_iterator rit, Text const & text)
881 {
882         // Is there a cursor inside an inset on this row, and is this inset
883         // the only "character" on this row
884         Cursor & cur = pi.base.bv->cursor();
885         if (rit->pos() + 1 != rit->endpos())
886                 return false;
887         for (size_type d = 0; d < cur.depth(); d++) {
888                 CursorSlice const & sl = cur[d];
889                 if (sl.text() == &text
890                     && sl.pit() == pit
891                     && sl.pos() == rit->pos())
892                         return d < cur.depth() - 1;
893         }
894         return false;
895 }
896
897
898 // FIXME: once wide() is obsolete, remove this as well!
899 bool inNarrowInset(PainterInfo & pi)
900 {
901         // check whether the current inset is nested in a non-wide inset
902         Cursor & cur = pi.base.bv->cursor();
903         for (int i = cur.depth() - 1; --i >= 0; ) {
904                 Inset * const in = &cur[i].inset();
905                 if (in) {
906                         InsetText * t =
907                                 const_cast<InsetText *>(in->asTextInset());
908                         if (t)
909                                 return !t->wide();
910                 }
911         }
912         return false;
913 }
914
915
916 void paintPar
917         (PainterInfo & pi, Text const & text, pit_type pit, int x, int y,
918          bool repaintAll)
919 {
920 //      lyxerr << "  paintPar: pit: " << pit << " at y: " << y << endl;
921         int const ww = pi.base.bv->workHeight();
922
923         pi.base.bv->coordCache().parPos()[&text][pit] = Point(x, y);
924
925         Paragraph const & par = text.paragraphs()[pit];
926         ParagraphMetrics const & pm = pi.base.bv->parMetrics(&text, pit);
927         if (pm.rows().empty())
928                 return;
929
930         RowList::const_iterator const rb = pm.rows().begin();
931         RowList::const_iterator const re = pm.rows().end();
932
933         Bidi bidi;
934
935         y -= rb->ascent();
936         size_type rowno = 0;
937         for (RowList::const_iterator rit = rb; rit != re; ++rit, ++rowno) {
938                 y += rit->ascent();
939                 // Allow setting of refreshInside for nested insets in
940                 // this row only
941                 bool tmp = refreshInside;
942
943                 // Row signature; has row changed since last paint?
944                 bool row_has_changed = pm.rowChangeStatus()[rowno];
945
946                 bool cursor_on_row = CursorOnRow(pi, pit, rit, text);
947                 bool in_inset_alone_on_row =
948                         innerCursorOnRow(pi, pit, rit, text);
949                 bool leftEdgeFixed =
950                         (par.getAlign() == LYX_ALIGN_LEFT ||
951                          par.getAlign() == LYX_ALIGN_BLOCK);
952                 bool inNarrowIns = inNarrowInset(pi);
953
954                 // If this is the only object on the row, we can make it wide
955                 //
956                 // FIXME: there is a const_cast here because paintPar() is not supposed
957                 // to touch the paragraph contents. So either we move this "wide"
958                 // property out of InsetText or we localize the feature to the painting
959                 // done here.
960                 // JSpitzm: We should aim at removing wide() altogether while retaining
961                 // typing speed within insets.
962                 for (pos_type i = rit->pos() ; i != rit->endpos(); ++i) {
963                         Inset const * const in = par.getInset(i);
964                         if (in) {
965                                 InsetText * t = const_cast<InsetText *>(in->asTextInset());
966                                 if (t)
967                                         t->setWide(in_inset_alone_on_row
968                                                    && leftEdgeFixed
969                                                    && !inNarrowIns);
970                         }
971                 }
972
973                 // If selection is on, the current row signature differs
974                 // from cache, or cursor is inside an inset _on this row_,
975                 // then paint the row
976                 if (repaintAll || row_has_changed || cursor_on_row) {
977                         bool const inside = (y + rit->descent() >= 0
978                                 && y - rit->ascent() < ww);
979                         // it is not needed to draw on screen if we are not inside.
980                         pi.pain.setDrawingEnabled(inside);
981                         RowPainter rp(pi, text, pit, *rit, bidi, x, y);
982                         // Clear background of this row
983                         // (if paragraph background was not cleared)
984                         if (!repaintAll &&
985                             (!(in_inset_alone_on_row && leftEdgeFixed)
986                                 || row_has_changed)) {
987                                 pi.pain.fillRectangle(x, y - rit->ascent(),
988                                     rp.maxWidth(), rit->height(),
989                                     text.backgroundColor());
990                                 // If outer row has changed, force nested
991                                 // insets to repaint completely
992                                 if (row_has_changed)
993                                         refreshInside = true;
994                         }
995
996                         // Instrumentation for testing row cache (see also
997                         // 12 lines lower):
998                         if (lyxerr.debugging(Debug::PAINTING)) {
999                                 if (text.isMainText(*pi.base.bv->buffer()))
1000                                         LYXERR(Debug::PAINTING) << "#";
1001                                 else
1002                                         LYXERR(Debug::PAINTING) << "[" <<
1003                                                 repaintAll << row_has_changed <<
1004                                                 cursor_on_row << "]";
1005                         }
1006                         rp.paintAppendix();
1007                         rp.paintDepthBar();
1008                         rp.paintChangeBar();
1009                         if (rit == rb)
1010                                 rp.paintFirst();
1011                         rp.paintText();
1012                         if (rit + 1 == re)
1013                                 rp.paintLast();
1014                 }
1015                 y += rit->descent();
1016                 // Restore, see above
1017                 refreshInside = tmp;
1018         }
1019         // Re-enable screen drawing for future use of the painter.
1020         pi.pain.setDrawingEnabled(true);
1021
1022         LYXERR(Debug::PAINTING) << "." << endl;
1023 }
1024
1025 } // namespace anon
1026
1027
1028 void paintText(BufferView & bv,
1029                Painter & pain)
1030 {
1031         BOOST_ASSERT(bv.buffer());
1032         Buffer const & buffer = *bv.buffer();
1033         Text & text = buffer.text();
1034         bool const select = bv.cursor().selection();
1035         ViewMetricsInfo const & vi = bv.viewMetricsInfo();
1036
1037         PainterInfo pi(const_cast<BufferView *>(&bv), pain);
1038         // Should the whole screen, including insets, be refreshed?
1039         // FIXME: We should also distinguish DecorationUpdate to avoid text
1040         // drawing if possible. This is not possible to do easily right now
1041         // because of the single backing pixmap.
1042         bool repaintAll = select || vi.update_strategy != SingleParUpdate;
1043
1044         if (repaintAll) {
1045                 // Clear background (if not delegated to rows)
1046                 pain.fillRectangle(0, vi.y1, bv.workWidth(), vi.y2 - vi.y1,
1047                         text.backgroundColor());
1048         }
1049         if (select) {
1050                 text.drawSelection(pi, 0, 0);
1051         }
1052
1053         int yy = vi.y1;
1054         // draw contents
1055         for (pit_type pit = vi.p1; pit <= vi.p2; ++pit) {
1056                 refreshInside = repaintAll;
1057                 ParagraphMetrics const & pm = bv.parMetrics(&text, pit);
1058                 yy += pm.ascent();
1059                 paintPar(pi, text, pit, 0, yy, repaintAll);
1060                 yy += pm.descent();
1061         }
1062
1063         // and grey out above (should not happen later)
1064 //      lyxerr << "par ascent: " << text.getPar(vi.p1).ascent() << endl;
1065         if (vi.y1 > 0 && vi.update_strategy == FullScreenUpdate)
1066                 pain.fillRectangle(0, 0, bv.workWidth(), vi.y1, Color::bottomarea);
1067
1068         // and possibly grey out below
1069 //      lyxerr << "par descent: " << text.getPar(vi.p1).ascent() << endl;
1070         if (vi.y2 < bv.workHeight() && vi.update_strategy == FullScreenUpdate)
1071                 pain.fillRectangle(0, vi.y2, bv.workWidth(), bv.workHeight() - vi.y2, Color::bottomarea);
1072 }
1073
1074
1075 void paintTextInset(Text const & text, PainterInfo & pi, int x, int y)
1076 {
1077 //      lyxerr << "  paintTextInset: y: " << y << endl;
1078
1079         y -= pi.base.bv->parMetrics(&text, 0).ascent();
1080         // This flag cannot be set from within same inset:
1081         bool repaintAll = refreshInside;
1082         for (int pit = 0; pit < int(text.paragraphs().size()); ++pit) {
1083                 ParagraphMetrics const & pmi
1084                         = pi.base.bv->parMetrics(&text, pit);
1085                 y += pmi.ascent();
1086                 paintPar(pi, text, pit, x, y, repaintAll);
1087                 y += pmi.descent();
1088         }
1089 }
1090
1091
1092 } // namespace lyx