]> git.lyx.org Git - features.git/blob - src/Row.cpp
Fix setting of row pos/endpos (overlapping rows)
[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                 break;
127         case INVALID:
128                 LYXERR0("x2pos: INVALID row element !");
129         }
130         //lyxerr << "=> p=" << pos + i << " x=" << x << endl;
131         return pos + i;
132 }
133
134
135 Row::Element Row::Element::splitAt(int w, bool force)
136 {
137         if (type != STRING || !(row_flags & CanBreakInside))
138                 return Element();
139
140         FontMetrics const & fm = theFontMetrics(font);
141         dim.wid = w;
142         int const i = fm.breakAt(str, dim.wid, isRTL(), force);
143         if (i != -1) {
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);
150
151                 // Now update ourselves
152                 str.erase(i);
153                 endpos = pos + i;
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);
157                 return ret;
158         }
159
160         return Element();
161 }
162
163
164 void Row::Element::rtrim()
165 {
166         if (type != STRING)
167                 return;
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.
172          */
173         str = support::rtrim(str);
174         endpos = pos + str.length();
175 }
176
177
178 bool Row::isMarginSelected(bool left, DocIterator const & beg,
179                 DocIterator const & end) const
180 {
181         pos_type const sel_pos = left ? sel_beg : sel_end;
182         pos_type const margin_pos = left ? pos_ : end_;
183
184         // Is there a selection and is the chosen margin selected ?
185         if (!selection() || sel_pos != margin_pos)
186                 return false;
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();
200         else
201                 return true;
202 }
203
204
205 void Row::setSelectionAndMargins(DocIterator const & beg,
206                 DocIterator const & end) const
207 {
208         setSelection(beg.pos(), end.pos());
209
210         change(end_margin_sel, isMarginSelected(false, beg, end));
211         change(begin_margin_sel, isMarginSelected(true, beg, end));
212 }
213
214
215 void Row::clearSelectionAndMargins() const
216 {
217         change(sel_beg, -1);
218         change(sel_end, -1);
219         change(end_margin_sel, false);
220         change(begin_margin_sel, false);
221 }
222
223
224 void Row::setSelection(pos_type beg, pos_type end) const
225 {
226         if (pos_ >= beg && pos_ <= end)
227                 change(sel_beg, pos_);
228         else if (beg > pos_ && beg <= end_)
229                 change(sel_beg, beg);
230         else
231                 change(sel_beg, -1);
232
233         if (end_ >= beg && end_ <= end)
234                 change(sel_end,end_);
235         else if (end < end_ && end >= pos_)
236                 change(sel_end, end);
237         else
238                 change(sel_end, -1);
239 }
240
241
242 bool Row::selection() const
243 {
244         return sel_beg != -1 && sel_end != -1;
245 }
246
247
248 ostream & operator<<(ostream & os, Row::Element const & e)
249 {
250         if (e.isRTL())
251                 os << e.endpos << "<<" << e.pos << " ";
252         else
253                 os << e.pos << ">>" << e.endpos << " ";
254
255         switch (e.type) {
256         case Row::STRING:
257                 os << "STRING: `" << to_utf8(e.str) << "' ("
258                    << e.countExpanders() << " expanders.), ";
259                 break;
260         case Row::VIRTUAL:
261                 os << "VIRTUAL: `" << to_utf8(e.str) << "', ";
262                 break;
263         case Row::INSET:
264                 os << "INSET: " << to_utf8(e.inset->layoutName()) << ", ";
265                 break;
266         case Row::SPACE:
267                 os << "SPACE: ";
268                 break;
269         case Row::INVALID:
270                 os << "INVALID: ";
271                 break;
272         }
273         os << "width=" << e.full_width() << ", row_flags=" << e.row_flags;
274         return os;
275 }
276
277
278 ostream & operator<<(ostream & os, Row const & row)
279 {
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();
294         }
295         return os;
296 }
297
298
299 int Row::left_x() const
300 {
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();
306                 ++cit;
307         }
308         return support::iround(x);
309 }
310
311
312 int Row::right_x() const
313 {
314         double x = dim_.wid;
315         const_iterator const begin = elements_.begin();
316         const_iterator cit = elements_.end();
317         while (cit != begin) {
318                 --cit;
319                 if (cit->isVirtual())
320                         x -= cit->full_width();
321                 else
322                         break;
323         }
324         return support::iround(x);
325 }
326
327
328 int Row::countSeparators() const
329 {
330         int n = 0;
331         const_iterator const end = elements_.end();
332         for (const_iterator cit = elements_.begin() ; cit != end ; ++cit)
333                 n += cit->countSeparators();
334         return n;
335 }
336
337
338 bool Row::setExtraWidth(int w)
339 {
340         if (w < 0)
341                 // this is not expected to happen (but it does)
342                 return false;
343         // amount of expansion: number of expanders time the em value for each
344         // string element
345         int exp_amount = 0;
346         for (Element const & e : elements_)
347                 exp_amount += e.expansionAmount();
348         if (!exp_amount)
349                 return false;
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
354                 return false;
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
360         dim_.wid += w;
361         return true;
362 }
363
364
365 bool Row::sameString(Font const & f, Change const & ch) const
366 {
367         if (elements_.empty())
368                 return false;
369         Element const & elt = elements_.back();
370         return elt.type == STRING && !elt.final
371                    && elt.font == f && elt.change == ch;
372 }
373
374
375 void Row::finalizeLast()
376 {
377         if (elements_.empty())
378                 return;
379         Element & elt = elements_.back();
380         if (elt.final)
381                 return;
382         elt.final = true;
383         if (elt.change.changed())
384                 changebar_ = true;
385
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;
389         }
390 }
391
392
393 void Row::add(pos_type const pos, Inset const * ins, Dimension const & dim,
394               Font const & f, Change const & ch)
395 {
396         finalizeLast();
397         Element e(INSET, pos, f, ch);
398         e.inset = ins;
399         e.dim = dim;
400         e.row_flags = ins->rowFlags();
401         elements_.push_back(e);
402         dim_.wid += dim.wid;
403         changebar_ |= ins->isChanged();
404 }
405
406
407 void Row::add(pos_type const pos, char_type const c,
408               Font const & f, Change const & ch, bool can_break)
409 {
410         if (!sameString(f, ch)) {
411                 finalizeLast();
412                 Element e(STRING, pos, f, ch);
413                 e.row_flags = can_break ? CanBreakInside : Inline;
414                 elements_.push_back(e);
415         }
416         back().str += c;
417         back().endpos = pos + 1;
418 }
419
420
421 void Row::addVirtual(pos_type const pos, docstring const & s,
422                      Font const & f, Change const & ch)
423 {
424         finalizeLast();
425         Element e(VIRTUAL, pos, f, ch);
426         e.str = s;
427         e.dim.wid = theFontMetrics(f).width(s);
428         dim_.wid += e.dim.wid;
429         e.endpos = pos;
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);
435         finalizeLast();
436 }
437
438
439 void Row::addSpace(pos_type const pos, int const width,
440                    Font const & f, Change const & ch)
441 {
442         finalizeLast();
443         Element e(SPACE, pos, f, ch);
444         e.dim.wid = width;
445         elements_.push_back(e);
446         dim_.wid += e.dim.wid;
447 }
448
449
450 void Row::push_back(Row::Element const & e)
451 {
452         dim_.wid += e.dim.wid;
453         elements_.push_back(e);
454 }
455
456
457 void Row::pop_back()
458 {
459         dim_.wid -= elements_.back().dim.wid;
460         elements_.pop_back();
461 }
462
463
464 namespace {
465
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())
470 {
471         Row::Elements ret;
472         if (init.isValid())
473                 ret.push_back(init);
474         ret.insert(ret.end(), it, elts.end());
475         elts.erase(it, elts.end());
476         if (!elts.empty())
477                 elts.back().row_flags = (elts.back().row_flags & ~AfterFlags) | BreakAfter;
478         return ret;
479 }
480
481 }
482
483
484 Row::Elements Row::shortenIfNeeded(int const w, int const next_width)
485 {
486         // FIXME: performance: if the last element is a string, we would
487         // like to avoid computing its length.
488         finalizeLast();
489         if (empty() || width() <= w)
490                 return Elements();
491
492         Elements::iterator const beg = elements_.begin();
493         Elements::iterator const end = elements_.end();
494         int wid = left_margin;
495
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)
500                         break;
501                 wid += cit->dim.wid;
502         }
503
504         if (cit == end) {
505                 // This should not happen since the row is too long.
506                 LYXERR0("Something is wrong, cannot shorten row: " << *this);
507                 return Elements();
508         }
509
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;
513         ++cit_brk;
514         while (cit_brk != beg) {
515                 --cit_brk;
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.
521                  */
522                 if (wid_brk <= w && brk.row_flags & CanBreakAfter) {
523                         end_ = brk.endpos;
524                         dim_.wid = wid_brk;
525                         return splitFrom(elements_, cit_brk + 1);
526                 }
527                 // assume now that the current element is not there
528                 wid_brk -= brk.dim.wid;
529                 /*
530                  * Some Asian languages split lines anywhere (no notion of
531                  * word). It seems that QTextLayout is not aware of this fact.
532                  * See for reference:
533                  *    https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
534                  *
535                  * FIXME: Something shall be done about characters which are
536                  * not allowed at the beginning or end of line.
537                 */
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
543                  *   break-up.
544                  */
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.
551                          */
552                         if (wid_brk + cit_brk->dim.wid < w
553                             && dim_.wid - (wid_brk + brk.dim.wid) >= next_width) {
554                                 break;
555                         }
556                         end_ = brk.endpos;
557                         *cit_brk = brk;
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));
563                         else
564                                 return splitFrom(elements_, next(cit_brk, 1), remainder);
565                 }
566         }
567
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)
571                 --cit;
572                 wid -= cit->dim.wid;
573         }
574
575         if (cit != beg) {
576                 // There is no usable separator, but several elements have
577                 // been added. We can cut right here.
578                 end_ = cit->pos;
579                 dim_.wid = wid;
580                 return splitFrom(elements_, cit);
581         }
582
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.
586          */
587         Element remainder = cit->splitAt(w - wid, true);
588         if (cit->row_flags & BreakAfter) {
589                 end_ = cit->endpos;
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);
593         }
594         return Elements();
595 }
596
597
598 void Row::reverseRTL(bool const rtl_par)
599 {
600         pos_type i = 0;
601         pos_type const end = elements_.size();
602         while (i < end) {
603                 // gather a sequence of elements with the same direction
604                 bool const rtl = elements_[i].isRTL();
605                 pos_type j = i;
606                 while (j < end && elements_[j].isRTL() == rtl)
607                         ++j;
608                 // if the direction is not the same as the paragraph
609                 // direction, the sequence has to be reverted.
610                 if (rtl != rtl_par)
611                         reverse(elements_.begin() + i, elements_.begin() + j);
612                 i = j;
613         }
614         // If the paragraph itself is RTL, reverse everything
615         if (rtl_par)
616                 reverse(elements_.begin(), elements_.end());
617         rtl_ = rtl_par;
618 }
619
620 Row::const_iterator const
621 Row::findElement(pos_type const pos, bool const boundary, double & x) const
622 {
623         /**
624          * When boundary is true, position i is in the row element (pos, endpos)
625          * if
626          *    pos < i <= endpos
627          * whereas, when boundary is false, the test is
628          *    pos <= i < endpos
629          * The correction below allows to handle both cases.
630         */
631         int const boundary_corr = (boundary && pos) ? -1 : 0;
632
633         x = left_margin;
634
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
640          * closer
641          */
642         if (empty()
643             || (pos == begin()->left_pos() && !boundary
644                         && !begin()->isVirtual()))
645                 return begin();
646
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.
653                  */
654                 if (cit->isVirtual() && pos + boundary_corr == cit->pos)
655                         break;
656                 else if (pos + boundary_corr >= cit->pos
657                          && pos + boundary_corr < cit->endpos) {
658                         x += cit->pos2x(pos);
659                         break;
660                 }
661                 x += cit->full_width();
662         }
663
664         if (cit == end())
665                 --cit;
666
667         return cit;
668 }
669
670
671 } // namespace lyx