2 * \file src/TextMetrics.C
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * \author Jürgen Vigna
13 * \author Abdelrazak Younes
15 * Full author contact details are available in file CREDITS.
20 #include "TextMetrics.h"
23 #include "bufferparams.h"
24 #include "BufferView.h"
25 #include "paragraph_funcs.h"
26 #include "pariterator.h"
27 #include "coordcache.h"
29 #include "funcrequest.h"
30 #include "FontIterator.h"
32 #include "lyxlength.h"
34 #include "metricsinfo.h"
35 #include "ParagraphParameters.h"
38 #include "frontends/FontMetrics.h"
39 #include "frontends/Painter.h"
47 using frontend::FontMetrics;
51 int numberOfSeparators(Paragraph const & par, Row const & row)
53 pos_type const first = max(row.pos(), par.beginOfBody());
54 pos_type const last = row.endpos() - 1;
56 for (pos_type p = first; p < last; ++p) {
57 if (par.isSeparator(p))
64 int numberOfLabelHfills(Paragraph const & par, Row const & row)
66 pos_type last = row.endpos() - 1;
67 pos_type first = row.pos();
69 // hfill *DO* count at the beginning of paragraphs!
71 while (first < last && par.isHfill(first))
75 last = min(last, par.beginOfBody());
77 for (pos_type p = first; p < last; ++p) {
85 int numberOfHfills(Paragraph const & par, Row const & row)
87 pos_type last = row.endpos();
88 pos_type first = row.pos();
89 pos_type const par_size = par.size();
91 // hfill *DO* count at the beginning of paragraphs!
93 while (first < last && first < par_size && par.isHfill(first))
97 first = max(first, par.beginOfBody());
98 last = min(last, par_size);
101 for (pos_type p = first; p < last; ++p) {
110 TextMetrics::TextMetrics(BufferView * bv, LyXText * text)
111 : bv_(bv), text_(text)
114 max_width_ = bv_->workWidth();
115 dim_.wid = max_width_;
119 //text_->updateLabels(*bv->buffer());
123 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
125 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
129 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit,
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;
137 if (pmc_it->second.rows().empty() && redo) {
140 return pmc_it->second;
144 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim)
146 BOOST_ASSERT(mi.base.textwidth);
147 max_width_ = mi.base.textwidth;
149 //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
150 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
152 bool changed = false;
156 for (pit_type pit = 0, n = text_->paragraphs().size(); pit != n; ++pit) {
157 changed |= redoParagraph(pit);
158 ParagraphMetrics const & pm = parMetrics(pit);
165 dim.asc = parMetrics(0).ascent();
166 dim.des = h - dim.asc;
168 changed |= dim_ != dim;
174 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
176 return main_text_? pm.rightMargin(*bv_->buffer()) : 0;
180 int TextMetrics::rightMargin(pit_type const pit) const
182 return main_text_? par_metrics_[pit].rightMargin(*bv_->buffer()) : 0;
186 bool TextMetrics::redoParagraph(pit_type const pit)
188 Paragraph & par = text_->getPar(pit);
189 ParagraphMetrics pm(par);
190 Buffer & buffer = *bv_->buffer();
191 main_text_ = (text_ == &buffer.text());
192 bool changed = false;
194 // FIXME: this has nothing to do here and is the reason why text_ is not
196 if (par.checkBiblio(buffer.params().trackChanges))
197 const_cast<LCursor &>(bv_->cursor()).posRight();
199 // Optimisation: this is used in the next two loops
200 // so better to calculate that once here.
201 int const right_margin = rightMargin(pm);
204 // FIXME: We should always use getFont(), see documentation of
205 // noFontChange() in insetbase.h.
206 LyXFont const bufferfont = buffer.params().getFont();
207 InsetList::const_iterator ii = par.insetlist.begin();
208 InsetList::const_iterator iend = par.insetlist.end();
209 for (; ii != iend; ++ii) {
211 int const w = max_width_ - text_->leftMargin(buffer, max_width_, pit, ii->pos)
213 LyXFont const & font = ii->inset->noFontChange() ?
214 bufferfont : text_->getFont(buffer, par, ii->pos);
215 MetricsInfo mi(bv_, font, w);
216 changed |= ii->inset->metrics(mi, dim);
219 // rebreak the paragraph
222 par.setBeginOfBody();
224 // maximum pixel width of a row
225 int width = max_width_ - right_margin; // - leftMargin(buffer, max_width_, pit, row);
228 rowBreakPoint(width, pit, row);
229 setRowWidth(right_margin, pit, row);
230 setHeightOfRow(pit, row);
231 pm.rows().push_back(row);
232 pm.dim().wid = std::max(pm.dim().wid, row.width());
233 pm.dim().des += row.height();
235 } while (z < par.size());
237 // Make sure that if a par ends in newline, there is one more row
239 // FIXME this is a dirty trick. Now the _same_ position in the
240 // paragraph occurs in _two_ different rows, and has two different
241 // display positions, leading to weird behaviour when moving up/down.
242 if (z > 0 && par.isNewline(z - 1)) {
245 setRowWidth(right_margin, pit, row);
246 setHeightOfRow(pit, row);
247 pm.rows().push_back(row);
248 pm.dim().des += row.height();
251 pm.dim().asc += pm.rows()[0].ascent();
252 pm.dim().des -= pm.rows()[0].ascent();
254 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
255 // redoParagraph() recursively inside parMetrics.
256 Dimension old_dim = parMetrics(pit, false).dim();
258 changed |= old_dim.height() != pm.dim().height();
260 par_metrics_[pit] = pm;
265 RowMetrics TextMetrics::computeRowMetrics(pit_type const pit,
266 Row const & row) const
269 Buffer & buffer = *bv_->buffer();
270 Paragraph const & par = text_->getPar(pit);
272 double w = dim_.wid - row.width();
274 bool const is_rtl = text_->isRTL(buffer, par);
276 result.x = rightMargin(pit);
278 result.x = text_->leftMargin(buffer, max_width_, pit, row.pos());
280 // is there a manual margin with a manual label
281 LyXLayout_ptr const & layout = par.layout();
283 if (layout->margintype == MARGIN_MANUAL
284 && layout->labeltype == LABEL_MANUAL) {
285 /// We might have real hfills in the label part
286 int nlh = numberOfLabelHfills(par, row);
288 // A manual label par (e.g. List) has an auto-hfill
289 // between the label text and the body of the
291 // But we don't want to do this auto hfill if the par
296 if (nlh && !par.getLabelWidthString().empty())
297 result.label_hfill = labelFill(par, row) / double(nlh);
300 // are there any hfills in the row?
301 int const nh = numberOfHfills(par, row);
305 result.hfill = w / nh;
306 // we don't have to look at the alignment if it is ALIGN_LEFT and
307 // if the row is already larger then the permitted width as then
308 // we force the LEFT_ALIGN'edness!
309 } else if (int(row.width()) < max_width_) {
310 // is it block, flushleft or flushright?
311 // set x how you need it
313 if (par.params().align() == LYX_ALIGN_LAYOUT)
314 align = layout->align;
316 align = par.params().align();
318 // Display-style insets should always be on a centred row
319 // The test on par.size() is to catch zero-size pars, which
320 // would trigger the assert in Paragraph::getInset().
321 //inset = par.size() ? par.getInset(row.pos()) : 0;
323 && par.isInset(row.pos())
324 && par.getInset(row.pos())->display())
326 align = LYX_ALIGN_CENTER;
330 case LYX_ALIGN_BLOCK: {
331 int const ns = numberOfSeparators(par, row);
332 bool disp_inset = false;
333 if (row.endpos() < par.size()) {
334 InsetBase const * in = par.getInset(row.endpos());
336 disp_inset = in->display();
338 // If we have separators, this is not the last row of a
339 // par, does not end in newline, and is not row above a
340 // display inset... then stretch it
342 && row.endpos() < par.size()
343 && !par.isNewline(row.endpos() - 1)
346 result.separator = w / ns;
352 case LYX_ALIGN_RIGHT:
355 case LYX_ALIGN_CENTER:
361 text_->bidi.computeTables(par, buffer, row);
363 pos_type body_pos = par.beginOfBody();
364 pos_type end = row.endpos();
367 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
369 docstring const lsep = from_utf8(layout->labelsep);
370 result.x += theFontMetrics(text_->getLabelFont(buffer, par)).width(lsep);
372 result.x += result.label_hfill;
380 int TextMetrics::labelFill(Paragraph const & par, Row const & row) const
382 Buffer & buffer = *bv_->buffer();
384 pos_type last = par.beginOfBody();
385 BOOST_ASSERT(last > 0);
387 // -1 because a label ends with a space that is in the label
390 // a separator at this end does not count
391 if (par.isLineSeparator(last))
395 for (pos_type i = row.pos(); i <= last; ++i)
396 w += text_->singleWidth(buffer, par, i);
398 docstring const & label = par.params().labelWidthString();
402 FontMetrics const & fm
403 = theFontMetrics(text_->getLabelFont(buffer, par));
405 return max(0, fm.width(label) - w);
411 // this needs special handling - only newlines count as a break point
412 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
414 pos_type const end = par.size();
417 if (par.isNewline(i))
426 int TextMetrics::labelEnd(pit_type const pit) const
428 // labelEnd is only needed if the layout fills a flushleft label.
429 if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
431 // return the beginning of the body
432 return text_->leftMargin(*bv_->buffer(), max_width_, pit);
436 void TextMetrics::rowBreakPoint(int width, pit_type const pit,
439 Buffer & buffer = *bv_->buffer();
440 Paragraph const & par = text_->getPar(pit);
441 pos_type const end = par.size();
442 pos_type const pos = row.pos();
453 LyXLayout_ptr const & layout = par.layout();
455 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
456 row.endpos(addressBreakPoint(pos, par));
460 pos_type const body_pos = par.beginOfBody();
463 // Now we iterate through until we reach the right margin
464 // or the end of the par, then choose the possible break
467 int label_end = labelEnd(pit);
468 int const left = text_->leftMargin(buffer, max_width_, pit, pos);
471 // pixel width since last breakpoint
474 FontIterator fi = FontIterator(buffer, *text_, par, pos);
475 pos_type point = end;
477 FontMetrics const & fm = theFontMetrics(text_->getLabelFont(buffer, par));
478 for ( ; i < end; ++i, ++fi) {
479 char_type const c = par.getChar(i);
480 int thiswidth = text_->singleWidth(par, i, c, *fi);
482 // add the auto-hfill from label end to the body
483 if (body_pos && i == body_pos) {
484 docstring lsep = from_utf8(layout->labelsep);
485 int add = fm.width(lsep);
486 if (par.isLineSeparator(i - 1))
487 add -= text_->singleWidth(buffer, par, i - 1);
489 add = std::max(add, label_end - x);
494 chunkwidth += thiswidth;
496 // break before a character that will fall off
497 // the right of the row
499 // if no break before, break here
500 if (point == end || chunkwidth >= width - left) {
507 // exit on last registered breakpoint:
511 if (par.isNewline(i)) {
517 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
522 if (par.isInset(i) && par.getInset(i)->display()) {
528 if (!par.isInset(i) || par.getInset(i)->isChar()) {
529 // some insets are line separators too
530 if (par.isLineSeparator(i)) {
531 // register breakpoint:
538 // maybe found one, but the par is short enough.
539 if (i == end && x < width)
542 // manual labels cannot be broken in LaTeX. But we
543 // want to make our on-screen rendering of footnotes
545 if (body_pos && point < body_pos)
552 void TextMetrics::setRowWidth(int right_margin,
553 pit_type const pit, Row & row) const
555 Buffer & buffer = *bv_->buffer();
556 // get the pure distance
557 pos_type const end = row.endpos();
559 Paragraph const & par = text_->getPar(pit);
560 docstring const labelsep = from_utf8(par.layout()->labelsep);
561 int w = text_->leftMargin(buffer, max_width_, pit, row.pos());
562 int label_end = labelEnd(pit);
564 pos_type const body_pos = par.beginOfBody();
565 pos_type i = row.pos();
567 FontMetrics const & fm = theFontMetrics(text_->getLabelFont(buffer, par));
570 FontIterator fi = FontIterator(buffer, *text_, par, i);
571 for ( ; i < end; ++i, ++fi) {
572 if (body_pos > 0 && i == body_pos) {
573 w += fm.width(labelsep);
574 if (par.isLineSeparator(i - 1))
575 w -= text_->singleWidth(buffer, par, i - 1);
576 w = max(w, label_end);
578 char_type const c = par.getChar(i);
579 w += text_->singleWidth(par, i, c, *fi);
583 if (body_pos > 0 && body_pos >= end) {
584 w += fm.width(labelsep);
585 if (end > 0 && par.isLineSeparator(end - 1))
586 w -= text_->singleWidth(buffer, par, end - 1);
587 w = max(w, label_end);
590 row.width(w + right_margin);
594 void TextMetrics::setHeightOfRow(pit_type const pit,
597 Paragraph const & par = text_->getPar(pit);
598 // get the maximum ascent and the maximum descent
599 double layoutasc = 0;
600 double layoutdesc = 0;
601 double const dh = defaultRowHeight();
603 // ok, let us initialize the maxasc and maxdesc value.
604 // Only the fontsize count. The other properties
605 // are taken from the layoutfont. Nicer on the screen :)
606 LyXLayout_ptr const & layout = par.layout();
608 // as max get the first character of this row then it can
609 // increase but not decrease the height. Just some point to
610 // start with so we don't have to do the assignment below too
612 Buffer const & buffer = *bv_->buffer();
613 LyXFont font = text_->getFont(buffer, par, row.pos());
614 LyXFont::FONT_SIZE const tmpsize = font.size();
615 font = text_->getLayoutFont(buffer, pit);
616 LyXFont::FONT_SIZE const size = font.size();
617 font.setSize(tmpsize);
619 LyXFont labelfont = text_->getLabelFont(buffer, par);
621 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
622 FontMetrics const & fontmetrics = theFontMetrics(font);
624 // these are minimum values
625 double const spacing_val = layout->spacing.getValue()
626 * text_->spacing(buffer, par);
627 //lyxerr << "spacing_val = " << spacing_val << endl;
628 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
629 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
631 // insets may be taller
632 InsetList::const_iterator ii = par.insetlist.begin();
633 InsetList::const_iterator iend = par.insetlist.end();
634 for ( ; ii != iend; ++ii) {
635 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
636 maxasc = max(maxasc, ii->inset->ascent());
637 maxdesc = max(maxdesc, ii->inset->descent());
641 // Check if any custom fonts are larger (Asger)
642 // This is not completely correct, but we can live with the small,
643 // cosmetic error for now.
645 pos_type const pos_end = row.endpos();
647 LyXFont::FONT_SIZE maxsize =
648 par.highestFontInRange(row.pos(), pos_end, size);
649 if (maxsize > font.size()) {
650 font.setSize(maxsize);
651 maxasc = max(maxasc, fontmetrics.maxAscent());
652 maxdesc = max(maxdesc, fontmetrics.maxDescent());
655 // This is nicer with box insets:
660 ParagraphList const & pars = text_->paragraphs();
663 if (row.pos() == 0) {
664 BufferParams const & bufparams = buffer.params();
665 // some parksips VERY EASY IMPLEMENTATION
666 if (bufparams.paragraph_separation
667 == BufferParams::PARSEP_SKIP
669 && ((layout->isParagraph() && par.getDepth() == 0)
670 || (pars[pit - 1].layout()->isParagraph()
671 && pars[pit - 1].getDepth() == 0)))
673 maxasc += bufparams.getDefSkip().inPixels(*bv_);
676 if (par.params().startOfAppendix())
677 maxasc += int(3 * dh);
679 // This is special code for the chapter, since the label of this
680 // layout is printed in an extra row
681 if (layout->counter == "chapter"
682 && !par.params().labelString().empty()) {
683 labeladdon = int(labelfont_metrics.maxHeight()
684 * layout->spacing.getValue()
685 * text_->spacing(buffer, par));
688 // special code for the top label
689 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
690 || layout->labeltype == LABEL_BIBLIO
691 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
692 && isFirstInSequence(pit, pars)
693 && !par.getLabelstring().empty())
696 labelfont_metrics.maxHeight()
697 * layout->spacing.getValue()
698 * text_->spacing(buffer, par)
699 + (layout->topsep + layout->labelbottomsep) * dh);
702 // Add the layout spaces, for example before and after
703 // a section, or between the items of a itemize or enumerate
706 pit_type prev = depthHook(pit, pars, par.getDepth());
708 && pars[prev].layout() == layout
709 && pars[prev].getDepth() == par.getDepth()
710 && pars[prev].getLabelWidthString() == par.getLabelWidthString())
712 layoutasc = layout->itemsep * dh;
713 } else if (pit != 0 || row.pos() != 0) {
714 if (layout->topsep > 0)
715 layoutasc = layout->topsep * dh;
718 prev = outerHook(pit, pars);
719 if (prev != pit_type(pars.size())) {
720 maxasc += int(pars[prev].layout()->parsep * dh);
721 } else if (pit != 0) {
722 if (pars[pit - 1].getDepth() != 0 ||
723 pars[pit - 1].layout() == layout) {
724 maxasc += int(layout->parsep * dh);
729 // is it a bottom line?
730 if (row.endpos() >= par.size()) {
731 // add the layout spaces, for example before and after
732 // a section, or between the items of a itemize or enumerate
734 pit_type nextpit = pit + 1;
735 if (nextpit != pit_type(pars.size())) {
740 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
741 usual = pars[cpit].layout()->bottomsep * dh;
742 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
743 if (pars[cpit].layout() != pars[nextpit].layout()
744 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
746 unusual = pars[cpit].layout()->bottomsep * dh;
748 layoutdesc = max(unusual, usual);
749 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
750 if (pars[cpit].layout() != pars[nextpit].layout()
751 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
752 layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
757 // incalculate the layout spaces
758 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
759 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
761 // FIXME: the correct way is to do the following is to move the
762 // following code in another method specially tailored for the
763 // main LyXText. The following test is thus bogus.
764 // Top and bottom margin of the document (only at top-level)
766 if (pit == 0 && row.pos() == 0)
768 if (pit + 1 == pit_type(pars.size()) &&
769 row.endpos() == par.size())
773 row.ascent(maxasc + labeladdon);
774 row.descent(maxdesc);
778 int defaultRowHeight()
780 return int(theFontMetrics(LyXFont(LyXFont::ALL_SANE)).maxHeight() * 1.2);