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