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