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