]> git.lyx.org Git - lyx.git/blob - src/TextMetrics.cpp
Fix wrapping bug within inset. dim_.wid was not set!
[lyx.git] / src / TextMetrics.cpp
1 /**
2  * \file src/TextMetrics.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Jürgen Vigna
13  * \author Abdelrazak Younes
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "TextMetrics.h"
21
22 #include "Buffer.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "bufferview_funcs.h"
26 #include "Color.h"
27 #include "CoordCache.h"
28 #include "debug.h"
29 #include "FontIterator.h"
30 #include "FuncRequest.h"
31 #include "Length.h"
32 #include "LyXRC.h"
33 #include "MetricsInfo.h"
34 #include "paragraph_funcs.h"
35 #include "ParagraphParameters.h"
36 #include "ParIterator.h"
37 #include "rowpainter.h"
38 #include "Text.h"
39 #include "VSpace.h"
40
41 #include "frontends/FontMetrics.h"
42 #include "frontends/Painter.h"
43
44 #include <boost/current_function.hpp>
45
46 using std::max;
47 using std::min;
48 using std::endl;
49
50 namespace lyx {
51
52 using frontend::FontMetrics;
53
54 namespace {
55
56 int numberOfSeparators(Paragraph const & par, Row const & row)
57 {
58         pos_type const first = max(row.pos(), par.beginOfBody());
59         pos_type const last = row.endpos() - 1;
60         int n = 0;
61         for (pos_type p = first; p < last; ++p) {
62                 if (par.isSeparator(p))
63                         ++n;
64         }
65         return n;
66 }
67
68
69 int numberOfLabelHfills(Paragraph const & par, Row const & row)
70 {
71         pos_type last = row.endpos() - 1;
72         pos_type first = row.pos();
73
74         // hfill *DO* count at the beginning of paragraphs!
75         if (first) {
76                 while (first < last && par.isHfill(first))
77                         ++first;
78         }
79
80         last = min(last, par.beginOfBody());
81         int n = 0;
82         for (pos_type p = first; p < last; ++p) {
83                 if (par.isHfill(p))
84                         ++n;
85         }
86         return n;
87 }
88
89
90 int numberOfHfills(Paragraph const & par, Row const & row)
91 {
92         pos_type const last = row.endpos();
93         pos_type first = row.pos();
94
95         // hfill *DO* count at the beginning of paragraphs!
96         if (first) {
97                 while (first < last && par.isHfill(first))
98                         ++first;
99         }
100
101         first = max(first, par.beginOfBody());
102
103         int n = 0;
104         for (pos_type p = first; p < last; ++p) {
105                 if (par.isHfill(p))
106                         ++n;
107         }
108         return n;
109 }
110
111 } // namespace anon
112
113 TextMetrics::TextMetrics(BufferView * bv, Text * text)
114         : bv_(bv), text_(text)
115 {
116         BOOST_ASSERT(bv_);
117         max_width_ = bv_->workWidth();
118         dim_.wid = max_width_;
119         dim_.asc = 10;
120         dim_.des = 10;
121
122         //text_->updateLabels(bv->buffer());
123 }
124
125
126 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
127 {
128         return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
129 }
130
131
132 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit,
133                 bool redo)
134 {
135         ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
136         if (pmc_it == par_metrics_.end()) {
137                 pmc_it = par_metrics_.insert(
138                         std::make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
139         }
140         if (pmc_it->second.rows().empty() && redo) {
141                 redoParagraph(pit);
142         }
143         return pmc_it->second;
144 }
145
146
147 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim)
148 {
149         BOOST_ASSERT(mi.base.textwidth);
150         max_width_ = mi.base.textwidth;
151         dim_.wid = max_width_;
152
153         lyxerr << "Text::metrics: width: " << mi.base.textwidth
154                 << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
155
156         bool changed = false;
157
158         unsigned int h = 0;
159         unsigned int w = 0;
160         for (pit_type pit = 0, n = text_->paragraphs().size(); pit != n; ++pit) {
161                 changed |= redoParagraph(pit);
162                 ParagraphMetrics const & pm = par_metrics_[pit];
163                 h += pm.height();
164                 if (w < pm.width())
165                         w = pm.width();
166         }
167
168         dim.wid = w;
169         dim.asc = par_metrics_[0].ascent();
170         dim.des = h - dim.asc;
171
172         changed |= dim_ != dim;
173         dim_ = dim;
174         return changed;
175 }
176
177
178 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
179 {
180         return main_text_? pm.rightMargin(bv_->buffer()) : 0;
181 }
182
183
184 int TextMetrics::rightMargin(pit_type const pit) const
185 {
186         return main_text_? par_metrics_[pit].rightMargin(bv_->buffer()) : 0;
187 }
188
189
190 bool TextMetrics::redoParagraph(pit_type const pit)
191 {
192         Paragraph & par = text_->getPar(pit);
193         // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
194         // redoParagraph() recursively inside parMetrics.
195         Dimension old_dim = parMetrics(pit, false).dim();
196         ParagraphMetrics & pm = par_metrics_[pit];
197         pm.reset(par);
198
199         Buffer & buffer = bv_->buffer();
200         BufferParams const & bparams = buffer.params();
201         main_text_ = (text_ == &buffer.text());
202         bool changed = false;
203
204         // FIXME This check ought to be done somewhere else. It is the reason
205         // why text_ is not     const. But then, where else to do it?
206         // Well, how can you end up with either (a) a biblio environment that
207         // has no InsetBibitem or (b) a biblio environment with more than one
208         // InsetBibitem? I think the answer is: when paragraphs are merged;
209         // when layout is set; when material is pasted.
210         int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
211         if (moveCursor > 0)
212                 const_cast<Cursor &>(bv_->cursor()).posRight();
213         else if (moveCursor < 0) {
214                 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
215                 if (cursor.pos() >= -moveCursor)
216                         cursor.posLeft();
217         }
218
219         // Optimisation: this is used in the next two loops
220         // so better to calculate that once here.
221         int const right_margin = rightMargin(pm);
222
223         // redo insets
224         // FIXME: We should always use getFont(), see documentation of
225         // noFontChange() in Inset.h.
226         Font const bufferfont = buffer.params().getFont();
227         InsetList::const_iterator ii = par.insetlist.begin();
228         InsetList::const_iterator iend = par.insetlist.end();
229         for (; ii != iend; ++ii) {
230                 Dimension old_dim = ii->inset->dimension();
231                 Dimension dim;
232                 int const w = max_width_ - text_->leftMargin(buffer, max_width_, pit, ii->pos)
233                         - right_margin;
234                 Font const & font = ii->inset->noFontChange() ?
235                         bufferfont : text_->getFont(buffer, par, ii->pos);
236                 MetricsInfo mi(bv_, font, w);
237                 changed |= ii->inset->metrics(mi, dim);
238                 changed |= (old_dim != dim);
239         }
240
241         par.setBeginOfBody();
242         pos_type first = 0;
243         size_t row_index = 0;
244         // maximum pixel width of a row
245         int width = max_width_ - right_margin; // - leftMargin(buffer, max_width_, pit, row);
246         do {
247                 Dimension dim;
248                 pos_type end = rowBreakPoint(width, pit, first);
249                 dim.wid = rowWidth(right_margin, pit, first, end);
250                 boost::tie(dim.asc, dim.des) = rowHeight(pit, first, end);
251                 if (row_index == pm.rows().size())
252                         pm.rows().push_back(Row());
253                 Row & row = pm.rows()[row_index];
254                 row.setChanged(false);
255                 row.pos(first);
256                 row.endpos(end);
257                 row.setDimension(dim);
258                 computeRowMetrics(pit, row);
259                 pm.computeRowSignature(row, bparams);
260                 first = end;
261                 ++row_index;
262
263                 pm.dim().wid = std::max(pm.dim().wid, dim.wid);
264                 pm.dim().des += dim.height();
265         } while (first < par.size());
266
267         if (row_index < pm.rows().size())
268                 pm.rows().resize(row_index);
269
270         // Make sure that if a par ends in newline, there is one more row
271         // under it
272         if (first > 0 && par.isNewline(first - 1)) {
273                 Dimension dim;
274                 dim.wid = rowWidth(right_margin, pit, first, first);
275                 boost::tie(dim.asc, dim.des) = rowHeight(pit, first, first);
276                 if (row_index == pm.rows().size())
277                         pm.rows().push_back(Row());
278                 Row & row = pm.rows()[row_index];
279                 row.setChanged(false);
280                 row.pos(first);
281                 row.endpos(first);
282                 row.setDimension(dim);
283                 computeRowMetrics(pit, row);
284                 pm.computeRowSignature(row, bparams);
285                 pm.dim().des += dim.height();
286         }
287
288         pm.dim().asc += pm.rows()[0].ascent();
289         pm.dim().des -= pm.rows()[0].ascent();
290
291         changed |= old_dim.height() != pm.dim().height();
292
293         return changed;
294 }
295
296 void TextMetrics::computeRowMetrics(pit_type const pit,
297                 Row & row) const
298 {
299         Buffer & buffer = bv_->buffer();
300         Paragraph const & par = text_->getPar(pit);
301
302         double w = dim_.wid - row.width();
303         //lyxerr << "\ndim_.wid " << dim_.wid << endl;
304         //lyxerr << "row.width() " << row.width() << endl;
305         //lyxerr << "w " << w << endl;
306
307         bool const is_rtl = text_->isRTL(buffer, par);
308         if (is_rtl)
309                 row.x = rightMargin(pit);
310         else
311                 row.x = text_->leftMargin(buffer, max_width_, pit, row.pos());
312
313         // is there a manual margin with a manual label
314         LayoutPtr const & layout = par.layout();
315
316         if (layout->margintype == MARGIN_MANUAL
317             && layout->labeltype == LABEL_MANUAL) {
318                 /// We might have real hfills in the label part
319                 int nlh = numberOfLabelHfills(par, row);
320
321                 // A manual label par (e.g. List) has an auto-hfill
322                 // between the label text and the body of the
323                 // paragraph too.
324                 // But we don't want to do this auto hfill if the par
325                 // is empty.
326                 if (!par.empty())
327                         ++nlh;
328
329                 if (nlh && !par.getLabelWidthString().empty())
330                         row.label_hfill = labelFill(pit, row) / double(nlh);
331         }
332
333         // are there any hfills in the row?
334         int const nh = numberOfHfills(par, row);
335
336         if (nh) {
337                 if (w > 0)
338                         row.hfill = w / nh;
339         // we don't have to look at the alignment if it is ALIGN_LEFT and
340         // if the row is already larger then the permitted width as then
341         // we force the LEFT_ALIGN'edness!
342         } else if (int(row.width()) < max_width_) {
343                 // is it block, flushleft or flushright?
344                 // set x how you need it
345                 int align;
346                 if (par.params().align() == LYX_ALIGN_LAYOUT)
347                         align = layout->align;
348                 else
349                         align = par.params().align();
350
351                 // Display-style insets should always be on a centred row
352                 // The test on par.size() is to catch zero-size pars, which
353                 // would trigger the assert in Paragraph::getInset().
354                 //inset = par.size() ? par.getInset(row.pos()) : 0;
355                 if (row.pos() < par.size()
356                     && par.isInset(row.pos()))
357                 {
358                     switch(par.getInset(row.pos())->display()) {
359                         case Inset::AlignLeft:
360                                 align = LYX_ALIGN_BLOCK;
361                                 break;
362                         case Inset::AlignCenter:
363                                 align = LYX_ALIGN_CENTER;
364                                 break;
365                         case Inset::Inline:
366                         case Inset::AlignRight:
367                                 // unchanged (use align)
368                                 break;
369                     }
370                 }
371
372                 switch (align) {
373                 case LYX_ALIGN_BLOCK: {
374                         int const ns = numberOfSeparators(par, row);
375                         bool disp_inset = false;
376                         if (row.endpos() < par.size()) {
377                                 Inset const * in = par.getInset(row.endpos());
378                                 if (in)
379                                         disp_inset = in->display();
380                         }
381                         // If we have separators, this is not the last row of a
382                         // par, does not end in newline, and is not row above a
383                         // display inset... then stretch it
384                         if (ns
385                             && row.endpos() < par.size()
386                             && !par.isNewline(row.endpos() - 1)
387                             && !disp_inset
388                                 ) {
389                                 row.separator = w / ns;
390                                 //lyxerr << "row.separator " << row.separator << endl;
391                                 //lyxerr << "ns " << ns << endl;
392                         } else if (is_rtl) {
393                                 row.x += w;
394                         }
395                         break;
396                 }
397                 case LYX_ALIGN_RIGHT:
398                         row.x += w;
399                         break;
400                 case LYX_ALIGN_CENTER:
401                         row.x += w / 2;
402                         break;
403                 }
404         }
405
406         if (is_rtl) {
407                 pos_type body_pos = par.beginOfBody();
408                 pos_type end = row.endpos();
409
410                 if (body_pos > 0
411                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
412                 {
413                         row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
414                                 width(layout->labelsep);
415                         if (body_pos <= end)
416                                 row.x += row.label_hfill;
417                 }
418         }
419 }
420
421
422 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
423 {
424         Buffer & buffer = bv_->buffer();
425         Paragraph const & par = text_->getPar(pit);
426
427         pos_type last = par.beginOfBody();
428         BOOST_ASSERT(last > 0);
429
430         // -1 because a label ends with a space that is in the label
431         --last;
432
433         // a separator at this end does not count
434         if (par.isLineSeparator(last))
435                 --last;
436
437         int w = 0;
438         for (pos_type i = row.pos(); i <= last; ++i)
439                 w += singleWidth(pit, i);
440
441         docstring const & label = par.params().labelWidthString();
442         if (label.empty())
443                 return 0;
444
445         FontMetrics const & fm
446                 = theFontMetrics(text_->getLabelFont(buffer, par));
447
448         return max(0, fm.width(label) - w);
449 }
450
451
452 namespace {
453
454 // this needs special handling - only newlines count as a break point
455 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
456 {
457         pos_type const end = par.size();
458
459         for (; i < end; ++i)
460                 if (par.isNewline(i))
461                         return i + 1;
462
463         return end;
464 }
465
466 };
467
468
469 int TextMetrics::labelEnd(pit_type const pit) const
470 {
471         // labelEnd is only needed if the layout fills a flushleft label.
472         if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
473                 return 0;
474         // return the beginning of the body
475         return text_->leftMargin(bv_->buffer(), max_width_, pit);
476 }
477
478
479 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
480                 pit_type pos) const
481 {
482         Buffer & buffer = bv_->buffer();
483         ParagraphMetrics const & pm = par_metrics_[pit];
484         Paragraph const & par = text_->getPar(pit);
485         pos_type const end = par.size();
486         if (pos == end || width < 0)
487                 return end;
488
489         LayoutPtr const & layout = par.layout();
490
491         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
492                 return addressBreakPoint(pos, par);
493
494         pos_type const body_pos = par.beginOfBody();
495
496
497         // Now we iterate through until we reach the right margin
498         // or the end of the par, then choose the possible break
499         // nearest that.
500
501         int label_end = labelEnd(pit);
502         int const left = text_->leftMargin(buffer, max_width_, pit, pos);
503         int x = left;
504
505         // pixel width since last breakpoint
506         int chunkwidth = 0;
507
508         FontIterator fi = FontIterator(buffer, *text_, par, pos);
509         pos_type point = end;
510         pos_type i = pos;
511         for ( ; i < end; ++i, ++fi) {
512                 int thiswidth = pm.singleWidth(i, *fi);
513
514                 // add the auto-hfill from label end to the body
515                 if (body_pos && i == body_pos) {
516                         FontMetrics const & fm = theFontMetrics(
517                                 text_->getLabelFont(buffer, par));
518                         int add = fm.width(layout->labelsep);
519                         if (par.isLineSeparator(i - 1))
520                                 add -= singleWidth(pit, i - 1);
521
522                         add = std::max(add, label_end - x);
523                         thiswidth += add;
524                 }
525
526                 x += thiswidth;
527                 chunkwidth += thiswidth;
528
529                 // break before a character that will fall off
530                 // the right of the row
531                 if (x >= width) {
532                         // if no break before, break here
533                         if (point == end || chunkwidth >= width - left) {
534                                 if (i > pos)
535                                         point = i;
536                                 else
537                                         point = i + 1;
538
539                         }
540                         // exit on last registered breakpoint:
541                         break;
542                 }
543
544                 if (par.isNewline(i)) {
545                         point = i + 1;
546                         break;
547                 }
548                 // Break before...
549                 if (i + 1 < end) {
550                         if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
551                                 point = i + 1;
552                                 break;
553                         }
554                         // ...and after.
555                         if (par.isInset(i) && par.getInset(i)->display()) {
556                                 point = i + 1;
557                                 break;
558                         }
559                 }
560
561                 if (!par.isInset(i) || par.getInset(i)->isChar()) {
562                         // some insets are line separators too
563                         if (par.isLineSeparator(i)) {
564                                 // register breakpoint:
565                                 point = i + 1;
566                                 chunkwidth = 0;
567                         }
568                 }
569         }
570
571         // maybe found one, but the par is short enough.
572         if (i == end && x < width)
573                 point = end;
574
575         // manual labels cannot be broken in LaTeX. But we
576         // want to make our on-screen rendering of footnotes
577         // etc. still break
578         if (body_pos && point < body_pos)
579                 point = body_pos;
580
581         return point;
582 }
583
584
585 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
586                 pos_type const first, pos_type const end) const
587 {
588         Buffer & buffer = bv_->buffer();
589         // get the pure distance
590         ParagraphMetrics const & pm = par_metrics_[pit];
591         Paragraph const & par = text_->getPar(pit);
592         int w = text_->leftMargin(buffer, max_width_, pit, first);
593         int label_end = labelEnd(pit);
594
595         pos_type const body_pos = par.beginOfBody();
596         pos_type i = first;
597
598         if (i < end) {
599                 FontIterator fi = FontIterator(buffer, *text_, par, i);
600                 for ( ; i < end; ++i, ++fi) {
601                         if (body_pos > 0 && i == body_pos) {
602                                 FontMetrics const & fm = theFontMetrics(
603                                         text_->getLabelFont(buffer, par));
604                                 w += fm.width(par.layout()->labelsep);
605                                 if (par.isLineSeparator(i - 1))
606                                         w -= singleWidth(pit, i - 1);
607                                 w = max(w, label_end);
608                         }
609                         w += pm.singleWidth(i, *fi);
610                 }
611         }
612
613         if (body_pos > 0 && body_pos >= end) {
614                 FontMetrics const & fm = theFontMetrics(
615                         text_->getLabelFont(buffer, par));
616                 w += fm.width(par.layout()->labelsep);
617                 if (end > 0 && par.isLineSeparator(end - 1))
618                         w -= singleWidth(pit, end - 1);
619                 w = max(w, label_end);
620         }
621
622         return w + right_margin;
623 }
624
625
626 boost::tuple<int, int> TextMetrics::rowHeight(pit_type const pit, pos_type const first,
627                 pos_type const end) const
628 {
629         Paragraph const & par = text_->getPar(pit);
630         // get the maximum ascent and the maximum descent
631         double layoutasc = 0;
632         double layoutdesc = 0;
633         double const dh = defaultRowHeight();
634
635         // ok, let us initialize the maxasc and maxdesc value.
636         // Only the fontsize count. The other properties
637         // are taken from the layoutfont. Nicer on the screen :)
638         LayoutPtr const & layout = par.layout();
639
640         // as max get the first character of this row then it can
641         // increase but not decrease the height. Just some point to
642         // start with so we don't have to do the assignment below too
643         // often.
644         Buffer const & buffer = bv_->buffer();
645         Font font = text_->getFont(buffer, par, first);
646         Font::FONT_SIZE const tmpsize = font.size();
647         font = text_->getLayoutFont(buffer, pit);
648         Font::FONT_SIZE const size = font.size();
649         font.setSize(tmpsize);
650
651         Font labelfont = text_->getLabelFont(buffer, par);
652
653         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
654         FontMetrics const & fontmetrics = theFontMetrics(font);
655
656         // these are minimum values
657         double const spacing_val = layout->spacing.getValue()
658                 * text_->spacing(buffer, par);
659         //lyxerr << "spacing_val = " << spacing_val << endl;
660         int maxasc  = int(fontmetrics.maxAscent()  * spacing_val);
661         int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
662
663         // insets may be taller
664         InsetList::const_iterator ii = par.insetlist.begin();
665         InsetList::const_iterator iend = par.insetlist.end();
666         for ( ; ii != iend; ++ii) {
667                 if (ii->pos >= first && ii->pos < end) {
668                         maxasc  = max(maxasc,  ii->inset->ascent());
669                         maxdesc = max(maxdesc, ii->inset->descent());
670                 }
671         }
672
673         // Check if any custom fonts are larger (Asger)
674         // This is not completely correct, but we can live with the small,
675         // cosmetic error for now.
676         int labeladdon = 0;
677
678         Font::FONT_SIZE maxsize =
679                 par.highestFontInRange(first, end, size);
680         if (maxsize > font.size()) {
681                 // use standard paragraph font with the maximal size
682                 Font maxfont = font;
683                 maxfont.setSize(maxsize);
684                 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
685                 maxasc  = max(maxasc,  maxfontmetrics.maxAscent());
686                 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
687         }
688
689         // This is nicer with box insets:
690         ++maxasc;
691         ++maxdesc;
692
693         ParagraphList const & pars = text_->paragraphs();
694
695         // is it a top line?
696         if (first == 0) {
697                 BufferParams const & bufparams = buffer.params();
698                 // some parskips VERY EASY IMPLEMENTATION
699                 if (bufparams.paragraph_separation
700                     == BufferParams::PARSEP_SKIP
701                         && par.ownerCode() != Inset::ERT_CODE
702                         && par.ownerCode() != Inset::LISTINGS_CODE
703                         && pit > 0
704                         && ((layout->isParagraph() && par.getDepth() == 0)
705                             || (pars[pit - 1].layout()->isParagraph()
706                                 && pars[pit - 1].getDepth() == 0)))
707                 {
708                                 maxasc += bufparams.getDefSkip().inPixels(*bv_);
709                 }
710
711                 if (par.params().startOfAppendix())
712                         maxasc += int(3 * dh);
713
714                 // This is special code for the chapter, since the label of this
715                 // layout is printed in an extra row
716                 if (layout->counter == "chapter"
717                     && !par.params().labelString().empty()) {
718                         labeladdon = int(labelfont_metrics.maxHeight()
719                                      * layout->spacing.getValue()
720                                      * text_->spacing(buffer, par));
721                 }
722
723                 // special code for the top label
724                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
725                      || layout->labeltype == LABEL_BIBLIO
726                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
727                     && isFirstInSequence(pit, pars)
728                     && !par.getLabelstring().empty())
729                 {
730                         labeladdon = int(
731                                   labelfont_metrics.maxHeight()
732                                         * layout->spacing.getValue()
733                                         * text_->spacing(buffer, par)
734                                 + (layout->topsep + layout->labelbottomsep) * dh);
735                 }
736
737                 // Add the layout spaces, for example before and after
738                 // a section, or between the items of a itemize or enumerate
739                 // environment.
740
741                 pit_type prev = depthHook(pit, pars, par.getDepth());
742                 Paragraph const & prevpar = pars[prev];
743                 if (prev != pit
744                     && prevpar.layout() == layout
745                     && prevpar.getDepth() == par.getDepth()
746                     && prevpar.getLabelWidthString()
747                                         == par.getLabelWidthString()) {
748                         layoutasc = layout->itemsep * dh;
749                 } else if (pit != 0 || first != 0) {
750                         if (layout->topsep > 0)
751                                 layoutasc = layout->topsep * dh;
752                 }
753
754                 prev = outerHook(pit, pars);
755                 if (prev != pit_type(pars.size())) {
756                         maxasc += int(pars[prev].layout()->parsep * dh);
757                 } else if (pit != 0) {
758                         Paragraph const & prevpar = pars[pit - 1];
759                         if (prevpar.getDepth() != 0 ||
760                                         prevpar.layout() == layout) {
761                                 maxasc += int(layout->parsep * dh);
762                         }
763                 }
764         }
765
766         // is it a bottom line?
767         if (end >= par.size()) {
768                 // add the layout spaces, for example before and after
769                 // a section, or between the items of a itemize or enumerate
770                 // environment
771                 pit_type nextpit = pit + 1;
772                 if (nextpit != pit_type(pars.size())) {
773                         pit_type cpit = pit;
774                         double usual = 0;
775                         double unusual = 0;
776
777                         if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
778                                 usual = pars[cpit].layout()->bottomsep * dh;
779                                 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
780                                 if (pars[cpit].layout() != pars[nextpit].layout()
781                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
782                                 {
783                                         unusual = pars[cpit].layout()->bottomsep * dh;
784                                 }
785                                 layoutdesc = max(unusual, usual);
786                         } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
787                                 if (pars[cpit].layout() != pars[nextpit].layout()
788                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
789                                         layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
790                         }
791                 }
792         }
793
794         // incalculate the layout spaces
795         maxasc  += int(layoutasc  * 2 / (2 + pars[pit].getDepth()));
796         maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
797
798         // FIXME: the correct way is to do the following is to move the
799         // following code in another method specially tailored for the
800         // main Text. The following test is thus bogus.
801         // Top and bottom margin of the document (only at top-level)
802         if (main_text_) {
803                 if (pit == 0 && first == 0)
804                         maxasc += 20;
805                 if (pit + 1 == pit_type(pars.size()) &&
806                     end == par.size() &&
807                                 !(end > 0 && par.isNewline(end - 1)))
808                         maxdesc += 20;
809         }
810
811         return boost::make_tuple(maxasc + labeladdon, maxdesc);
812 }
813
814
815 // x is an absolute screen coord
816 // returns the column near the specified x-coordinate of the row
817 // x is set to the real beginning of this column
818 pos_type TextMetrics::getColumnNearX(pit_type const pit,
819                 Row const & row, int & x, bool & boundary) const
820 {
821         Buffer const & buffer = bv_->buffer();
822
823         /// For the main Text, it is possible that this pit is not
824         /// yet in the CoordCache when moving cursor up.
825         /// x Paragraph coordinate is always 0 for main text anyway.
826         int const xo = main_text_? 0 : bv_->coordCache().get(text_, pit).x_;
827         x -= xo;
828         Paragraph const & par = text_->getPar(pit);
829         ParagraphMetrics const & pm = par_metrics_[pit];
830         Bidi bidi;
831         bidi.computeTables(par, buffer, row);
832
833         pos_type vc = row.pos();
834         pos_type end = row.endpos();
835         pos_type c = 0;
836         LayoutPtr const & layout = par.layout();
837
838         bool left_side = false;
839
840         pos_type body_pos = par.beginOfBody();
841
842         double tmpx = row.x;
843         double last_tmpx = tmpx;
844
845         if (body_pos > 0 &&
846             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
847                 body_pos = 0;
848
849         // check for empty row
850         if (vc == end) {
851                 x = int(tmpx) + xo;
852                 return 0;
853         }
854
855         while (vc < end && tmpx <= x) {
856                 c = bidi.vis2log(vc);
857                 last_tmpx = tmpx;
858                 if (body_pos > 0 && c == body_pos - 1) {
859                         FontMetrics const & fm = theFontMetrics(
860                                 text_->getLabelFont(buffer, par));
861                         tmpx += row.label_hfill + fm.width(layout->labelsep);
862                         if (par.isLineSeparator(body_pos - 1))
863                                 tmpx -= singleWidth(pit, body_pos - 1);
864                 }
865
866                 if (pm.hfillExpansion(row, c)) {
867                         tmpx += singleWidth(pit, c);
868                         if (c >= body_pos)
869                                 tmpx += row.hfill;
870                         else
871                                 tmpx += row.label_hfill;
872                 } else if (par.isSeparator(c)) {
873                         tmpx += singleWidth(pit, c);
874                         if (c >= body_pos)
875                                 tmpx += row.separator;
876                 } else {
877                         tmpx += singleWidth(pit, c);
878                 }
879                 ++vc;
880         }
881
882         if ((tmpx + last_tmpx) / 2 > x) {
883                 tmpx = last_tmpx;
884                 left_side = true;
885         }
886
887         BOOST_ASSERT(vc <= end);  // This shouldn't happen.
888
889         boundary = false;
890         // This (rtl_support test) is not needed, but gives
891         // some speedup if rtl_support == false
892         bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
893
894         // If lastrow is false, we don't need to compute
895         // the value of rtl.
896         bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
897         if (lastrow &&
898             ((rtl  &&  left_side && vc == row.pos() && x < tmpx - 5) ||
899              (!rtl && !left_side && vc == end  && x > tmpx + 5)))
900                 c = end;
901         else if (vc == row.pos()) {
902                 c = bidi.vis2log(vc);
903                 if (bidi.level(c) % 2 == 1)
904                         ++c;
905         } else {
906                 c = bidi.vis2log(vc - 1);
907                 bool const rtl = (bidi.level(c) % 2 == 1);
908                 if (left_side == rtl) {
909                         ++c;
910                         boundary = text_->isRTLBoundary(buffer, par, c);
911                 }
912         }
913
914 // I believe this code is not needed anymore (Jug 20050717)
915 #if 0
916         // The following code is necessary because the cursor position past
917         // the last char in a row is logically equivalent to that before
918         // the first char in the next row. That's why insets causing row
919         // divisions -- Newline and display-style insets -- must be treated
920         // specially, so cursor up/down doesn't get stuck in an air gap -- MV
921         // Newline inset, air gap below:
922         if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
923                 if (bidi.level(end -1) % 2 == 0)
924                         tmpx -= singleWidth(pit, end - 1);
925                 else
926                         tmpx += singleWidth(pit, end - 1);
927                 c = end - 1;
928         }
929
930         // Air gap above display inset:
931         if (row.pos() < end && c >= end && end < par.size()
932             && par.isInset(end) && par.getInset(end)->display()) {
933                 c = end - 1;
934         }
935         // Air gap below display inset:
936         if (row.pos() < end && c >= end && par.isInset(end - 1)
937             && par.getInset(end - 1)->display()) {
938                 c = end - 1;
939         }
940 #endif
941
942         x = int(tmpx) + xo;
943         pos_type const col = c - row.pos();
944
945         if (!c || end == par.size())
946                 return col;
947
948         if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
949                 boundary = true;
950                 return col;
951         }
952
953         return min(col, end - 1 - row.pos());
954 }
955
956
957 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
958 {
959         ParagraphMetrics const & pm = par_metrics_[pit];
960         BOOST_ASSERT(!pm.rows().empty());
961         BOOST_ASSERT(row < int(pm.rows().size()));
962         bool bound = false;
963         Row const & r = pm.rows()[row];
964         return r.pos() + getColumnNearX(pit, r, x, bound);
965 }
966
967
968 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
969 {
970         Buffer const & buffer = bv_->buffer();
971         ParagraphMetrics const & pm = par_metrics_[pit];
972
973         return pm.singleWidth(pos, text_->getFont(buffer, text_->getPar(pit), pos));
974 }
975
976
977 // only used for inset right now. should also be used for main text
978 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
979 {
980         if (par_metrics_.empty())
981                 return;
982
983         ParMetricsCache::const_iterator it = par_metrics_.begin();
984         ParMetricsCache::const_iterator const end = par_metrics_.end();
985         y -= it->second.ascent();
986         for (; it != end; ++it) {
987                 ParagraphMetrics const & pmi = it->second;
988                 y += pmi.ascent();
989                 drawParagraph(pi, it->first, x, y);
990                 y += pmi.descent();
991         }
992 }
993
994
995 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
996 {
997 //      lyxerr << "  paintPar: pit: " << pit << " at y: " << y << endl;
998         int const ww = bv_->workHeight();
999
1000         bv_->coordCache().parPos()[text_][pit] = Point(x, y);
1001
1002         ParagraphMetrics const & pm = par_metrics_[pit];
1003         if (pm.rows().empty())
1004                 return;
1005
1006         RowList::const_iterator const rb = pm.rows().begin();
1007         RowList::const_iterator const re = pm.rows().end();
1008
1009         Bidi bidi;
1010
1011         y -= rb->ascent();
1012         for (RowList::const_iterator rit = rb; rit != re; ++rit) {
1013                 y += rit->ascent();
1014
1015                 bool const inside = (y + rit->descent() >= 0
1016                         && y - rit->ascent() < ww);
1017                 // it is not needed to draw on screen if we are not inside.
1018                 pi.pain.setDrawingEnabled(inside);
1019                 RowPainter rp(pi, *text_, pit, *rit, bidi, x, y);
1020
1021                 // Row signature; has row changed since last paint?
1022                 bool row_has_changed = rit->changed();
1023                 
1024                 if (!pi.full_repaint && !row_has_changed) {
1025                         // Paint the only the insets if the text itself is
1026                         // unchanged.
1027                         rp.paintOnlyInsets();
1028                         y += rit->descent();
1029                         continue;
1030                 }
1031
1032                 // Paint the row if a full repaint has been requested or it has
1033                 // changed.
1034                 // Clear background of this row
1035                 // (if paragraph background was not cleared)
1036                 if (!pi.full_repaint && row_has_changed) {
1037                         pi.pain.fillRectangle(x, y - rit->ascent(),
1038                         width(), rit->height(),
1039                         text_->backgroundColor());
1040                 }
1041
1042                 // Instrumentation for testing row cache (see also
1043                 // 12 lines lower):
1044                 if (lyxerr.debugging(Debug::PAINTING)) {
1045                         if (text_->isMainText(bv_->buffer()))
1046                                 LYXERR(Debug::PAINTING) << "\n{" <<
1047                                 pi.full_repaint << row_has_changed << "}";
1048                         else
1049                                 LYXERR(Debug::PAINTING) << "[" <<
1050                                 pi.full_repaint << row_has_changed << "]";
1051                 }
1052
1053                 // Backup full_repaint status and force full repaint
1054                 // for inner insets as the Row has been cleared out.
1055                 bool tmp = pi.full_repaint;
1056                 pi.full_repaint = true;
1057                 rp.paintAppendix();
1058                 rp.paintDepthBar();
1059                 rp.paintChangeBar();
1060                 if (rit == rb)
1061                         rp.paintFirst();
1062                 rp.paintText();
1063                 if (rit + 1 == re)
1064                         rp.paintLast();
1065                 y += rit->descent();
1066                 // Restore full_repaint status.
1067                 pi.full_repaint = tmp;
1068         }
1069         // Re-enable screen drawing for future use of the painter.
1070         pi.pain.setDrawingEnabled(true);
1071
1072         //LYXERR(Debug::PAINTING) << "." << endl;
1073 }
1074
1075
1076 // only used for inset right now. should also be used for main text
1077 void TextMetrics::drawSelection(PainterInfo & pi, int x, int) const
1078 {
1079         Cursor & cur = bv_->cursor();
1080         if (!cur.selection())
1081                 return;
1082         if (!ptr_cmp(cur.text(), text_))
1083                 return;
1084
1085         LYXERR(Debug::DEBUG)
1086                 << BOOST_CURRENT_FUNCTION
1087                 << "draw selection at " << x
1088                 << endl;
1089
1090         DocIterator beg = cur.selectionBegin();
1091         DocIterator end = cur.selectionEnd();
1092
1093         // the selection doesn't touch the visible screen?
1094         if (bv_funcs::status(bv_, beg) == bv_funcs::CUR_BELOW
1095             || bv_funcs::status(bv_, end) == bv_funcs::CUR_ABOVE)
1096                 return;
1097
1098         ParagraphMetrics const & pm1 = par_metrics_[beg.pit()];
1099         ParagraphMetrics const & pm2 = par_metrics_[end.pit()];
1100         Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
1101         Row const & row2 = pm2.getRow(end.pos(), end.boundary());
1102
1103         // clip above
1104         int middleTop;
1105         bool const clipAbove = 
1106                 (bv_funcs::status(bv_, beg) == bv_funcs::CUR_ABOVE);
1107         if (clipAbove)
1108                 middleTop = 0;
1109         else
1110                 middleTop = bv_funcs::getPos(*bv_, beg, beg.boundary()).y_ + row1.descent();
1111         
1112         // clip below
1113         int middleBottom;
1114         bool const clipBelow = 
1115                 (bv_funcs::status(bv_, end) == bv_funcs::CUR_BELOW);
1116         if (clipBelow)
1117                 middleBottom = bv_->workHeight();
1118         else
1119                 middleBottom = bv_funcs::getPos(*bv_, end, end.boundary()).y_ - row2.ascent();
1120
1121         // start and end in the same line?
1122         if (!(clipAbove || clipBelow) && &row1 == &row2)
1123                 // then only draw this row's selection
1124                 drawRowSelection(pi, x, row1, beg, end, false, false);
1125         else {
1126                 if (!clipAbove) {
1127                         // get row end
1128                         DocIterator begRowEnd = beg;
1129                         begRowEnd.pos() = row1.endpos();
1130                         begRowEnd.boundary(true);
1131                         
1132                         // draw upper rectangle
1133                         drawRowSelection(pi, x, row1, beg, begRowEnd, false, true);
1134                 }
1135                         
1136                 if (middleTop < middleBottom) {
1137                         // draw middle rectangle
1138                         pi.pain.fillRectangle(x, middleTop, width(), middleBottom - middleTop,
1139                                 Color::selection);
1140                 }
1141
1142                 if (!clipBelow) {
1143                         // get row begin
1144                         DocIterator endRowBeg = end;
1145                         endRowBeg.pos() = row2.pos();
1146                         endRowBeg.boundary(false);
1147                         
1148                         // draw low rectangle
1149                         drawRowSelection(pi, x, row2, endRowBeg, end, true, false);
1150                 }
1151         }
1152 }
1153
1154
1155 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
1156                 DocIterator const & beg, DocIterator const & end,
1157                 bool drawOnBegMargin, bool drawOnEndMargin) const
1158 {
1159         Buffer & buffer = bv_->buffer();
1160         DocIterator cur = beg;
1161         int x1 = text_->cursorX(*bv_, beg.top(), beg.boundary());
1162         int x2 = text_->cursorX(*bv_, end.top(), end.boundary());
1163         int y1 = bv_funcs::getPos(*bv_, cur, cur.boundary()).y_ - row.ascent();
1164         int y2 = y1 + row.height();
1165         
1166         // draw the margins
1167         if (drawOnBegMargin) {
1168                 if (text_->isRTL(buffer, beg.paragraph()))
1169                         pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color::selection);
1170                 else
1171                         pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color::selection);
1172         }
1173         
1174         if (drawOnEndMargin) {
1175                 if (text_->isRTL(buffer, beg.paragraph()))
1176                         pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color::selection);
1177                 else
1178                         pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color::selection);
1179         }
1180         
1181         // if we are on a boundary from the beginning, it's probably
1182         // a RTL boundary and we jump to the other side directly as this
1183         // segement is 0-size and confuses the logic below
1184         if (cur.boundary())
1185                 cur.boundary(false);
1186         
1187         // go through row and draw from RTL boundary to RTL boundary
1188         while (cur < end) {
1189                 bool drawNow = false;
1190                 
1191                 // simplified cursorRight code below which does not
1192                 // descend into insets and which does not go into the
1193                 // next line. Compare the logic with the original cursorRight
1194                 
1195                 // if left of boundary -> just jump to right side
1196                 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
1197                 if (cur.boundary()) {
1198                         cur.boundary(false);
1199                 }       else if (text_->isRTLBoundary(buffer, cur.paragraph(), cur.pos() + 1)) {
1200                         // in front of RTL boundary -> Stay on this side of the boundary because:
1201                         //   ab|cDDEEFFghi -> abc|DDEEFFghi
1202                         ++cur.pos();
1203                         cur.boundary(true);
1204                         drawNow = true;
1205                 } else {
1206                         // move right
1207                         ++cur.pos();
1208                         
1209                         // line end?
1210                         if (cur.pos() == row.endpos())
1211                                 cur.boundary(true);
1212                 }
1213                         
1214                 if (x1 == -1) {
1215                         // the previous segment was just drawn, now the next starts
1216                         x1 = text_->cursorX(*bv_, cur.top(), cur.boundary());
1217                 }
1218                 
1219                 if (!(cur < end) || drawNow) {
1220                         x2 = text_->cursorX(*bv_, cur.top(), cur.boundary());
1221                         pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
1222                                 Color::selection);
1223                         
1224                         // reset x1, so it is set again next round (which will be on the 
1225                         // right side of a boundary or at the selection end)
1226                         x1 = -1;
1227                 }
1228         }
1229 }
1230
1231 //int Text::pos2x(pit_type pit, pos_type pos) const
1232 //{
1233 //      ParagraphMetrics const & pm = par_metrics_[pit];
1234 //      Row const & r = pm.rows()[row];
1235 //      int x = 0;
1236 //      pos -= r.pos();
1237 //}
1238
1239
1240 int defaultRowHeight()
1241 {
1242         return int(theFontMetrics(Font(Font::ALL_SANE)).maxHeight() *  1.2);
1243 }
1244
1245 } // namespace lyx