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