]> git.lyx.org Git - lyx.git/blob - src/Row.cpp
Fix quotation marks in PDF TOC
[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 #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/lyxalgo.h"
30
31 #include <ostream>
32
33 using namespace std;
34
35 namespace lyx {
36
37 using support::rtrim;
38 using frontend::FontMetrics;
39
40
41 // Maximum length that a space can be stretched when justifying text
42 static double const MAX_SPACE_STRETCH = 1.5; //em
43
44
45 int Row::Element::countSeparators() const
46 {
47         if (type != STRING)
48                 return 0;
49         return count(str.begin(), str.end(), ' ');
50 }
51
52
53 int Row::Element::countExpanders() const
54 {
55         if (type != STRING)
56                 return 0;
57         return theFontMetrics(font).countExpanders(str);
58 }
59
60
61 int Row::Element::expansionAmount() const
62 {
63         if (type != STRING)
64                 return 0;
65         return countExpanders() * theFontMetrics(font).em();
66 }
67
68
69 void Row::Element::setExtra(double extra_per_em)
70 {
71         if (type != STRING)
72                 return;
73         extra = extra_per_em * theFontMetrics(font).em();
74 }
75
76
77 double Row::Element::pos2x(pos_type const i) const
78 {
79         // This can happen with inline completion when clicking on the
80         // row after the completion.
81         if (i < pos || i > endpos)
82                 return 0;
83
84         double w = 0;
85         //handle first the two bounds of the element
86         if (i == endpos && type != VIRTUAL)
87                 w = isRTL() ? 0 : full_width();
88         else if (i == pos || type != STRING)
89                 w = isRTL() ? full_width() : 0;
90         else {
91                 FontMetrics const & fm = theFontMetrics(font);
92                 w = fm.pos2x(str, i - pos, isRTL(), extra);
93         }
94
95         return w;
96 }
97
98
99 pos_type Row::Element::x2pos(int &x) const
100 {
101         //lyxerr << "x2pos: x=" << x << " w=" << width() << " " << *this;
102         size_t i = 0;
103
104         switch (type) {
105         case STRING: {
106                 FontMetrics const & fm = theFontMetrics(font);
107                 i = fm.x2pos(str, x, isRTL(), extra);
108                 break;
109         }
110         case VIRTUAL:
111                 // those elements are actually empty (but they have a width)
112                 i = 0;
113                 x = isRTL() ? int(full_width()) : 0;
114                 break;
115         case INSET:
116         case SPACE:
117                 // those elements contain only one position. Round to
118                 // the closest side.
119                 if (x > (full_width() + 1) / 2) {
120                         x = int(full_width());
121                         i = !isRTL();
122                 } else {
123                         x = 0;
124                         i = isRTL();
125                 }
126         }
127         //lyxerr << "=> p=" << pos + i << " x=" << x << endl;
128         return pos + i;
129 }
130
131
132 bool Row::Element::breakAt(int w, bool force)
133 {
134         if (type != STRING || dim.wid <= w)
135                 return false;
136
137         FontMetrics const & fm = theFontMetrics(font);
138         int x = w;
139         if(fm.breakAt(str, x, isRTL(), force)) {
140                 dim.wid = x;
141                 endpos = pos + str.length();
142                 //lyxerr << "breakAt(" << w << ")  Row element Broken at " << x << "(w(str)=" << fm.width(str) << "): e=" << *this << endl;
143                 return true;
144         }
145
146         return false;
147 }
148
149
150 pos_type Row::Element::left_pos() const
151 {
152         return isRTL() ? endpos : pos;
153 }
154
155
156 pos_type Row::Element::right_pos() const
157 {
158         return isRTL() ? pos : endpos;
159 }
160
161
162 Row::Row()
163         : separator(0), label_hfill(0), left_margin(0), right_margin(0),
164           sel_beg(-1), sel_end(-1),
165           begin_margin_sel(false), end_margin_sel(false),
166           changed_(true),
167           pit_(0), pos_(0), end_(0),
168           right_boundary_(false), flushed_(false), rtl_(false),
169           changebar_(false)
170 {}
171
172
173 bool Row::isMarginSelected(bool left_margin, DocIterator const & beg,
174                 DocIterator const & end) const
175 {
176         pos_type const sel_pos = left_margin ? sel_beg : sel_end;
177         pos_type const margin_pos = left_margin ? pos_ : end_;
178
179         // Is the chosen margin selected ?
180         if (sel_pos == margin_pos) {
181                 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         return false;
198 }
199
200
201 void Row::setSelectionAndMargins(DocIterator const & beg,
202                 DocIterator const & end) const
203 {
204         setSelection(beg.pos(), end.pos());
205
206         if (selection()) {
207                 change(end_margin_sel, isMarginSelected(false, beg, end));
208                 change(begin_margin_sel, isMarginSelected(true, beg, end));
209         }
210 }
211
212
213 void Row::setSelection(pos_type beg, pos_type end) const
214 {
215         if (pos_ >= beg && pos_ <= end)
216                 change(sel_beg, pos_);
217         else if (beg > pos_ && beg <= end_)
218                 change(sel_beg, beg);
219         else
220                 change(sel_beg, -1);
221
222         if (end_ >= beg && end_ <= end)
223                 change(sel_end,end_);
224         else if (end < end_ && end >= pos_)
225                 change(sel_end, end);
226         else
227                 change(sel_end, -1);
228 }
229
230
231 bool Row::selection() const
232 {
233         return sel_beg != -1 && sel_end != -1;
234 }
235
236
237 ostream & operator<<(ostream & os, Row::Element const & e)
238 {
239         if (e.isRTL())
240                 os << e.endpos << "<<" << e.pos << " ";
241         else
242                 os << e.pos << ">>" << e.endpos << " ";
243
244         switch (e.type) {
245         case Row::STRING:
246                 os << "STRING: `" << to_utf8(e.str) << "' ("
247                    << e.countExpanders() << " expanders.), ";
248                 break;
249         case Row::VIRTUAL:
250                 os << "VIRTUAL: `" << to_utf8(e.str) << "', ";
251                 break;
252         case Row::INSET:
253                 os << "INSET: " << to_utf8(e.inset->layoutName()) << ", ";
254                 break;
255         case Row::SPACE:
256                 os << "SPACE: ";
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 int(x + 0.5);
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 int(x + 0.5);
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 (Row::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 (Row::Element & e : elements_)
343                 if (e.type == Row::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 }
390
391
392 void Row::add(pos_type const pos, char_type const c,
393               Font const & f, Change const & ch)
394 {
395         if (!sameString(f, ch)) {
396                 finalizeLast();
397                 Element e(STRING, pos, f, ch);
398                 elements_.push_back(e);
399         }
400         if (back().str.length() % 30 == 0) {
401                 dim_.wid -= back().dim.wid;
402                 back().str += c;
403                 back().endpos = pos + 1;
404                 back().dim.wid = theFontMetrics(back().font).width(back().str);
405                 dim_.wid += back().dim.wid;
406         } else {
407                 back().str += c;
408                 back().endpos = pos + 1;
409         }
410 }
411
412
413 void Row::addVirtual(pos_type const pos, docstring const & s,
414                      Font const & f, Change const & ch)
415 {
416         finalizeLast();
417         Element e(VIRTUAL, pos, f, ch);
418         e.str = s;
419         e.dim.wid = theFontMetrics(f).width(s);
420         dim_.wid += e.dim.wid;
421         e.endpos = pos;
422         elements_.push_back(e);
423         finalizeLast();
424 }
425
426
427 void Row::addSpace(pos_type const pos, int const width,
428                    Font const & f, Change const & ch)
429 {
430         finalizeLast();
431         Element e(SPACE, pos, f, ch);
432         e.dim.wid = width;
433         elements_.push_back(e);
434         dim_.wid += e.dim.wid;
435 }
436
437
438 void Row::pop_back()
439 {
440         dim_.wid -= elements_.back().dim.wid;
441         elements_.pop_back();
442 }
443
444
445 bool Row::shortenIfNeeded(pos_type const keep, int const w, int const next_width)
446 {
447         if (empty() || width() <= w)
448                 return false;
449
450         Elements::iterator const beg = elements_.begin();
451         Elements::iterator const end = elements_.end();
452         int wid = left_margin;
453
454         // Search for the first element that goes beyond right margin
455         Elements::iterator cit = beg;
456         for ( ; cit != end ; ++cit) {
457                 if (wid + cit->dim.wid > w)
458                         break;
459                 wid += cit->dim.wid;
460         }
461
462         if (cit == end) {
463                 // This should not happen since the row is too long.
464                 LYXERR0("Something is wrong cannot shorten row: " << *this);
465                 return false;
466         }
467
468         // Iterate backwards over breakable elements and try to break them
469         Elements::iterator cit_brk = cit;
470         int wid_brk = wid + cit_brk->dim.wid;
471         ++cit_brk;
472         while (cit_brk != beg) {
473                 --cit_brk;
474                 // make a copy of the element to work on it.
475                 Element brk = *cit_brk;
476                 wid_brk -= brk.dim.wid;
477                 /*
478                  * Some Asian languages split lines anywhere (no notion of
479                  * word). It seems that QTextLayout is not aware of this fact.
480                  * See for reference:
481                  *    https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
482                  *
483                  * FIXME: Something shall be done about characters which are
484                  * not allowed at the beginning or end of line.
485                  *
486                  * FIXME: hardcoding languages is bad. Put this information in
487                  * `languages' file.
488                 */
489                 string const lang = brk.font.language()->lang();
490                 bool force = lang == "chinese-simplified"
491                              || lang == "chinese-traditional"
492                              || lang == "japanese"
493                              || lang == "japanese-cjk"
494                              || lang == "korean";
495                 // FIXME: is it important to check for separators?
496                 if ((!force && brk.countSeparators() == 0) || brk.pos < keep)
497                         continue;
498                 /* We have found a suitable separable element. This is the common case.
499                  * Try to break it cleanly (at word boundary) at a length that is both
500                  * - less than the available space on the row
501                  * - shorter than the natural width of the element, in order to enforce
502                  *   break-up.
503                  */
504                 if (brk.breakAt(min(w - wid_brk, brk.dim.wid - 2), force)) {
505                         /* if this element originally did not cause a row overflow
506                          * in itself, and the remainder of the row would still be
507                          * too large after breaking, then we will have issues in
508                          * next row. Thus breaking does not help.
509                          */
510                         if (wid_brk + cit_brk->dim.wid < w
511                             && dim_.wid - (wid_brk + brk.dim.wid) >= next_width) {
512                                 break;
513                         }
514                         end_ = brk.endpos;
515                         /* after breakAt, there may be spaces at the end of the
516                          * string, but they are not counted in the string length
517                          * (QTextLayout feature, actually). We remove them, but do
518                          * not change the end of the row, since spaces at row
519                          * break are invisible.
520                          */
521                         brk.str = rtrim(brk.str);
522                         brk.endpos = brk.pos + brk.str.length();
523                         *cit_brk = brk;
524                         dim_.wid = wid_brk + brk.dim.wid;
525                         // If there are other elements, they should be removed.
526                         elements_.erase(cit_brk + 1, end);
527                         return true;
528                 }
529         }
530
531         if (cit != beg && cit->type == VIRTUAL) {
532                 // It is not possible to separate a virtual element from the
533                 // previous one.
534                 --cit;
535                 wid -= cit->dim.wid;
536         }
537
538         if (cit != beg) {
539                 // There is no usable separator, but several elements have
540                 // been added. We can cut right here.
541                 end_ = cit->pos;
542                 dim_.wid = wid;
543                 elements_.erase(cit, end);
544                 return true;
545         }
546
547         /* If we are here, it means that we have not found a separator to
548          * shorten the row. Let's try to break it again, but not at word
549          * boundary this time.
550          */
551         if (cit->breakAt(w - wid, true)) {
552                 end_ = cit->endpos;
553                 // See comment above.
554                 cit->str = rtrim(cit->str);
555                 cit->endpos = cit->pos + cit->str.length();
556                 dim_.wid = wid + cit->dim.wid;
557                 // If there are other elements, they should be removed.
558                 elements_.erase(next(cit, 1), end);
559                 return true;
560         }
561         return false;
562 }
563
564
565 void Row::reverseRTL(bool const rtl_par)
566 {
567         pos_type i = 0;
568         pos_type const end = elements_.size();
569         while (i < end) {
570                 // gather a sequence of elements with the same direction
571                 bool const rtl = elements_[i].isRTL();
572                 pos_type j = i;
573                 while (j < end && elements_[j].isRTL() == rtl)
574                         ++j;
575                 // if the direction is not the same as the paragraph
576                 // direction, the sequence has to be reverted.
577                 if (rtl != rtl_par)
578                         reverse(elements_.begin() + i, elements_.begin() + j);
579                 i = j;
580         }
581         // If the paragraph itself is RTL, reverse everything
582         if (rtl_par)
583                 reverse(elements_.begin(), elements_.end());
584         rtl_ = rtl_par;
585 }
586
587 Row::const_iterator const
588 Row::findElement(pos_type const pos, bool const boundary, double & x) const
589 {
590         /**
591          * When boundary is true, position i is in the row element (pos, endpos)
592          * if
593          *    pos < i <= endpos
594          * whereas, when boundary is false, the test is
595          *    pos <= i < endpos
596          * The correction below allows to handle both cases.
597         */
598         int const boundary_corr = (boundary && pos) ? -1 : 0;
599
600         x = left_margin;
601
602         /** Early return in trivial cases
603          * 1) the row is empty
604          * 2) the position is the left-most position of the row; there
605          * is a quirk here however: if the first element is virtual
606          * (end-of-par marker for example), then we have to look
607          * closer
608          */
609         if (empty()
610             || (pos == begin()->left_pos() && !boundary
611                         && !begin()->isVirtual()))
612                 return begin();
613
614         Row::const_iterator cit = begin();
615         for ( ; cit != end() ; ++cit) {
616                 /** Look whether the cursor is inside the element's
617                  * span. Note that it is necessary to take the
618                  * boundary into account, and to accept virtual
619                  * elements, which have pos == endpos.
620                  */
621                 if (pos + boundary_corr >= cit->pos
622                     && (pos + boundary_corr < cit->endpos || cit->isVirtual())) {
623                                 x += cit->pos2x(pos);
624                                 break;
625                 }
626                 x += cit->full_width();
627         }
628
629         if (cit == end())
630                 --cit;
631
632         return cit;
633 }
634
635
636 } // namespace lyx