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