]> git.lyx.org Git - lyx.git/blob - src/Row.cpp
Introduce the notion of math class
[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()) {
119                         x = int(full_width());
120                         i = !isRTL();
121                 } else {
122                         x = 0;
123                         i = isRTL();
124                 }
125
126         }
127         //lyxerr << "=> p=" << pos + i << " x=" << x << endl;
128         return pos + i;
129
130 }
131
132
133 bool Row::Element::breakAt(int w, bool force)
134 {
135         if (type != STRING || dim.wid <= w)
136                 return false;
137
138         FontMetrics const & fm = theFontMetrics(font);
139         int x = w;
140         if(fm.breakAt(str, x, isRTL(), force)) {
141                 dim.wid = x;
142                 endpos = pos + str.length();
143                 //lyxerr << "breakAt(" << w << ")  Row element Broken at " << x << "(w(str)=" << fm.width(str) << "): e=" << *this << endl;
144                 return true;
145         }
146
147         return false;
148 }
149
150
151 pos_type Row::Element::left_pos() const
152 {
153         return isRTL() ? endpos : pos;
154 }
155
156
157 pos_type Row::Element::right_pos() const
158 {
159         return isRTL() ? pos : endpos;
160 }
161
162
163 Row::Row()
164         : separator(0), label_hfill(0), left_margin(0), right_margin(0),
165           sel_beg(-1), sel_end(-1),
166           begin_margin_sel(false), end_margin_sel(false),
167           changed_(false), crc_(0),
168           pit_(0), pos_(0), end_(0), right_boundary_(false)
169 {}
170
171
172 void Row::setCrc(size_type crc) const
173 {
174         changed_ = crc != crc_;
175         crc_ = crc;
176 }
177
178
179 bool Row::isMarginSelected(bool left_margin, DocIterator const & beg,
180                 DocIterator const & end) const
181 {
182         pos_type const sel_pos = left_margin ? sel_beg : sel_end;
183         pos_type const margin_pos = left_margin ? pos_ : end_;
184
185         // Is the chosen margin selected ?
186         if (sel_pos == margin_pos) {
187                 if (beg.pos() == end.pos())
188                         // This is a special case in which the space between after
189                         // pos i-1 and before pos i is selected, i.e. the margins
190                         // (see DocIterator::boundary_).
191                         return beg.boundary() && !end.boundary();
192                 else if (end.pos() == margin_pos)
193                         // If the selection ends around the margin, it is only
194                         // drawn if the cursor is after the margin.
195                         return !end.boundary();
196                 else if (beg.pos() == margin_pos)
197                         // If the selection begins around the margin, it is
198                         // only drawn if the cursor is before the margin.
199                         return beg.boundary();
200                 else
201                         return true;
202         }
203         return false;
204 }
205
206
207 void Row::setSelectionAndMargins(DocIterator const & beg,
208                 DocIterator const & end) const
209 {
210         setSelection(beg.pos(), end.pos());
211
212         if (selection()) {
213                 end_margin_sel = isMarginSelected(false, beg, end);
214                 begin_margin_sel = isMarginSelected(true, beg, end);
215         }
216 }
217
218
219 void Row::setSelection(pos_type beg, pos_type end) const
220 {
221         if (pos_ >= beg && pos_ <= end)
222                 sel_beg = pos_;
223         else if (beg > pos_ && beg <= end_)
224                 sel_beg = beg;
225         else
226                 sel_beg = -1;
227
228         if (end_ >= beg && end_ <= end)
229                 sel_end = end_;
230         else if (end < end_ && end >= pos_)
231                 sel_end = end;
232         else
233                 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         // extra length per expander per em
341         double extra_per_em = double(w) / exp_amount;
342         if (extra_per_em > MAX_SPACE_STRETCH)
343                 // do not stretch more than MAX_SPACE_STRETCH em per expander
344                 return false;
345         // add extra length to each element proportionally to its em.
346         for (Row::Element & e : elements_)
347                 if (e.type == Row::STRING)
348                         e.setExtra(extra_per_em);
349         // update row dimension
350         dim_.wid += w;
351         return true;
352 }
353
354
355 bool Row::sameString(Font const & f, Change const & ch) const
356 {
357         if (elements_.empty())
358                 return false;
359         Element const & elt = elements_.back();
360         return elt.type == STRING && !elt.final
361                    && elt.font == f && elt.change == ch;
362 }
363
364
365 void Row::finalizeLast()
366 {
367         if (elements_.empty())
368                 return;
369         Element & elt = elements_.back();
370         if (elt.final)
371                 return;
372         elt.final = true;
373
374         if (elt.type == STRING) {
375                 dim_.wid -= elt.dim.wid;
376                 elt.dim.wid = theFontMetrics(elt.font).width(elt.str);
377                 dim_.wid += elt.dim.wid;
378         }
379 }
380
381
382 void Row::add(pos_type const pos, Inset const * ins, Dimension const & dim,
383               Font const & f, Change const & ch)
384 {
385         finalizeLast();
386         Element e(INSET, pos, f, ch);
387         e.inset = ins;
388         e.dim = dim;
389         elements_.push_back(e);
390         dim_.wid += dim.wid;
391 }
392
393
394 void Row::add(pos_type const pos, char_type const c,
395               Font const & f, Change const & ch)
396 {
397         if (!sameString(f, ch)) {
398                 finalizeLast();
399                 Element e(STRING, pos, f, ch);
400                 elements_.push_back(e);
401         }
402         if (back().str.length() % 30 == 0) {
403                 dim_.wid -= back().dim.wid;
404                 back().str += c;
405                 back().endpos = pos + 1;
406                 back().dim.wid = theFontMetrics(back().font).width(back().str);
407                 dim_.wid += back().dim.wid;
408         } else {
409                 back().str += c;
410                 back().endpos = pos + 1;
411         }
412 }
413
414
415 void Row::addVirtual(pos_type const pos, docstring const & s,
416                      Font const & f, Change const & ch)
417 {
418         finalizeLast();
419         Element e(VIRTUAL, pos, f, ch);
420         e.str = s;
421         e.dim.wid = theFontMetrics(f).width(s);
422         dim_.wid += e.dim.wid;
423         e.endpos = pos;
424         elements_.push_back(e);
425         finalizeLast();
426 }
427
428
429 void Row::addSpace(pos_type const pos, int const width,
430                    Font const & f, Change const & ch)
431 {
432         finalizeLast();
433         Element e(SPACE, pos, f, ch);
434         e.dim.wid = width;
435         elements_.push_back(e);
436         dim_.wid += e.dim.wid;
437 }
438
439
440 void Row::pop_back()
441 {
442         dim_.wid -= elements_.back().dim.wid;
443         elements_.pop_back();
444 }
445
446
447 bool Row::shortenIfNeeded(pos_type const keep, int const w)
448 {
449         if (empty() || width() <= w)
450                 return false;
451
452         Elements::iterator const beg = elements_.begin();
453         Elements::iterator const end = elements_.end();
454         int wid = left_margin;
455
456         // Search for the first element that goes beyond right margin
457         Elements::iterator cit = beg;
458         for ( ; cit != end ; ++cit) {
459                 if (wid + cit->dim.wid > w)
460                         break;
461                 wid += cit->dim.wid;
462         }
463
464         if (cit == end) {
465                 // This should not happen since the row is too long.
466                 LYXERR0("Something is wrong cannot shorten row: " << *this);
467                 return false;
468         }
469
470         // Iterate backwards over breakable elements and try to break them
471         Elements::iterator cit_brk = cit;
472         int wid_brk = wid + cit_brk->dim.wid;
473         ++cit_brk;
474         while (cit_brk != beg) {
475                 --cit_brk;
476                 // make a copy of the element to work on it.
477                 Element brk = *cit_brk;
478                 wid_brk -= brk.dim.wid;
479                 if (brk.countSeparators() == 0 || brk.pos < keep)
480                         continue;
481                 /* We have found a suitable separable element. This is the common case.
482                  * Try to break it cleanly (at word boundary) at a length that is both
483                  * - less than the available space on the row
484                  * - shorter than the natural width of the element, in order to enforce
485                  *   break-up.
486                  */
487                 if (brk.breakAt(min(w - wid_brk, brk.dim.wid - 2), false)) {
488                         /* if this element originally did not cause a row overflow
489                          * in itself, and the remainder of the row would still be
490                          * too large after breaking, then we will have issues in
491                          * next row. Thus breaking does not help.
492                          */
493                         if (wid_brk + cit_brk->dim.wid < w
494                             && dim_.wid - (wid_brk + brk.dim.wid) >= w) {
495                                 break;
496                         }
497                         end_ = brk.endpos;
498                         /* after breakAt, there may be spaces at the end of the
499                          * string, but they are not counted in the string length
500                          * (QTextLayout feature, actually). We remove them, but do
501                          * not change the end of the row, since spaces at row
502                          * break are invisible.
503                          */
504                         brk.str = rtrim(brk.str);
505                         brk.endpos = brk.pos + brk.str.length();
506                         *cit_brk = brk;
507                         dim_.wid = wid_brk + brk.dim.wid;
508                         // If there are other elements, they should be removed.
509                         elements_.erase(cit_brk + 1, end);
510                         return true;
511                 }
512         }
513
514         if (cit != beg && cit->type == VIRTUAL) {
515                 // It is not possible to separate a virtual element from the
516                 // previous one.
517                 --cit;
518                 wid -= cit->dim.wid;
519         }
520
521         if (cit != beg) {
522                 // There is no usable separator, but several elements have
523                 // been added. We can cut right here.
524                 end_ = cit->pos;
525                 dim_.wid = wid;
526                 elements_.erase(cit, end);
527                 return true;
528         }
529
530         /* If we are here, it means that we have not found a separator to
531          * shorten the row. Let's try to break it again, but not at word
532          * boundary this time.
533          */
534         if (cit->breakAt(w - wid, true)) {
535                 end_ = cit->endpos;
536                 // See comment above.
537                 cit->str = rtrim(cit->str);
538                 cit->endpos = cit->pos + cit->str.length();
539                 dim_.wid = wid + cit->dim.wid;
540                 // If there are other elements, they should be removed.
541                 elements_.erase(next(cit, 1), end);
542                 return true;
543         }
544         return false;
545 }
546
547
548 void Row::reverseRTL(bool const rtl_par)
549 {
550         pos_type i = 0;
551         pos_type const end = elements_.size();
552         while (i < end) {
553                 // gather a sequence of elements with the same direction
554                 bool const rtl = elements_[i].isRTL();
555                 pos_type j = i;
556                 while (j < end && elements_[j].isRTL() == rtl)
557                         ++j;
558                 // if the direction is not the same as the paragraph
559                 // direction, the sequence has to be reverted.
560                 if (rtl != rtl_par)
561                         reverse(elements_.begin() + i, elements_.begin() + j);
562                 i = j;
563         }
564         // If the paragraph itself is RTL, reverse everything
565         if (rtl_par)
566                 reverse(elements_.begin(), elements_.end());
567 }
568
569 } // namespace lyx