]> git.lyx.org Git - lyx.git/blob - src/Row.cpp
FindAdv: Amend b21c8b21: Expand the list for handled latin characters
[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, DocIterator const & beg,
173                 DocIterator const & end) const
174 {
175         pos_type const sel_pos = left ? sel_beg : sel_end;
176         pos_type const margin_pos = left ? pos_ : end_;
177
178         // Is there a selection and is the chosen margin selected ?
179         if (!selection() || sel_pos != margin_pos)
180                 return false;
181         else if (beg.pos() == end.pos())
182                 // This is a special case in which the space between after
183                 // pos i-1 and before pos i is selected, i.e. the margins
184                 // (see DocIterator::boundary_).
185                 return beg.boundary() && !end.boundary();
186         else if (end.pos() == margin_pos)
187                 // If the selection ends around the margin, it is only
188                 // drawn if the cursor is after the margin.
189                 return !end.boundary();
190         else if (beg.pos() == margin_pos)
191                 // If the selection begins around the margin, it is
192                 // only drawn if the cursor is before the margin.
193                 return beg.boundary();
194         else
195                 return true;
196 }
197
198
199 void Row::setSelectionAndMargins(DocIterator const & beg,
200                 DocIterator const & end) const
201 {
202         setSelection(beg.pos(), end.pos());
203
204         change(end_margin_sel, isMarginSelected(false, beg, end));
205         change(begin_margin_sel, isMarginSelected(true, beg, end));
206 }
207
208
209 void Row::clearSelectionAndMargins() const
210 {
211         change(sel_beg, -1);
212         change(sel_end, -1);
213         change(end_margin_sel, false);
214         change(begin_margin_sel, false);
215 }
216
217
218 void Row::setSelection(pos_type beg, pos_type end) const
219 {
220         if (pos_ >= beg && pos_ <= end)
221                 change(sel_beg, pos_);
222         else if (beg > pos_ && beg <= end_)
223                 change(sel_beg, beg);
224         else
225                 change(sel_beg, -1);
226
227         if (end_ >= beg && end_ <= end)
228                 change(sel_end,end_);
229         else if (end < end_ && end >= pos_)
230                 change(sel_end, end);
231         else
232                 change(sel_end, -1);
233 }
234
235
236 bool Row::selection() const
237 {
238         return sel_beg != -1 && sel_end != -1;
239 }
240
241
242 ostream & operator<<(ostream & os, Row::Element const & e)
243 {
244         if (e.isRTL())
245                 os << e.endpos << "<<" << e.pos << " ";
246         else
247                 os << e.pos << ">>" << e.endpos << " ";
248
249         switch (e.type) {
250         case Row::STRING:
251                 os << "STRING: `" << to_utf8(e.str) << "' ("
252                    << e.countExpanders() << " expanders.), ";
253                 break;
254         case Row::VIRTUAL:
255                 os << "VIRTUAL: `" << to_utf8(e.str) << "', ";
256                 break;
257         case Row::INSET:
258                 os << "INSET: " << to_utf8(e.inset->layoutName()) << ", ";
259                 break;
260         case Row::SPACE:
261                 os << "SPACE: ";
262                 break;
263         }
264         os << "width=" << e.full_width();
265         return os;
266 }
267
268
269 ostream & operator<<(ostream & os, Row const & row)
270 {
271         os << " pos: " << row.pos_ << " end: " << row.end_
272            << " left_margin: " << row.left_margin
273            << " width: " << row.dim_.wid
274            << " right_margin: " << row.right_margin
275            << " ascent: " << row.dim_.asc
276            << " descent: " << row.dim_.des
277            << " separator: " << row.separator
278            << " label_hfill: " << row.label_hfill
279            << " row_boundary: " << row.right_boundary() << "\n";
280         double x = row.left_margin;
281         Row::Elements::const_iterator it = row.elements_.begin();
282         for ( ; it != row.elements_.end() ; ++it) {
283                 os << "x=" << x << " => " << *it << endl;
284                 x += it->full_width();
285         }
286         return os;
287 }
288
289
290 int Row::left_x() const
291 {
292         double x = left_margin;
293         const_iterator const end = elements_.end();
294         const_iterator cit = elements_.begin();
295         while (cit != end && cit->isVirtual()) {
296                 x += cit->full_width();
297                 ++cit;
298         }
299         return int(x + 0.5);
300 }
301
302
303 int Row::right_x() const
304 {
305         double x = dim_.wid;
306         const_iterator const begin = elements_.begin();
307         const_iterator cit = elements_.end();
308         while (cit != begin) {
309                 --cit;
310                 if (cit->isVirtual())
311                         x -= cit->full_width();
312                 else
313                         break;
314         }
315         return int(x + 0.5);
316 }
317
318
319 int Row::countSeparators() const
320 {
321         int n = 0;
322         const_iterator const end = elements_.end();
323         for (const_iterator cit = elements_.begin() ; cit != end ; ++cit)
324                 n += cit->countSeparators();
325         return n;
326 }
327
328
329 bool Row::setExtraWidth(int w)
330 {
331         if (w < 0)
332                 // this is not expected to happen (but it does)
333                 return false;
334         // amount of expansion: number of expanders time the em value for each
335         // string element
336         int exp_amount = 0;
337         for (Row::Element const & e : elements_)
338                 exp_amount += e.expansionAmount();
339         if (!exp_amount)
340                 return false;
341         // extra length per expander per em
342         double extra_per_em = double(w) / exp_amount;
343         if (extra_per_em > MAX_SPACE_STRETCH)
344                 // do not stretch more than MAX_SPACE_STRETCH em per expander
345                 return false;
346         // add extra length to each element proportionally to its em.
347         for (Row::Element & e : elements_)
348                 if (e.type == Row::STRING)
349                         e.setExtra(extra_per_em);
350         // update row dimension
351         dim_.wid += w;
352         return true;
353 }
354
355
356 bool Row::sameString(Font const & f, Change const & ch) const
357 {
358         if (elements_.empty())
359                 return false;
360         Element const & elt = elements_.back();
361         return elt.type == STRING && !elt.final
362                    && elt.font == f && elt.change == ch;
363 }
364
365
366 void Row::finalizeLast()
367 {
368         if (elements_.empty())
369                 return;
370         Element & elt = elements_.back();
371         if (elt.final)
372                 return;
373         elt.final = true;
374         if (elt.change.changed())
375                 changebar_ = true;
376
377         if (elt.type == STRING) {
378                 dim_.wid -= elt.dim.wid;
379                 FontMetrics const & fm = theFontMetrics(elt.font);
380                 elt.dim.wid = fm.width(elt.str);
381                 dim_.wid += elt.dim.wid;
382                 dim_.asc = fm.maxAscent() + fm.leading();
383                 dim_.des = fm.maxDescent();
384         }
385 }
386
387
388 void Row::add(pos_type const pos, Inset const * ins, Dimension const & dim,
389               Font const & f, Change const & ch)
390 {
391         finalizeLast();
392         Element e(INSET, pos, f, ch);
393         e.inset = ins;
394         e.dim = dim;
395         elements_.push_back(e);
396         dim_.wid += dim.wid;
397 }
398
399
400 void Row::add(pos_type const pos, char_type const c,
401               Font const & f, Change const & ch)
402 {
403         if (!sameString(f, ch)) {
404                 finalizeLast();
405                 Element e(STRING, pos, f, ch);
406                 elements_.push_back(e);
407         }
408         if (back().str.length() % 30 == 0) {
409                 dim_.wid -= back().dim.wid;
410                 back().str += c;
411                 back().endpos = pos + 1;
412                 back().dim.wid = theFontMetrics(back().font).width(back().str);
413                 dim_.wid += back().dim.wid;
414         } else {
415                 back().str += c;
416                 back().endpos = pos + 1;
417         }
418 }
419
420
421 void Row::addVirtual(pos_type const pos, docstring const & s,
422                      Font const & f, Change const & ch)
423 {
424         finalizeLast();
425         Element e(VIRTUAL, pos, f, ch);
426         e.str = s;
427         e.dim.wid = theFontMetrics(f).width(s);
428         dim_.wid += e.dim.wid;
429         e.endpos = pos;
430         elements_.push_back(e);
431         finalizeLast();
432 }
433
434
435 void Row::addSpace(pos_type const pos, int const width,
436                    Font const & f, Change const & ch)
437 {
438         finalizeLast();
439         Element e(SPACE, pos, f, ch);
440         e.dim.wid = width;
441         elements_.push_back(e);
442         dim_.wid += e.dim.wid;
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                 wid_brk -= brk.dim.wid;
485                 if (brk.countSeparators() == 0 || brk.pos < keep)
486                         continue;
487                 /* We have found a suitable separable element. This is the common case.
488                  * Try to break it cleanly (at word boundary) at a length that is both
489                  * - less than the available space on the row
490                  * - shorter than the natural width of the element, in order to enforce
491                  *   break-up.
492                  */
493                 if (brk.breakAt(min(w - wid_brk, brk.dim.wid - 2), false)) {
494                         /* if this element originally did not cause a row overflow
495                          * in itself, and the remainder of the row would still be
496                          * too large after breaking, then we will have issues in
497                          * next row. Thus breaking does not help.
498                          */
499                         if (wid_brk + cit_brk->dim.wid < w
500                             && dim_.wid - (wid_brk + brk.dim.wid) >= next_width) {
501                                 break;
502                         }
503                         end_ = brk.endpos;
504                         /* after breakAt, there may be spaces at the end of the
505                          * string, but they are not counted in the string length
506                          * (QTextLayout feature, actually). We remove them, but do
507                          * not change the end of the row, since spaces at row
508                          * break are invisible.
509                          */
510                         brk.str = rtrim(brk.str);
511                         brk.endpos = brk.pos + brk.str.length();
512                         *cit_brk = brk;
513                         dim_.wid = wid_brk + brk.dim.wid;
514                         // If there are other elements, they should be removed.
515                         elements_.erase(cit_brk + 1, end);
516                         return true;
517                 }
518         }
519
520         if (cit != beg && cit->type == VIRTUAL) {
521                 // It is not possible to separate a virtual element from the
522                 // previous one.
523                 --cit;
524                 wid -= cit->dim.wid;
525         }
526
527         if (cit != beg) {
528                 // There is no usable separator, but several elements have
529                 // been added. We can cut right here.
530                 end_ = cit->pos;
531                 dim_.wid = wid;
532                 elements_.erase(cit, end);
533                 return true;
534         }
535
536         /* If we are here, it means that we have not found a separator to
537          * shorten the row. Let's try to break it again, but not at word
538          * boundary this time.
539          */
540         if (cit->breakAt(w - wid, true)) {
541                 end_ = cit->endpos;
542                 // See comment above.
543                 cit->str = rtrim(cit->str);
544                 cit->endpos = cit->pos + cit->str.length();
545                 dim_.wid = wid + cit->dim.wid;
546                 // If there are other elements, they should be removed.
547                 elements_.erase(next(cit, 1), end);
548                 return true;
549         }
550         return false;
551 }
552
553
554 void Row::reverseRTL(bool const rtl_par)
555 {
556         pos_type i = 0;
557         pos_type const end = elements_.size();
558         while (i < end) {
559                 // gather a sequence of elements with the same direction
560                 bool const rtl = elements_[i].isRTL();
561                 pos_type j = i;
562                 while (j < end && elements_[j].isRTL() == rtl)
563                         ++j;
564                 // if the direction is not the same as the paragraph
565                 // direction, the sequence has to be reverted.
566                 if (rtl != rtl_par)
567                         reverse(elements_.begin() + i, elements_.begin() + j);
568                 i = j;
569         }
570         // If the paragraph itself is RTL, reverse everything
571         if (rtl_par)
572                 reverse(elements_.begin(), elements_.end());
573         rtl_ = rtl_par;
574 }
575
576 Row::const_iterator const
577 Row::findElement(pos_type const pos, bool const boundary, double & x) const
578 {
579         /**
580          * When boundary is true, position i is in the row element (pos, endpos)
581          * if
582          *    pos < i <= endpos
583          * whereas, when boundary is false, the test is
584          *    pos <= i < endpos
585          * The correction below allows to handle both cases.
586         */
587         int const boundary_corr = (boundary && pos) ? -1 : 0;
588
589         x = left_margin;
590
591         /** Early return in trivial cases
592          * 1) the row is empty
593          * 2) the position is the left-most position of the row; there
594          * is a quirk here however: if the first element is virtual
595          * (end-of-par marker for example), then we have to look
596          * closer
597          */
598         if (empty()
599             || (pos == begin()->left_pos() && !boundary
600                         && !begin()->isVirtual()))
601                 return begin();
602
603         Row::const_iterator cit = begin();
604         for ( ; cit != end() ; ++cit) {
605                 /** Look whether the cursor is inside the element's
606                  * span. Note that it is necessary to take the
607                  * boundary into account, and to accept virtual
608                  * elements, which have pos == endpos.
609                  */
610                 if (pos + boundary_corr >= cit->pos
611                     && (pos + boundary_corr < cit->endpos || cit->isVirtual())) {
612                                 x += cit->pos2x(pos);
613                                 break;
614                 }
615                 x += cit->full_width();
616         }
617
618         if (cit == end())
619                 --cit;
620
621         return cit;
622 }
623
624
625 } // namespace lyx