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 const last = row.endpos();
88 pos_type first = row.pos();
90 // hfill *DO* count at the beginning of paragraphs!
92 while (first < last && par.isHfill(first))
96 first = max(first, par.beginOfBody());
99 for (pos_type p = first; p < last; ++p) {
108 TextMetrics::TextMetrics(BufferView * bv, LyXText * text)
109 : bv_(bv), text_(text)
112 max_width_ = bv_->workWidth();
113 dim_.wid = max_width_;
117 //text_->updateLabels(*bv->buffer());
121 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
123 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
127 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit,
130 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
131 if (pmc_it == par_metrics_.end()) {
132 pmc_it = par_metrics_.insert(
133 std::make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
135 if (pmc_it->second.rows().empty() && redo) {
138 return pmc_it->second;
142 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim)
144 BOOST_ASSERT(mi.base.textwidth);
145 max_width_ = mi.base.textwidth;
147 //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
148 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
150 bool changed = false;
154 for (pit_type pit = 0, n = text_->paragraphs().size(); pit != n; ++pit) {
155 changed |= redoParagraph(pit);
156 ParagraphMetrics const & pm = parMetrics(pit);
163 dim.asc = parMetrics(0).ascent();
164 dim.des = h - dim.asc;
166 changed |= dim_ != dim;
172 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
174 return main_text_? pm.rightMargin(*bv_->buffer()) : 0;
178 int TextMetrics::rightMargin(pit_type const pit) const
180 return main_text_? par_metrics_[pit].rightMargin(*bv_->buffer()) : 0;
184 bool TextMetrics::redoParagraph(pit_type const pit)
186 Paragraph & par = text_->getPar(pit);
187 ParagraphMetrics pm(par);
188 Buffer & buffer = *bv_->buffer();
189 main_text_ = (text_ == &buffer.text());
190 bool changed = false;
192 // FIXME: this has nothing to do here and is the reason why text_ is not
194 if (par.checkBiblio(buffer.params().trackChanges))
195 const_cast<LCursor &>(bv_->cursor()).posRight();
197 // Optimisation: this is used in the next two loops
198 // so better to calculate that once here.
199 int const right_margin = rightMargin(pm);
202 // FIXME: We should always use getFont(), see documentation of
203 // noFontChange() in insetbase.h.
204 LyXFont const bufferfont = buffer.params().getFont();
205 InsetList::const_iterator ii = par.insetlist.begin();
206 InsetList::const_iterator iend = par.insetlist.end();
207 for (; ii != iend; ++ii) {
209 int const w = max_width_ - text_->leftMargin(buffer, max_width_, pit, ii->pos)
211 LyXFont const & font = ii->inset->noFontChange() ?
212 bufferfont : text_->getFont(buffer, par, ii->pos);
213 MetricsInfo mi(bv_, font, w);
214 changed |= ii->inset->metrics(mi, dim);
217 // rebreak the paragraph
220 par.setBeginOfBody();
222 // maximum pixel width of a row
223 int width = max_width_ - right_margin; // - leftMargin(buffer, max_width_, pit, row);
226 rowBreakPoint(width, pit, row);
227 setRowWidth(right_margin, pit, row);
228 setHeightOfRow(pit, row);
229 pm.rows().push_back(row);
230 pm.dim().wid = std::max(pm.dim().wid, row.width());
231 pm.dim().des += row.height();
233 } while (z < par.size());
235 // Make sure that if a par ends in newline, there is one more row
237 // FIXME this is a dirty trick. Now the _same_ position in the
238 // paragraph occurs in _two_ different rows, and has two different
239 // display positions, leading to weird behaviour when moving up/down.
240 if (z > 0 && par.isNewline(z - 1)) {
243 setRowWidth(right_margin, pit, row);
244 setHeightOfRow(pit, row);
245 pm.rows().push_back(row);
246 pm.dim().des += row.height();
249 pm.dim().asc += pm.rows()[0].ascent();
250 pm.dim().des -= pm.rows()[0].ascent();
252 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
253 // redoParagraph() recursively inside parMetrics.
254 Dimension old_dim = parMetrics(pit, false).dim();
256 changed |= old_dim.height() != pm.dim().height();
258 par_metrics_[pit] = pm;
263 RowMetrics TextMetrics::computeRowMetrics(pit_type const pit,
264 Row const & row) const
267 Buffer & buffer = *bv_->buffer();
268 Paragraph const & par = text_->getPar(pit);
270 double w = dim_.wid - row.width();
272 bool const is_rtl = text_->isRTL(buffer, par);
274 result.x = rightMargin(pit);
276 result.x = text_->leftMargin(buffer, max_width_, pit, row.pos());
278 // is there a manual margin with a manual label
279 LyXLayout_ptr const & layout = par.layout();
281 if (layout->margintype == MARGIN_MANUAL
282 && layout->labeltype == LABEL_MANUAL) {
283 /// We might have real hfills in the label part
284 int nlh = numberOfLabelHfills(par, row);
286 // A manual label par (e.g. List) has an auto-hfill
287 // between the label text and the body of the
289 // But we don't want to do this auto hfill if the par
294 if (nlh && !par.getLabelWidthString().empty())
295 result.label_hfill = labelFill(par, row) / double(nlh);
298 // are there any hfills in the row?
299 int const nh = numberOfHfills(par, row);
303 result.hfill = w / nh;
304 // we don't have to look at the alignment if it is ALIGN_LEFT and
305 // if the row is already larger then the permitted width as then
306 // we force the LEFT_ALIGN'edness!
307 } else if (int(row.width()) < max_width_) {
308 // is it block, flushleft or flushright?
309 // set x how you need it
311 if (par.params().align() == LYX_ALIGN_LAYOUT)
312 align = layout->align;
314 align = par.params().align();
316 // Display-style insets should always be on a centred row
317 // The test on par.size() is to catch zero-size pars, which
318 // would trigger the assert in Paragraph::getInset().
319 //inset = par.size() ? par.getInset(row.pos()) : 0;
321 && par.isInset(row.pos())
322 && par.getInset(row.pos())->display())
324 align = LYX_ALIGN_CENTER;
328 case LYX_ALIGN_BLOCK: {
329 int const ns = numberOfSeparators(par, row);
330 bool disp_inset = false;
331 if (row.endpos() < par.size()) {
332 InsetBase const * in = par.getInset(row.endpos());
334 disp_inset = in->display();
336 // If we have separators, this is not the last row of a
337 // par, does not end in newline, and is not row above a
338 // display inset... then stretch it
340 && row.endpos() < par.size()
341 && !par.isNewline(row.endpos() - 1)
344 result.separator = w / ns;
350 case LYX_ALIGN_RIGHT:
353 case LYX_ALIGN_CENTER:
359 text_->bidi.computeTables(par, buffer, row);
361 pos_type body_pos = par.beginOfBody();
362 pos_type end = row.endpos();
365 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
367 docstring const lsep = from_utf8(layout->labelsep);
368 result.x += theFontMetrics(text_->getLabelFont(buffer, par)).width(lsep);
370 result.x += result.label_hfill;
378 int TextMetrics::labelFill(Paragraph const & par, Row const & row) const
380 Buffer & buffer = *bv_->buffer();
382 pos_type last = par.beginOfBody();
383 BOOST_ASSERT(last > 0);
385 // -1 because a label ends with a space that is in the label
388 // a separator at this end does not count
389 if (par.isLineSeparator(last))
393 for (pos_type i = row.pos(); i <= last; ++i)
394 w += text_->singleWidth(buffer, par, i);
396 docstring const & label = par.params().labelWidthString();
400 FontMetrics const & fm
401 = theFontMetrics(text_->getLabelFont(buffer, par));
403 return max(0, fm.width(label) - w);
409 // this needs special handling - only newlines count as a break point
410 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
412 pos_type const end = par.size();
415 if (par.isNewline(i))
424 int TextMetrics::labelEnd(pit_type const pit) const
426 // labelEnd is only needed if the layout fills a flushleft label.
427 if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
429 // return the beginning of the body
430 return text_->leftMargin(*bv_->buffer(), max_width_, pit);
434 void TextMetrics::rowBreakPoint(int width, pit_type const pit,
437 Buffer & buffer = *bv_->buffer();
438 Paragraph const & par = text_->getPar(pit);
439 pos_type const end = par.size();
440 pos_type const pos = row.pos();
451 LyXLayout_ptr const & layout = par.layout();
453 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
454 row.endpos(addressBreakPoint(pos, par));
458 pos_type const body_pos = par.beginOfBody();
461 // Now we iterate through until we reach the right margin
462 // or the end of the par, then choose the possible break
465 int label_end = labelEnd(pit);
466 int const left = text_->leftMargin(buffer, max_width_, pit, pos);
469 // pixel width since last breakpoint
472 FontIterator fi = FontIterator(buffer, *text_, par, pos);
473 pos_type point = end;
475 FontMetrics const & fm = theFontMetrics(text_->getLabelFont(buffer, par));
476 for ( ; i < end; ++i, ++fi) {
477 char_type const c = par.getChar(i);
478 int thiswidth = text_->singleWidth(par, i, c, *fi);
480 // add the auto-hfill from label end to the body
481 if (body_pos && i == body_pos) {
482 docstring lsep = from_utf8(layout->labelsep);
483 int add = fm.width(lsep);
484 if (par.isLineSeparator(i - 1))
485 add -= text_->singleWidth(buffer, par, i - 1);
487 add = std::max(add, label_end - x);
492 chunkwidth += thiswidth;
494 // break before a character that will fall off
495 // the right of the row
497 // if no break before, break here
498 if (point == end || chunkwidth >= width - left) {
505 // exit on last registered breakpoint:
509 if (par.isNewline(i)) {
515 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
520 if (par.isInset(i) && par.getInset(i)->display()) {
526 if (!par.isInset(i) || par.getInset(i)->isChar()) {
527 // some insets are line separators too
528 if (par.isLineSeparator(i)) {
529 // register breakpoint:
536 // maybe found one, but the par is short enough.
537 if (i == end && x < width)
540 // manual labels cannot be broken in LaTeX. But we
541 // want to make our on-screen rendering of footnotes
543 if (body_pos && point < body_pos)
550 void TextMetrics::setRowWidth(int right_margin,
551 pit_type const pit, Row & row) const
553 Buffer & buffer = *bv_->buffer();
554 // get the pure distance
555 pos_type const end = row.endpos();
557 Paragraph const & par = text_->getPar(pit);
558 docstring const labelsep = from_utf8(par.layout()->labelsep);
559 int w = text_->leftMargin(buffer, max_width_, pit, row.pos());
560 int label_end = labelEnd(pit);
562 pos_type const body_pos = par.beginOfBody();
563 pos_type i = row.pos();
565 FontMetrics const & fm = theFontMetrics(text_->getLabelFont(buffer, par));
568 FontIterator fi = FontIterator(buffer, *text_, par, i);
569 for ( ; i < end; ++i, ++fi) {
570 if (body_pos > 0 && i == body_pos) {
571 w += fm.width(labelsep);
572 if (par.isLineSeparator(i - 1))
573 w -= text_->singleWidth(buffer, par, i - 1);
574 w = max(w, label_end);
576 char_type const c = par.getChar(i);
577 w += text_->singleWidth(par, i, c, *fi);
581 if (body_pos > 0 && body_pos >= end) {
582 w += fm.width(labelsep);
583 if (end > 0 && par.isLineSeparator(end - 1))
584 w -= text_->singleWidth(buffer, par, end - 1);
585 w = max(w, label_end);
588 row.width(w + right_margin);
592 void TextMetrics::setHeightOfRow(pit_type const pit,
595 Paragraph const & par = text_->getPar(pit);
596 // get the maximum ascent and the maximum descent
597 double layoutasc = 0;
598 double layoutdesc = 0;
599 double const dh = defaultRowHeight();
601 // ok, let us initialize the maxasc and maxdesc value.
602 // Only the fontsize count. The other properties
603 // are taken from the layoutfont. Nicer on the screen :)
604 LyXLayout_ptr const & layout = par.layout();
606 // as max get the first character of this row then it can
607 // increase but not decrease the height. Just some point to
608 // start with so we don't have to do the assignment below too
610 Buffer const & buffer = *bv_->buffer();
611 LyXFont font = text_->getFont(buffer, par, row.pos());
612 LyXFont::FONT_SIZE const tmpsize = font.size();
613 font = text_->getLayoutFont(buffer, pit);
614 LyXFont::FONT_SIZE const size = font.size();
615 font.setSize(tmpsize);
617 LyXFont labelfont = text_->getLabelFont(buffer, par);
619 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
620 FontMetrics const & fontmetrics = theFontMetrics(font);
622 // these are minimum values
623 double const spacing_val = layout->spacing.getValue()
624 * text_->spacing(buffer, par);
625 //lyxerr << "spacing_val = " << spacing_val << endl;
626 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
627 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
629 // insets may be taller
630 InsetList::const_iterator ii = par.insetlist.begin();
631 InsetList::const_iterator iend = par.insetlist.end();
632 for ( ; ii != iend; ++ii) {
633 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
634 maxasc = max(maxasc, ii->inset->ascent());
635 maxdesc = max(maxdesc, ii->inset->descent());
639 // Check if any custom fonts are larger (Asger)
640 // This is not completely correct, but we can live with the small,
641 // cosmetic error for now.
643 pos_type const pos_end = row.endpos();
645 LyXFont::FONT_SIZE maxsize =
646 par.highestFontInRange(row.pos(), pos_end, size);
647 if (maxsize > font.size()) {
648 font.setSize(maxsize);
649 maxasc = max(maxasc, fontmetrics.maxAscent());
650 maxdesc = max(maxdesc, fontmetrics.maxDescent());
653 // This is nicer with box insets:
658 ParagraphList const & pars = text_->paragraphs();
661 if (row.pos() == 0) {
662 BufferParams const & bufparams = buffer.params();
663 // some parksips VERY EASY IMPLEMENTATION
664 if (bufparams.paragraph_separation
665 == BufferParams::PARSEP_SKIP
667 && ((layout->isParagraph() && par.getDepth() == 0)
668 || (pars[pit - 1].layout()->isParagraph()
669 && pars[pit - 1].getDepth() == 0)))
671 maxasc += bufparams.getDefSkip().inPixels(*bv_);
674 if (par.params().startOfAppendix())
675 maxasc += int(3 * dh);
677 // This is special code for the chapter, since the label of this
678 // layout is printed in an extra row
679 if (layout->counter == "chapter"
680 && !par.params().labelString().empty()) {
681 labeladdon = int(labelfont_metrics.maxHeight()
682 * layout->spacing.getValue()
683 * text_->spacing(buffer, par));
686 // special code for the top label
687 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
688 || layout->labeltype == LABEL_BIBLIO
689 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
690 && isFirstInSequence(pit, pars)
691 && !par.getLabelstring().empty())
694 labelfont_metrics.maxHeight()
695 * layout->spacing.getValue()
696 * text_->spacing(buffer, par)
697 + (layout->topsep + layout->labelbottomsep) * dh);
700 // Add the layout spaces, for example before and after
701 // a section, or between the items of a itemize or enumerate
704 pit_type prev = depthHook(pit, pars, par.getDepth());
706 && pars[prev].layout() == layout
707 && pars[prev].getDepth() == par.getDepth()
708 && pars[prev].getLabelWidthString() == par.getLabelWidthString())
710 layoutasc = layout->itemsep * dh;
711 } else if (pit != 0 || row.pos() != 0) {
712 if (layout->topsep > 0)
713 layoutasc = layout->topsep * dh;
716 prev = outerHook(pit, pars);
717 if (prev != pit_type(pars.size())) {
718 maxasc += int(pars[prev].layout()->parsep * dh);
719 } else if (pit != 0) {
720 if (pars[pit - 1].getDepth() != 0 ||
721 pars[pit - 1].layout() == layout) {
722 maxasc += int(layout->parsep * dh);
727 // is it a bottom line?
728 if (row.endpos() >= par.size()) {
729 // add the layout spaces, for example before and after
730 // a section, or between the items of a itemize or enumerate
732 pit_type nextpit = pit + 1;
733 if (nextpit != pit_type(pars.size())) {
738 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
739 usual = pars[cpit].layout()->bottomsep * dh;
740 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
741 if (pars[cpit].layout() != pars[nextpit].layout()
742 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
744 unusual = pars[cpit].layout()->bottomsep * dh;
746 layoutdesc = max(unusual, usual);
747 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
748 if (pars[cpit].layout() != pars[nextpit].layout()
749 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
750 layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
755 // incalculate the layout spaces
756 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
757 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
759 // FIXME: the correct way is to do the following is to move the
760 // following code in another method specially tailored for the
761 // main LyXText. The following test is thus bogus.
762 // Top and bottom margin of the document (only at top-level)
764 if (pit == 0 && row.pos() == 0)
766 if (pit + 1 == pit_type(pars.size()) &&
767 row.endpos() == par.size())
771 row.ascent(maxasc + labeladdon);
772 row.descent(maxdesc);
776 int defaultRowHeight()
778 return int(theFontMetrics(LyXFont(LyXFont::ALL_SANE)).maxHeight() * 1.2);