]> git.lyx.org Git - features.git/blob - src/Row.cpp
Last step of transition: use sortenIfNeeded again.
[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 support::rtrim;
39 using frontend::FontMetrics;
40
41
42 // Maximum length that a space can be stretched when justifying text
43 static double const MAX_SPACE_STRETCH = 1.5; //em
44
45
46 int Row::Element::countSeparators() const
47 {
48         if (type != STRING)
49                 return 0;
50         return count(str.begin(), str.end(), ' ');
51 }
52
53
54 int Row::Element::countExpanders() const
55 {
56         if (type != STRING)
57                 return 0;
58         return theFontMetrics(font).countExpanders(str);
59 }
60
61
62 int Row::Element::expansionAmount() const
63 {
64         if (type != STRING)
65                 return 0;
66         return countExpanders() * theFontMetrics(font).em();
67 }
68
69
70 void Row::Element::setExtra(double extra_per_em)
71 {
72         if (type != STRING)
73                 return;
74         extra = extra_per_em * theFontMetrics(font).em();
75 }
76
77
78 double Row::Element::pos2x(pos_type const i) const
79 {
80         // This can happen with inline completion when clicking on the
81         // row after the completion.
82         if (i < pos || i > endpos)
83                 return 0;
84
85         double w = 0;
86         //handle first the two bounds of the element
87         if (i == endpos && type != VIRTUAL)
88                 w = isRTL() ? 0 : full_width();
89         else if (i == pos || type != STRING)
90                 w = isRTL() ? full_width() : 0;
91         else {
92                 FontMetrics const & fm = theFontMetrics(font);
93                 w = fm.pos2x(str, i - pos, isRTL(), extra);
94         }
95
96         return w;
97 }
98
99
100 pos_type Row::Element::x2pos(int &x) const
101 {
102         //lyxerr << "x2pos: x=" << x << " w=" << width() << " " << *this;
103         size_t i = 0;
104
105         switch (type) {
106         case STRING: {
107                 FontMetrics const & fm = theFontMetrics(font);
108                 i = fm.x2pos(str, x, isRTL(), extra);
109                 break;
110         }
111         case VIRTUAL:
112                 // those elements are actually empty (but they have a width)
113                 i = 0;
114                 x = isRTL() ? int(full_width()) : 0;
115                 break;
116         case INSET:
117         case SPACE:
118                 // those elements contain only one position. Round to
119                 // the closest side.
120                 if (x > (full_width() + 1) / 2) {
121                         x = int(full_width());
122                         i = !isRTL();
123                 } else {
124                         x = 0;
125                         i = isRTL();
126                 }
127                 break;
128         case INVALID:
129                 LYXERR0("x2pos: INVALID row element !");
130         }
131         //lyxerr << "=> p=" << pos + i << " x=" << x << endl;
132         return pos + i;
133 }
134
135
136 Row::Element Row::Element::splitAt(int w, bool force)
137 {
138         if (type != STRING || !(row_flags & CanBreakInside))
139                 return Element();
140
141         FontMetrics const & fm = theFontMetrics(font);
142         dim.wid = w;
143         int const i = fm.breakAt(str, dim.wid, isRTL(), force);
144         if (i != -1) {
145                 Element ret(STRING, pos + i, font, change);
146                 ret.str = str.substr(i);
147                 ret.endpos = ret.pos + ret.str.length();
148                 ret.row_flags = row_flags & (CanBreakInside | AfterFlags);
149                 str.erase(i);
150                 endpos = pos + i;
151                 //lyxerr << "breakAt(" << w << ")  Row element Broken at " << x << "(w(str)=" << fm.width(str) << "): e=" << *this << endl;
152                 return ret;
153         }
154
155         return Element();
156 }
157
158
159 bool Row::isMarginSelected(bool left, DocIterator const & beg,
160                 DocIterator const & end) const
161 {
162         pos_type const sel_pos = left ? sel_beg : sel_end;
163         pos_type const margin_pos = left ? pos_ : end_;
164
165         // Is there a selection and is the chosen margin selected ?
166         if (!selection() || sel_pos != margin_pos)
167                 return false;
168         else if (beg.pos() == end.pos())
169                 // This is a special case in which the space between after
170                 // pos i-1 and before pos i is selected, i.e. the margins
171                 // (see DocIterator::boundary_).
172                 return beg.boundary() && !end.boundary();
173         else if (end.pos() == margin_pos)
174                 // If the selection ends around the margin, it is only
175                 // drawn if the cursor is after the margin.
176                 return !end.boundary();
177         else if (beg.pos() == margin_pos)
178                 // If the selection begins around the margin, it is
179                 // only drawn if the cursor is before the margin.
180                 return beg.boundary();
181         else
182                 return true;
183 }
184
185
186 void Row::setSelectionAndMargins(DocIterator const & beg,
187                 DocIterator const & end) const
188 {
189         setSelection(beg.pos(), end.pos());
190
191         change(end_margin_sel, isMarginSelected(false, beg, end));
192         change(begin_margin_sel, isMarginSelected(true, beg, end));
193 }
194
195
196 void Row::clearSelectionAndMargins() const
197 {
198         change(sel_beg, -1);
199         change(sel_end, -1);
200         change(end_margin_sel, false);
201         change(begin_margin_sel, false);
202 }
203
204
205 void Row::setSelection(pos_type beg, pos_type end) const
206 {
207         if (pos_ >= beg && pos_ <= end)
208                 change(sel_beg, pos_);
209         else if (beg > pos_ && beg <= end_)
210                 change(sel_beg, beg);
211         else
212                 change(sel_beg, -1);
213
214         if (end_ >= beg && end_ <= end)
215                 change(sel_end,end_);
216         else if (end < end_ && end >= pos_)
217                 change(sel_end, end);
218         else
219                 change(sel_end, -1);
220 }
221
222
223 bool Row::selection() const
224 {
225         return sel_beg != -1 && sel_end != -1;
226 }
227
228
229 ostream & operator<<(ostream & os, Row::Element const & e)
230 {
231         if (e.isRTL())
232                 os << e.endpos << "<<" << e.pos << " ";
233         else
234                 os << e.pos << ">>" << e.endpos << " ";
235
236         switch (e.type) {
237         case Row::STRING:
238                 os << "STRING: `" << to_utf8(e.str) << "' ("
239                    << e.countExpanders() << " expanders.), ";
240                 break;
241         case Row::VIRTUAL:
242                 os << "VIRTUAL: `" << to_utf8(e.str) << "', ";
243                 break;
244         case Row::INSET:
245                 os << "INSET: " << to_utf8(e.inset->layoutName()) << ", ";
246                 break;
247         case Row::SPACE:
248                 os << "SPACE: ";
249                 break;
250         case Row::INVALID:
251                 os << "INVALID: ";
252                 break;
253         }
254         os << "width=" << e.full_width();
255         return os;
256 }
257
258
259 ostream & operator<<(ostream & os, Row const & row)
260 {
261         os << " pos: " << row.pos_ << " end: " << row.end_
262            << " left_margin: " << row.left_margin
263            << " width: " << row.dim_.wid
264            << " right_margin: " << row.right_margin
265            << " ascent: " << row.dim_.asc
266            << " descent: " << row.dim_.des
267            << " separator: " << row.separator
268            << " label_hfill: " << row.label_hfill
269            << " row_boundary: " << row.right_boundary() << "\n";
270         double x = row.left_margin;
271         Row::Elements::const_iterator it = row.elements_.begin();
272         for ( ; it != row.elements_.end() ; ++it) {
273                 os << "x=" << x << " => " << *it << endl;
274                 x += it->full_width();
275         }
276         return os;
277 }
278
279
280 int Row::left_x() const
281 {
282         double x = left_margin;
283         const_iterator const end = elements_.end();
284         const_iterator cit = elements_.begin();
285         while (cit != end && cit->isVirtual()) {
286                 x += cit->full_width();
287                 ++cit;
288         }
289         return support::iround(x);
290 }
291
292
293 int Row::right_x() const
294 {
295         double x = dim_.wid;
296         const_iterator const begin = elements_.begin();
297         const_iterator cit = elements_.end();
298         while (cit != begin) {
299                 --cit;
300                 if (cit->isVirtual())
301                         x -= cit->full_width();
302                 else
303                         break;
304         }
305         return support::iround(x);
306 }
307
308
309 int Row::countSeparators() const
310 {
311         int n = 0;
312         const_iterator const end = elements_.end();
313         for (const_iterator cit = elements_.begin() ; cit != end ; ++cit)
314                 n += cit->countSeparators();
315         return n;
316 }
317
318
319 bool Row::setExtraWidth(int w)
320 {
321         if (w < 0)
322                 // this is not expected to happen (but it does)
323                 return false;
324         // amount of expansion: number of expanders time the em value for each
325         // string element
326         int exp_amount = 0;
327         for (Element const & e : elements_)
328                 exp_amount += e.expansionAmount();
329         if (!exp_amount)
330                 return false;
331         // extra length per expander per em
332         double extra_per_em = double(w) / exp_amount;
333         if (extra_per_em > MAX_SPACE_STRETCH)
334                 // do not stretch more than MAX_SPACE_STRETCH em per expander
335                 return false;
336         // add extra length to each element proportionally to its em.
337         for (Element & e : elements_)
338                 if (e.type == STRING)
339                         e.setExtra(extra_per_em);
340         // update row dimension
341         dim_.wid += w;
342         return true;
343 }
344
345
346 bool Row::sameString(Font const & f, Change const & ch) const
347 {
348         if (elements_.empty())
349                 return false;
350         Element const & elt = elements_.back();
351         return elt.type == STRING && !elt.final
352                    && elt.font == f && elt.change == ch;
353 }
354
355
356 void Row::finalizeLast()
357 {
358         if (elements_.empty())
359                 return;
360         Element & elt = elements_.back();
361         if (elt.final)
362                 return;
363         elt.final = true;
364         if (elt.change.changed())
365                 changebar_ = true;
366
367         if (elt.type == STRING && elt.dim.wid == 0) {
368                 elt.dim.wid = theFontMetrics(elt.font).width(elt.str);
369                 dim_.wid += elt.dim.wid;
370         }
371 }
372
373
374 void Row::add(pos_type const pos, Inset const * ins, Dimension const & dim,
375               Font const & f, Change const & ch)
376 {
377         finalizeLast();
378         Element e(INSET, pos, f, ch);
379         e.inset = ins;
380         e.dim = dim;
381         e.row_flags = ins->rowFlags();
382         elements_.push_back(e);
383         dim_.wid += dim.wid;
384         changebar_ |= ins->isChanged();
385 }
386
387
388 void Row::add(pos_type const pos, char_type const c,
389               Font const & f, Change const & ch, bool can_break)
390 {
391         if (!sameString(f, ch)) {
392                 finalizeLast();
393                 Element e(STRING, pos, f, ch);
394                 e.row_flags = can_break ? CanBreakInside : Inline;
395                 elements_.push_back(e);
396         }
397         back().str += c;
398         back().endpos = pos + 1;
399 }
400
401
402 void Row::addVirtual(pos_type const pos, docstring const & s,
403                      Font const & f, Change const & ch)
404 {
405         finalizeLast();
406         Element e(VIRTUAL, pos, f, ch);
407         e.str = s;
408         e.dim.wid = theFontMetrics(f).width(s);
409         dim_.wid += e.dim.wid;
410         e.endpos = pos;
411         // Copy after* flags from previous elements, forbid break before element
412         int const prev_row_flags = elements_.empty() ? Inline : elements_.back().row_flags;
413         int const can_inherit = AfterFlags & ~AlwaysBreakAfter;
414         e.row_flags = (prev_row_flags & can_inherit) | NoBreakBefore;
415         elements_.push_back(e);
416         finalizeLast();
417 }
418
419
420 void Row::addSpace(pos_type const pos, int const width,
421                    Font const & f, Change const & ch)
422 {
423         finalizeLast();
424         Element e(SPACE, pos, f, ch);
425         e.dim.wid = width;
426         elements_.push_back(e);
427         dim_.wid += e.dim.wid;
428 }
429
430
431 void Row::push_back(Row::Element const & e)
432 {
433         dim_.wid += e.dim.wid;
434         elements_.push_back(e);
435 }
436
437
438 void Row::pop_back()
439 {
440         dim_.wid -= elements_.back().dim.wid;
441         elements_.pop_back();
442 }
443
444
445 namespace {
446
447 // Remove stuff after it from elts, and return it.
448 // if init is provided, it will be in front of the rest
449 Row::Elements splitFrom(Row::Elements & elts, Row::Elements::iterator const & it,
450                         Row::Element const & init = Row::Element())
451 {
452         Row::Elements ret;
453         if (init.isValid())
454                 ret.push_back(init);
455         ret.insert(ret.end(), it, elts.end());
456         elts.erase(it, elts.end());
457         return ret;
458 }
459
460 }
461
462
463 Row::Elements Row::shortenIfNeeded(int const w, int const next_width)
464 {
465         // FIXME: performance: if the last element is a string, we would
466         // like to avoid computing its length.
467         finalizeLast();
468         if (empty() || width() <= w)
469                 return Elements();
470
471         Elements::iterator const beg = elements_.begin();
472         Elements::iterator const end = elements_.end();
473         int wid = left_margin;
474
475         // Search for the first element that goes beyond right margin
476         Elements::iterator cit = beg;
477         for ( ; cit != end ; ++cit) {
478                 if (wid + cit->dim.wid > w)
479                         break;
480                 wid += cit->dim.wid;
481         }
482
483         if (cit == end) {
484                 // This should not happen since the row is too long.
485                 LYXERR0("Something is wrong, cannot shorten row: " << *this);
486                 return Elements();
487         }
488
489         // Iterate backwards over breakable elements and try to break them
490         Elements::iterator cit_brk = cit;
491         int wid_brk = wid + cit_brk->dim.wid;
492         ++cit_brk;
493         while (cit_brk != beg) {
494                 --cit_brk;
495                 // make a copy of the element to work on it.
496                 Element brk = *cit_brk;
497                 /* If the current element is an inset that allows breaking row
498                  * after itself, and if the row is already short enough after
499                  * this inset, then cut right after this element.
500                  */
501                 if (wid_brk <= w && brk.row_flags & CanBreakAfter) {
502                         end_ = brk.endpos;
503                         dim_.wid = wid_brk;
504                         return splitFrom(elements_, cit_brk + 1);
505                 }
506                 // assume now that the current element is not there
507                 wid_brk -= brk.dim.wid;
508                 /*
509                  * Some Asian languages split lines anywhere (no notion of
510                  * word). It seems that QTextLayout is not aware of this fact.
511                  * See for reference:
512                  *    https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
513                  *
514                  * FIXME: Something shall be done about characters which are
515                  * not allowed at the beginning or end of line.
516                 */
517                 bool const word_wrap = brk.font.language()->wordWrap();
518                 /* We have found a suitable separable element. This is the common case.
519                  * Try to break it cleanly (at word boundary) at a length that is both
520                  * - less than the available space on the row
521                  * - shorter than the natural width of the element, in order to enforce
522                  *   break-up.
523                  */
524                 Element remainder = brk.splitAt(min(w - wid_brk, brk.dim.wid - 2), !word_wrap);
525                 if (remainder.isValid()) {
526                         /* if this element originally did not cause a row overflow
527                          * in itself, and the remainder of the row would still be
528                          * too large after breaking, then we will have issues in
529                          * next row. Thus breaking does not help.
530                          */
531                         if (wid_brk + cit_brk->dim.wid < w
532                             && dim_.wid - (wid_brk + brk.dim.wid) >= next_width) {
533                                 break;
534                         }
535                         end_ = brk.endpos;
536                         /* after breakAt, there may be spaces at the end of the
537                          * string, but they are not counted in the string length
538                          * (QTextLayout feature, actually). We remove them, but do
539                          * not change the end of the row, since spaces at row
540                          * break are invisible.
541                          */
542                         brk.str = rtrim(brk.str);
543                         brk.endpos = brk.pos + brk.str.length();
544                         *cit_brk = brk;
545                         dim_.wid = wid_brk + brk.dim.wid;
546                         // If there are other elements, they should be removed.
547                         return splitFrom(elements_, next(cit_brk, 1), remainder);
548                 }
549         }
550
551         if (cit != beg && cit->row_flags & NoBreakBefore) {
552                 // It is not possible to separate this element from the
553                 // previous one. (e.g. VIRTUAL)
554                 --cit;
555                 wid -= cit->dim.wid;
556         }
557
558         if (cit != beg) {
559                 // There is no usable separator, but several elements have
560                 // been added. We can cut right here.
561                 end_ = cit->pos;
562                 dim_.wid = wid;
563                 return splitFrom(elements_, cit);
564         }
565
566         /* If we are here, it means that we have not found a separator to
567          * shorten the row. Let's try to break it again, but not at word
568          * boundary this time.
569          */
570         Element remainder = cit->splitAt(w - wid, true);
571         if (remainder.isValid()) {
572                 end_ = cit->endpos;
573                 // See comment above.
574                 cit->str = rtrim(cit->str);
575                 cit->endpos = cit->pos + cit->str.length();
576                 dim_.wid = wid + cit->dim.wid;
577                 // If there are other elements, they should be removed.
578                 return splitFrom(elements_, next(cit, 1), remainder);
579         }
580         return Elements();
581 }
582
583
584 void Row::reverseRTL(bool const rtl_par)
585 {
586         pos_type i = 0;
587         pos_type const end = elements_.size();
588         while (i < end) {
589                 // gather a sequence of elements with the same direction
590                 bool const rtl = elements_[i].isRTL();
591                 pos_type j = i;
592                 while (j < end && elements_[j].isRTL() == rtl)
593                         ++j;
594                 // if the direction is not the same as the paragraph
595                 // direction, the sequence has to be reverted.
596                 if (rtl != rtl_par)
597                         reverse(elements_.begin() + i, elements_.begin() + j);
598                 i = j;
599         }
600         // If the paragraph itself is RTL, reverse everything
601         if (rtl_par)
602                 reverse(elements_.begin(), elements_.end());
603         rtl_ = rtl_par;
604 }
605
606 Row::const_iterator const
607 Row::findElement(pos_type const pos, bool const boundary, double & x) const
608 {
609         /**
610          * When boundary is true, position i is in the row element (pos, endpos)
611          * if
612          *    pos < i <= endpos
613          * whereas, when boundary is false, the test is
614          *    pos <= i < endpos
615          * The correction below allows to handle both cases.
616         */
617         int const boundary_corr = (boundary && pos) ? -1 : 0;
618
619         x = left_margin;
620
621         /** Early return in trivial cases
622          * 1) the row is empty
623          * 2) the position is the left-most position of the row; there
624          * is a quirk here however: if the first element is virtual
625          * (end-of-par marker for example), then we have to look
626          * closer
627          */
628         if (empty()
629             || (pos == begin()->left_pos() && !boundary
630                         && !begin()->isVirtual()))
631                 return begin();
632
633         const_iterator cit = begin();
634         for ( ; cit != end() ; ++cit) {
635                 /** Look whether the cursor is inside the element's span. Note
636                  * that it is necessary to take the boundary into account, and
637                  * to accept virtual elements, in which case the position
638                  * will be before the virtual element.
639                  */
640                 if (cit->isVirtual() && pos + boundary_corr == cit->pos)
641                         break;
642                 else if (pos + boundary_corr >= cit->pos
643                          && pos + boundary_corr < cit->endpos) {
644                         x += cit->pos2x(pos);
645                         break;
646                 }
647                 x += cit->full_width();
648         }
649
650         if (cit == end())
651                 --cit;
652
653         return cit;
654 }
655
656
657 } // namespace lyx