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