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