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