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