]> git.lyx.org Git - features.git/blob - src/Row.cpp
Break multi-row strings in one pass
[features.git] / src / Row.cpp
1 /**
2  * \file Row.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author André Pönitz
9  * \author Jürgen Vigna
10  * \author Jean-Marc Lasgouttes
11  *
12  * Full author contact details are available in file CREDITS.
13  *
14  * Metrics for an on-screen text row.
15  */
16
17 #include <config.h>
18
19 #include "Row.h"
20
21 #include "DocIterator.h"
22 #include "Language.h"
23
24 #include "frontends/FontMetrics.h"
25
26 #include "support/debug.h"
27 #include "support/lassert.h"
28 #include "support/lstrings.h"
29 #include "support/lyxlib.h"
30
31 #include <algorithm>
32 #include <ostream>
33
34 using namespace std;
35
36 namespace lyx {
37
38 using frontend::FontMetrics;
39
40
41 // Maximum length that a space can be stretched when justifying text
42 static double const MAX_SPACE_STRETCH = 1.5; //em
43
44
45 int Row::Element::countSeparators() const
46 {
47         if (type != STRING)
48                 return 0;
49         return count(str.begin(), str.end(), ' ');
50 }
51
52
53 int Row::Element::countExpanders() const
54 {
55         if (type != STRING)
56                 return 0;
57         return theFontMetrics(font).countExpanders(str);
58 }
59
60
61 int Row::Element::expansionAmount() const
62 {
63         if (type != STRING)
64                 return 0;
65         return countExpanders() * theFontMetrics(font).em();
66 }
67
68
69 void Row::Element::setExtra(double extra_per_em)
70 {
71         if (type != STRING)
72                 return;
73         extra = extra_per_em * theFontMetrics(font).em();
74 }
75
76
77 double Row::Element::pos2x(pos_type const i) const
78 {
79         // This can happen with inline completion when clicking on the
80         // row after the completion.
81         if (i < pos || i > endpos)
82                 return 0;
83
84         double w = 0;
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;
90         else {
91                 FontMetrics const & fm = theFontMetrics(font);
92                 w = fm.pos2x(str, i - pos, isRTL(), extra);
93         }
94
95         return w;
96 }
97
98
99 pos_type Row::Element::x2pos(int &x) const
100 {
101         //lyxerr << "x2pos: x=" << x << " w=" << width() << " " << *this;
102         size_t i = 0;
103
104         switch (type) {
105         case STRING: {
106                 FontMetrics const & fm = theFontMetrics(font);
107                 i = fm.x2pos(str, x, isRTL(), extra);
108                 break;
109         }
110         case VIRTUAL:
111                 // those elements are actually empty (but they have a width)
112                 i = 0;
113                 x = isRTL() ? int(full_width()) : 0;
114                 break;
115         case INSET:
116         case SPACE:
117                 // those elements contain only one position. Round to
118                 // the closest side.
119                 if (x > (full_width() + 1) / 2) {
120                         x = int(full_width());
121                         i = !isRTL();
122                 } else {
123                         x = 0;
124                         i = isRTL();
125                 }
126         }
127         //lyxerr << "=> p=" << pos + i << " x=" << x << endl;
128         return pos + i;
129 }
130
131
132 bool Row::Element::splitAt(int const width, int next_width, bool force,
133                            Row::Elements & tail)
134 {
135         // Not a string or already OK.
136         if (type != STRING || (dim.wid > 0 && dim.wid < width))
137                 return false;
138
139         FontMetrics const & fm = theFontMetrics(font);
140
141         // A a string that is not breakable
142         if (!(row_flags & CanBreakInside)) {
143                 // has width been computed yet?
144                 if (dim.wid == 0)
145                         dim.wid = fm.width(str);
146                 return false;
147         }
148
149         bool const wrap_any = !font.language()->wordWrap();
150         FontMetrics::Breaks breaks = fm.breakString(str, width, next_width,
151                                                 isRTL(), wrap_any | force);
152
153         // if breaking did not really work, give up
154         if (!force && breaks.front().wid > width) {
155                 if (dim.wid == 0)
156                         dim.wid = fm.width(str);
157                 return false;
158         }
159
160         Element first_e(STRING, pos, font, change);
161         // should next element eventually replace *this?
162         bool first = true;
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;
168                 e.dim.wid = brk.wid;
169                 e.row_flags = CanBreakInside | BreakAfter;
170                 if (first) {
171                         // this element eventually goes to *this
172                         e.row_flags |= row_flags & ~AfterFlags;
173                         first_e = e;
174                         first = false;
175                 } else
176                         tail.push_back(e);
177                 i += brk.len;
178         }
179
180         if (!tail.empty()) {
181                 // Avoid having a last empty element. This happens when
182                 // breaking at the trailing space of string
183                 if (tail.back().str.empty())
184                         tail.pop_back();
185                 else {
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;
189                 }
190                 // first_e row should be broken after the original element
191                 first_e.row_flags |= BreakAfter;
192         } else {
193                 // Restore the after flags of the original element.
194                 first_e.row_flags &= ~BreakAfter;
195                 first_e.row_flags |= row_flags & AfterFlags;
196         }
197
198         // update ourselves
199         swap(first_e, *this);
200         return true;
201 }
202
203
204 void Row::Element::rtrim()
205 {
206         if (type != STRING)
207                 return;
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.
212          */
213         str = support::rtrim(str);
214         endpos = pos + str.length();
215 }
216
217
218 bool Row::isMarginSelected(bool left, DocIterator const & beg,
219                 DocIterator const & end) const
220 {
221         pos_type const sel_pos = left ? sel_beg : sel_end;
222         pos_type const margin_pos = left ? pos_ : end_;
223
224         // Is there a selection and is the chosen margin selected ?
225         if (!selection() || sel_pos != margin_pos)
226                 return false;
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();
240         else
241                 return true;
242 }
243
244
245 void Row::setSelectionAndMargins(DocIterator const & beg,
246                 DocIterator const & end) const
247 {
248         setSelection(beg.pos(), end.pos());
249
250         change(end_margin_sel, isMarginSelected(false, beg, end));
251         change(begin_margin_sel, isMarginSelected(true, beg, end));
252 }
253
254
255 void Row::clearSelectionAndMargins() const
256 {
257         change(sel_beg, -1);
258         change(sel_end, -1);
259         change(end_margin_sel, false);
260         change(begin_margin_sel, false);
261 }
262
263
264 void Row::setSelection(pos_type beg, pos_type end) const
265 {
266         if (pos_ >= beg && pos_ <= end)
267                 change(sel_beg, pos_);
268         else if (beg > pos_ && beg <= end_)
269                 change(sel_beg, beg);
270         else
271                 change(sel_beg, -1);
272
273         if (end_ >= beg && end_ <= end)
274                 change(sel_end,end_);
275         else if (end < end_ && end >= pos_)
276                 change(sel_end, end);
277         else
278                 change(sel_end, -1);
279 }
280
281
282 bool Row::selection() const
283 {
284         return sel_beg != -1 && sel_end != -1;
285 }
286
287
288 ostream & operator<<(ostream & os, Row::Element const & e)
289 {
290         if (e.isRTL())
291                 os << e.endpos << "<<" << e.pos << " ";
292         else
293                 os << e.pos << ">>" << e.endpos << " ";
294
295         switch (e.type) {
296         case Row::STRING:
297                 os << "STRING: `" << to_utf8(e.str) << "' ("
298                    << e.countExpanders() << " expanders.), ";
299                 break;
300         case Row::VIRTUAL:
301                 os << "VIRTUAL: `" << to_utf8(e.str) << "', ";
302                 break;
303         case Row::INSET:
304                 os << "INSET: " << to_utf8(e.inset->layoutName()) << ", ";
305                 break;
306         case Row::SPACE:
307                 os << "SPACE: ";
308         }
309         os << "width=" << e.full_width() << ", row_flags=" << e.row_flags;
310         return os;
311 }
312
313
314 ostream & operator<<(ostream & os, Row::Elements const & elts)
315 {
316         double x = 0;
317         for (Row::Element const & e : elts) {
318                 os << "x=" << x << " => " << e << endl;
319                 x += e.full_width();
320         }
321         return os;
322 }
323
324
325 ostream & operator<<(ostream & os, Row const & row)
326 {
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;
340                 x += e.full_width();
341         }
342         return os;
343 }
344
345
346 int Row::left_x() const
347 {
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();
353                 ++cit;
354         }
355         return support::iround(x);
356 }
357
358
359 int Row::right_x() const
360 {
361         double x = dim_.wid;
362         const_iterator const begin = elements_.begin();
363         const_iterator cit = elements_.end();
364         while (cit != begin) {
365                 --cit;
366                 if (cit->isVirtual())
367                         x -= cit->full_width();
368                 else
369                         break;
370         }
371         return support::iround(x);
372 }
373
374
375 int Row::countSeparators() const
376 {
377         int n = 0;
378         const_iterator const end = elements_.end();
379         for (const_iterator cit = elements_.begin() ; cit != end ; ++cit)
380                 n += cit->countSeparators();
381         return n;
382 }
383
384
385 bool Row::setExtraWidth(int w)
386 {
387         if (w < 0)
388                 // this is not expected to happen (but it does)
389                 return false;
390         // amount of expansion: number of expanders time the em value for each
391         // string element
392         int exp_amount = 0;
393         for (Element const & e : elements_)
394                 exp_amount += e.expansionAmount();
395         if (!exp_amount)
396                 return false;
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
401                 return false;
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
407         dim_.wid += w;
408         return true;
409 }
410
411
412 bool Row::sameString(Font const & f, Change const & ch) const
413 {
414         if (elements_.empty())
415                 return false;
416         Element const & elt = elements_.back();
417         return elt.type == STRING && !elt.final
418                    && elt.font == f && elt.change == ch;
419 }
420
421
422 void Row::finalizeLast()
423 {
424         if (elements_.empty())
425                 return;
426         Element & elt = elements_.back();
427         if (elt.final)
428                 return;
429         elt.final = true;
430         if (elt.change.changed())
431                 changebar_ = true;
432 }
433
434
435 void Row::add(pos_type const pos, Inset const * ins, Dimension const & dim,
436               Font const & f, Change const & ch)
437 {
438         finalizeLast();
439         Element e(INSET, pos, f, ch);
440         e.inset = ins;
441         e.dim = dim;
442         e.row_flags = ins->rowFlags();
443         elements_.push_back(e);
444         dim_.wid += dim.wid;
445         changebar_ |= ins->isChanged();
446 }
447
448
449 void Row::add(pos_type const pos, char_type const c,
450               Font const & f, Change const & ch, bool can_break)
451 {
452         if (!sameString(f, ch)) {
453                 finalizeLast();
454                 Element e(STRING, pos, f, ch);
455                 e.row_flags = can_break ? CanBreakInside : Inline;
456                 elements_.push_back(e);
457         }
458         back().str += c;
459         back().endpos = pos + 1;
460 }
461
462
463 void Row::addVirtual(pos_type const pos, docstring const & s,
464                      Font const & f, Change const & ch)
465 {
466         finalizeLast();
467         Element e(VIRTUAL, pos, f, ch);
468         e.str = s;
469         e.dim.wid = theFontMetrics(f).width(s);
470         dim_.wid += e.dim.wid;
471         e.endpos = pos;
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);
477         finalizeLast();
478 }
479
480
481 void Row::addSpace(pos_type const pos, int const width,
482                    Font const & f, Change const & ch)
483 {
484         finalizeLast();
485         Element e(SPACE, pos, f, ch);
486         e.dim.wid = width;
487         elements_.push_back(e);
488         dim_.wid += e.dim.wid;
489 }
490
491
492 void Row::push_back(Row::Element const & e)
493 {
494         dim_.wid += e.dim.wid;
495         elements_.push_back(e);
496 }
497
498
499 void Row::pop_back()
500 {
501         dim_.wid -= elements_.back().dim.wid;
502         elements_.pop_back();
503 }
504
505
506 namespace {
507
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,
510                   Row::Elements & to)
511 {
512         to.insert(to.end(), it, from.end());
513         from.erase(it, from.end());
514         if (!from.empty())
515                 from.back().row_flags = (from.back().row_flags & ~AfterFlags) | BreakAfter;
516 }
517
518 }
519
520
521 Row::Elements Row::shortenIfNeeded(int const w, int const next_width)
522 {
523         // FIXME: performance: if the last element is a string, we would
524         // like to avoid computing its length.
525         finalizeLast();
526         if (empty() || width() <= w)
527                 return Elements();
528
529         Elements::iterator const beg = elements_.begin();
530         Elements::iterator const end = elements_.end();
531         int wid = left_margin;
532
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)
537                         break;
538                 wid += cit->dim.wid;
539         }
540
541         if (cit == end) {
542                 // This should not happen since the row is too long.
543                 LYXERR0("Something is wrong, cannot shorten row: " << *this);
544                 return Elements();
545         }
546
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;
550         ++cit_brk;
551         Elements tail;
552         while (cit_brk != beg) {
553                 --cit_brk;
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.
559                  */
560                 if (wid_brk <= w && brk.row_flags & CanBreakAfter) {
561                         end_ = brk.endpos;
562                         dim_.wid = wid_brk;
563                         moveElements(elements_, cit_brk + 1, tail);
564                         return tail;
565                 }
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
572                  *   break-up.
573                  */
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.
579                          */
580                         if (wid_brk + cit_brk->dim.wid < w
581                             && dim_.wid - (wid_brk + brk.dim.wid) >= next_width) {
582                                 break;
583                         }
584                         end_ = brk.endpos;
585                         *cit_brk = brk;
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);
589                         return tail;
590                 }
591                 LATTEST(tail.empty());
592         }
593
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)
597                 --cit;
598                 wid -= cit->dim.wid;
599         }
600
601         if (cit != beg) {
602                 // There is no usable separator, but several elements have
603                 // been added. We can cut right here.
604                 end_ = cit->pos;
605                 dim_.wid = wid;
606                 moveElements(elements_, cit, tail);
607                 return tail;
608         }
609
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.
613          */
614         if (cit->splitAt(w - wid, next_width, true, tail)) {
615                 LYXERR0(*cit);
616                 end_ = cit->endpos;
617                 dim_.wid = wid + cit->dim.wid;
618                 // If there are other elements, they should be removed.
619                 moveElements(elements_, cit + 1, tail);
620                 return tail;
621         }
622
623         return Elements();
624 }
625
626
627 void Row::reverseRTL(bool const rtl_par)
628 {
629         pos_type i = 0;
630         pos_type const end = elements_.size();
631         while (i < end) {
632                 // gather a sequence of elements with the same direction
633                 bool const rtl = elements_[i].isRTL();
634                 pos_type j = i;
635                 while (j < end && elements_[j].isRTL() == rtl)
636                         ++j;
637                 // if the direction is not the same as the paragraph
638                 // direction, the sequence has to be reverted.
639                 if (rtl != rtl_par)
640                         reverse(elements_.begin() + i, elements_.begin() + j);
641                 i = j;
642         }
643         // If the paragraph itself is RTL, reverse everything
644         if (rtl_par)
645                 reverse(elements_.begin(), elements_.end());
646         rtl_ = rtl_par;
647 }
648
649 Row::const_iterator const
650 Row::findElement(pos_type const pos, bool const boundary, double & x) const
651 {
652         /**
653          * When boundary is true, position i is in the row element (pos, endpos)
654          * if
655          *    pos < i <= endpos
656          * whereas, when boundary is false, the test is
657          *    pos <= i < endpos
658          * The correction below allows to handle both cases.
659         */
660         int const boundary_corr = (boundary && pos) ? -1 : 0;
661
662         x = left_margin;
663
664         /** Early return in trivial cases
665          * 1) the row is empty
666          * 2) the position is the left-most position of the row; there
667          * is a quirk here however: if the first element is virtual
668          * (end-of-par marker for example), then we have to look
669          * closer
670          */
671         if (empty()
672             || (pos == begin()->left_pos() && !boundary
673                         && !begin()->isVirtual()))
674                 return begin();
675
676         const_iterator cit = begin();
677         for ( ; cit != end() ; ++cit) {
678                 /** Look whether the cursor is inside the element's span. Note
679                  * that it is necessary to take the boundary into account, and
680                  * to accept virtual elements, in which case the position
681                  * will be before the virtual element.
682                  */
683                 if (cit->isVirtual() && pos + boundary_corr == cit->pos)
684                         break;
685                 else if (pos + boundary_corr >= cit->pos
686                          && pos + boundary_corr < cit->endpos) {
687                         x += cit->pos2x(pos);
688                         break;
689                 }
690                 x += cit->full_width();
691         }
692
693         if (cit == end())
694                 --cit;
695
696         return cit;
697 }
698
699
700 } // namespace lyx