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