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"
38 using frontend::FontMetrics;
41 // Maximum length that a space can be stretched when justifying text
42 static double const MAX_SPACE_STRETCH = 1.5; //em
45 int Row::Element::countSeparators() const
49 return count(str.begin(), str.end(), ' ');
53 int Row::Element::countExpanders() const
57 return theFontMetrics(font).countExpanders(str);
61 int Row::Element::expansionAmount() const
65 return countExpanders() * theFontMetrics(font).em();
69 void Row::Element::setExtra(double extra_per_em)
73 extra = extra_per_em * theFontMetrics(font).em();
77 double Row::Element::pos2x(pos_type const i) const
79 // This can happen with inline completion when clicking on the
80 // row after the completion.
81 if (i < pos || i > endpos)
85 //handle first the two bounds of the element
86 if (i == endpos && type != VIRTUAL)
87 w = isRTL() ? 0 : full_width();
88 else if (i == pos || type != STRING)
89 w = isRTL() ? full_width() : 0;
91 FontMetrics const & fm = theFontMetrics(font);
92 w = fm.pos2x(str, i - pos, isRTL(), extra);
99 pos_type Row::Element::x2pos(int &x) const
101 //lyxerr << "x2pos: x=" << x << " w=" << width() << " " << *this;
106 FontMetrics const & fm = theFontMetrics(font);
107 i = fm.x2pos(str, x, isRTL(), extra);
111 // those elements are actually empty (but they have a width)
113 x = isRTL() ? int(full_width()) : 0;
117 // those elements contain only one position. Round to
119 if (x > (full_width() + 1) / 2) {
120 x = int(full_width());
127 //lyxerr << "=> p=" << pos + i << " x=" << x << endl;
132 bool Row::Element::splitAt(int const width, int next_width, bool force,
133 Row::Elements & tail)
135 // Not a string or already OK.
136 if (type != STRING || (dim.wid > 0 && dim.wid < width))
139 FontMetrics const & fm = theFontMetrics(font);
141 // A a string that is not breakable
142 if (!(row_flags & CanBreakInside)) {
143 // has width been computed yet?
145 dim.wid = fm.width(str);
149 bool const wrap_any = !font.language()->wordWrap();
150 FontMetrics::Breaks breaks = fm.breakString(str, width, next_width,
151 isRTL(), wrap_any | force);
153 // if breaking did not really work, give up
154 if (!force && breaks.front().wid > width) {
156 dim.wid = fm.width(str);
160 Element first_e(STRING, pos, font, change);
161 // should next element eventually replace *this?
163 docstring::size_type i = 0;
164 for (FontMetrics::Break const & brk : breaks) {
165 Element e(STRING, pos + i, font, change);
166 e.str = str.substr(i, brk.len);
167 e.endpos = e.pos + brk.len;
169 e.row_flags = CanBreakInside | BreakAfter;
171 // this element eventually goes to *this
172 e.row_flags |= row_flags & ~AfterFlags;
181 // Avoid having a last empty element. This happens when
182 // breaking at the trailing space of string
183 if (tail.back().str.empty())
186 // Copy the after flags of the original element to the last one.
187 tail.back().row_flags &= ~BreakAfter;
188 tail.back().row_flags |= row_flags & AfterFlags;
190 // first_e row should be broken after the original element
191 first_e.row_flags |= BreakAfter;
193 // Restore the after flags of the original element.
194 first_e.row_flags &= ~BreakAfter;
195 first_e.row_flags |= row_flags & AfterFlags;
199 swap(first_e, *this);
204 void Row::Element::rtrim()
208 /* This is intended for strings that have been created by splitAt.
209 * They may have trailing spaces, but they are not counted in the
210 * string length (QTextLayout feature, actually). We remove them,
211 * and decrease endpos, since spaces at row break are invisible.
213 str = support::rtrim(str);
214 endpos = pos + str.length();
218 bool Row::isMarginSelected(bool left, DocIterator const & beg,
219 DocIterator const & end) const
221 pos_type const sel_pos = left ? sel_beg : sel_end;
222 pos_type const margin_pos = left ? pos_ : end_;
224 // Is there a selection and is the chosen margin selected ?
225 if (!selection() || sel_pos != margin_pos)
227 else if (beg.pos() == end.pos())
228 // This is a special case in which the space between after
229 // pos i-1 and before pos i is selected, i.e. the margins
230 // (see DocIterator::boundary_).
231 return beg.boundary() && !end.boundary();
232 else if (end.pos() == margin_pos)
233 // If the selection ends around the margin, it is only
234 // drawn if the cursor is after the margin.
235 return !end.boundary();
236 else if (beg.pos() == margin_pos)
237 // If the selection begins around the margin, it is
238 // only drawn if the cursor is before the margin.
239 return beg.boundary();
245 void Row::setSelectionAndMargins(DocIterator const & beg,
246 DocIterator const & end) const
248 setSelection(beg.pos(), end.pos());
250 change(end_margin_sel, isMarginSelected(false, beg, end));
251 change(begin_margin_sel, isMarginSelected(true, beg, end));
255 void Row::clearSelectionAndMargins() const
259 change(end_margin_sel, false);
260 change(begin_margin_sel, false);
264 void Row::setSelection(pos_type beg, pos_type end) const
266 if (pos_ >= beg && pos_ <= end)
267 change(sel_beg, pos_);
268 else if (beg > pos_ && beg <= end_)
269 change(sel_beg, beg);
273 if (end_ >= beg && end_ <= end)
274 change(sel_end,end_);
275 else if (end < end_ && end >= pos_)
276 change(sel_end, end);
282 bool Row::selection() const
284 return sel_beg != -1 && sel_end != -1;
288 ostream & operator<<(ostream & os, Row::Element const & e)
291 os << e.endpos << "<<" << e.pos << " ";
293 os << e.pos << ">>" << e.endpos << " ";
297 os << "STRING: `" << to_utf8(e.str) << "' ("
298 << e.countExpanders() << " expanders.), ";
301 os << "VIRTUAL: `" << to_utf8(e.str) << "', ";
304 os << "INSET: " << to_utf8(e.inset->layoutName()) << ", ";
309 os << "width=" << e.full_width() << ", row_flags=" << e.row_flags;
314 ostream & operator<<(ostream & os, Row::Elements const & elts)
317 for (Row::Element const & e : elts) {
318 os << "x=" << x << " => " << e << endl;
325 ostream & operator<<(ostream & os, Row const & row)
327 os << " pos: " << row.pos_ << " end: " << row.end_
328 << " left_margin: " << row.left_margin
329 << " width: " << row.dim_.wid
330 << " right_margin: " << row.right_margin
331 << " ascent: " << row.dim_.asc
332 << " descent: " << row.dim_.des
333 << " separator: " << row.separator
334 << " label_hfill: " << row.label_hfill
335 << " row_boundary: " << row.right_boundary() << "\n";
336 // We cannot use the operator above, unfortunately
337 double x = row.left_margin;
338 for (Row::Element const & e : row.elements_) {
339 os << "x=" << x << " => " << e << endl;
346 int Row::left_x() const
348 double x = left_margin;
349 const_iterator const end = elements_.end();
350 const_iterator cit = elements_.begin();
351 while (cit != end && cit->isVirtual()) {
352 x += cit->full_width();
355 return support::iround(x);
359 int Row::right_x() const
362 const_iterator const begin = elements_.begin();
363 const_iterator cit = elements_.end();
364 while (cit != begin) {
366 if (cit->isVirtual())
367 x -= cit->full_width();
371 return support::iround(x);
375 int Row::countSeparators() const
378 const_iterator const end = elements_.end();
379 for (const_iterator cit = elements_.begin() ; cit != end ; ++cit)
380 n += cit->countSeparators();
385 bool Row::setExtraWidth(int w)
388 // this is not expected to happen (but it does)
390 // amount of expansion: number of expanders time the em value for each
393 for (Element const & e : elements_)
394 exp_amount += e.expansionAmount();
397 // extra length per expander per em
398 double extra_per_em = double(w) / exp_amount;
399 if (extra_per_em > MAX_SPACE_STRETCH)
400 // do not stretch more than MAX_SPACE_STRETCH em per expander
402 // add extra length to each element proportionally to its em.
403 for (Element & e : elements_)
404 if (e.type == STRING)
405 e.setExtra(extra_per_em);
406 // update row dimension
412 bool Row::sameString(Font const & f, Change const & ch) const
414 if (elements_.empty())
416 Element const & elt = elements_.back();
417 return elt.type == STRING && !elt.final
418 && elt.font == f && elt.change == ch;
422 void Row::finalizeLast()
424 if (elements_.empty())
426 Element & elt = elements_.back();
430 if (elt.change.changed())
435 void Row::add(pos_type const pos, Inset const * ins, Dimension const & dim,
436 Font const & f, Change const & ch)
439 Element e(INSET, pos, f, ch);
442 e.row_flags = ins->rowFlags();
443 elements_.push_back(e);
445 changebar_ |= ins->isChanged();
449 void Row::add(pos_type const pos, char_type const c,
450 Font const & f, Change const & ch, bool can_break)
452 if (!sameString(f, ch)) {
454 Element e(STRING, pos, f, ch);
455 e.row_flags = can_break ? CanBreakInside : Inline;
456 elements_.push_back(e);
459 back().endpos = pos + 1;
463 void Row::addVirtual(pos_type const pos, docstring const & s,
464 Font const & f, Change const & ch)
467 Element e(VIRTUAL, pos, f, ch);
469 e.dim.wid = theFontMetrics(f).width(s);
470 dim_.wid += e.dim.wid;
472 // Copy after* flags from previous elements, forbid break before element
473 int const prev_row_flags = elements_.empty() ? Inline : elements_.back().row_flags;
474 int const can_inherit = AfterFlags & ~AlwaysBreakAfter;
475 e.row_flags = (prev_row_flags & can_inherit) | NoBreakBefore;
476 elements_.push_back(e);
481 void Row::addSpace(pos_type const pos, int const width,
482 Font const & f, Change const & ch)
485 Element e(SPACE, pos, f, ch);
487 elements_.push_back(e);
488 dim_.wid += e.dim.wid;
492 void Row::push_back(Row::Element const & e)
494 dim_.wid += e.dim.wid;
495 elements_.push_back(e);
501 dim_.wid -= elements_.back().dim.wid;
502 elements_.pop_back();
508 // Move stuff after \c it from \c from and the end of \c to.
509 void moveElements(Row::Elements & from, Row::Elements::iterator const & it,
512 to.insert(to.end(), it, from.end());
513 from.erase(it, from.end());
515 from.back().row_flags = (from.back().row_flags & ~AfterFlags) | BreakAfter;
521 Row::Elements Row::shortenIfNeeded(int const w, int const next_width)
523 // FIXME: performance: if the last element is a string, we would
524 // like to avoid computing its length.
526 if (empty() || width() <= w)
529 Elements::iterator const beg = elements_.begin();
530 Elements::iterator const end = elements_.end();
531 int wid = left_margin;
533 // Search for the first element that goes beyond right margin
534 Elements::iterator cit = beg;
535 for ( ; cit != end ; ++cit) {
536 if (wid + cit->dim.wid > w)
542 // This should not happen since the row is too long.
543 LYXERR0("Something is wrong, cannot shorten row: " << *this);
547 // Iterate backwards over breakable elements and try to break them
548 Elements::iterator cit_brk = cit;
549 int wid_brk = wid + cit_brk->dim.wid;
552 while (cit_brk != beg) {
554 // make a copy of the element to work on it.
555 Element brk = *cit_brk;
556 /* If the current element is an inset that allows breaking row
557 * after itself, and if the row is already short enough after
558 * this inset, then cut right after this element.
560 if (wid_brk <= w && brk.row_flags & CanBreakAfter) {
563 moveElements(elements_, cit_brk + 1, tail);
566 // assume now that the current element is not there
567 wid_brk -= brk.dim.wid;
568 /* We have found a suitable separable element. This is the common case.
569 * Try to break it cleanly at a length that is both
570 * - less than the available space on the row
571 * - shorter than the natural width of the element, in order to enforce
574 if (brk.splitAt(min(w - wid_brk, brk.dim.wid - 2), next_width, false, tail)) {
575 /* if this element originally did not cause a row overflow
576 * in itself, and the remainder of the row would still be
577 * too large after breaking, then we will have issues in
578 * next row. Thus breaking does not help.
580 if (wid_brk + cit_brk->dim.wid < w
581 && dim_.wid - (wid_brk + brk.dim.wid) >= next_width) {
586 dim_.wid = wid_brk + brk.dim.wid;
587 // If there are other elements, they should be removed.
588 moveElements(elements_, cit_brk + 1, tail);
591 LATTEST(tail.empty());
594 if (cit != beg && cit->row_flags & NoBreakBefore) {
595 // It is not possible to separate this element from the
596 // previous one. (e.g. VIRTUAL)
602 // There is no usable separator, but several elements have
603 // been added. We can cut right here.
606 moveElements(elements_, cit, tail);
610 /* If we are here, it means that we have not found a separator to
611 * shorten the row. Let's try to break it again, but force
612 * splitting this time.
614 if (cit->splitAt(w - wid, next_width, true, tail)) {
617 dim_.wid = wid + cit->dim.wid;
618 // If there are other elements, they should be removed.
619 moveElements(elements_, cit + 1, tail);
627 void Row::reverseRTL()
630 pos_type const end = elements_.size();
632 // gather a sequence of elements with the same direction
633 bool const rtl = elements_[i].isRTL();
635 while (j < end && elements_[j].isRTL() == rtl)
637 // if the direction is not the same as the paragraph
638 // direction, the sequence has to be reverted.
640 reverse(elements_.begin() + i, elements_.begin() + j);
643 // If the paragraph itself is RTL, reverse everything
645 reverse(elements_.begin(), elements_.end());
648 Row::const_iterator const
649 Row::findElement(pos_type const pos, bool const boundary, double & x) const
652 * When boundary is true, position i is in the row element (pos, endpos)
655 * whereas, when boundary is false, the test is
657 * The correction below allows to handle both cases.
659 int const boundary_corr = (boundary && pos) ? -1 : 0;
663 /** Early return in trivial cases
664 * 1) the row is empty
665 * 2) the position is the left-most position of the row; there
666 * is a quirk here however: if the first element is virtual
667 * (end-of-par marker for example), then we have to look
671 || (pos == begin()->left_pos() && !boundary
672 && !begin()->isVirtual()))
675 const_iterator cit = begin();
676 for ( ; cit != end() ; ++cit) {
677 /** Look whether the cursor is inside the element's span. Note
678 * that it is necessary to take the boundary into account, and
679 * to accept virtual elements, in which case the position
680 * will be before the virtual element.
682 if (cit->isVirtual() && pos + boundary_corr == cit->pos)
684 else if (pos + boundary_corr >= cit->pos
685 && pos + boundary_corr < cit->endpos) {
686 x += cit->pos2x(pos);
689 x += cit->full_width();