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