]> git.lyx.org Git - lyx.git/blob - src/Row.cpp
b7e4c07c95c3903c608f78996d0e4a6fe6bff95f
[lyx.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::Elements const & elts)
279 {
280         double x = 0;
281         for (Row::Element const & e : elts) {
282                 os << "x=" << x << " => " << e << endl;
283                 x += e.full_width();
284         }
285         return os;
286 }
287
288
289 ostream & operator<<(ostream & os, Row const & row)
290 {
291         os << " pos: " << row.pos_ << " end: " << row.end_
292            << " left_margin: " << row.left_margin
293            << " width: " << row.dim_.wid
294            << " right_margin: " << row.right_margin
295            << " ascent: " << row.dim_.asc
296            << " descent: " << row.dim_.des
297            << " separator: " << row.separator
298            << " label_hfill: " << row.label_hfill
299            << " row_boundary: " << row.right_boundary() << "\n";
300         // We cannot use the operator above, unfortunately
301         double x = row.left_margin;
302         for (Row::Element const & e : row.elements_) {
303                 os << "x=" << x << " => " << e << endl;
304                 x += e.full_width();
305         }
306         return os;
307 }
308
309
310 int Row::left_x() const
311 {
312         double x = left_margin;
313         const_iterator const end = elements_.end();
314         const_iterator cit = elements_.begin();
315         while (cit != end && cit->isVirtual()) {
316                 x += cit->full_width();
317                 ++cit;
318         }
319         return support::iround(x);
320 }
321
322
323 int Row::right_x() const
324 {
325         double x = dim_.wid;
326         const_iterator const begin = elements_.begin();
327         const_iterator cit = elements_.end();
328         while (cit != begin) {
329                 --cit;
330                 if (cit->isVirtual())
331                         x -= cit->full_width();
332                 else
333                         break;
334         }
335         return support::iround(x);
336 }
337
338
339 int Row::countSeparators() const
340 {
341         int n = 0;
342         const_iterator const end = elements_.end();
343         for (const_iterator cit = elements_.begin() ; cit != end ; ++cit)
344                 n += cit->countSeparators();
345         return n;
346 }
347
348
349 bool Row::setExtraWidth(int w)
350 {
351         if (w < 0)
352                 // this is not expected to happen (but it does)
353                 return false;
354         // amount of expansion: number of expanders time the em value for each
355         // string element
356         int exp_amount = 0;
357         for (Element const & e : elements_)
358                 exp_amount += e.expansionAmount();
359         if (!exp_amount)
360                 return false;
361         // extra length per expander per em
362         double extra_per_em = double(w) / exp_amount;
363         if (extra_per_em > MAX_SPACE_STRETCH)
364                 // do not stretch more than MAX_SPACE_STRETCH em per expander
365                 return false;
366         // add extra length to each element proportionally to its em.
367         for (Element & e : elements_)
368                 if (e.type == STRING)
369                         e.setExtra(extra_per_em);
370         // update row dimension
371         dim_.wid += w;
372         return true;
373 }
374
375
376 bool Row::sameString(Font const & f, Change const & ch) const
377 {
378         if (elements_.empty())
379                 return false;
380         Element const & elt = elements_.back();
381         return elt.type == STRING && !elt.final
382                    && elt.font == f && elt.change == ch;
383 }
384
385
386 void Row::finalizeLast()
387 {
388         if (elements_.empty())
389                 return;
390         Element & elt = elements_.back();
391         if (elt.final)
392                 return;
393         elt.final = true;
394         if (elt.change.changed())
395                 changebar_ = true;
396
397         if (elt.type == STRING && elt.dim.wid == 0) {
398                 elt.dim.wid = theFontMetrics(elt.font).width(elt.str);
399                 dim_.wid += elt.dim.wid;
400         }
401 }
402
403
404 void Row::add(pos_type const pos, Inset const * ins, Dimension const & dim,
405               Font const & f, Change const & ch)
406 {
407         finalizeLast();
408         Element e(INSET, pos, f, ch);
409         e.inset = ins;
410         e.dim = dim;
411         e.row_flags = ins->rowFlags();
412         elements_.push_back(e);
413         dim_.wid += dim.wid;
414         changebar_ |= ins->isChanged();
415 }
416
417
418 void Row::add(pos_type const pos, char_type const c,
419               Font const & f, Change const & ch, bool can_break)
420 {
421         if (!sameString(f, ch)) {
422                 finalizeLast();
423                 Element e(STRING, pos, f, ch);
424                 e.row_flags = can_break ? CanBreakInside : Inline;
425                 elements_.push_back(e);
426         }
427         back().str += c;
428         back().endpos = pos + 1;
429 }
430
431
432 void Row::addVirtual(pos_type const pos, docstring const & s,
433                      Font const & f, Change const & ch)
434 {
435         finalizeLast();
436         Element e(VIRTUAL, pos, f, ch);
437         e.str = s;
438         e.dim.wid = theFontMetrics(f).width(s);
439         dim_.wid += e.dim.wid;
440         e.endpos = pos;
441         // Copy after* flags from previous elements, forbid break before element
442         int const prev_row_flags = elements_.empty() ? Inline : elements_.back().row_flags;
443         int const can_inherit = AfterFlags & ~AlwaysBreakAfter;
444         e.row_flags = (prev_row_flags & can_inherit) | NoBreakBefore;
445         elements_.push_back(e);
446         finalizeLast();
447 }
448
449
450 void Row::addSpace(pos_type const pos, int const width,
451                    Font const & f, Change const & ch)
452 {
453         finalizeLast();
454         Element e(SPACE, pos, f, ch);
455         e.dim.wid = width;
456         elements_.push_back(e);
457         dim_.wid += e.dim.wid;
458 }
459
460
461 void Row::push_back(Row::Element const & e)
462 {
463         dim_.wid += e.dim.wid;
464         elements_.push_back(e);
465 }
466
467
468 void Row::pop_back()
469 {
470         dim_.wid -= elements_.back().dim.wid;
471         elements_.pop_back();
472 }
473
474
475 namespace {
476
477 // Remove stuff after \c it from \c elts, and return it.
478 // if \c init is provided, it will prepended to the rest
479 Row::Elements splitFrom(Row::Elements & elts, Row::Elements::iterator const & it,
480                         Row::Element const & init = Row::Element())
481 {
482         Row::Elements ret;
483         if (init.isValid())
484                 ret.push_back(init);
485         ret.insert(ret.end(), it, elts.end());
486         elts.erase(it, elts.end());
487         if (!elts.empty())
488                 elts.back().row_flags = (elts.back().row_flags & ~AfterFlags) | BreakAfter;
489         return ret;
490 }
491
492 }
493
494
495 Row::Elements Row::shortenIfNeeded(int const w, int const next_width)
496 {
497         // FIXME: performance: if the last element is a string, we would
498         // like to avoid computing its length.
499         finalizeLast();
500         if (empty() || width() <= w)
501                 return Elements();
502
503         Elements::iterator const beg = elements_.begin();
504         Elements::iterator const end = elements_.end();
505         int wid = left_margin;
506
507         // Search for the first element that goes beyond right margin
508         Elements::iterator cit = beg;
509         for ( ; cit != end ; ++cit) {
510                 if (wid + cit->dim.wid > w)
511                         break;
512                 wid += cit->dim.wid;
513         }
514
515         if (cit == end) {
516                 // This should not happen since the row is too long.
517                 LYXERR0("Something is wrong, cannot shorten row: " << *this);
518                 return Elements();
519         }
520
521         // Iterate backwards over breakable elements and try to break them
522         Elements::iterator cit_brk = cit;
523         int wid_brk = wid + cit_brk->dim.wid;
524         ++cit_brk;
525         while (cit_brk != beg) {
526                 --cit_brk;
527                 // make a copy of the element to work on it.
528                 Element brk = *cit_brk;
529                 /* If the current element is an inset that allows breaking row
530                  * after itself, and if the row is already short enough after
531                  * this inset, then cut right after this element.
532                  */
533                 if (wid_brk <= w && brk.row_flags & CanBreakAfter) {
534                         end_ = brk.endpos;
535                         dim_.wid = wid_brk;
536                         return splitFrom(elements_, cit_brk + 1);
537                 }
538                 // assume now that the current element is not there
539                 wid_brk -= brk.dim.wid;
540                 /*
541                  * Some Asian languages split lines anywhere (no notion of
542                  * word). It seems that QTextLayout is not aware of this fact.
543                  * See for reference:
544                  *    https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
545                  *
546                  * FIXME: Something shall be done about characters which are
547                  * not allowed at the beginning or end of line.
548                 */
549                 bool const word_wrap = brk.font.language()->wordWrap();
550                 /* We have found a suitable separable element. This is the common case.
551                  * Try to break it cleanly (at word boundary) at a length that is both
552                  * - less than the available space on the row
553                  * - shorter than the natural width of the element, in order to enforce
554                  *   break-up.
555                  */
556                 Element remainder = brk.splitAt(min(w - wid_brk, brk.dim.wid - 2), !word_wrap);
557                 if (brk.row_flags & BreakAfter) {
558                         /* if this element originally did not cause a row overflow
559                          * in itself, and the remainder of the row would still be
560                          * too large after breaking, then we will have issues in
561                          * next row. Thus breaking does not help.
562                          */
563                         if (wid_brk + cit_brk->dim.wid < w
564                             && dim_.wid - (wid_brk + brk.dim.wid) >= next_width) {
565                                 break;
566                         }
567                         end_ = brk.endpos;
568                         *cit_brk = brk;
569                         dim_.wid = wid_brk + brk.dim.wid;
570                         // If there are other elements, they should be removed.
571                         // remainder can be empty when splitting at trailing space
572                         if (remainder.str.empty())
573                                 return splitFrom(elements_, next(cit_brk, 1));
574                         else
575                                 return splitFrom(elements_, next(cit_brk, 1), remainder);
576                 }
577         }
578
579         if (cit != beg && cit->row_flags & NoBreakBefore) {
580                 // It is not possible to separate this element from the
581                 // previous one. (e.g. VIRTUAL)
582                 --cit;
583                 wid -= cit->dim.wid;
584         }
585
586         if (cit != beg) {
587                 // There is no usable separator, but several elements have
588                 // been added. We can cut right here.
589                 end_ = cit->pos;
590                 dim_.wid = wid;
591                 return splitFrom(elements_, cit);
592         }
593
594         /* If we are here, it means that we have not found a separator to
595          * shorten the row. Let's try to break it again, but not at word
596          * boundary this time.
597          */
598         Element remainder = cit->splitAt(w - wid, true);
599         if (cit->row_flags & BreakAfter) {
600                 end_ = cit->endpos;
601                 dim_.wid = wid + cit->dim.wid;
602                 // If there are other elements, they should be removed.
603                 return splitFrom(elements_, next(cit, 1), remainder);
604         }
605         return Elements();
606 }
607
608
609 void Row::reverseRTL(bool const rtl_par)
610 {
611         pos_type i = 0;
612         pos_type const end = elements_.size();
613         while (i < end) {
614                 // gather a sequence of elements with the same direction
615                 bool const rtl = elements_[i].isRTL();
616                 pos_type j = i;
617                 while (j < end && elements_[j].isRTL() == rtl)
618                         ++j;
619                 // if the direction is not the same as the paragraph
620                 // direction, the sequence has to be reverted.
621                 if (rtl != rtl_par)
622                         reverse(elements_.begin() + i, elements_.begin() + j);
623                 i = j;
624         }
625         // If the paragraph itself is RTL, reverse everything
626         if (rtl_par)
627                 reverse(elements_.begin(), elements_.end());
628         rtl_ = rtl_par;
629 }
630
631 Row::const_iterator const
632 Row::findElement(pos_type const pos, bool const boundary, double & x) const
633 {
634         /**
635          * When boundary is true, position i is in the row element (pos, endpos)
636          * if
637          *    pos < i <= endpos
638          * whereas, when boundary is false, the test is
639          *    pos <= i < endpos
640          * The correction below allows to handle both cases.
641         */
642         int const boundary_corr = (boundary && pos) ? -1 : 0;
643
644         x = left_margin;
645
646         /** Early return in trivial cases
647          * 1) the row is empty
648          * 2) the position is the left-most position of the row; there
649          * is a quirk here however: if the first element is virtual
650          * (end-of-par marker for example), then we have to look
651          * closer
652          */
653         if (empty()
654             || (pos == begin()->left_pos() && !boundary
655                         && !begin()->isVirtual()))
656                 return begin();
657
658         const_iterator cit = begin();
659         for ( ; cit != end() ; ++cit) {
660                 /** Look whether the cursor is inside the element's span. Note
661                  * that it is necessary to take the boundary into account, and
662                  * to accept virtual elements, in which case the position
663                  * will be before the virtual element.
664                  */
665                 if (cit->isVirtual() && pos + boundary_corr == cit->pos)
666                         break;
667                 else if (pos + boundary_corr >= cit->pos
668                          && pos + boundary_corr < cit->endpos) {
669                         x += cit->pos2x(pos);
670                         break;
671                 }
672                 x += cit->full_width();
673         }
674
675         if (cit == end())
676                 --cit;
677
678         return cit;
679 }
680
681
682 } // namespace lyx