]> git.lyx.org Git - lyx.git/blob - src/Row.cpp
Fix crash when selecting text with changes
[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
23 #include "frontends/FontMetrics.h"
24
25 #include "support/debug.h"
26 #include "support/lassert.h"
27 #include "support/lstrings.h"
28 #include "support/lyxalgo.h"
29
30 #include <ostream>
31
32 using namespace std;
33
34 namespace lyx {
35
36 using support::rtrim;
37 using frontend::FontMetrics;
38
39
40 // Maximum length that a space can be stretched when justifying text
41 static double const MAX_SPACE_STRETCH = 1.5; //em
42
43
44 int Row::Element::countSeparators() const
45 {
46         if (type != STRING)
47                 return 0;
48         return count(str.begin(), str.end(), ' ');
49 }
50
51
52 int Row::Element::countExpanders() const
53 {
54         if (type != STRING)
55                 return 0;
56         return theFontMetrics(font).countExpanders(str);
57 }
58
59
60 int Row::Element::expansionAmount() const
61 {
62         if (type != STRING)
63                 return 0;
64         return countExpanders() * theFontMetrics(font).em();
65 }
66
67
68 void Row::Element::setExtra(double extra_per_em)
69 {
70         if (type != STRING)
71                 return;
72         extra = extra_per_em * theFontMetrics(font).em();
73 }
74
75
76 double Row::Element::pos2x(pos_type const i) const
77 {
78         // This can happen with inline completion when clicking on the
79         // row after the completion.
80         if (i < pos || i > endpos)
81                 return 0;
82
83         double w = 0;
84         //handle first the two bounds of the element
85         if (i == endpos && type != VIRTUAL)
86                 w = isRTL() ? 0 : full_width();
87         else if (i == pos || type != STRING)
88                 w = isRTL() ? full_width() : 0;
89         else {
90                 FontMetrics const & fm = theFontMetrics(font);
91                 w = fm.pos2x(str, i - pos, isRTL(), extra);
92         }
93
94         return w;
95 }
96
97
98 pos_type Row::Element::x2pos(int &x) const
99 {
100         //lyxerr << "x2pos: x=" << x << " w=" << width() << " " << *this;
101         size_t i = 0;
102
103         switch (type) {
104         case STRING: {
105                 FontMetrics const & fm = theFontMetrics(font);
106                 i = fm.x2pos(str, x, isRTL(), extra);
107                 break;
108         }
109         case VIRTUAL:
110                 // those elements are actually empty (but they have a width)
111                 i = 0;
112                 x = isRTL() ? int(full_width()) : 0;
113                 break;
114         case INSET:
115         case SPACE:
116                 // those elements contain only one position. Round to
117                 // the closest side.
118                 if (x > (full_width() + 1) / 2) {
119                         x = int(full_width());
120                         i = !isRTL();
121                 } else {
122                         x = 0;
123                         i = isRTL();
124                 }
125         }
126         //lyxerr << "=> p=" << pos + i << " x=" << x << endl;
127         return pos + i;
128 }
129
130
131 bool Row::Element::breakAt(int w, bool force)
132 {
133         if (type != STRING || dim.wid <= w)
134                 return false;
135
136         FontMetrics const & fm = theFontMetrics(font);
137         int x = w;
138         if(fm.breakAt(str, x, isRTL(), force)) {
139                 dim.wid = x;
140                 endpos = pos + str.length();
141                 //lyxerr << "breakAt(" << w << ")  Row element Broken at " << x << "(w(str)=" << fm.width(str) << "): e=" << *this << endl;
142                 return true;
143         }
144
145         return false;
146 }
147
148
149 pos_type Row::Element::left_pos() const
150 {
151         return isRTL() ? endpos : pos;
152 }
153
154
155 pos_type Row::Element::right_pos() const
156 {
157         return isRTL() ? pos : endpos;
158 }
159
160
161 Row::Row()
162         : separator(0), label_hfill(0), left_margin(0), right_margin(0),
163           sel_beg(-1), sel_end(-1),
164           begin_margin_sel(false), end_margin_sel(false),
165           changed_(true),
166           pit_(0), pos_(0), end_(0),
167           right_boundary_(false), flushed_(false), rtl_(false),
168           changebar_(false)
169 {}
170
171
172 bool Row::isMarginSelected(bool left_margin, DocIterator const & beg,
173                 DocIterator const & end) const
174 {
175         pos_type const sel_pos = left_margin ? sel_beg : sel_end;
176         pos_type const margin_pos = left_margin ? pos_ : end_;
177
178         // Is the chosen margin selected ?
179         if (sel_pos == margin_pos) {
180                 if (beg.pos() == end.pos())
181                         // This is a special case in which the space between after
182                         // pos i-1 and before pos i is selected, i.e. the margins
183                         // (see DocIterator::boundary_).
184                         return beg.boundary() && !end.boundary();
185                 else if (end.pos() == margin_pos)
186                         // If the selection ends around the margin, it is only
187                         // drawn if the cursor is after the margin.
188                         return !end.boundary();
189                 else if (beg.pos() == margin_pos)
190                         // If the selection begins around the margin, it is
191                         // only drawn if the cursor is before the margin.
192                         return beg.boundary();
193                 else
194                         return true;
195         }
196         return false;
197 }
198
199
200 void Row::setSelectionAndMargins(DocIterator const & beg,
201                 DocIterator const & end) const
202 {
203         setSelection(beg.pos(), end.pos());
204
205         if (selection()) {
206                 change(end_margin_sel, isMarginSelected(false, beg, end));
207                 change(begin_margin_sel, isMarginSelected(true, beg, end));
208         }
209 }
210
211
212 void Row::setSelection(pos_type beg, pos_type end) const
213 {
214         if (pos_ >= beg && pos_ <= end)
215                 change(sel_beg, pos_);
216         else if (beg > pos_ && beg <= end_)
217                 change(sel_beg, beg);
218         else
219                 change(sel_beg, -1);
220
221         if (end_ >= beg && end_ <= end)
222                 change(sel_end,end_);
223         else if (end < end_ && end >= pos_)
224                 change(sel_end, end);
225         else
226                 change(sel_end, -1);
227 }
228
229
230 bool Row::selection() const
231 {
232         return sel_beg != -1 && sel_end != -1;
233 }
234
235
236 ostream & operator<<(ostream & os, Row::Element const & e)
237 {
238         if (e.isRTL())
239                 os << e.endpos << "<<" << e.pos << " ";
240         else
241                 os << e.pos << ">>" << e.endpos << " ";
242
243         switch (e.type) {
244         case Row::STRING:
245                 os << "STRING: `" << to_utf8(e.str) << "' ("
246                    << e.countExpanders() << " expanders.), ";
247                 break;
248         case Row::VIRTUAL:
249                 os << "VIRTUAL: `" << to_utf8(e.str) << "', ";
250                 break;
251         case Row::INSET:
252                 os << "INSET: " << to_utf8(e.inset->layoutName()) << ", ";
253                 break;
254         case Row::SPACE:
255                 os << "SPACE: ";
256                 break;
257         }
258         os << "width=" << e.full_width();
259         return os;
260 }
261
262
263 ostream & operator<<(ostream & os, Row const & row)
264 {
265         os << " pos: " << row.pos_ << " end: " << row.end_
266            << " left_margin: " << row.left_margin
267            << " width: " << row.dim_.wid
268            << " right_margin: " << row.right_margin
269            << " ascent: " << row.dim_.asc
270            << " descent: " << row.dim_.des
271            << " separator: " << row.separator
272            << " label_hfill: " << row.label_hfill
273            << " row_boundary: " << row.right_boundary() << "\n";
274         double x = row.left_margin;
275         Row::Elements::const_iterator it = row.elements_.begin();
276         for ( ; it != row.elements_.end() ; ++it) {
277                 os << "x=" << x << " => " << *it << endl;
278                 x += it->full_width();
279         }
280         return os;
281 }
282
283
284 int Row::left_x() const
285 {
286         double x = left_margin;
287         const_iterator const end = elements_.end();
288         const_iterator cit = elements_.begin();
289         while (cit != end && cit->isVirtual()) {
290                 x += cit->full_width();
291                 ++cit;
292         }
293         return int(x + 0.5);
294 }
295
296
297 int Row::right_x() const
298 {
299         double x = dim_.wid;
300         const_iterator const begin = elements_.begin();
301         const_iterator cit = elements_.end();
302         while (cit != begin) {
303                 --cit;
304                 if (cit->isVirtual())
305                         x -= cit->full_width();
306                 else
307                         break;
308         }
309         return int(x + 0.5);
310 }
311
312
313 int Row::countSeparators() const
314 {
315         int n = 0;
316         const_iterator const end = elements_.end();
317         for (const_iterator cit = elements_.begin() ; cit != end ; ++cit)
318                 n += cit->countSeparators();
319         return n;
320 }
321
322
323 bool Row::setExtraWidth(int w)
324 {
325         if (w < 0)
326                 // this is not expected to happen (but it does)
327                 return false;
328         // amount of expansion: number of expanders time the em value for each
329         // string element
330         int exp_amount = 0;
331         for (Row::Element const & e : elements_)
332                 exp_amount += e.expansionAmount();
333         if (!exp_amount)
334                 return false;
335         // extra length per expander per em
336         double extra_per_em = double(w) / exp_amount;
337         if (extra_per_em > MAX_SPACE_STRETCH)
338                 // do not stretch more than MAX_SPACE_STRETCH em per expander
339                 return false;
340         // add extra length to each element proportionally to its em.
341         for (Row::Element & e : elements_)
342                 if (e.type == Row::STRING)
343                         e.setExtra(extra_per_em);
344         // update row dimension
345         dim_.wid += w;
346         return true;
347 }
348
349
350 bool Row::sameString(Font const & f, Change const & ch) const
351 {
352         if (elements_.empty())
353                 return false;
354         Element const & elt = elements_.back();
355         return elt.type == STRING && !elt.final
356                    && elt.font == f && elt.change == ch;
357 }
358
359
360 void Row::finalizeLast()
361 {
362         if (elements_.empty())
363                 return;
364         Element & elt = elements_.back();
365         if (elt.final)
366                 return;
367         elt.final = true;
368         if (elt.change.changed())
369                 changebar_ = true;
370
371         if (elt.type == STRING) {
372                 dim_.wid -= elt.dim.wid;
373                 elt.dim.wid = theFontMetrics(elt.font).width(elt.str);
374                 dim_.wid += elt.dim.wid;
375         }
376 }
377
378
379 void Row::add(pos_type const pos, Inset const * ins, Dimension const & dim,
380               Font const & f, Change const & ch)
381 {
382         finalizeLast();
383         Element e(INSET, pos, f, ch);
384         e.inset = ins;
385         e.dim = dim;
386         elements_.push_back(e);
387         dim_.wid += dim.wid;
388 }
389
390
391 void Row::add(pos_type const pos, char_type const c,
392               Font const & f, Change const & ch)
393 {
394         if (!sameString(f, ch)) {
395                 finalizeLast();
396                 Element e(STRING, pos, f, ch);
397                 elements_.push_back(e);
398         }
399         if (back().str.length() % 30 == 0) {
400                 dim_.wid -= back().dim.wid;
401                 back().str += c;
402                 back().endpos = pos + 1;
403                 back().dim.wid = theFontMetrics(back().font).width(back().str);
404                 dim_.wid += back().dim.wid;
405         } else {
406                 back().str += c;
407                 back().endpos = pos + 1;
408         }
409 }
410
411
412 void Row::addVirtual(pos_type const pos, docstring const & s,
413                      Font const & f, Change const & ch)
414 {
415         finalizeLast();
416         Element e(VIRTUAL, pos, f, ch);
417         e.str = s;
418         e.dim.wid = theFontMetrics(f).width(s);
419         dim_.wid += e.dim.wid;
420         e.endpos = pos;
421         elements_.push_back(e);
422         finalizeLast();
423 }
424
425
426 void Row::addSpace(pos_type const pos, int const width,
427                    Font const & f, Change const & ch)
428 {
429         finalizeLast();
430         Element e(SPACE, pos, f, ch);
431         e.dim.wid = width;
432         elements_.push_back(e);
433         dim_.wid += e.dim.wid;
434 }
435
436
437 void Row::pop_back()
438 {
439         dim_.wid -= elements_.back().dim.wid;
440         elements_.pop_back();
441 }
442
443
444 bool Row::shortenIfNeeded(pos_type const keep, int const w, int const next_width)
445 {
446         if (empty() || width() <= w)
447                 return false;
448
449         Elements::iterator const beg = elements_.begin();
450         Elements::iterator const end = elements_.end();
451         int wid = left_margin;
452
453         // Search for the first element that goes beyond right margin
454         Elements::iterator cit = beg;
455         for ( ; cit != end ; ++cit) {
456                 if (wid + cit->dim.wid > w)
457                         break;
458                 wid += cit->dim.wid;
459         }
460
461         if (cit == end) {
462                 // This should not happen since the row is too long.
463                 LYXERR0("Something is wrong cannot shorten row: " << *this);
464                 return false;
465         }
466
467         // Iterate backwards over breakable elements and try to break them
468         Elements::iterator cit_brk = cit;
469         int wid_brk = wid + cit_brk->dim.wid;
470         ++cit_brk;
471         while (cit_brk != beg) {
472                 --cit_brk;
473                 // make a copy of the element to work on it.
474                 Element brk = *cit_brk;
475                 wid_brk -= brk.dim.wid;
476                 if (brk.countSeparators() == 0 || brk.pos < keep)
477                         continue;
478                 /* We have found a suitable separable element. This is the common case.
479                  * Try to break it cleanly (at word boundary) at a length that is both
480                  * - less than the available space on the row
481                  * - shorter than the natural width of the element, in order to enforce
482                  *   break-up.
483                  */
484                 if (brk.breakAt(min(w - wid_brk, brk.dim.wid - 2), false)) {
485                         /* if this element originally did not cause a row overflow
486                          * in itself, and the remainder of the row would still be
487                          * too large after breaking, then we will have issues in
488                          * next row. Thus breaking does not help.
489                          */
490                         if (wid_brk + cit_brk->dim.wid < w
491                             && dim_.wid - (wid_brk + brk.dim.wid) >= next_width) {
492                                 break;
493                         }
494                         end_ = brk.endpos;
495                         /* after breakAt, there may be spaces at the end of the
496                          * string, but they are not counted in the string length
497                          * (QTextLayout feature, actually). We remove them, but do
498                          * not change the end of the row, since spaces at row
499                          * break are invisible.
500                          */
501                         brk.str = rtrim(brk.str);
502                         brk.endpos = brk.pos + brk.str.length();
503                         *cit_brk = brk;
504                         dim_.wid = wid_brk + brk.dim.wid;
505                         // If there are other elements, they should be removed.
506                         elements_.erase(cit_brk + 1, end);
507                         return true;
508                 }
509         }
510
511         if (cit != beg && cit->type == VIRTUAL) {
512                 // It is not possible to separate a virtual element from the
513                 // previous one.
514                 --cit;
515                 wid -= cit->dim.wid;
516         }
517
518         if (cit != beg) {
519                 // There is no usable separator, but several elements have
520                 // been added. We can cut right here.
521                 end_ = cit->pos;
522                 dim_.wid = wid;
523                 elements_.erase(cit, end);
524                 return true;
525         }
526
527         /* If we are here, it means that we have not found a separator to
528          * shorten the row. Let's try to break it again, but not at word
529          * boundary this time.
530          */
531         if (cit->breakAt(w - wid, true)) {
532                 end_ = cit->endpos;
533                 // See comment above.
534                 cit->str = rtrim(cit->str);
535                 cit->endpos = cit->pos + cit->str.length();
536                 dim_.wid = wid + cit->dim.wid;
537                 // If there are other elements, they should be removed.
538                 elements_.erase(next(cit, 1), end);
539                 return true;
540         }
541         return false;
542 }
543
544
545 void Row::reverseRTL(bool const rtl_par)
546 {
547         pos_type i = 0;
548         pos_type const end = elements_.size();
549         while (i < end) {
550                 // gather a sequence of elements with the same direction
551                 bool const rtl = elements_[i].isRTL();
552                 pos_type j = i;
553                 while (j < end && elements_[j].isRTL() == rtl)
554                         ++j;
555                 // if the direction is not the same as the paragraph
556                 // direction, the sequence has to be reverted.
557                 if (rtl != rtl_par)
558                         reverse(elements_.begin() + i, elements_.begin() + j);
559                 i = j;
560         }
561         // If the paragraph itself is RTL, reverse everything
562         if (rtl_par)
563                 reverse(elements_.begin(), elements_.end());
564         rtl_ = rtl_par;
565 }
566
567 Row::const_iterator const
568 Row::findElement(pos_type const pos, bool const boundary, double & x) const
569 {
570         /**
571          * When boundary is true, position i is in the row element (pos, endpos)
572          * if
573          *    pos < i <= endpos
574          * whereas, when boundary is false, the test is
575          *    pos <= i < endpos
576          * The correction below allows to handle both cases.
577         */
578         int const boundary_corr = (boundary && pos) ? -1 : 0;
579
580         x = left_margin;
581
582         /** Early return in trivial cases
583          * 1) the row is empty
584          * 2) the position is the left-most position of the row; there
585          * is a quirk here however: if the first element is virtual
586          * (end-of-par marker for example), then we have to look
587          * closer
588          */
589         if (empty()
590             || (pos == begin()->left_pos() && !boundary
591                         && !begin()->isVirtual()))
592                 return begin();
593
594         Row::const_iterator cit = begin();
595         for ( ; cit != end() ; ++cit) {
596                 /** Look whether the cursor is inside the element's
597                  * span. Note that it is necessary to take the
598                  * boundary into account, and to accept virtual
599                  * elements, which have pos == endpos.
600                  */
601                 if (pos + boundary_corr >= cit->pos
602                     && (pos + boundary_corr < cit->endpos || cit->isVirtual())) {
603                                 x += cit->pos2x(pos);
604                                 break;
605                 }
606                 x += cit->full_width();
607         }
608
609         if (cit == end())
610                 --cit;
611
612         return cit;
613 }
614
615
616 } // namespace lyx