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