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