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