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