3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
10 * \author Jean-Marc Lasgouttes
12 * Full author contact details are available in file CREDITS.
14 * Metrics for an on-screen text row.
21 #include "DocIterator.h"
24 #include "frontends/FontMetrics.h"
26 #include "support/debug.h"
27 #include "support/lassert.h"
28 #include "support/lstrings.h"
29 #include "support/lyxlib.h"
30 #include "support/textutils.h"
39 using frontend::FontMetrics;
42 // Maximum length that a space can be stretched when justifying text
43 static double const MAX_SPACE_STRETCH = 1.5; //em
46 int Row::Element::countExpanders() const
50 return support::countExpanders(str);
54 int Row::Element::expansionAmount() const
58 return countExpanders() * theFontMetrics(font).em();
62 void Row::Element::setExtra(double extra_per_em)
66 extra = extra_per_em * theFontMetrics(font).em();
70 double Row::Element::pos2x(pos_type const i) const
72 // This can happen with inline completion when clicking on the
73 // row after the completion.
74 if (i < pos || i > endpos)
78 //handle first the two bounds of the element
79 if (i == endpos && type != VIRTUAL)
80 w = isRTL() ? 0 : full_width();
81 else if (i == pos || type != STRING)
82 w = isRTL() ? full_width() : 0;
84 FontMetrics const & fm = theFontMetrics(font);
85 w = fm.pos2x(str, i - pos, isRTL(), extra);
92 pos_type Row::Element::x2pos(int &x) const
94 //lyxerr << "x2pos: x=" << x << " w=" << width() << " " << *this;
99 FontMetrics const & fm = theFontMetrics(font);
100 i = fm.x2pos(str, x, isRTL(), extra);
104 // those elements are actually empty (but they have a width)
106 x = isRTL() ? int(full_width()) : 0;
111 // those elements contain only one position. Round to
113 if (x > (full_width() + 1) / 2) {
114 x = int(full_width());
121 //lyxerr << "=> p=" << pos + i << " x=" << x << endl;
126 bool Row::Element::splitAt(int const width, int next_width, bool force,
127 Row::Elements & tail)
129 // Not a string or already OK.
130 if (type != STRING || (dim.wid > 0 && dim.wid < width))
133 FontMetrics const & fm = theFontMetrics(font);
135 // A a string that is not breakable
136 if (!(row_flags & CanBreakInside)) {
137 // has width been computed yet?
139 dim.wid = fm.width(str);
143 bool const wrap_any = !font.language()->wordWrap();
144 FontMetrics::Breaks breaks = fm.breakString(str, width, next_width,
145 isRTL(), wrap_any | force);
147 /** if breaking did not really work, give up
148 * case 1: we do not force break and the first element is longer than the limit;
149 * case 2: the first break occurs at the front of the string
151 if ((!force && breaks.front().nspc_wid > width)
152 || (breaks.size() > 1 && breaks.front().len == 0)) {
154 dim.wid = fm.width(str);
158 Element first_e(STRING, pos, font, change);
159 // should next element eventually replace *this?
161 docstring::size_type i = 0;
162 for (FontMetrics::Break const & brk : breaks) {
163 Element e(STRING, pos + i, font, change);
164 e.str = str.substr(i, brk.len);
165 e.endpos = e.pos + brk.len;
167 e.nspc_wid = brk.nspc_wid;
168 e.row_flags = CanBreakInside | BreakAfter;
170 // this element eventually goes to *this
171 e.row_flags |= row_flags & ~AfterFlags;
180 // Avoid having a last empty element. This happens when
181 // breaking at the trailing space of string
182 if (tail.back().str.empty())
185 // Copy the after flags of the original element to the last one.
186 tail.back().row_flags &= ~BreakAfter;
187 tail.back().row_flags |= row_flags & AfterFlags;
189 // first_e row should be broken after the original element
190 first_e.row_flags |= BreakAfter;
193 // remove the BreakAfter that got added above.
194 first_e.row_flags &= ~BreakAfter;
196 // FIXME : the code below looks like a good idea, but I do not
197 // have a use case yet. The question is what happens
198 // when breaking at the end of a string with a
200 // if it turns out that no breaking was necessary, remove the
201 // BreakAfter that got added above.
202 if (first_e.dim.wid <= width)
203 first_e.row_flags &= ~BreakAfter;
205 // Restore the after flags of the original element.
206 first_e.row_flags |= row_flags & AfterFlags;
210 swap(first_e, *this);
215 void Row::Element::rtrim()
217 if (type != STRING || str.empty() || !isSpace(str.back()))
219 /* This is intended for strings that have been created by splitAt.
220 * If There is a trailing space, we remove it and decrease endpos,
221 * since spaces at row break are invisible.
224 endpos = pos + str.length();
229 bool Row::isMarginSelected(bool left, DocIterator const & beg,
230 DocIterator const & end) const
232 pos_type const sel_pos = left ? sel_beg : sel_end;
233 pos_type const margin_pos = left ? pos_ : end_;
235 // Is there a selection and is the chosen margin selected ?
236 if (!selection() || sel_pos != margin_pos)
238 else if (beg.pos() == end.pos())
239 // This is a special case in which the space between after
240 // pos i-1 and before pos i is selected, i.e. the margins
241 // (see DocIterator::boundary_).
242 return beg.boundary() && !end.boundary();
243 else if (end.pos() == margin_pos)
244 // If the selection ends around the margin, it is only
245 // drawn if the cursor is after the margin.
246 return !end.boundary();
247 else if (beg.pos() == margin_pos)
248 // If the selection begins around the margin, it is
249 // only drawn if the cursor is before the margin.
250 return beg.boundary();
256 void Row::setSelectionAndMargins(DocIterator const & beg,
257 DocIterator const & end) const
259 setSelection(beg.pos(), end.pos());
261 change(end_margin_sel, isMarginSelected(false, beg, end));
262 change(begin_margin_sel, isMarginSelected(true, beg, end));
266 void Row::clearSelectionAndMargins() const
270 change(end_margin_sel, false);
271 change(begin_margin_sel, false);
275 void Row::setSelection(pos_type beg, pos_type end) const
277 if (pos_ >= beg && pos_ <= end)
278 change(sel_beg, pos_);
279 else if (beg > pos_ && beg <= end_)
280 change(sel_beg, beg);
284 if (end_ >= beg && end_ <= end)
285 change(sel_end,end_);
286 else if (end < end_ && end >= pos_)
287 change(sel_end, end);
293 bool Row::selection() const
295 return sel_beg != -1 && sel_end != -1;
299 ostream & operator<<(ostream & os, Row::Element const & e)
302 os << e.endpos << "<<" << e.pos << " ";
304 os << e.pos << ">>" << e.endpos << " ";
308 os << "STRING: `" << to_utf8(e.str) << "' ("
309 << e.countExpanders() << " expanders.), ";
312 os << "VIRTUAL: `" << to_utf8(e.str) << "', ";
315 os << "INSET: " << to_utf8(e.inset->layoutName()) << ", ";
320 case Row::MARGINSPACE:
321 os << "MARGINSPACE: ";
323 os << "width=" << e.full_width() << ", row_flags=" << e.row_flags;
328 ostream & operator<<(ostream & os, Row::Elements const & elts)
331 for (Row::Element const & e : elts) {
332 os << "x=" << x << " => " << e << endl;
339 ostream & operator<<(ostream & os, Row const & row)
341 os << " pit: " << row.pit_ << " pos: " << row.pos_ << " end: " << row.end_
342 << " left_margin: " << row.left_margin
343 << " width: " << row.dim_.wid
344 << " right_margin: " << row.right_margin
345 << " ascent: " << row.dim_.asc
346 << " descent: " << row.dim_.des
347 << " separator: " << row.separator
348 << " label_hfill: " << row.label_hfill
349 << " end_boundary: " << row.end_boundary()
350 << " flushed: " << row.flushed_
351 << " rtl=" << row.rtl_ << "\n";
352 // We cannot use the operator above, unfortunately
353 double x = row.left_margin;
354 for (Row::Element const & e : row.elements_) {
355 os << "x=" << x << " => " << e << endl;
362 int Row::left_x() const
364 double x = left_margin;
365 const_iterator const end = elements_.end();
366 const_iterator cit = elements_.begin();
367 while (cit != end && cit->isVirtual()) {
368 x += cit->full_width();
371 return support::iround(x);
375 int Row::right_x() const
378 const_iterator const begin = elements_.begin();
379 const_iterator cit = elements_.end();
380 while (cit != begin) {
382 if (cit->isVirtual())
383 x -= cit->full_width();
387 return support::iround(x);
391 bool Row::setExtraWidth(int w)
394 // this is not expected to happen (but it does)
396 // amount of expansion: number of expanders time the em value for each
399 for (Element const & e : elements_)
400 exp_amount += e.expansionAmount();
403 // extra length per expander per em
404 double extra_per_em = double(w) / exp_amount;
405 if (extra_per_em > MAX_SPACE_STRETCH)
406 // do not stretch more than MAX_SPACE_STRETCH em per expander
408 // add extra length to each element proportionally to its em.
409 for (Element & e : elements_)
410 if (e.type == STRING)
411 e.setExtra(extra_per_em);
412 // update row dimension
418 bool Row::sameString(Font const & f, Change const & ch) const
420 if (elements_.empty())
422 Element const & elt = elements_.back();
423 return elt.type == STRING && !elt.final
424 && elt.font == f && elt.change == ch;
428 void Row::finalizeLast()
430 if (elements_.empty())
432 Element & elt = elements_.back();
436 if (elt.change.changed())
441 void Row::add(pos_type const pos, Inset const * ins, Dimension const & dim,
442 Font const & f, Change const & ch)
445 Element e(INSET, pos, f, ch);
448 e.row_flags = ins->rowFlags();
449 elements_.push_back(e);
451 changebar_ |= ins->isChanged();
455 void Row::add(pos_type const pos, char_type const c,
456 Font const & f, Change const & ch)
458 if (!sameString(f, ch)) {
460 Element e(STRING, pos, f, ch);
461 e.row_flags = CanBreakInside;
462 elements_.push_back(e);
465 back().endpos = pos + 1;
469 void Row::addVirtual(pos_type const pos, docstring const & s,
470 Font const & f, Change const & ch)
473 Element e(VIRTUAL, pos, f, ch);
475 e.dim.wid = theFontMetrics(f).width(s);
476 dim_.wid += e.dim.wid;
478 // Copy after* flags from previous elements, forbid break before element
479 int const prev_row_flags = elements_.empty() ? Inline : elements_.back().row_flags;
480 int const can_inherit = AfterFlags & ~AlwaysBreakAfter;
481 e.row_flags = (prev_row_flags & can_inherit) | NoBreakBefore;
482 elements_.push_back(e);
487 void Row::addSpace(pos_type const pos, int const width,
488 Font const & f, Change const & ch)
491 Element e(SPACE, pos, f, ch);
493 elements_.push_back(e);
494 dim_.wid += e.dim.wid;
498 void Row::addMarginSpace(pos_type const pos, int const width,
499 Font const & f, Change const & ch)
502 Element e(MARGINSPACE, pos, f, ch);
504 e.row_flags = NoBreakBefore;
505 elements_.push_back(e);
506 dim_.wid += e.dim.wid;
510 void Row::push_back(Row::Element const & e)
512 dim_.wid += e.dim.wid;
513 elements_.push_back(e);
519 dim_.wid -= elements_.back().dim.wid;
520 elements_.pop_back();
526 // Move stuff after \c it from \c from and the end of \c to.
527 void moveElements(Row::Elements & from, Row::Elements::iterator const & it,
530 to.insert(to.end(), it, from.end());
531 from.erase(it, from.end());
533 from.back().row_flags = (from.back().row_flags & ~AfterFlags) | AlwaysBreakAfter;
539 Row::Elements Row::shortenIfNeeded(int const w, int const next_width)
541 // FIXME: performance: if the last element is a string, we would
542 // like to avoid computing its length.
544 if (empty() || width() <= w)
547 Elements::iterator const beg = elements_.begin();
548 Elements::iterator const end = elements_.end();
549 int wid = left_margin;
551 // Search for the first element that goes beyond right margin
552 Elements::iterator cit = beg;
553 for ( ; cit != end ; ++cit) {
554 if (wid + cit->dim.wid > w)
560 // This should not happen since the row is too long.
561 LYXERR0("Something is wrong, cannot shorten row: " << *this);
565 // Iterate backwards over breakable elements and try to break them
566 Elements::iterator cit_brk = cit;
567 int wid_brk = wid + cit_brk->dim.wid;
570 while (cit_brk != beg) {
572 // make a copy of the element to work on it.
573 Element brk = *cit_brk;
574 /* If the current element is an inset that allows breaking row
575 * after itself, and if the row is already short enough after
576 * this element, then cut right after it.
578 if (wid_brk <= w && brk.row_flags & CanBreakAfter) {
581 moveElements(elements_, cit_brk + 1, tail);
584 // assume now that the current element is not there
585 wid_brk -= brk.dim.wid;
586 /* If the current element is an inset that allows breaking row
587 * before itself, and if the row is already short enough before
588 * this element, then cut right before it.
590 if (wid_brk <= w && brk.row_flags & CanBreakBefore && cit_brk != beg) {
591 end_ = (cit_brk -1)->endpos;
593 moveElements(elements_, cit_brk, tail);
596 /* We have found a suitable separable element. This is the common case.
597 * Try to break it cleanly at a length that is both
598 * - less than the available space on the row
599 * - shorter than the natural width of the element, in order to enforce
602 if (brk.splitAt(min(w - wid_brk, brk.dim.wid - 2), next_width, false, tail)) {
603 /* if this element originally did not cause a row overflow
604 * in itself, and the next item is not breakable and would
605 * still be too large after breaking, then we will have
606 * issues in next row. Thus breaking does not help.
608 * FIXME: this is not perfect, since it is difficult to
609 * know whether next element in tail is too large:
611 * - next element could be a very long word, which is
612 * theoretically breakable, but not in practice
613 * (difficult to solve).
615 * - next element could be short enough, but linked to
616 * another one with a NoBreak bond.
618 * Basically, it is difficult to solve that in a purely
619 * left-to-right algorithm; implementing the TeX badness
620 * algorithm is more difficult and more costly, so we do
621 * our best in our restricted setting.
623 auto const cit_next = cit_brk + 1;
624 int const tail_wid = !tail.empty() ? tail.front().dim.wid : 0;
625 if (wid_brk + cit_brk->dim.wid < w
626 && cit_next != elements_.end()
627 && tail_wid + cit_next->dim.wid > next_width
628 && !(cit_next->row_flags & CanBreakInside)) {
634 dim_.wid = wid_brk + brk.dim.wid;
635 // If there are other elements, they should be removed.
636 moveElements(elements_, cit_brk + 1, tail);
639 LATTEST(tail.empty());
642 if (cit != beg && cit->row_flags & NoBreakBefore) {
643 // It is not possible to separate this element from the
644 // previous one. (e.g. VIRTUAL)
650 // There is no usable separator, but several elements have
651 // been added. We can cut right here.
654 moveElements(elements_, cit, tail);
658 /* If we are here, it means that we have not found a separator to
659 * shorten the row. Let's try to break it again, but force
660 * splitting this time.
662 if (cit->splitAt(w - wid, next_width, true, tail)) {
664 dim_.wid = wid + cit->dim.wid;
665 // If there are other elements, they should be removed.
666 moveElements(elements_, cit + 1, tail);
670 // cit == beg; remove all elements after the first one.
671 moveElements(elements_, cit + 1, tail);
676 void Row::reverseRTL()
679 pos_type const end = elements_.size();
681 // gather a sequence of elements with the same direction
682 bool const rtl = elements_[i].isRTL();
684 while (j < end && elements_[j].isRTL() == rtl)
686 // if the direction is not the same as the paragraph
687 // direction, the sequence has to be reverted.
689 reverse(elements_.begin() + i, elements_.begin() + j);
692 // If the paragraph itself is RTL, reverse everything
694 reverse(elements_.begin(), elements_.end());
697 Row::const_iterator const
698 Row::findElement(pos_type const pos, bool const boundary, double & x) const
701 * When boundary is true, position i is in the row element (pos, endpos)
704 * whereas, when boundary is false, the test is
706 * The correction below allows to handle both cases.
708 int const boundary_corr = (boundary && pos) ? -1 : 0;
712 /** Early return in trivial cases
713 * 1) the row is empty
714 * 2) the position is the left-most position of the row; there
715 * is a quirk here however: if the first element is virtual
716 * (end-of-par marker for example), then we have to look
720 || (pos == begin()->left_pos() && !boundary
721 && !begin()->isVirtual()))
724 const_iterator cit = begin();
725 for ( ; cit != end() ; ++cit) {
726 /** Look whether the cursor is inside the element's span. Note
727 * that it is necessary to take the boundary into account, and
728 * to accept virtual elements, in which case the position
729 * will be before the virtual element.
731 if (cit->isVirtual() && pos + boundary_corr == cit->pos)
733 else if (pos + boundary_corr >= cit->pos
734 && pos + boundary_corr < cit->endpos) {
735 x += cit->pos2x(pos);
738 x += cit->full_width();