]> git.lyx.org Git - features.git/blob - src/Row.cpp
Better handling of trailing spaces in 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         }
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                 /* For some reason breakString can decide to break before the
166                  * first character (normally we use a 0-width nbsp to prevent
167                  * that). Skip leading empty elements, they are never wanted.
168                  */
169                 if (first && brk.len == 0 && breaks.size() > 1)
170                         continue;
171                 Element e(STRING, pos + i, font, change);
172                 e.str = str.substr(i, brk.len);
173                 e.endpos = e.pos + brk.len;
174                 e.dim.wid = brk.wid;
175                 e.nspc_wid = brk.nspc_wid;
176                 e.row_flags = CanBreakInside | BreakAfter;
177                 if (first) {
178                         // this element eventually goes to *this
179                         e.row_flags |= row_flags & ~AfterFlags;
180                         first_e = e;
181                         first = false;
182                 } else
183                         tail.push_back(e);
184                 i += brk.len;
185         }
186
187         if (!tail.empty()) {
188                 // Avoid having a last empty element. This happens when
189                 // breaking at the trailing space of string
190                 if (tail.back().str.empty())
191                         tail.pop_back();
192                 else {
193                         // Copy the after flags of the original element to the last one.
194                         tail.back().row_flags &= ~BreakAfter;
195                         tail.back().row_flags |= row_flags & AfterFlags;
196                 }
197                 // first_e row should be broken after the original element
198                 first_e.row_flags |= BreakAfter;
199         } else {
200                 // Restore the after flags of the original element.
201                 first_e.row_flags &= ~BreakAfter;
202                 first_e.row_flags |= row_flags & AfterFlags;
203         }
204
205         // update ourselves
206         swap(first_e, *this);
207         return true;
208 }
209
210
211 void Row::Element::rtrim()
212 {
213         if (type != STRING)
214                 return;
215         /* This is intended for strings that have been created by splitAt.
216          * They may have trailing spaces, but they are not counted in the
217          * string length (QTextLayout feature, actually). We remove them,
218          * and decrease endpos, since spaces at row break are invisible.
219          */
220         str = support::rtrim(str);
221         endpos = pos + str.length();
222         dim.wid = nspc_wid;
223 }
224
225
226 bool Row::isMarginSelected(bool left, DocIterator const & beg,
227                 DocIterator const & end) const
228 {
229         pos_type const sel_pos = left ? sel_beg : sel_end;
230         pos_type const margin_pos = left ? pos_ : end_;
231
232         // Is there a selection and is the chosen margin selected ?
233         if (!selection() || sel_pos != margin_pos)
234                 return false;
235         else if (beg.pos() == end.pos())
236                 // This is a special case in which the space between after
237                 // pos i-1 and before pos i is selected, i.e. the margins
238                 // (see DocIterator::boundary_).
239                 return beg.boundary() && !end.boundary();
240         else if (end.pos() == margin_pos)
241                 // If the selection ends around the margin, it is only
242                 // drawn if the cursor is after the margin.
243                 return !end.boundary();
244         else if (beg.pos() == margin_pos)
245                 // If the selection begins around the margin, it is
246                 // only drawn if the cursor is before the margin.
247                 return beg.boundary();
248         else
249                 return true;
250 }
251
252
253 void Row::setSelectionAndMargins(DocIterator const & beg,
254                 DocIterator const & end) const
255 {
256         setSelection(beg.pos(), end.pos());
257
258         change(end_margin_sel, isMarginSelected(false, beg, end));
259         change(begin_margin_sel, isMarginSelected(true, beg, end));
260 }
261
262
263 void Row::clearSelectionAndMargins() const
264 {
265         change(sel_beg, -1);
266         change(sel_end, -1);
267         change(end_margin_sel, false);
268         change(begin_margin_sel, false);
269 }
270
271
272 void Row::setSelection(pos_type beg, pos_type end) const
273 {
274         if (pos_ >= beg && pos_ <= end)
275                 change(sel_beg, pos_);
276         else if (beg > pos_ && beg <= end_)
277                 change(sel_beg, beg);
278         else
279                 change(sel_beg, -1);
280
281         if (end_ >= beg && end_ <= end)
282                 change(sel_end,end_);
283         else if (end < end_ && end >= pos_)
284                 change(sel_end, end);
285         else
286                 change(sel_end, -1);
287 }
288
289
290 bool Row::selection() const
291 {
292         return sel_beg != -1 && sel_end != -1;
293 }
294
295
296 ostream & operator<<(ostream & os, Row::Element const & e)
297 {
298         if (e.isRTL())
299                 os << e.endpos << "<<" << e.pos << " ";
300         else
301                 os << e.pos << ">>" << e.endpos << " ";
302
303         switch (e.type) {
304         case Row::STRING:
305                 os << "STRING: `" << to_utf8(e.str) << "' ("
306                    << e.countExpanders() << " expanders.), ";
307                 break;
308         case Row::VIRTUAL:
309                 os << "VIRTUAL: `" << to_utf8(e.str) << "', ";
310                 break;
311         case Row::INSET:
312                 os << "INSET: " << to_utf8(e.inset->layoutName()) << ", ";
313                 break;
314         case Row::SPACE:
315                 os << "SPACE: ";
316         }
317         os << "width=" << e.full_width() << ", row_flags=" << e.row_flags;
318         return os;
319 }
320
321
322 ostream & operator<<(ostream & os, Row::Elements const & elts)
323 {
324         double x = 0;
325         for (Row::Element const & e : elts) {
326                 os << "x=" << x << " => " << e << endl;
327                 x += e.full_width();
328         }
329         return os;
330 }
331
332
333 ostream & operator<<(ostream & os, Row const & row)
334 {
335         os << " pos: " << row.pos_ << " end: " << row.end_
336            << " left_margin: " << row.left_margin
337            << " width: " << row.dim_.wid
338            << " right_margin: " << row.right_margin
339            << " ascent: " << row.dim_.asc
340            << " descent: " << row.dim_.des
341            << " separator: " << row.separator
342            << " label_hfill: " << row.label_hfill
343            << " right_boundary: " << row.right_boundary()
344            << " flushed: " << row.flushed() << "\n";
345         // We cannot use the operator above, unfortunately
346         double x = row.left_margin;
347         for (Row::Element const & e : row.elements_) {
348                 os << "x=" << x << " => " << e << endl;
349                 x += e.full_width();
350         }
351         return os;
352 }
353
354
355 int Row::left_x() const
356 {
357         double x = left_margin;
358         const_iterator const end = elements_.end();
359         const_iterator cit = elements_.begin();
360         while (cit != end && cit->isVirtual()) {
361                 x += cit->full_width();
362                 ++cit;
363         }
364         return support::iround(x);
365 }
366
367
368 int Row::right_x() const
369 {
370         double x = dim_.wid;
371         const_iterator const begin = elements_.begin();
372         const_iterator cit = elements_.end();
373         while (cit != begin) {
374                 --cit;
375                 if (cit->isVirtual())
376                         x -= cit->full_width();
377                 else
378                         break;
379         }
380         return support::iround(x);
381 }
382
383
384 int Row::countSeparators() const
385 {
386         int n = 0;
387         const_iterator const end = elements_.end();
388         for (const_iterator cit = elements_.begin() ; cit != end ; ++cit)
389                 n += cit->countSeparators();
390         return n;
391 }
392
393
394 bool Row::setExtraWidth(int w)
395 {
396         if (w < 0)
397                 // this is not expected to happen (but it does)
398                 return false;
399         // amount of expansion: number of expanders time the em value for each
400         // string element
401         int exp_amount = 0;
402         for (Element const & e : elements_)
403                 exp_amount += e.expansionAmount();
404         if (!exp_amount)
405                 return false;
406         // extra length per expander per em
407         double extra_per_em = double(w) / exp_amount;
408         if (extra_per_em > MAX_SPACE_STRETCH)
409                 // do not stretch more than MAX_SPACE_STRETCH em per expander
410                 return false;
411         // add extra length to each element proportionally to its em.
412         for (Element & e : elements_)
413                 if (e.type == STRING)
414                         e.setExtra(extra_per_em);
415         // update row dimension
416         dim_.wid += w;
417         return true;
418 }
419
420
421 bool Row::sameString(Font const & f, Change const & ch) const
422 {
423         if (elements_.empty())
424                 return false;
425         Element const & elt = elements_.back();
426         return elt.type == STRING && !elt.final
427                    && elt.font == f && elt.change == ch;
428 }
429
430
431 void Row::finalizeLast()
432 {
433         if (elements_.empty())
434                 return;
435         Element & elt = elements_.back();
436         if (elt.final)
437                 return;
438         elt.final = true;
439         if (elt.change.changed())
440                 changebar_ = true;
441 }
442
443
444 void Row::add(pos_type const pos, Inset const * ins, Dimension const & dim,
445               Font const & f, Change const & ch)
446 {
447         finalizeLast();
448         Element e(INSET, pos, f, ch);
449         e.inset = ins;
450         e.dim = dim;
451         e.row_flags = ins->rowFlags();
452         elements_.push_back(e);
453         dim_.wid += dim.wid;
454         changebar_ |= ins->isChanged();
455 }
456
457
458 void Row::add(pos_type const pos, char_type const c,
459               Font const & f, Change const & ch, bool can_break)
460 {
461         if (!sameString(f, ch)) {
462                 finalizeLast();
463                 Element e(STRING, pos, f, ch);
464                 e.row_flags = can_break ? CanBreakInside : Inline;
465                 elements_.push_back(e);
466         }
467         back().str += c;
468         back().endpos = pos + 1;
469 }
470
471
472 void Row::addVirtual(pos_type const pos, docstring const & s,
473                      Font const & f, Change const & ch)
474 {
475         finalizeLast();
476         Element e(VIRTUAL, pos, f, ch);
477         e.str = s;
478         e.dim.wid = theFontMetrics(f).width(s);
479         dim_.wid += e.dim.wid;
480         e.endpos = pos;
481         // Copy after* flags from previous elements, forbid break before element
482         int const prev_row_flags = elements_.empty() ? Inline : elements_.back().row_flags;
483         int const can_inherit = AfterFlags & ~AlwaysBreakAfter;
484         e.row_flags = (prev_row_flags & can_inherit) | NoBreakBefore;
485         elements_.push_back(e);
486         finalizeLast();
487 }
488
489
490 void Row::addSpace(pos_type const pos, int const width,
491                    Font const & f, Change const & ch)
492 {
493         finalizeLast();
494         Element e(SPACE, pos, f, ch);
495         e.dim.wid = width;
496         elements_.push_back(e);
497         dim_.wid += e.dim.wid;
498 }
499
500
501 void Row::push_back(Row::Element const & e)
502 {
503         dim_.wid += e.dim.wid;
504         elements_.push_back(e);
505 }
506
507
508 void Row::pop_back()
509 {
510         dim_.wid -= elements_.back().dim.wid;
511         elements_.pop_back();
512 }
513
514
515 namespace {
516
517 // Move stuff after \c it from \c from and the end of \c to.
518 void moveElements(Row::Elements & from, Row::Elements::iterator const & it,
519                   Row::Elements & to)
520 {
521         to.insert(to.end(), it, from.end());
522         from.erase(it, from.end());
523         if (!from.empty())
524                 from.back().row_flags = (from.back().row_flags & ~AfterFlags) | BreakAfter;
525 }
526
527 }
528
529
530 Row::Elements Row::shortenIfNeeded(int const w, int const next_width)
531 {
532         // FIXME: performance: if the last element is a string, we would
533         // like to avoid computing its length.
534         finalizeLast();
535         if (empty() || width() <= w)
536                 return Elements();
537
538         Elements::iterator const beg = elements_.begin();
539         Elements::iterator const end = elements_.end();
540         int wid = left_margin;
541
542         // Search for the first element that goes beyond right margin
543         Elements::iterator cit = beg;
544         for ( ; cit != end ; ++cit) {
545                 if (wid + cit->dim.wid > w)
546                         break;
547                 wid += cit->dim.wid;
548         }
549
550         if (cit == end) {
551                 // This should not happen since the row is too long.
552                 LYXERR0("Something is wrong, cannot shorten row: " << *this);
553                 return Elements();
554         }
555
556         // Iterate backwards over breakable elements and try to break them
557         Elements::iterator cit_brk = cit;
558         int wid_brk = wid + cit_brk->dim.wid;
559         ++cit_brk;
560         Elements tail;
561         while (cit_brk != beg) {
562                 --cit_brk;
563                 // make a copy of the element to work on it.
564                 Element brk = *cit_brk;
565                 /* If the current element is an inset that allows breaking row
566                  * after itself, and if the row is already short enough after
567                  * this inset, then cut right after this element.
568                  */
569                 if (wid_brk <= w && brk.row_flags & CanBreakAfter) {
570                         end_ = brk.endpos;
571                         dim_.wid = wid_brk;
572                         moveElements(elements_, cit_brk + 1, tail);
573                         return tail;
574                 }
575                 // assume now that the current element is not there
576                 wid_brk -= brk.dim.wid;
577                 /* We have found a suitable separable element. This is the common case.
578                  * Try to break it cleanly at a length that is both
579                  * - less than the available space on the row
580                  * - shorter than the natural width of the element, in order to enforce
581                  *   break-up.
582                  */
583                 if (brk.splitAt(min(w - wid_brk, brk.dim.wid - 2), next_width, false, tail)) {
584                         /* if this element originally did not cause a row overflow
585                          * in itself, and the remainder of the row would still be
586                          * too large after breaking, then we will have issues in
587                          * next row. Thus breaking does not help.
588                          */
589                         if (wid_brk + cit_brk->dim.wid < w
590                             && dim_.wid - (wid_brk + brk.dim.wid) >= next_width) {
591                                 tail.clear();
592                                 break;
593                         }
594                         end_ = brk.endpos;
595                         *cit_brk = brk;
596                         dim_.wid = wid_brk + brk.dim.wid;
597                         // If there are other elements, they should be removed.
598                         moveElements(elements_, cit_brk + 1, tail);
599                         return tail;
600                 }
601                 LATTEST(tail.empty());
602         }
603
604         if (cit != beg && cit->row_flags & NoBreakBefore) {
605                 // It is not possible to separate this element from the
606                 // previous one. (e.g. VIRTUAL)
607                 --cit;
608                 wid -= cit->dim.wid;
609         }
610
611         if (cit != beg) {
612                 // There is no usable separator, but several elements have
613                 // been added. We can cut right here.
614                 end_ = cit->pos;
615                 dim_.wid = wid;
616                 moveElements(elements_, cit, tail);
617                 return tail;
618         }
619
620         /* If we are here, it means that we have not found a separator to
621          * shorten the row. Let's try to break it again, but force
622          * splitting this time.
623          */
624         if (cit->splitAt(w - wid, next_width, true, tail)) {
625                 end_ = cit->endpos;
626                 dim_.wid = wid + cit->dim.wid;
627                 // If there are other elements, they should be removed.
628                 moveElements(elements_, cit + 1, tail);
629                 return tail;
630         }
631
632         return Elements();
633 }
634
635
636 void Row::reverseRTL()
637 {
638         pos_type i = 0;
639         pos_type const end = elements_.size();
640         while (i < end) {
641                 // gather a sequence of elements with the same direction
642                 bool const rtl = elements_[i].isRTL();
643                 pos_type j = i;
644                 while (j < end && elements_[j].isRTL() == rtl)
645                         ++j;
646                 // if the direction is not the same as the paragraph
647                 // direction, the sequence has to be reverted.
648                 if (rtl != rtl_)
649                         reverse(elements_.begin() + i, elements_.begin() + j);
650                 i = j;
651         }
652         // If the paragraph itself is RTL, reverse everything
653         if (rtl_)
654                 reverse(elements_.begin(), elements_.end());
655 }
656
657 Row::const_iterator const
658 Row::findElement(pos_type const pos, bool const boundary, double & x) const
659 {
660         /**
661          * When boundary is true, position i is in the row element (pos, endpos)
662          * if
663          *    pos < i <= endpos
664          * whereas, when boundary is false, the test is
665          *    pos <= i < endpos
666          * The correction below allows to handle both cases.
667         */
668         int const boundary_corr = (boundary && pos) ? -1 : 0;
669
670         x = left_margin;
671
672         /** Early return in trivial cases
673          * 1) the row is empty
674          * 2) the position is the left-most position of the row; there
675          * is a quirk here however: if the first element is virtual
676          * (end-of-par marker for example), then we have to look
677          * closer
678          */
679         if (empty()
680             || (pos == begin()->left_pos() && !boundary
681                         && !begin()->isVirtual()))
682                 return begin();
683
684         const_iterator cit = begin();
685         for ( ; cit != end() ; ++cit) {
686                 /** Look whether the cursor is inside the element's span. Note
687                  * that it is necessary to take the boundary into account, and
688                  * to accept virtual elements, in which case the position
689                  * will be before the virtual element.
690                  */
691                 if (cit->isVirtual() && pos + boundary_corr == cit->pos)
692                         break;
693                 else if (pos + boundary_corr >= cit->pos
694                          && pos + boundary_corr < cit->endpos) {
695                         x += cit->pos2x(pos);
696                         break;
697                 }
698                 x += cit->full_width();
699         }
700
701         if (cit == end())
702                 --cit;
703
704         return cit;
705 }
706
707
708 } // namespace lyx