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