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"
35 #include "metricsinfo.h"
36 #include "ParagraphParameters.h"
39 #include "frontends/FontMetrics.h"
40 #include "frontends/Painter.h"
48 using frontend::FontMetrics;
52 int numberOfSeparators(Paragraph const & par, Row const & row)
54 pos_type const first = max(row.pos(), par.beginOfBody());
55 pos_type const last = row.endpos() - 1;
57 for (pos_type p = first; p < last; ++p) {
58 if (par.isSeparator(p))
65 int numberOfLabelHfills(Paragraph const & par, Row const & row)
67 pos_type last = row.endpos() - 1;
68 pos_type first = row.pos();
70 // hfill *DO* count at the beginning of paragraphs!
72 while (first < last && par.isHfill(first))
76 last = min(last, par.beginOfBody());
78 for (pos_type p = first; p < last; ++p) {
86 int numberOfHfills(Paragraph const & par, Row const & row)
88 pos_type last = row.endpos();
89 pos_type first = row.pos();
90 pos_type const par_size = par.size();
92 // hfill *DO* count at the beginning of paragraphs!
94 while (first < last && first < par_size && par.isHfill(first))
98 first = max(first, par.beginOfBody());
99 last = min(last, par_size);
102 for (pos_type p = first; p < last; ++p) {
111 TextMetrics::TextMetrics(BufferView * bv, LyXText * text)
112 : bv_(bv), text_(text)
115 max_width_ = bv_->workWidth();
116 dim_.wid = max_width_;
120 //text_->updateLabels(*bv->buffer());
124 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
126 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
130 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit,
133 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
134 if (pmc_it == par_metrics_.end()) {
135 pmc_it = par_metrics_.insert(
136 std::make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
138 if (pmc_it->second.rows().empty() && redo) {
141 return pmc_it->second;
145 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim)
147 BOOST_ASSERT(mi.base.textwidth);
148 max_width_ = mi.base.textwidth;
150 //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
151 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
153 bool changed = false;
157 for (pit_type pit = 0, n = text_->paragraphs().size(); pit != n; ++pit) {
158 changed |= redoParagraph(pit);
159 ParagraphMetrics const & pm = parMetrics(pit);
166 dim.asc = parMetrics(0).ascent();
167 dim.des = h - dim.asc;
169 changed |= dim_ != dim;
175 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
177 return main_text_? pm.rightMargin(*bv_->buffer()) : 0;
181 int TextMetrics::rightMargin(pit_type const pit) const
183 return main_text_? par_metrics_[pit].rightMargin(*bv_->buffer()) : 0;
187 bool TextMetrics::redoParagraph(pit_type const pit)
189 Paragraph & par = text_->getPar(pit);
190 ParagraphMetrics pm(par);
191 Buffer & buffer = *bv_->buffer();
192 main_text_ = (text_ == &buffer.text());
193 bool changed = false;
195 // FIXME: this has nothing to do here and is the reason why text_ is not
197 if (par.checkBiblio(buffer.params().trackChanges))
198 const_cast<LCursor &>(bv_->cursor()).posRight();
200 // Optimisation: this is used in the next two loops
201 // so better to calculate that once here.
202 int const right_margin = rightMargin(pm);
205 // FIXME: We should always use getFont(), see documentation of
206 // noFontChange() in insetbase.h.
207 LyXFont const bufferfont = buffer.params().getFont();
208 InsetList::const_iterator ii = par.insetlist.begin();
209 InsetList::const_iterator iend = par.insetlist.end();
210 for (; ii != iend; ++ii) {
212 int const w = max_width_ - text_->leftMargin(buffer, max_width_, pit, ii->pos)
214 LyXFont const & font = ii->inset->noFontChange() ?
215 bufferfont : text_->getFont(buffer, par, ii->pos);
216 MetricsInfo mi(bv_, font, w);
217 changed |= ii->inset->metrics(mi, dim);
220 // rebreak the paragraph
223 par.setBeginOfBody();
225 // maximum pixel width of a row
226 int width = max_width_ - right_margin; // - leftMargin(buffer, max_width_, pit, row);
229 rowBreakPoint(width, pit, row);
230 setRowWidth(right_margin, pit, row);
231 setHeightOfRow(pit, row);
232 pm.rows().push_back(row);
233 pm.dim().wid = std::max(pm.dim().wid, row.width());
234 pm.dim().des += row.height();
236 } while (z < par.size());
238 // Make sure that if a par ends in newline, there is one more row
240 // FIXME this is a dirty trick. Now the _same_ position in the
241 // paragraph occurs in _two_ different rows, and has two different
242 // display positions, leading to weird behaviour when moving up/down.
243 if (z > 0 && par.isNewline(z - 1)) {
246 setRowWidth(right_margin, pit, row);
247 setHeightOfRow(pit, row);
248 pm.rows().push_back(row);
249 pm.dim().des += row.height();
252 pm.dim().asc += pm.rows()[0].ascent();
253 pm.dim().des -= pm.rows()[0].ascent();
255 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
256 // redoParagraph() recursively inside parMetrics.
257 Dimension old_dim = parMetrics(pit, false).dim();
259 changed |= old_dim.height() != pm.dim().height();
261 par_metrics_[pit] = pm;
266 RowMetrics TextMetrics::computeRowMetrics(pit_type const pit,
267 Row const & row) const
270 Buffer & buffer = *bv_->buffer();
271 Paragraph const & par = text_->getPar(pit);
273 double w = dim_.wid - row.width();
275 bool const is_rtl = text_->isRTL(buffer, par);
277 result.x = rightMargin(pit);
279 result.x = text_->leftMargin(buffer, max_width_, pit, row.pos());
281 // is there a manual margin with a manual label
282 LyXLayout_ptr const & layout = par.layout();
284 if (layout->margintype == MARGIN_MANUAL
285 && layout->labeltype == LABEL_MANUAL) {
286 /// We might have real hfills in the label part
287 int nlh = numberOfLabelHfills(par, row);
289 // A manual label par (e.g. List) has an auto-hfill
290 // between the label text and the body of the
292 // But we don't want to do this auto hfill if the par
297 if (nlh && !par.getLabelWidthString().empty())
298 result.label_hfill = labelFill(par, row) / double(nlh);
301 // are there any hfills in the row?
302 int const nh = numberOfHfills(par, row);
306 result.hfill = w / nh;
307 // we don't have to look at the alignment if it is ALIGN_LEFT and
308 // if the row is already larger then the permitted width as then
309 // we force the LEFT_ALIGN'edness!
310 } else if (int(row.width()) < max_width_) {
311 // is it block, flushleft or flushright?
312 // set x how you need it
314 if (par.params().align() == LYX_ALIGN_LAYOUT)
315 align = layout->align;
317 align = par.params().align();
319 // Display-style insets should always be on a centred row
320 // The test on par.size() is to catch zero-size pars, which
321 // would trigger the assert in Paragraph::getInset().
322 //inset = par.size() ? par.getInset(row.pos()) : 0;
324 && par.isInset(row.pos())
325 && par.getInset(row.pos())->display())
327 align = LYX_ALIGN_CENTER;
331 case LYX_ALIGN_BLOCK: {
332 int const ns = numberOfSeparators(par, row);
333 bool disp_inset = false;
334 if (row.endpos() < par.size()) {
335 InsetBase const * in = par.getInset(row.endpos());
337 disp_inset = in->display();
339 // If we have separators, this is not the last row of a
340 // par, does not end in newline, and is not row above a
341 // display inset... then stretch it
343 && row.endpos() < par.size()
344 && !par.isNewline(row.endpos() - 1)
347 result.separator = w / ns;
353 case LYX_ALIGN_RIGHT:
356 case LYX_ALIGN_CENTER:
362 text_->bidi.computeTables(par, buffer, row);
364 pos_type body_pos = par.beginOfBody();
365 pos_type end = row.endpos();
368 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
370 docstring const lsep = from_utf8(layout->labelsep);
371 result.x += theFontMetrics(text_->getLabelFont(buffer, par)).width(lsep);
373 result.x += result.label_hfill;
381 int TextMetrics::labelFill(Paragraph const & par, Row const & row) const
383 Buffer & buffer = *bv_->buffer();
385 pos_type last = par.beginOfBody();
386 BOOST_ASSERT(last > 0);
388 // -1 because a label ends with a space that is in the label
391 // a separator at this end does not count
392 if (par.isLineSeparator(last))
396 for (pos_type i = row.pos(); i <= last; ++i)
397 w += text_->singleWidth(buffer, par, i);
399 docstring const & label = par.params().labelWidthString();
403 FontMetrics const & fm
404 = theFontMetrics(text_->getLabelFont(buffer, par));
406 return max(0, fm.width(label) - w);
412 // this needs special handling - only newlines count as a break point
413 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
415 pos_type const end = par.size();
418 if (par.isNewline(i))
427 int TextMetrics::labelEnd(pit_type const pit) const
429 // labelEnd is only needed if the layout fills a flushleft label.
430 if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
432 // return the beginning of the body
433 return text_->leftMargin(*bv_->buffer(), max_width_, pit);
437 void TextMetrics::rowBreakPoint(int width, pit_type const pit,
440 Buffer & buffer = *bv_->buffer();
441 Paragraph const & par = text_->getPar(pit);
442 pos_type const end = par.size();
443 pos_type const pos = row.pos();
454 LyXLayout_ptr const & layout = par.layout();
456 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
457 row.endpos(addressBreakPoint(pos, par));
461 pos_type const body_pos = par.beginOfBody();
464 // Now we iterate through until we reach the right margin
465 // or the end of the par, then choose the possible break
468 int label_end = labelEnd(pit);
469 int const left = text_->leftMargin(buffer, max_width_, pit, pos);
472 // pixel width since last breakpoint
475 FontIterator fi = FontIterator(buffer, *text_, par, pos);
476 pos_type point = end;
478 FontMetrics const & fm = theFontMetrics(text_->getLabelFont(buffer, par));
479 for ( ; i < end; ++i, ++fi) {
480 char_type const c = par.getChar(i);
481 int thiswidth = text_->singleWidth(par, i, c, *fi);
483 // add the auto-hfill from label end to the body
484 if (body_pos && i == body_pos) {
485 docstring lsep = from_utf8(layout->labelsep);
486 int add = fm.width(lsep);
487 if (par.isLineSeparator(i - 1))
488 add -= text_->singleWidth(buffer, par, i - 1);
490 add = std::max(add, label_end - x);
495 chunkwidth += thiswidth;
497 // break before a character that will fall off
498 // the right of the row
500 // if no break before, break here
501 if (point == end || chunkwidth >= width - left) {
508 // exit on last registered breakpoint:
512 if (par.isNewline(i)) {
518 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
523 if (par.isInset(i) && par.getInset(i)->display()) {
529 if (!par.isInset(i) || par.getInset(i)->isChar()) {
530 // some insets are line separators too
531 if (par.isLineSeparator(i)) {
532 // register breakpoint:
539 // maybe found one, but the par is short enough.
540 if (i == end && x < width)
543 // manual labels cannot be broken in LaTeX. But we
544 // want to make our on-screen rendering of footnotes
546 if (body_pos && point < body_pos)
553 void TextMetrics::setRowWidth(int right_margin,
554 pit_type const pit, Row & row) const
556 Buffer & buffer = *bv_->buffer();
557 // get the pure distance
558 pos_type const end = row.endpos();
560 Paragraph const & par = text_->getPar(pit);
561 docstring const labelsep = from_utf8(par.layout()->labelsep);
562 int w = text_->leftMargin(buffer, max_width_, pit, row.pos());
563 int label_end = labelEnd(pit);
565 pos_type const body_pos = par.beginOfBody();
566 pos_type i = row.pos();
568 FontMetrics const & fm = theFontMetrics(text_->getLabelFont(buffer, par));
571 FontIterator fi = FontIterator(buffer, *text_, par, i);
572 for ( ; i < end; ++i, ++fi) {
573 if (body_pos > 0 && i == body_pos) {
574 w += fm.width(labelsep);
575 if (par.isLineSeparator(i - 1))
576 w -= text_->singleWidth(buffer, par, i - 1);
577 w = max(w, label_end);
579 char_type const c = par.getChar(i);
580 w += text_->singleWidth(par, i, c, *fi);
584 if (body_pos > 0 && body_pos >= end) {
585 w += fm.width(labelsep);
586 if (end > 0 && par.isLineSeparator(end - 1))
587 w -= text_->singleWidth(buffer, par, end - 1);
588 w = max(w, label_end);
591 row.width(w + right_margin);
595 void TextMetrics::setHeightOfRow(pit_type const pit,
598 Paragraph const & par = text_->getPar(pit);
599 // get the maximum ascent and the maximum descent
600 double layoutasc = 0;
601 double layoutdesc = 0;
602 double const dh = defaultRowHeight();
604 // ok, let us initialize the maxasc and maxdesc value.
605 // Only the fontsize count. The other properties
606 // are taken from the layoutfont. Nicer on the screen :)
607 LyXLayout_ptr const & layout = par.layout();
609 // as max get the first character of this row then it can
610 // increase but not decrease the height. Just some point to
611 // start with so we don't have to do the assignment below too
613 Buffer const & buffer = *bv_->buffer();
614 LyXFont font = text_->getFont(buffer, par, row.pos());
615 LyXFont::FONT_SIZE const tmpsize = font.size();
616 font = text_->getLayoutFont(buffer, pit);
617 LyXFont::FONT_SIZE const size = font.size();
618 font.setSize(tmpsize);
620 LyXFont labelfont = text_->getLabelFont(buffer, par);
622 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
623 FontMetrics const & fontmetrics = theFontMetrics(font);
625 // these are minimum values
626 double const spacing_val = layout->spacing.getValue()
627 * text_->spacing(buffer, par);
628 //lyxerr << "spacing_val = " << spacing_val << endl;
629 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
630 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
632 // insets may be taller
633 InsetList::const_iterator ii = par.insetlist.begin();
634 InsetList::const_iterator iend = par.insetlist.end();
635 for ( ; ii != iend; ++ii) {
636 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
637 maxasc = max(maxasc, ii->inset->ascent());
638 maxdesc = max(maxdesc, ii->inset->descent());
642 // Check if any custom fonts are larger (Asger)
643 // This is not completely correct, but we can live with the small,
644 // cosmetic error for now.
646 pos_type const pos_end = row.endpos();
648 LyXFont::FONT_SIZE maxsize =
649 par.highestFontInRange(row.pos(), pos_end, size);
650 if (maxsize > font.size()) {
651 font.setSize(maxsize);
652 maxasc = max(maxasc, fontmetrics.maxAscent());
653 maxdesc = max(maxdesc, fontmetrics.maxDescent());
656 // This is nicer with box insets:
661 ParagraphList const & pars = text_->paragraphs();
664 if (row.pos() == 0) {
665 BufferParams const & bufparams = buffer.params();
666 // some parksips VERY EASY IMPLEMENTATION
667 if (bufparams.paragraph_separation
668 == BufferParams::PARSEP_SKIP
670 && ((layout->isParagraph() && par.getDepth() == 0)
671 || (pars[pit - 1].layout()->isParagraph()
672 && pars[pit - 1].getDepth() == 0)))
674 maxasc += bufparams.getDefSkip().inPixels(*bv_);
677 if (par.params().startOfAppendix())
678 maxasc += int(3 * dh);
680 // This is special code for the chapter, since the label of this
681 // layout is printed in an extra row
682 if (layout->counter == "chapter"
683 && !par.params().labelString().empty()) {
684 labeladdon = int(labelfont_metrics.maxHeight()
685 * layout->spacing.getValue()
686 * text_->spacing(buffer, par));
689 // special code for the top label
690 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
691 || layout->labeltype == LABEL_BIBLIO
692 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
693 && isFirstInSequence(pit, pars)
694 && !par.getLabelstring().empty())
697 labelfont_metrics.maxHeight()
698 * layout->spacing.getValue()
699 * text_->spacing(buffer, par)
700 + (layout->topsep + layout->labelbottomsep) * dh);
703 // Add the layout spaces, for example before and after
704 // a section, or between the items of a itemize or enumerate
707 pit_type prev = depthHook(pit, pars, par.getDepth());
709 && pars[prev].layout() == layout
710 && pars[prev].getDepth() == par.getDepth()
711 && pars[prev].getLabelWidthString() == par.getLabelWidthString())
713 layoutasc = layout->itemsep * dh;
714 } else if (pit != 0 || row.pos() != 0) {
715 if (layout->topsep > 0)
716 layoutasc = layout->topsep * dh;
719 prev = outerHook(pit, pars);
720 if (prev != pit_type(pars.size())) {
721 maxasc += int(pars[prev].layout()->parsep * dh);
722 } else if (pit != 0) {
723 if (pars[pit - 1].getDepth() != 0 ||
724 pars[pit - 1].layout() == layout) {
725 maxasc += int(layout->parsep * dh);
730 // is it a bottom line?
731 if (row.endpos() >= par.size()) {
732 // add the layout spaces, for example before and after
733 // a section, or between the items of a itemize or enumerate
735 pit_type nextpit = pit + 1;
736 if (nextpit != pit_type(pars.size())) {
741 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
742 usual = pars[cpit].layout()->bottomsep * dh;
743 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
744 if (pars[cpit].layout() != pars[nextpit].layout()
745 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
747 unusual = pars[cpit].layout()->bottomsep * dh;
749 layoutdesc = max(unusual, usual);
750 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
751 if (pars[cpit].layout() != pars[nextpit].layout()
752 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
753 layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
758 // incalculate the layout spaces
759 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
760 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
762 // FIXME: the correct way is to do the following is to move the
763 // following code in another method specially tailored for the
764 // main LyXText. The following test is thus bogus.
765 // Top and bottom margin of the document (only at top-level)
767 if (pit == 0 && row.pos() == 0)
769 if (pit + 1 == pit_type(pars.size()) &&
770 row.endpos() == par.size())
774 row.ascent(maxasc + labeladdon);
775 row.descent(maxdesc);
779 // x is an absolute screen coord
780 // returns the column near the specified x-coordinate of the row
781 // x is set to the real beginning of this column
782 pos_type TextMetrics::getColumnNearX(pit_type const pit,
783 Row const & row, int & x, bool & boundary) const
785 Buffer const & buffer = *bv_->buffer();
787 /// For the main LyXText, it is possible that this pit is not
788 /// yet in the CoordCache when moving cursor up.
789 /// x Paragraph coordinate is always 0 for main text anyway.
790 int const xo = main_text_? 0 : bv_->coordCache().get(text_, pit).x_;
792 RowMetrics const r = computeRowMetrics(pit, row);
793 Paragraph const & par = text_->getPar(pit);
795 pos_type vc = row.pos();
796 pos_type end = row.endpos();
798 LyXLayout_ptr const & layout = par.layout();
800 bool left_side = false;
802 pos_type body_pos = par.beginOfBody();
805 double last_tmpx = tmpx;
808 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
811 // check for empty row
817 frontend::FontMetrics const & fm
818 = theFontMetrics(text_->getLabelFont(buffer, par));
820 while (vc < end && tmpx <= x) {
821 c = text_->bidi.vis2log(vc);
823 if (body_pos > 0 && c == body_pos - 1) {
825 docstring const lsep = from_utf8(layout->labelsep);
826 tmpx += r.label_hfill + fm.width(lsep);
827 if (par.isLineSeparator(body_pos - 1))
828 tmpx -= text_->singleWidth(buffer, par, body_pos - 1);
831 if (par.hfillExpansion(row, c)) {
832 tmpx += text_->singleWidth(buffer, par, c);
836 tmpx += r.label_hfill;
837 } else if (par.isSeparator(c)) {
838 tmpx += text_->singleWidth(buffer, par, c);
842 tmpx += text_->singleWidth(buffer, par, c);
847 if ((tmpx + last_tmpx) / 2 > x) {
852 BOOST_ASSERT(vc <= end); // This shouldn't happen.
855 // This (rtl_support test) is not needed, but gives
856 // some speedup if rtl_support == false
857 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
859 // If lastrow is false, we don't need to compute
861 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
863 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
864 (!rtl && !left_side && vc == end && x > tmpx + 5)))
866 else if (vc == row.pos()) {
867 c = text_->bidi.vis2log(vc);
868 if (text_->bidi.level(c) % 2 == 1)
871 c = text_->bidi.vis2log(vc - 1);
872 bool const rtl = (text_->bidi.level(c) % 2 == 1);
873 if (left_side == rtl) {
875 boundary = text_->bidi.isBoundary(buffer, par, c);
879 // I believe this code is not needed anymore (Jug 20050717)
881 // The following code is necessary because the cursor position past
882 // the last char in a row is logically equivalent to that before
883 // the first char in the next row. That's why insets causing row
884 // divisions -- Newline and display-style insets -- must be treated
885 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
886 // Newline inset, air gap below:
887 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
888 if (text_->bidi.level(end -1) % 2 == 0)
889 tmpx -= text_->singleWidth(buffer, par, end - 1);
891 tmpx += text_->singleWidth(buffer, par, end - 1);
895 // Air gap above display inset:
896 if (row.pos() < end && c >= end && end < par.size()
897 && par.isInset(end) && par.getInset(end)->display()) {
900 // Air gap below display inset:
901 if (row.pos() < end && c >= end && par.isInset(end - 1)
902 && par.getInset(end - 1)->display()) {
908 pos_type const col = c - row.pos();
910 if (!c || end == par.size())
913 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
918 return min(col, end - 1 - row.pos());
922 int defaultRowHeight()
924 return int(theFontMetrics(LyXFont(LyXFont::ALL_SANE)).maxHeight() * 1.2);