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());
128 LYXERR0("x2pos: INVALID row element !");
130 //lyxerr << "=> p=" << pos + i << " x=" << x << endl;
135 Row::Element Row::Element::splitAt(int w, bool force)
137 if (type != STRING || !(row_flags & CanBreakInside))
140 FontMetrics const & fm = theFontMetrics(font);
142 int const i = fm.breakAt(str, dim.wid, isRTL(), force);
144 //Create a second row element to return
145 Element ret(STRING, pos + i, font, change);
146 ret.str = str.substr(i);
147 ret.endpos = ret.pos + ret.str.length();
148 // Copy the after flags of the original element to the second one.
149 ret.row_flags = row_flags & (CanBreakInside | AfterFlags);
151 // Now update ourselves
154 // Row should be broken after the original element
155 row_flags = (row_flags & ~AfterFlags) | BreakAfter;
156 //LYXERR0("breakAt(" << w << ") Row element Broken at " << w << "(w(str)=" << fm.width(str) << "): e=" << *this);
164 void Row::Element::rtrim()
168 /* This is intended for strings that have been created by splitAt.
169 * They may have trailing spaces, but they are not counted in the
170 * string length (QTextLayout feature, actually). We remove them,
171 * and decrease endpos, since spaces at row break are invisible.
173 str = support::rtrim(str);
174 endpos = pos + str.length();
178 bool Row::isMarginSelected(bool left, DocIterator const & beg,
179 DocIterator const & end) const
181 pos_type const sel_pos = left ? sel_beg : sel_end;
182 pos_type const margin_pos = left ? pos_ : end_;
184 // Is there a selection and is the chosen margin selected ?
185 if (!selection() || sel_pos != margin_pos)
187 else if (beg.pos() == end.pos())
188 // This is a special case in which the space between after
189 // pos i-1 and before pos i is selected, i.e. the margins
190 // (see DocIterator::boundary_).
191 return beg.boundary() && !end.boundary();
192 else if (end.pos() == margin_pos)
193 // If the selection ends around the margin, it is only
194 // drawn if the cursor is after the margin.
195 return !end.boundary();
196 else if (beg.pos() == margin_pos)
197 // If the selection begins around the margin, it is
198 // only drawn if the cursor is before the margin.
199 return beg.boundary();
205 void Row::setSelectionAndMargins(DocIterator const & beg,
206 DocIterator const & end) const
208 setSelection(beg.pos(), end.pos());
210 change(end_margin_sel, isMarginSelected(false, beg, end));
211 change(begin_margin_sel, isMarginSelected(true, beg, end));
215 void Row::clearSelectionAndMargins() const
219 change(end_margin_sel, false);
220 change(begin_margin_sel, false);
224 void Row::setSelection(pos_type beg, pos_type end) const
226 if (pos_ >= beg && pos_ <= end)
227 change(sel_beg, pos_);
228 else if (beg > pos_ && beg <= end_)
229 change(sel_beg, beg);
233 if (end_ >= beg && end_ <= end)
234 change(sel_end,end_);
235 else if (end < end_ && end >= pos_)
236 change(sel_end, end);
242 bool Row::selection() const
244 return sel_beg != -1 && sel_end != -1;
248 ostream & operator<<(ostream & os, Row::Element const & e)
251 os << e.endpos << "<<" << e.pos << " ";
253 os << e.pos << ">>" << e.endpos << " ";
257 os << "STRING: `" << to_utf8(e.str) << "' ("
258 << e.countExpanders() << " expanders.), ";
261 os << "VIRTUAL: `" << to_utf8(e.str) << "', ";
264 os << "INSET: " << to_utf8(e.inset->layoutName()) << ", ";
273 os << "width=" << e.full_width() << ", row_flags=" << e.row_flags;
278 ostream & operator<<(ostream & os, Row const & row)
280 os << " pos: " << row.pos_ << " end: " << row.end_
281 << " left_margin: " << row.left_margin
282 << " width: " << row.dim_.wid
283 << " right_margin: " << row.right_margin
284 << " ascent: " << row.dim_.asc
285 << " descent: " << row.dim_.des
286 << " separator: " << row.separator
287 << " label_hfill: " << row.label_hfill
288 << " row_boundary: " << row.right_boundary() << "\n";
289 double x = row.left_margin;
290 Row::Elements::const_iterator it = row.elements_.begin();
291 for ( ; it != row.elements_.end() ; ++it) {
292 os << "x=" << x << " => " << *it << endl;
293 x += it->full_width();
299 int Row::left_x() const
301 double x = left_margin;
302 const_iterator const end = elements_.end();
303 const_iterator cit = elements_.begin();
304 while (cit != end && cit->isVirtual()) {
305 x += cit->full_width();
308 return support::iround(x);
312 int Row::right_x() const
315 const_iterator const begin = elements_.begin();
316 const_iterator cit = elements_.end();
317 while (cit != begin) {
319 if (cit->isVirtual())
320 x -= cit->full_width();
324 return support::iround(x);
328 int Row::countSeparators() const
331 const_iterator const end = elements_.end();
332 for (const_iterator cit = elements_.begin() ; cit != end ; ++cit)
333 n += cit->countSeparators();
338 bool Row::setExtraWidth(int w)
341 // this is not expected to happen (but it does)
343 // amount of expansion: number of expanders time the em value for each
346 for (Element const & e : elements_)
347 exp_amount += e.expansionAmount();
350 // extra length per expander per em
351 double extra_per_em = double(w) / exp_amount;
352 if (extra_per_em > MAX_SPACE_STRETCH)
353 // do not stretch more than MAX_SPACE_STRETCH em per expander
355 // add extra length to each element proportionally to its em.
356 for (Element & e : elements_)
357 if (e.type == STRING)
358 e.setExtra(extra_per_em);
359 // update row dimension
365 bool Row::sameString(Font const & f, Change const & ch) const
367 if (elements_.empty())
369 Element const & elt = elements_.back();
370 return elt.type == STRING && !elt.final
371 && elt.font == f && elt.change == ch;
375 void Row::finalizeLast()
377 if (elements_.empty())
379 Element & elt = elements_.back();
383 if (elt.change.changed())
386 if (elt.type == STRING && elt.dim.wid == 0) {
387 elt.dim.wid = theFontMetrics(elt.font).width(elt.str);
388 dim_.wid += elt.dim.wid;
393 void Row::add(pos_type const pos, Inset const * ins, Dimension const & dim,
394 Font const & f, Change const & ch)
397 Element e(INSET, pos, f, ch);
400 e.row_flags = ins->rowFlags();
401 elements_.push_back(e);
403 changebar_ |= ins->isChanged();
407 void Row::add(pos_type const pos, char_type const c,
408 Font const & f, Change const & ch, bool can_break)
410 if (!sameString(f, ch)) {
412 Element e(STRING, pos, f, ch);
413 e.row_flags = can_break ? CanBreakInside : Inline;
414 elements_.push_back(e);
417 back().endpos = pos + 1;
421 void Row::addVirtual(pos_type const pos, docstring const & s,
422 Font const & f, Change const & ch)
425 Element e(VIRTUAL, pos, f, ch);
427 e.dim.wid = theFontMetrics(f).width(s);
428 dim_.wid += e.dim.wid;
430 // Copy after* flags from previous elements, forbid break before element
431 int const prev_row_flags = elements_.empty() ? Inline : elements_.back().row_flags;
432 int const can_inherit = AfterFlags & ~AlwaysBreakAfter;
433 e.row_flags = (prev_row_flags & can_inherit) | NoBreakBefore;
434 elements_.push_back(e);
439 void Row::addSpace(pos_type const pos, int const width,
440 Font const & f, Change const & ch)
443 Element e(SPACE, pos, f, ch);
445 elements_.push_back(e);
446 dim_.wid += e.dim.wid;
450 void Row::push_back(Row::Element const & e)
452 dim_.wid += e.dim.wid;
453 elements_.push_back(e);
459 dim_.wid -= elements_.back().dim.wid;
460 elements_.pop_back();
466 // Remove stuff after \c it from \c elts, and return it.
467 // if \c init is provided, it will prepended to the rest
468 Row::Elements splitFrom(Row::Elements & elts, Row::Elements::iterator const & it,
469 Row::Element const & init = Row::Element())
474 ret.insert(ret.end(), it, elts.end());
475 elts.erase(it, elts.end());
477 elts.back().row_flags = (elts.back().row_flags & ~AfterFlags) | BreakAfter;
484 Row::Elements Row::shortenIfNeeded(int const w, int const next_width)
486 // FIXME: performance: if the last element is a string, we would
487 // like to avoid computing its length.
489 if (empty() || width() <= w)
492 Elements::iterator const beg = elements_.begin();
493 Elements::iterator const end = elements_.end();
494 int wid = left_margin;
496 // Search for the first element that goes beyond right margin
497 Elements::iterator cit = beg;
498 for ( ; cit != end ; ++cit) {
499 if (wid + cit->dim.wid > w)
505 // This should not happen since the row is too long.
506 LYXERR0("Something is wrong, cannot shorten row: " << *this);
510 // Iterate backwards over breakable elements and try to break them
511 Elements::iterator cit_brk = cit;
512 int wid_brk = wid + cit_brk->dim.wid;
514 while (cit_brk != beg) {
516 // make a copy of the element to work on it.
517 Element brk = *cit_brk;
518 /* If the current element is an inset that allows breaking row
519 * after itself, and if the row is already short enough after
520 * this inset, then cut right after this element.
522 if (wid_brk <= w && brk.row_flags & CanBreakAfter) {
525 return splitFrom(elements_, cit_brk + 1);
527 // assume now that the current element is not there
528 wid_brk -= brk.dim.wid;
530 * Some Asian languages split lines anywhere (no notion of
531 * word). It seems that QTextLayout is not aware of this fact.
533 * https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
535 * FIXME: Something shall be done about characters which are
536 * not allowed at the beginning or end of line.
538 bool const word_wrap = brk.font.language()->wordWrap();
539 /* We have found a suitable separable element. This is the common case.
540 * Try to break it cleanly (at word boundary) at a length that is both
541 * - less than the available space on the row
542 * - shorter than the natural width of the element, in order to enforce
545 Element remainder = brk.splitAt(min(w - wid_brk, brk.dim.wid - 2), !word_wrap);
546 if (brk.row_flags & BreakAfter) {
547 /* if this element originally did not cause a row overflow
548 * in itself, and the remainder of the row would still be
549 * too large after breaking, then we will have issues in
550 * next row. Thus breaking does not help.
552 if (wid_brk + cit_brk->dim.wid < w
553 && dim_.wid - (wid_brk + brk.dim.wid) >= next_width) {
558 dim_.wid = wid_brk + brk.dim.wid;
559 // If there are other elements, they should be removed.
560 // remainder can be empty when splitting at trailing space
561 if (remainder.str.empty())
562 return splitFrom(elements_, next(cit_brk, 1));
564 return splitFrom(elements_, next(cit_brk, 1), remainder);
568 if (cit != beg && cit->row_flags & NoBreakBefore) {
569 // It is not possible to separate this element from the
570 // previous one. (e.g. VIRTUAL)
576 // There is no usable separator, but several elements have
577 // been added. We can cut right here.
580 return splitFrom(elements_, cit);
583 /* If we are here, it means that we have not found a separator to
584 * shorten the row. Let's try to break it again, but not at word
585 * boundary this time.
587 Element remainder = cit->splitAt(w - wid, true);
588 if (cit->row_flags & BreakAfter) {
590 dim_.wid = wid + cit->dim.wid;
591 // If there are other elements, they should be removed.
592 return splitFrom(elements_, next(cit, 1), remainder);
598 void Row::reverseRTL(bool const rtl_par)
601 pos_type const end = elements_.size();
603 // gather a sequence of elements with the same direction
604 bool const rtl = elements_[i].isRTL();
606 while (j < end && elements_[j].isRTL() == rtl)
608 // if the direction is not the same as the paragraph
609 // direction, the sequence has to be reverted.
611 reverse(elements_.begin() + i, elements_.begin() + j);
614 // If the paragraph itself is RTL, reverse everything
616 reverse(elements_.begin(), elements_.end());
620 Row::const_iterator const
621 Row::findElement(pos_type const pos, bool const boundary, double & x) const
624 * When boundary is true, position i is in the row element (pos, endpos)
627 * whereas, when boundary is false, the test is
629 * The correction below allows to handle both cases.
631 int const boundary_corr = (boundary && pos) ? -1 : 0;
635 /** Early return in trivial cases
636 * 1) the row is empty
637 * 2) the position is the left-most position of the row; there
638 * is a quirk here however: if the first element is virtual
639 * (end-of-par marker for example), then we have to look
643 || (pos == begin()->left_pos() && !boundary
644 && !begin()->isVirtual()))
647 const_iterator cit = begin();
648 for ( ; cit != end() ; ++cit) {
649 /** Look whether the cursor is inside the element's span. Note
650 * that it is necessary to take the boundary into account, and
651 * to accept virtual elements, in which case the position
652 * will be before the virtual element.
654 if (cit->isVirtual() && pos + boundary_corr == cit->pos)
656 else if (pos + boundary_corr >= cit->pos
657 && pos + boundary_corr < cit->endpos) {
658 x += cit->pos2x(pos);
661 x += cit->full_width();