]> git.lyx.org Git - lyx.git/blob - src/TextMetrics.cpp
\\spellchecker_ignore: use LyX language name rather than langcode
[lyx.git] / src / TextMetrics.cpp
1 /**
2  * \file src/TextMetrics.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Jürgen Vigna
13  * \author Abdelrazak Younes
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "TextMetrics.h"
21
22 #include "Buffer.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CoordCache.h"
26 #include "Cursor.h"
27 #include "CutAndPaste.h"
28 #include "Layout.h"
29 #include "LyXRC.h"
30 #include "MetricsInfo.h"
31 #include "ParagraphParameters.h"
32 #include "RowPainter.h"
33 #include "Session.h"
34 #include "Text.h"
35 #include "TextClass.h"
36 #include "VSpace.h"
37
38 #include "insets/InsetText.h"
39
40 #include "mathed/MacroTable.h"
41
42 #include "frontends/FontMetrics.h"
43 #include "frontends/NullPainter.h"
44
45 #include "support/debug.h"
46 #include "support/lassert.h"
47 #include "support/Changer.h"
48
49 #include <stdlib.h>
50 #include <cmath>
51
52 using namespace std;
53
54
55 namespace lyx {
56
57 using frontend::FontMetrics;
58
59 namespace {
60
61
62 int numberOfLabelHfills(Paragraph const & par, Row const & row)
63 {
64         pos_type last = row.endpos() - 1;
65         pos_type first = row.pos();
66
67         // hfill *DO* count at the beginning of paragraphs!
68         if (first) {
69                 while (first < last && par.isHfill(first))
70                         ++first;
71         }
72
73         last = min(last, par.beginOfBody());
74         int n = 0;
75         for (pos_type p = first; p < last; ++p) {
76                 if (par.isHfill(p))
77                         ++n;
78         }
79         return n;
80 }
81
82 // FIXME: this needs to be rewritten, probably by merging it into some
83 // code that, besides counting, sets the active status of the space
84 // inset in the row element.
85 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
86                    pos_type const body_pos)
87 {
88         int n = 0;
89         Row::const_iterator cit = row.begin();
90         Row::const_iterator const end = row.end();
91         for ( ; cit != end ; ++cit)
92                 if (cit->pos >= body_pos
93                     && cit->inset && pm.hfillExpansion(row, cit->pos))
94                         ++n;
95         return n;
96 }
97
98
99 } // namespace
100
101 /////////////////////////////////////////////////////////////////////
102 //
103 // TextMetrics
104 //
105 /////////////////////////////////////////////////////////////////////
106
107
108 TextMetrics::TextMetrics(BufferView * bv, Text * text)
109         : bv_(bv), text_(text)
110 {
111         LBUFERR(bv_);
112         max_width_ = bv_->workWidth();
113         dim_.wid = max_width_;
114         dim_.asc = 10;
115         dim_.des = 10;
116 }
117
118
119 bool TextMetrics::contains(pit_type pit) const
120 {
121         return par_metrics_.find(pit) != par_metrics_.end();
122 }
123
124
125 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
126 {
127         ParMetricsCache::const_iterator it = par_metrics_.begin();
128         return make_pair(it->first, &it->second);
129 }
130
131
132 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
133 {
134         LBUFERR(!par_metrics_.empty());
135         ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
136         return make_pair(it->first, &it->second);
137 }
138
139
140 bool TextMetrics::isLastRow(Row const & row) const
141 {
142         ParagraphList const & pars = text_->paragraphs();
143         return row.endpos() >= pars[row.pit()].size()
144                 && row.pit() + 1 == pit_type(pars.size());
145 }
146
147
148 bool TextMetrics::isFirstRow(Row const & row) const
149 {
150         return row.pos() == 0 && row.pit() == 0;
151 }
152
153
154 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
155 {
156         for (auto & pm_pair : par_metrics_)
157                 if (pm_pair.first == pit)
158                         for (Row & row : pm_pair.second.rows())
159                                 if (row.pos() == pos)
160                                         row.changed(true);
161 }
162
163
164 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
165 {
166         ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
167         if (pmc_it == par_metrics_.end()) {
168                 pmc_it = par_metrics_.insert(
169                         make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
170         }
171         if (pmc_it->second.rows().empty() && redo)
172                 redoParagraph(pit);
173         return pmc_it->second;
174 }
175
176
177 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
178 {
179         return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
180 }
181
182
183 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit)
184 {
185         return parMetrics(pit, true);
186 }
187
188
189 void TextMetrics::newParMetricsDown()
190 {
191         pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
192         pit_type const pit = last.first + 1;
193         if (pit == int(text_->paragraphs().size()))
194                 return;
195
196         // do it and update its position.
197         redoParagraph(pit);
198         par_metrics_[pit].setPosition(last.second.position()
199                 + last.second.descent() + par_metrics_[pit].ascent());
200         updatePosCache(pit);
201 }
202
203
204 void TextMetrics::newParMetricsUp()
205 {
206         pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
207         if (first.first == 0)
208                 return;
209
210         pit_type const pit = first.first - 1;
211         // do it and update its position.
212         redoParagraph(pit);
213         par_metrics_[pit].setPosition(first.second.position()
214                 - first.second.ascent() - par_metrics_[pit].descent());
215         updatePosCache(pit);
216 }
217
218
219 bool TextMetrics::metrics(MetricsInfo const & mi, Dimension & dim, int min_width,
220                           bool const expand_on_multipars)
221 {
222         LBUFERR(mi.base.textwidth > 0);
223         max_width_ = mi.base.textwidth;
224         // backup old dimension.
225         Dimension const old_dim = dim_;
226         // reset dimension.
227         dim_ = Dimension();
228         dim_.wid = min_width;
229         pit_type const npar = text_->paragraphs().size();
230         if (npar > 1 && expand_on_multipars)
231                 // If there is more than one row, expand the text to
232                 // the full allowable width.
233                 dim_.wid = max_width_;
234
235         //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
236         //      << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
237
238         bool changed = false;
239         int h = 0;
240         for (pit_type pit = 0; pit != npar; ++pit) {
241                 // create rows, but do not set alignment yet
242                 changed |= redoParagraph(pit, false);
243                 ParagraphMetrics const & pm = par_metrics_[pit];
244                 h += pm.height();
245                 if (dim_.wid < pm.width())
246                         dim_.wid = pm.width();
247         }
248
249         // Now set alignment for all rows (the width might not have been known before).
250         for (pit_type pit = 0; pit != npar; ++pit) {
251                 ParagraphMetrics & pm = par_metrics_[pit];
252                 for (Row & row : pm.rows())
253                         setRowAlignment(row, dim_.wid);
254         }
255
256         dim_.asc = par_metrics_[0].ascent();
257         dim_.des = h - dim_.asc;
258         //lyxerr << "dim_.wid " << dim_.wid << endl;
259         //lyxerr << "dim_.asc " << dim_.asc << endl;
260         //lyxerr << "dim_.des " << dim_.des << endl;
261
262         changed |= dim_ != old_dim;
263         dim = dim_;
264         return changed;
265 }
266
267
268 void TextMetrics::updatePosCache(pit_type pit) const
269 {
270         frontend::NullPainter np;
271         PainterInfo pi(bv_, np);
272         drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
273 }
274
275
276 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
277 {
278         return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
279 }
280
281
282 int TextMetrics::rightMargin(pit_type const pit) const
283 {
284         return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
285 }
286
287
288 void TextMetrics::applyOuterFont(Font & font) const
289 {
290         FontInfo lf(font_.fontInfo());
291         lf.reduce(bv_->buffer().params().getFont().fontInfo());
292         font.fontInfo().realize(lf);
293 }
294
295
296 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
297 {
298         LASSERT(pos >= 0, { static Font f; return f; });
299
300         ParagraphList const & pars = text_->paragraphs();
301         Paragraph const & par = pars[pit];
302         Layout const & layout = par.layout();
303         Buffer const & buffer = bv_->buffer();
304         // FIXME: broken?
305         BufferParams const & params = buffer.params();
306         pos_type const body_pos = par.beginOfBody();
307
308         // We specialize the 95% common case:
309         if (!par.getDepth()) {
310                 Font f = par.getFontSettings(params, pos);
311                 if (!text_->isMainText())
312                         applyOuterFont(f);
313                 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
314
315                 FontInfo const & lf = lab ? layout.labelfont : layout.font;
316                 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
317
318                 // In case the default family has been customized
319                 if (lf.family() == INHERIT_FAMILY)
320                         rlf.setFamily(params.getFont().fontInfo().family());
321                 f.fontInfo().realize(rlf);
322                 return f;
323         }
324
325         // The uncommon case need not be optimized as much
326         FontInfo const & layoutfont = pos < body_pos ?
327                 layout.labelfont : layout.font;
328
329         Font font = par.getFontSettings(params, pos);
330         font.fontInfo().realize(layoutfont);
331
332         if (!text_->isMainText())
333                 applyOuterFont(font);
334
335         // Realize against environment font information
336         // NOTE: the cast to pit_type should be removed when pit_type
337         // changes to a unsigned integer.
338         if (pit < pit_type(pars.size()))
339                 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
340
341         // Realize with the fonts of lesser depth.
342         font.fontInfo().realize(params.getFont().fontInfo());
343
344         return font;
345 }
346
347
348 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
349 {
350         if (!sl.text())
351                 return false;
352
353         int correction = 0;
354         if (boundary && sl.pos() > 0)
355                 correction = -1;
356
357         return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
358 }
359
360
361 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
362 {
363         // no RTL boundary at paragraph start
364         if (pos == 0)
365                 return false;
366
367         Font const & left_font = displayFont(pit, pos - 1);
368
369         return isRTLBoundary(pit, pos, left_font);
370 }
371
372
373 // isRTLBoundary returns false on a real end-of-line boundary,
374 // because otherwise the two boundary types get mixed up.
375 // This is the whole purpose of this being in TextMetrics.
376 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
377                 Font const & font) const
378 {
379         if (// no RTL boundary at paragraph start
380             pos == 0
381             // if the metrics have not been calculated, then we are not
382             // on screen and can safely ignore issues about boundaries.
383             || !contains(pit))
384                 return false;
385
386         ParagraphMetrics const & pm = par_metrics_[pit];
387         // no RTL boundary in empty paragraph
388         if (pm.rows().empty())
389                 return false;
390
391         pos_type const endpos = pm.getRow(pos - 1, false).endpos();
392         pos_type const startpos = pm.getRow(pos, false).pos();
393         // no RTL boundary at line start:
394         // abc\n   -> toggle to RTL ->    abc\n     (and not:    abc\n|
395         // |                              |                               )
396         if (pos == startpos && pos == endpos) // start of cur row, end of prev row
397                 return false;
398
399         Paragraph const & par = text_->getPar(pit);
400         // no RTL boundary at line break:
401         // abc|\n    -> move right ->   abc\n       (and not:    abc\n|
402         // FED                          FED|                     FED     )
403         if (startpos == pos && endpos == pos && endpos != par.size()
404                 && (par.isNewline(pos - 1)
405                         || par.isEnvSeparator(pos - 1)
406                         || par.isLineSeparator(pos - 1)
407                         || par.isSeparator(pos - 1)))
408                 return false;
409
410         bool const left = font.isVisibleRightToLeft();
411         bool right;
412         if (pos == par.size())
413                 right = par.isRTL(bv_->buffer().params());
414         else
415                 right = displayFont(pit, pos).isVisibleRightToLeft();
416
417         return left != right;
418 }
419
420
421 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
422 {
423         Paragraph & par = text_->getPar(pit);
424         // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
425         // redoParagraph() recursively inside parMetrics.
426         Dimension old_dim = parMetrics(pit, false).dim();
427         ParagraphMetrics & pm = par_metrics_[pit];
428         pm.reset(par);
429
430         Buffer & buffer = bv_->buffer();
431         bool changed = false;
432
433         // Check whether there are InsetBibItems that need fixing
434         // FIXME: This check ought to be done somewhere else. It is the reason
435         // why text_ is not const. But then, where else to do it?
436         // Well, how can you end up with either (a) a biblio environment that
437         // has no InsetBibitem, (b) a biblio environment with more than one
438         // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
439         // environment? I think the answer is: when paragraphs are merged;
440         // when layout is set; when material is pasted.
441         if (par.brokenBiblio()) {
442                 Cursor & cur = const_cast<Cursor &>(bv_->cursor());
443                 // In some cases, we do not know how to record undo
444                 if (&cur.inset() == &text_->inset())
445                         cur.recordUndo(pit, pit);
446
447                 int const moveCursor = par.fixBiblio(buffer);
448
449                 // Is it necessary to update the cursor?
450                 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
451                         if (moveCursor > 0)
452                                 cur.posForward();
453                         else if (moveCursor < 0 && cur.pos() >= -moveCursor)
454                                 cur.posBackward();
455                 }
456         }
457
458         // Optimisation: this is used in the next two loops
459         // so better to calculate that once here.
460         int const right_margin = rightMargin(pm);
461
462         // iterator pointing to paragraph to resolve macros
463         DocIterator parPos = text_->macrocontextPosition();
464         if (!parPos.empty())
465                 parPos.pit() = pit;
466         else {
467                 LYXERR(Debug::INFO, "MacroContext not initialised!"
468                         << " Going through the buffer again and hope"
469                         << " the context is better then.");
470                 // FIXME audit updateBuffer calls
471                 // This should not be here, but it is not clear yet where else it
472                 // should be.
473                 bv_->buffer().updateBuffer();
474                 parPos = text_->macrocontextPosition();
475                 LBUFERR(!parPos.empty());
476                 parPos.pit() = pit;
477         }
478
479         // redo insets
480         par.setBeginOfBody();
481         Font const bufferfont = buffer.params().getFont();
482         CoordCache::Insets & insetCache = bv_->coordCache().insets();
483         for (auto const & e : par.insetList()) {
484                 // FIXME Doesn't this HAVE to be non-empty?
485                 // position already initialized?
486                 if (!parPos.empty()) {
487                         parPos.pos() = e.pos;
488
489                         // A macro template would normally not be visible
490                         // by itself. But the tex macro semantics allow
491                         // recursion, so we artifically take the context
492                         // after the macro template to simulate this.
493                         if (e.inset->lyxCode() == MATHMACRO_CODE)
494                                 parPos.pos()++;
495                 }
496
497                 // If there is an end of paragraph marker, its size should be
498                 // substracted to the available width. The logic here is
499                 // almost the same as in breakRow, remember keep them in sync.
500                 int eop = 0;
501                 if (lyxrc.paragraph_markers && e.pos + 1 == par.size()
502                     && size_type(pit + 1) < text_->paragraphs().size()) {
503                         Font f(text_->layoutFont(pit));
504                         // ¶ U+00B6 PILCROW SIGN
505                         eop = theFontMetrics(f).width(char_type(0x00B6));
506                 }
507
508                 // do the metric calculation
509                 Dimension dim;
510                 int const w = max_width_ - leftMargin(pit, e.pos)
511                         - right_margin - eop;
512                 Font const & font = e.inset->inheritFont() ?
513                         displayFont(pit, e.pos) : bufferfont;
514                 MacroContext mc(&buffer, parPos);
515                 MetricsInfo mi(bv_, font.fontInfo(), w, mc, e.pos == 0);
516                 e.inset->metrics(mi, dim);
517                 if (!insetCache.has(e.inset) || insetCache.dim(e.inset) != dim) {
518                         insetCache.add(e.inset, dim);
519                         changed = true;
520                 }
521         }
522
523         pos_type first = 0;
524         size_t row_index = 0;
525         bool need_new_row = false;
526         // maximum pixel width of a row
527         do {
528                 if (row_index == pm.rows().size())
529                         pm.rows().push_back(Row());
530                 else
531                         pm.rows()[row_index] = Row();
532                 Row & row = pm.rows()[row_index];
533                 row.pit(pit);
534                 row.pos(first);
535                 need_new_row = breakRow(row, right_margin);
536                 setRowHeight(row);
537                 row.changed(true);
538                 if ((row_index || row.endpos() < par.size() || row.right_boundary())
539                     && par.inInset().lyxCode() != CELL_CODE) {
540                         /* If there is more than one row or the row has been
541                          * broken by a display inset or a newline, expand the text
542                          * to the full allowable width. This setting here is
543                          * needed for the setRowAlignment() below.
544                          * We do nothing when inside a table cell.
545                          */
546                         if (dim_.wid < max_width_)
547                                 dim_.wid = max_width_;
548                 }
549                 if (align_rows)
550                         setRowAlignment(row, max(dim_.wid, row.width()));
551                 first = row.endpos();
552                 ++row_index;
553
554                 pm.dim().wid = max(pm.dim().wid, row.width() + row.right_margin);
555                 pm.dim().des += row.height();
556         } while (first < par.size() || need_new_row);
557
558         if (row_index < pm.rows().size())
559                 pm.rows().resize(row_index);
560
561         // This type of margin can only be handled at the global paragraph level
562         if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX) {
563                 int offset = 0;
564                 if (par.isRTL(buffer.params())) {
565                         // globally align the paragraph to the left.
566                         int minleft = max_width_;
567                         for (Row const & row : pm.rows())
568                                 minleft = min(minleft, row.left_margin);
569                         offset = right_margin - minleft;
570                 } else {
571                         // globally align the paragraph to the right.
572                         int maxwid = 0;
573                         for (Row const & row : pm.rows())
574                                 maxwid = max(maxwid, row.width());
575                         offset = max_width_ - right_margin - maxwid;
576                 }
577
578                 for (Row & row : pm.rows()) {
579                         row.left_margin += offset;
580                         row.dim().wid += offset;
581                 }
582         }
583
584         // The space above and below the paragraph.
585         int top = parTopSpacing(pit);
586         int bottom = parBottomSpacing(pit);
587
588         // Top and bottom margin of the document (only at top-level)
589         // FIXME: It might be better to move this in another method
590         // specially tailored for the main text.
591         if (text_->isMainText()) {
592                 if (pit == 0)
593                         top += bv_->topMargin();
594                 if (pit + 1 == pit_type(text_->paragraphs().size())) {
595                         bottom += bv_->bottomMargin();
596                 }
597         }
598
599         // Add the top/bottom space to rows and paragraph metrics
600         pm.rows().front().dim().asc += top;
601         pm.rows().back().dim().des += bottom;
602         pm.dim().des += top + bottom;
603
604         // Move the pm ascent to be the same as the first row ascent
605         pm.dim().asc += pm.rows().front().ascent();
606         pm.dim().des -= pm.rows().front().ascent();
607
608         changed |= old_dim.height() != pm.dim().height();
609
610         return changed;
611 }
612
613
614 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
615 {
616         LyXAlignment align = par.getAlign(bv_->buffer().params());
617
618         // handle alignment inside tabular cells
619         Inset const & owner = text_->inset();
620         bool forced_block = false;
621         switch (owner.contentAlignment()) {
622         case LYX_ALIGN_BLOCK:
623                 // In general block align is the default state, but here it is
624                 // an explicit choice. Therefore it should not be overridden
625                 // later.
626                 forced_block = true;
627                 // fall through
628         case LYX_ALIGN_CENTER:
629         case LYX_ALIGN_LEFT:
630         case LYX_ALIGN_RIGHT:
631                 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
632                         align = owner.contentAlignment();
633                 break;
634         default:
635                 // unchanged (use align)
636                 break;
637         }
638
639         // Display-style insets should always be on a centered row
640         if (Inset const * inset = par.getInset(row.pos())) {
641                 if (inset->rowFlags() & Inset::Display) {
642                         if (inset->rowFlags() & Inset::AlignLeft)
643                                 align = LYX_ALIGN_BLOCK;
644                         else if (inset->rowFlags() & Inset::AlignRight)
645                                 align = LYX_ALIGN_RIGHT;
646                         else
647                                 align = LYX_ALIGN_CENTER;
648                 }
649         }
650
651         if (align == LYX_ALIGN_BLOCK) {
652                 // If this row has been broken abruptly by a display inset, or
653                 // it is the end of the paragraph, or the user requested we
654                 // not justify stuff, then don't stretch.
655                 // A forced block alignment can only be overridden the 'no
656                 // justification on screen' setting.
657                 if ((row.flushed() && !forced_block)
658                     || !bv_->buffer().params().justification)
659                         align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
660         }
661
662         return align;
663 }
664
665
666 void TextMetrics::setRowAlignment(Row & row, int width) const
667 {
668         row.label_hfill = 0;
669         row.separator = 0;
670
671         Paragraph const & par = text_->getPar(row.pit());
672
673         int const w = width - row.right_margin - row.width();
674         // FIXME: put back this assertion when the crash on new doc is solved.
675         //LASSERT(w >= 0, /**/);
676
677         // is there a manual margin with a manual label
678         Layout const & layout = par.layout();
679
680         int nlh = 0;
681         if (layout.margintype == MARGIN_MANUAL
682             && layout.labeltype == LABEL_MANUAL) {
683                 /// We might have real hfills in the label part
684                 nlh = numberOfLabelHfills(par, row);
685
686                 // A manual label par (e.g. List) has an auto-hfill
687                 // between the label text and the body of the
688                 // paragraph too.
689                 // But we don't want to do this auto hfill if the par
690                 // is empty.
691                 if (!par.empty())
692                         ++nlh;
693
694                 if (nlh && !par.getLabelWidthString().empty())
695                         row.label_hfill = labelFill(row) / double(nlh);
696         }
697
698         // are there any hfills in the row?
699         ParagraphMetrics const & pm = par_metrics_[row.pit()];
700         int nh = numberOfHfills(row, pm, par.beginOfBody());
701         int hfill = 0;
702         int hfill_rem = 0;
703
704         // We don't have to look at the alignment if the row is already
705         // larger then the permitted width as then we force the
706         // LEFT_ALIGN'edness!
707         if (int(row.width()) >= max_width_)
708                 return;
709
710         if (nh == 0) {
711                 // Common case : there is no hfill, and the alignment will be
712                 // meaningful
713                 switch (getAlign(par, row)) {
714                 case LYX_ALIGN_BLOCK:
715                         // Expand expanding characters by a total of w
716                         if (!row.setExtraWidth(w) && row.isRTL()) {
717                                 // Justification failed and the text is RTL: align to the right
718                                 row.left_margin += w;
719                                 row.dim().wid += w;
720                         }
721                         break;
722                 case LYX_ALIGN_LEFT:
723                         // a displayed inset that is flushed
724                         if (Inset const * inset = par.getInset(row.pos())) {
725                                 row.left_margin += inset->indent(*bv_);
726                                 row.dim().wid += inset->indent(*bv_);
727                         }
728                         break;
729                 case LYX_ALIGN_RIGHT:
730                         if (Inset const * inset = par.getInset(row.pos())) {
731                                 int const new_w = max(w - inset->indent(*bv_), 0);
732                                 row.left_margin += new_w;
733                                 row.dim().wid += new_w;
734                         } else {
735                                 row.left_margin += w;
736                                 row.dim().wid += w;
737                         }
738                         break;
739                 case LYX_ALIGN_CENTER:
740                         row.dim().wid += w / 2;
741                         row.left_margin += w / 2;
742                         break;
743                 case LYX_ALIGN_NONE:
744                 case LYX_ALIGN_LAYOUT:
745                 case LYX_ALIGN_SPECIAL:
746                 case LYX_ALIGN_DECIMAL:
747                         break;
748                 }
749                 return;
750         }
751
752         // Case nh > 0. There are hfill separators.
753         hfill = w / nh;
754         hfill_rem = w % nh;
755         row.dim().wid += w;
756         // Set size of hfill insets
757         pos_type const endpos = row.endpos();
758         pos_type body_pos = par.beginOfBody();
759         if (body_pos > 0
760             && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
761                 body_pos = 0;
762
763         CoordCache::Insets & insetCache = bv_->coordCache().insets();
764         for (Row::Element & e : row) {
765                 if (row.label_hfill && e.endpos == body_pos
766                     && e.type == Row::SPACE)
767                         e.dim.wid -= int(row.label_hfill * (nlh - 1));
768                 if (e.inset && pm.hfillExpansion(row, e.pos)) {
769                         if (e.pos >= body_pos) {
770                                 e.dim.wid += hfill;
771                                 --nh;
772                                 if (nh == 0)
773                                         e.dim.wid += hfill_rem;
774                         } else
775                                 e.dim.wid += int(row.label_hfill);
776                         // Cache the inset dimension.
777                         insetCache.add(e.inset, e.dim);
778                 }
779         }
780 }
781
782
783 int TextMetrics::labelFill(Row const & row) const
784 {
785         Paragraph const & par = text_->getPar(row.pit());
786         LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
787
788         int w = 0;
789         // iterate over elements before main body (except the last one,
790         // which is extra space).
791         for (Row::Element const & e : row) {
792                 if (e.endpos >= par.beginOfBody())
793                         break;
794                 w += e.dim.wid;
795         }
796
797         docstring const & label = par.params().labelWidthString();
798         if (label.empty())
799                 return 0;
800
801         FontMetrics const & fm
802                 = theFontMetrics(text_->labelFont(par));
803
804         return max(0, fm.width(label) - w);
805 }
806
807
808 int TextMetrics::labelEnd(pit_type const pit) const
809 {
810         // labelEnd is only needed if the layout fills a flushleft label.
811         if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
812                 return 0;
813         // return the beginning of the body
814         return leftMargin(pit);
815 }
816
817 namespace {
818
819 /**
820  * Calling Text::getFont is slow. While rebreaking we scan a
821  * paragraph from left to right calling getFont for every char.  This
822  * simple class address this problem by hidding an optimization trick
823  * (not mine btw -AB): the font is reused in the whole font span.  The
824  * class handles transparently the "hidden" (not part of the fontlist)
825  * label font (as getFont does).
826  **/
827 class FontIterator
828 {
829 public:
830         ///
831         FontIterator(TextMetrics const & tm,
832                 Paragraph const & par, pit_type pit, pos_type pos)
833                 : tm_(tm), par_(par), pit_(pit), pos_(pos),
834                 font_(tm.displayFont(pit, pos)),
835                 endspan_(par.fontSpan(pos).last),
836                 bodypos_(par.beginOfBody())
837         {}
838
839         ///
840         Font const & operator*() const { return font_; }
841
842         ///
843         FontIterator & operator++()
844         {
845                 ++pos_;
846                 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
847                         font_ = tm_.displayFont(pit_, pos_);
848                         endspan_ = par_.fontSpan(pos_).last;
849                 }
850                 return *this;
851         }
852
853         ///
854         Font * operator->() { return &font_; }
855
856 private:
857         ///
858         TextMetrics const & tm_;
859         ///
860         Paragraph const & par_;
861         ///
862         pit_type pit_;
863         ///
864         pos_type pos_;
865         ///
866         Font font_;
867         ///
868         pos_type endspan_;
869         ///
870         pos_type bodypos_;
871 };
872
873 } // namespace
874
875 /** This is the function where the hard work is done. The code here is
876  * very sensitive to small changes :) Note that part of the
877  * intelligence is also in Row::shortenIfNeeded.
878  */
879 bool TextMetrics::breakRow(Row & row, int const right_margin) const
880 {
881         LATTEST(row.empty());
882         Paragraph const & par = text_->getPar(row.pit());
883         pos_type const end = par.size();
884         pos_type const pos = row.pos();
885         pos_type const body_pos = par.beginOfBody();
886         bool const is_rtl = text_->isRTL(row.pit());
887         bool need_new_row = false;
888
889         row.left_margin = leftMargin(row.pit(), pos);
890         row.right_margin = right_margin;
891         if (is_rtl)
892                 swap(row.left_margin, row.right_margin);
893         // Remember that the row width takes into account the left_margin
894         // but not the right_margin.
895         row.dim().wid = row.left_margin;
896         // the width available for the row.
897         int const width = max_width_ - row.right_margin;
898
899         // check for possible inline completion
900         DocIterator const & ic_it = bv_->inlineCompletionPos();
901         pos_type ic_pos = -1;
902         if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == row.pit())
903                 ic_pos = ic_it.pos();
904
905         // Now we iterate through until we reach the right margin
906         // or the end of the par, then build a representation of the row.
907         pos_type i = pos;
908         FontIterator fi = FontIterator(*this, par, row.pit(), pos);
909         while (i < end && (i == pos || row.width() <= width)) {
910                 char_type c = par.getChar(i);
911                 // The most special cases are handled first.
912                 if (par.isInset(i)) {
913                         Inset const * ins = par.getInset(i);
914                         Dimension dim = bv_->coordCache().insets().dim(ins);
915                         row.add(i, ins, dim, *fi, par.lookupChange(i));
916                 } else if (c == ' ' && i + 1 == body_pos) {
917                         // There is a space at i, but it should not be
918                         // added as a separator, because it is just
919                         // before body_pos. Instead, insert some spacing to
920                         // align text
921                         FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
922                         // this is needed to make sure that the row width is correct
923                         row.finalizeLast();
924                         int const add = max(fm.width(par.layout().labelsep),
925                                             labelEnd(row.pit()) - row.width());
926                         row.addSpace(i, add, *fi, par.lookupChange(i));
927                 } else if (c == '\t')
928                         row.addSpace(i, theFontMetrics(*fi).width(from_ascii("    ")),
929                                      *fi, par.lookupChange(i));
930                 else if (c == 0x2028 || c == 0x2029) {
931                         /**
932                          * U+2028 LINE SEPARATOR
933                          * U+2029 PARAGRAPH SEPARATOR
934
935                          * These are special unicode characters that break
936                          * lines/pragraphs. Not handling them lead to trouble wrt
937                          * Qt QTextLayout formatting. We add a visible character
938                          * on screen so that the user can see that something is
939                          * happening.
940                         */
941                         row.finalizeLast();
942                         // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
943                         // ¶ U+00B6 PILCROW SIGN
944                         char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
945                         row.add(i, screen_char, *fi, par.lookupChange(i));
946                 } else
947                         row.add(i, c, *fi, par.lookupChange(i));
948
949                 // add inline completion width
950                 // draw logically behind the previous character
951                 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
952                         docstring const comp = bv_->inlineCompletion();
953                         size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
954                         Font f = *fi;
955
956                         if (uniqueTo > 0) {
957                                 f.fontInfo().setColor(Color_inlinecompletion);
958                                 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
959                         }
960                         f.fontInfo().setColor(Color_nonunique_inlinecompletion);
961                         row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
962                 }
963
964                 // Handle some situations that abruptly terminate the row
965                 // - Before an inset with BreakBefore
966                 // - After an inset with BreakAfter
967                 Inset const * prevInset = !row.empty() ? row.back().inset : 0;
968                 Inset const * nextInset = (i + 1 < end) ? par.getInset(i + 1) : 0;
969                 if ((nextInset && nextInset->rowFlags() & Inset::BreakBefore)
970                     || (prevInset && prevInset->rowFlags() & Inset::BreakAfter)) {
971                         row.flushed(true);
972                         // Force a row creation after this one if it is ended by
973                         // an inset that either
974                         // - has row flag RowAfter that enforces that;
975                         // - or (1) did force the row breaking, (2) is at end of
976                         //   paragraph and (3) the said paragraph has an end label.
977                         need_new_row = prevInset &&
978                                 (prevInset->rowFlags() & Inset::RowAfter
979                                  || (prevInset->rowFlags() & Inset::BreakAfter && i + 1 == end
980                                      && text_->getEndLabel(row.pit()) != END_LABEL_NO_LABEL));
981                         ++i;
982                         break;
983                 }
984
985                 ++i;
986                 ++fi;
987         }
988         row.finalizeLast();
989         row.endpos(i);
990
991         // End of paragraph marker. The logic here is almost the
992         // same as in redoParagraph, remember keep them in sync.
993         ParagraphList const & pars = text_->paragraphs();
994         Change const & change = par.lookupChange(i);
995         if ((lyxrc.paragraph_markers || change.changed())
996             && !need_new_row
997             && i == end && size_type(row.pit() + 1) < pars.size()) {
998                 // add a virtual element for the end-of-paragraph
999                 // marker; it is shown on screen, but does not exist
1000                 // in the paragraph.
1001                 Font f(text_->layoutFont(row.pit()));
1002                 f.fontInfo().setColor(Color_paragraphmarker);
1003                 BufferParams const & bparams
1004                         = text_->inset().buffer().params();
1005                 f.setLanguage(par.getParLanguage(bparams));
1006                 // ¶ U+00B6 PILCROW SIGN
1007                 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, change);
1008         }
1009
1010         // Is there a end-of-paragaph change?
1011         if (i == end && par.lookupChange(end).changed() && !need_new_row)
1012                 row.needsChangeBar(true);
1013
1014         // if the row is too large, try to cut at last separator. In case
1015         // of success, reset indication that the row was broken abruptly.
1016         int const next_width = max_width_ - leftMargin(row.pit(), row.endpos())
1017                 - rightMargin(row.pit());
1018
1019         if (row.shortenIfNeeded(body_pos, width, next_width))
1020                 row.flushed(false);
1021         row.right_boundary(!row.empty() && row.endpos() < end
1022                            && row.back().endpos == row.endpos());
1023         // Last row in paragraph is flushed
1024         if (row.endpos() == end)
1025                 row.flushed(true);
1026
1027         // make sure that the RTL elements are in reverse ordering
1028         row.reverseRTL(is_rtl);
1029         //LYXERR0("breakrow: row is " << row);
1030
1031         return need_new_row;
1032 }
1033
1034 int TextMetrics::parTopSpacing(pit_type const pit) const
1035 {
1036         Paragraph const & par = text_->getPar(pit);
1037         Layout const & layout = par.layout();
1038
1039         int asc = 0;
1040         ParagraphList const & pars = text_->paragraphs();
1041         double const dh = defaultRowHeight();
1042
1043         BufferParams const & bparams = bv_->buffer().params();
1044         Inset const & inset = text_->inset();
1045         // some parskips VERY EASY IMPLEMENTATION
1046         if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1047                 && !inset.getLayout().parbreakIsNewline()
1048                 && !par.layout().parbreak_is_newline
1049                 && pit > 0
1050                 && ((layout.isParagraph() && par.getDepth() == 0)
1051                     || (pars[pit - 1].layout().isParagraph()
1052                         && pars[pit - 1].getDepth() == 0))) {
1053                 asc += bparams.getDefSkip().inPixels(*bv_);
1054         }
1055
1056         if (par.params().startOfAppendix())
1057                 asc += int(3 * dh);
1058
1059         // special code for the top label
1060         if (layout.labelIsAbove()
1061             && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1062             && !par.labelString().empty()) {
1063                 FontInfo labelfont = text_->labelFont(par);
1064                 FontMetrics const & lfm = theFontMetrics(labelfont);
1065                 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1066                                            * text_->spacing(par)
1067                            + (layout.topsep + layout.labelbottomsep) * dh);
1068         }
1069
1070         // Add the layout spaces, for example before and after
1071         // a section, or between the items of a itemize or enumerate
1072         // environment.
1073
1074         pit_type prev = text_->depthHook(pit, par.getDepth());
1075         Paragraph const & prevpar = pars[prev];
1076         double layoutasc = 0;
1077         if (prev != pit
1078             && prevpar.layout() == layout
1079             && prevpar.getDepth() == par.getDepth()
1080             && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1081                 layoutasc = layout.itemsep * dh;
1082         } else if (pit != 0 && layout.topsep > 0)
1083                 layoutasc = layout.topsep * dh;
1084
1085         asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1086
1087         prev = text_->outerHook(pit);
1088         if (prev != pit_type(pars.size())) {
1089                 asc += int(pars[prev].layout().parsep * dh);
1090         } else if (pit != 0) {
1091                 Paragraph const & prevpar2 = pars[pit - 1];
1092                 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1093                         asc += int(layout.parsep * dh);
1094         }
1095
1096         return asc;
1097 }
1098
1099
1100 int TextMetrics::parBottomSpacing(pit_type const pit) const
1101 {
1102         double layoutdesc = 0;
1103         ParagraphList const & pars = text_->paragraphs();
1104         double const dh = defaultRowHeight();
1105
1106         // add the layout spaces, for example before and after
1107         // a section, or between the items of a itemize or enumerate
1108         // environment
1109         pit_type nextpit = pit + 1;
1110         if (nextpit != pit_type(pars.size())) {
1111                 pit_type cpit = pit;
1112
1113                 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1114                         double usual = pars[cpit].layout().bottomsep * dh;
1115                         double unusual = 0;
1116                         cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1117                         if (pars[cpit].layout() != pars[nextpit].layout()
1118                                 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1119                                 unusual = pars[cpit].layout().bottomsep * dh;
1120                         layoutdesc = max(unusual, usual);
1121                 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1122                         if (pars[cpit].layout() != pars[nextpit].layout()
1123                                 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1124                                 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1125                 }
1126         }
1127
1128         return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1129 }
1130
1131
1132 void TextMetrics::setRowHeight(Row & row) const
1133 {
1134         Paragraph const & par = text_->getPar(row.pit());
1135         Layout const & layout = par.layout();
1136         double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1137
1138         // Initial value for ascent (useful if row is empty).
1139         Font const font = displayFont(row.pit(), row.pos());
1140         FontMetrics const & fm = theFontMetrics(font);
1141         int maxasc = int(fm.maxAscent() * spacing_val);
1142         int maxdes = int(fm.maxDescent() * spacing_val);
1143
1144         // Take label string into account (useful if labelfont is large)
1145         if (row.pos() == 0 && layout.labelIsInline()) {
1146                 FontInfo const labelfont = text_->labelFont(par);
1147                 FontMetrics const & lfm = theFontMetrics(labelfont);
1148                 maxasc = max(maxasc, int(lfm.maxAscent() * spacing_val));
1149                 maxdes = max(maxdes, int(lfm.maxDescent() * spacing_val));
1150         }
1151
1152         // Find the ascent/descent of the row contents
1153         for (Row::Element const & e : row) {
1154                 if (e.inset) {
1155                         maxasc = max(maxasc, e.dim.ascent());
1156                         maxdes = max(maxdes, e.dim.descent());
1157                 } else {
1158                         FontMetrics const & fm2 = theFontMetrics(e.font);
1159                         maxasc = max(maxasc, int(fm2.maxAscent() * spacing_val));
1160                         maxdes = max(maxdes, int(fm2.maxDescent() * spacing_val));
1161                 }
1162         }
1163
1164         // This is nicer with box insets
1165         ++maxasc;
1166         ++maxdes;
1167
1168         row.dim().asc = maxasc;
1169         row.dim().des = maxdes;
1170
1171         // This is useful for selections
1172         row.contents_dim() = row.dim();
1173 }
1174
1175
1176 // x is an absolute screen coord
1177 // returns the column near the specified x-coordinate of the row
1178 // x is set to the real beginning of this column
1179 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1180                                   bool & boundary) const
1181 {
1182         //LYXERR0("getPosNearX(" << x << ") row=" << row);
1183         /// For the main Text, it is possible that this pit is not
1184         /// yet in the CoordCache when moving cursor up.
1185         /// x Paragraph coordinate is always 0 for main text anyway.
1186         int const xo = origin_.x_;
1187         x -= xo;
1188
1189         // Adapt to cursor row scroll offset if applicable.
1190         int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1191         x += offset;
1192
1193         pos_type pos = row.pos();
1194         boundary = false;
1195         if (row.empty())
1196                 x = row.left_margin;
1197         else if (x <= row.left_margin) {
1198                 pos = row.front().left_pos();
1199                 x = row.left_margin;
1200         } else if (x >= row.width()) {
1201                 pos = row.back().right_pos();
1202                 x = row.width();
1203         } else {
1204                 double w = row.left_margin;
1205                 Row::const_iterator cit = row.begin();
1206                 Row::const_iterator cend = row.end();
1207                 for ( ; cit != cend; ++cit) {
1208                         if (w <= x &&  w + cit->full_width() > x) {
1209                                 int x_offset = int(x - w);
1210                                 pos = cit->x2pos(x_offset);
1211                                 x = int(x_offset + w);
1212                                 break;
1213                         }
1214                         w += cit->full_width();
1215                 }
1216                 if (cit == row.end()) {
1217                         pos = row.back().right_pos();
1218                         x = row.width();
1219                 }
1220                 /** This tests for the case where the cursor is placed
1221                  * just before a font direction change. See comment on
1222                  * the boundary_ member in DocIterator.h to understand
1223                  * how boundary helps here.
1224                  */
1225                 else if (pos == cit->endpos
1226                          && ((!cit->isRTL() && cit + 1 != row.end()
1227                               && (cit + 1)->isRTL())
1228                              || (cit->isRTL() && cit != row.begin()
1229                                  && !(cit - 1)->isRTL())))
1230                         boundary = true;
1231         }
1232
1233         /** This tests for the case where the cursor is set at the end
1234          * of a row which has been broken due something else than a
1235          * separator (a display inset or a forced breaking of the
1236          * row). We know that there is a separator when the end of the
1237          * row is larger than the end of its last element.
1238          */
1239         if (!row.empty() && pos == row.back().endpos
1240             && row.back().endpos == row.endpos()) {
1241                 Inset const * inset = row.back().inset;
1242                 if (inset && (inset->lyxCode() == NEWLINE_CODE
1243                               || inset->lyxCode() == SEPARATOR_CODE))
1244                         pos = row.back().pos;
1245                 else
1246                         boundary = row.right_boundary();
1247         }
1248
1249         x += xo - offset;
1250         //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1251
1252         return pos;
1253 }
1254
1255
1256 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1257 {
1258         // We play safe and use parMetrics(pit) to make sure the
1259         // ParagraphMetrics will be redone and OK to use if needed.
1260         // Otherwise we would use an empty ParagraphMetrics in
1261         // upDownInText() while in selection mode.
1262         ParagraphMetrics const & pm = parMetrics(pit);
1263
1264         LBUFERR(row < int(pm.rows().size()));
1265         bool bound = false;
1266         Row const & r = pm.rows()[row];
1267         return getPosNearX(r, x, bound);
1268 }
1269
1270
1271 // y is screen coordinate
1272 pit_type TextMetrics::getPitNearY(int y)
1273 {
1274         LASSERT(!text_->paragraphs().empty(), return -1);
1275         LASSERT(!par_metrics_.empty(), return -1);
1276         LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1277
1278         // look for highest numbered paragraph with y coordinate less than given y
1279         pit_type pit = -1;
1280         int yy = -1;
1281         ParMetricsCache::const_iterator it = par_metrics_.begin();
1282         ParMetricsCache::const_iterator et = par_metrics_.end();
1283         ParMetricsCache::const_iterator last = et;
1284         --last;
1285
1286         ParagraphMetrics const & pm = it->second;
1287
1288         if (y < it->second.position() - int(pm.ascent())) {
1289                 // We are looking for a position that is before the first paragraph in
1290                 // the cache (which is in priciple off-screen, that is before the
1291                 // visible part.
1292                 if (it->first == 0)
1293                         // We are already at the first paragraph in the inset.
1294                         return 0;
1295                 // OK, this is the paragraph we are looking for.
1296                 pit = it->first - 1;
1297                 newParMetricsUp();
1298                 return pit;
1299         }
1300
1301         ParagraphMetrics const & pm_last = par_metrics_[last->first];
1302
1303         if (y >= last->second.position() + int(pm_last.descent())) {
1304                 // We are looking for a position that is after the last paragraph in
1305                 // the cache (which is in priciple off-screen), that is before the
1306                 // visible part.
1307                 pit = last->first + 1;
1308                 if (pit == int(text_->paragraphs().size()))
1309                         //  We are already at the last paragraph in the inset.
1310                         return last->first;
1311                 // OK, this is the paragraph we are looking for.
1312                 newParMetricsDown();
1313                 return pit;
1314         }
1315
1316         for (; it != et; ++it) {
1317                 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1318                         << " y: " << it->second.position());
1319
1320                 ParagraphMetrics const & pm2 = par_metrics_[it->first];
1321
1322                 if (it->first >= pit && int(it->second.position()) - int(pm2.ascent()) <= y) {
1323                         pit = it->first;
1324                         yy = it->second.position();
1325                 }
1326         }
1327
1328         LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1329
1330         return pit;
1331 }
1332
1333
1334 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1335         bool assert_in_view, bool up)
1336 {
1337         ParagraphMetrics const & pm = par_metrics_[pit];
1338
1339         int yy = pm.position() - pm.ascent();
1340         LBUFERR(!pm.rows().empty());
1341         RowList::const_iterator rit = pm.rows().begin();
1342         RowList::const_iterator rlast = pm.rows().end();
1343         --rlast;
1344         for (; rit != rlast; yy += rit->height(), ++rit)
1345                 if (yy + rit->height() > y)
1346                         break;
1347
1348         if (assert_in_view) {
1349                 if (!up && yy + rit->height() > y) {
1350                         if (rit != pm.rows().begin()) {
1351                                 y = yy;
1352                                 --rit;
1353                         } else if (pit != 0) {
1354                                 --pit;
1355                                 newParMetricsUp();
1356                                 ParagraphMetrics const & pm2 = par_metrics_[pit];
1357                                 rit = pm2.rows().end();
1358                                 --rit;
1359                                 y = yy;
1360                         }
1361                 } else if (up && yy != y) {
1362                         if (rit != rlast) {
1363                                 y = yy + rit->height();
1364                                 ++rit;
1365                         } else if (pit < int(text_->paragraphs().size()) - 1) {
1366                                 ++pit;
1367                                 newParMetricsDown();
1368                                 ParagraphMetrics const & pm2 = par_metrics_[pit];
1369                                 rit = pm2.rows().begin();
1370                                 y = pm2.position();
1371                         }
1372                 }
1373         }
1374         return *rit;
1375 }
1376
1377
1378 // x,y are absolute screen coordinates
1379 // sets cursor recursively descending into nested editable insets
1380 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1381         bool assert_in_view, bool up)
1382 {
1383         if (lyxerr.debugging(Debug::WORKAREA)) {
1384                 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1385                 cur.bv().coordCache().dump();
1386         }
1387         pit_type pit = getPitNearY(y);
1388         LASSERT(pit != -1, return 0);
1389         Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1390         cur.pit() = pit;
1391
1392         // Do we cover an inset?
1393         InsetList::Element * e = checkInsetHit(pit, x, y);
1394
1395         if (!e) {
1396                 // No inset, set position in the text
1397                 bool bound = false; // is modified by getPosNearX
1398                 cur.pos() = getPosNearX(row, x, bound);
1399                 cur.boundary(bound);
1400                 cur.setCurrentFont();
1401                 cur.setTargetX(x);
1402                 return 0;
1403         }
1404
1405         Inset * inset = e->inset;
1406         //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1407
1408         // Set position in front of inset
1409         cur.pos() = e->pos;
1410         cur.boundary(false);
1411         cur.setTargetX(x);
1412
1413         // Try to descend recursively inside the inset.
1414         Inset * edited = inset->editXY(cur, x, y);
1415         // FIXME: it is not clear that the test on position is needed
1416         // Remove it if/when semantics of editXY is clarified
1417         if (cur.text() == text_ && cur.pos() == e->pos) {
1418                 // non-editable inset, set cursor after the inset if x is
1419                 // nearer to that position (bug 9628)
1420                 bool bound = false; // is modified by getPosNearX
1421                 cur.pos() = getPosNearX(row, x, bound);
1422                 cur.boundary(bound);
1423                 cur.setCurrentFont();
1424                 cur.setTargetX(x);
1425         }
1426
1427         if (cur.top().text() == text_)
1428                 cur.setCurrentFont();
1429         return edited;
1430 }
1431
1432
1433 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1434 {
1435         LASSERT(text_ == cur.text(), return);
1436         pit_type const pit = getPitNearY(y);
1437         LASSERT(pit != -1, return);
1438
1439         ParagraphMetrics const & pm = par_metrics_[pit];
1440
1441         int yy = pm.position() - pm.rows().front().ascent();
1442         LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1443                 " pit: " << pit << " yy: " << yy);
1444
1445         int r = 0;
1446         LBUFERR(pm.rows().size());
1447         for (; r < int(pm.rows().size()) - 1; ++r) {
1448                 Row const & row = pm.rows()[r];
1449                 if (int(yy + row.height()) > y)
1450                         break;
1451                 yy += row.height();
1452         }
1453
1454         Row const & row = pm.rows()[r];
1455
1456         LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1457
1458         bool bound = false;
1459         int xx = x;
1460         pos_type const pos = getPosNearX(row, xx, bound);
1461
1462         LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1463
1464         text_->setCursor(cur, pit, pos, true, bound);
1465         // remember new position.
1466         cur.setTargetX();
1467 }
1468
1469
1470 //takes screen x,y coordinates
1471 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1472 {
1473         Paragraph const & par = text_->paragraphs()[pit];
1474         CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1475
1476         LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << "  pit: " << pit);
1477
1478         for (InsetList::Element const & e : par.insetList()) {
1479                 LYXERR(Debug::DEBUG, "examining inset " << e.inset);
1480
1481                 if (insetCache.covers(e.inset, x, y)) {
1482                         LYXERR(Debug::DEBUG, "Hit inset: " << e.inset);
1483                         return const_cast<InsetList::Element *>(&e);
1484                 }
1485         }
1486
1487         LYXERR(Debug::DEBUG, "No inset hit. ");
1488         return nullptr;
1489 }
1490
1491
1492 //takes screen x,y coordinates
1493 Inset * TextMetrics::checkInsetHit(int x, int y)
1494 {
1495         pit_type const pit = getPitNearY(y);
1496         LASSERT(pit != -1, return 0);
1497         InsetList::Element * e = checkInsetHit(pit, x, y);
1498
1499         if (!e)
1500                 return 0;
1501
1502         return e->inset;
1503 }
1504
1505
1506 int TextMetrics::cursorX(CursorSlice const & sl,
1507                 bool boundary) const
1508 {
1509         LASSERT(sl.text() == text_, return 0);
1510
1511         ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1512         if (pm.rows().empty())
1513                 return 0;
1514         Row const & row = pm.getRow(sl.pos(), boundary);
1515         pos_type const pos = sl.pos();
1516
1517         double x = 0;
1518         row.findElement(pos, boundary, x);
1519         return int(x);
1520
1521 }
1522
1523
1524 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1525 {
1526         //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1527         ParagraphMetrics const & pm = parMetrics(sl.pit());
1528         if (pm.rows().empty())
1529                 return 0;
1530
1531         int h = 0;
1532         h -= parMetrics(0).rows()[0].ascent();
1533         for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1534                 h += parMetrics(pit).height();
1535         }
1536         int pos = sl.pos();
1537         if (pos && boundary)
1538                 --pos;
1539         size_t const rend = pm.pos2row(pos);
1540         for (size_t rit = 0; rit != rend; ++rit)
1541                 h += pm.rows()[rit].height();
1542         h += pm.rows()[rend].ascent();
1543         return h;
1544 }
1545
1546
1547 // the cursor set functions have a special mechanism. When they
1548 // realize you left an empty paragraph, they will delete it.
1549
1550 bool TextMetrics::cursorHome(Cursor & cur)
1551 {
1552         LASSERT(text_ == cur.text(), return false);
1553         ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1554         Row const & row = pm.getRow(cur.pos(),cur.boundary());
1555         return text_->setCursor(cur, cur.pit(), row.pos());
1556 }
1557
1558
1559 bool TextMetrics::cursorEnd(Cursor & cur)
1560 {
1561         LASSERT(text_ == cur.text(), return false);
1562         // if not on the last row of the par, put the cursor before
1563         // the final space exept if I have a spanning inset or one string
1564         // is so long that we force a break.
1565         pos_type end = cur.textRow().endpos();
1566         if (end == 0)
1567                 // empty text, end-1 is no valid position
1568                 return false;
1569         bool boundary = false;
1570         if (end != cur.lastpos()) {
1571                 if (!cur.paragraph().isLineSeparator(end-1)
1572                     && !cur.paragraph().isNewline(end-1)
1573                     && !cur.paragraph().isEnvSeparator(end-1))
1574                         boundary = true;
1575                 else
1576                         --end;
1577         } else if (cur.paragraph().isEnvSeparator(end-1))
1578                 --end;
1579         return text_->setCursor(cur, cur.pit(), end, true, boundary);
1580 }
1581
1582
1583 void TextMetrics::deleteLineForward(Cursor & cur)
1584 {
1585         LASSERT(text_ == cur.text(), return);
1586         if (cur.lastpos() == 0) {
1587                 // Paragraph is empty, so we just go forward
1588                 text_->cursorForward(cur);
1589         } else {
1590                 cur.resetAnchor();
1591                 cur.selection(true); // to avoid deletion
1592                 cursorEnd(cur);
1593                 cur.setSelection();
1594                 // What is this test for ??? (JMarc)
1595                 if (!cur.selection())
1596                         text_->deleteWordForward(cur);
1597                 else
1598                         cap::cutSelection(cur, false);
1599                 cur.checkBufferStructure();
1600         }
1601 }
1602
1603
1604 int TextMetrics::leftMargin(pit_type pit) const
1605 {
1606         // FIXME: what is the semantics? It depends on whether the
1607         // paragraph is empty!
1608         return leftMargin(pit, text_->paragraphs()[pit].size());
1609 }
1610
1611
1612 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1613 {
1614         ParagraphList const & pars = text_->paragraphs();
1615
1616         LASSERT(pit >= 0, return 0);
1617         LASSERT(pit < int(pars.size()), return 0);
1618         Paragraph const & par = pars[pit];
1619         LASSERT(pos >= 0, return 0);
1620         // We do not really care whether pos > par.size(), since we do not
1621         // access the data. It can be actually useful, when querying the
1622         // margin without indentation (see leftMargin(pit_type).
1623
1624         Buffer const & buffer = bv_->buffer();
1625         //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1626         DocumentClass const & tclass = buffer.params().documentClass();
1627         Layout const & layout = par.layout();
1628         FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1629
1630         docstring parindent = layout.parindent;
1631
1632         int l_margin = 0;
1633
1634         if (text_->isMainText()) {
1635                 l_margin += bv_->leftMargin();
1636                 l_margin += bfm.signedWidth(tclass.leftmargin());
1637         }
1638
1639         int depth = par.getDepth();
1640         if (depth != 0) {
1641                 // find the next level paragraph
1642                 pit_type newpar = text_->outerHook(pit);
1643                 if (newpar != pit_type(pars.size())) {
1644                         if (pars[newpar].layout().isEnvironment()) {
1645                                 int nestmargin = depth * nestMargin();
1646                                 if (text_->isMainText())
1647                                         nestmargin += changebarMargin();
1648                                 l_margin = max(leftMargin(newpar), nestmargin);
1649                                 // Remove the parindent that has been added
1650                                 // if the paragraph was empty.
1651                                 if (pars[newpar].empty() &&
1652                                     buffer.params().paragraph_separation ==
1653                                     BufferParams::ParagraphIndentSeparation) {
1654                                         docstring pi = pars[newpar].layout().parindent;
1655                                         l_margin -= bfm.signedWidth(pi);
1656                                 }
1657                         }
1658                         if (tclass.isDefaultLayout(par.layout())
1659                             || tclass.isPlainLayout(par.layout())) {
1660                                 if (pars[newpar].params().noindent())
1661                                         parindent.erase();
1662                                 else
1663                                         parindent = pars[newpar].layout().parindent;
1664                         }
1665                 }
1666         }
1667
1668         // This happens after sections or environments in standard classes.
1669         // We have to check the previous layout at same depth.
1670         if (buffer.params().paragraph_separation ==
1671                         BufferParams::ParagraphSkipSeparation)
1672                 parindent.erase();
1673         else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1674                 pit_type prev = text_->depthHook(pit, par.getDepth());
1675                 if (par.layout() == pars[prev].layout()) {
1676                         if (prev != pit - 1
1677                             && pars[pit - 1].layout().nextnoindent)
1678                                 parindent.erase();
1679                 } else if (pars[prev].layout().nextnoindent)
1680                         parindent.erase();
1681         }
1682
1683         FontInfo const labelfont = text_->labelFont(par);
1684         FontMetrics const & lfm = theFontMetrics(labelfont);
1685
1686         switch (layout.margintype) {
1687         case MARGIN_DYNAMIC:
1688                 if (!layout.leftmargin.empty()) {
1689                         l_margin += bfm.signedWidth(layout.leftmargin);
1690                 }
1691                 if (!par.labelString().empty()) {
1692                         l_margin += lfm.signedWidth(layout.labelindent);
1693                         l_margin += lfm.width(par.labelString());
1694                         l_margin += lfm.width(layout.labelsep);
1695                 }
1696                 break;
1697
1698         case MARGIN_MANUAL: {
1699                 l_margin += lfm.signedWidth(layout.labelindent);
1700                 // The width of an empty par, even with manual label, should be 0
1701                 if (!par.empty() && pos >= par.beginOfBody()) {
1702                         if (!par.getLabelWidthString().empty()) {
1703                                 docstring labstr = par.getLabelWidthString();
1704                                 l_margin += lfm.width(labstr);
1705                                 l_margin += lfm.width(layout.labelsep);
1706                         }
1707                 }
1708                 break;
1709         }
1710
1711         case MARGIN_STATIC: {
1712                 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1713                              / (par.getDepth() + 4);
1714                 break;
1715         }
1716
1717         case MARGIN_FIRST_DYNAMIC:
1718                 if (layout.labeltype == LABEL_MANUAL) {
1719                         // if we are at position 0, we are never in the body
1720                         if (pos > 0 && pos >= par.beginOfBody())
1721                                 l_margin += lfm.signedWidth(layout.leftmargin);
1722                         else
1723                                 l_margin += lfm.signedWidth(layout.labelindent);
1724                 } else if (pos != 0
1725                            // Special case to fix problems with
1726                            // theorems (JMarc)
1727                            || (layout.labeltype == LABEL_STATIC
1728                                && layout.latextype == LATEX_ENVIRONMENT
1729                                && !text_->isFirstInSequence(pit))) {
1730                         l_margin += lfm.signedWidth(layout.leftmargin);
1731                 } else if (!layout.labelIsAbove()) {
1732                         l_margin += lfm.signedWidth(layout.labelindent);
1733                         l_margin += lfm.width(layout.labelsep);
1734                         l_margin += lfm.width(par.labelString());
1735                 }
1736                 break;
1737
1738         case MARGIN_RIGHT_ADDRESS_BOX:
1739                 // This is handled globally in redoParagraph().
1740                 break;
1741         }
1742
1743         if (!par.params().leftIndent().zero())
1744                 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1745
1746         LyXAlignment align = par.getAlign(bv_->buffer().params());
1747
1748         // set the correct parindent
1749         if (pos == 0
1750             && (layout.labeltype == LABEL_NO_LABEL
1751                 || layout.labeltype == LABEL_ABOVE
1752                 || layout.labeltype == LABEL_CENTERED
1753                 || (layout.labeltype == LABEL_STATIC
1754                     && layout.latextype == LATEX_ENVIRONMENT
1755                     && !text_->isFirstInSequence(pit)))
1756             && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1757             && !par.params().noindent()
1758             // in some insets, paragraphs are never indented
1759             && !text_->inset().neverIndent()
1760             // display style insets do not need indentation
1761             && !(!par.empty()
1762                  && par.isInset(0)
1763                  && par.getInset(0)->rowFlags() & Inset::Display)
1764             && (!(tclass.isDefaultLayout(par.layout())
1765                 || tclass.isPlainLayout(par.layout()))
1766                 || buffer.params().paragraph_separation
1767                                 == BufferParams::ParagraphIndentSeparation)) {
1768                 /* use the parindent of the layout when the default
1769                  * indentation is used otherwise use the indentation set in
1770                  * the document settings
1771                  */
1772                 if (buffer.params().getParIndent().empty())
1773                         l_margin += bfm.signedWidth(parindent);
1774                 else
1775                         l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1776         }
1777
1778         return l_margin;
1779 }
1780
1781
1782 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1783 {
1784         if (par_metrics_.empty())
1785                 return;
1786
1787         origin_.x_ = x;
1788         origin_.y_ = y;
1789
1790         y -= par_metrics_.begin()->second.ascent();
1791         for (auto & pm_pair : par_metrics_) {
1792                 pit_type const pit = pm_pair.first;
1793                 ParagraphMetrics & pm = pm_pair.second;
1794                 y += pm.ascent();
1795                 // Save the paragraph position in the cache.
1796                 pm.setPosition(y);
1797                 drawParagraph(pi, pit, x, y);
1798                 y += pm.descent();
1799         }
1800 }
1801
1802
1803 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1804 {
1805         ParagraphMetrics const & pm = par_metrics_[pit];
1806         if (pm.rows().empty())
1807                 return;
1808         size_t const nrows = pm.rows().size();
1809         // Remember left and right margin for drawing math numbers
1810         Changer changeleft = changeVar(pi.leftx, x + leftMargin(pit));
1811         Changer changeright = changeVar(pi.rightx, x + width() - rightMargin(pit));
1812
1813         // Use fast lane in nodraw stage.
1814         if (pi.pain.isNull()) {
1815                 for (size_t i = 0; i != nrows; ++i) {
1816
1817                         Row const & row = pm.rows()[i];
1818                         // Adapt to cursor row scroll offset if applicable.
1819                         int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1820                         if (i)
1821                                 y += row.ascent();
1822
1823                         RowPainter rp(pi, *text_, row, row_x, y);
1824
1825                         rp.paintOnlyInsets();
1826                         y += row.descent();
1827                 }
1828                 return;
1829         }
1830
1831         int const ww = bv_->workHeight();
1832         Cursor const & cur = bv_->cursor();
1833         DocIterator sel_beg = cur.selectionBegin();
1834         DocIterator sel_end = cur.selectionEnd();
1835         bool selection = cur.selection()
1836                 // This is our text.
1837                 && cur.text() == text_
1838                 // if the anchor is outside, this is not our selection
1839                 && cur.normalAnchor().text() == text_
1840                 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1841
1842         // We store the begin and end pos of the selection relative to this par
1843         DocIterator sel_beg_par = cur.selectionBegin();
1844         DocIterator sel_end_par = cur.selectionEnd();
1845
1846         // We care only about visible selection.
1847         if (selection) {
1848                 if (pit != sel_beg.pit()) {
1849                         sel_beg_par.pit() = pit;
1850                         sel_beg_par.pos() = 0;
1851                 }
1852                 if (pit != sel_end.pit()) {
1853                         sel_end_par.pit() = pit;
1854                         sel_end_par.pos() = sel_end_par.lastpos();
1855                 }
1856         }
1857
1858         if (text_->isRTL(pit))
1859                 swap(pi.leftx, pi.rightx);
1860
1861         BookmarksSection::BookmarkPosList bpl =
1862                 theSession().bookmarks().bookmarksInPar(bv_->buffer().fileName(), pm.par().id());
1863
1864         for (size_t i = 0; i != nrows; ++i) {
1865
1866                 Row const & row = pm.rows()[i];
1867                 // Adapt to cursor row scroll offset if applicable.
1868                 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1869                 if (i)
1870                         y += row.ascent();
1871
1872                 // It is not needed to draw on screen if we are not inside.
1873                 bool const inside = (y + row.descent() >= 0
1874                         && y - row.ascent() < ww);
1875                 if (!inside) {
1876                         // Inset positions have already been set in nodraw stage.
1877                         y += row.descent();
1878                         continue;
1879                 }
1880
1881                 if (selection)
1882                         row.setSelectionAndMargins(sel_beg_par, sel_end_par);
1883                 else
1884                         row.clearSelectionAndMargins();
1885
1886                 // The row knows nothing about the paragraph, so we have to check
1887                 // whether this row is the first or last and update the margins.
1888                 if (row.selection()) {
1889                         if (row.sel_beg == 0)
1890                                 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
1891                         if (row.sel_end == sel_end_par.lastpos())
1892                                 row.change(row.end_margin_sel, sel_end.pit() > pit);
1893                 }
1894
1895                 // Take this opportunity to spellcheck the row contents.
1896                 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
1897                         text_->getPar(pit).spellCheck();
1898                 }
1899
1900                 RowPainter rp(pi, *text_, row, row_x, y);
1901
1902                 // Don't paint the row if a full repaint has not been requested
1903                 // and if it has not changed.
1904                 if (!pi.full_repaint && !row.changed()) {
1905                         // Paint only the insets if the text itself is
1906                         // unchanged.
1907                         rp.paintOnlyInsets();
1908                         row.changed(false);
1909                         y += row.descent();
1910                         continue;
1911                 }
1912
1913                 // Clear background of this row if paragraph background was not
1914                 // already cleared because of a full repaint.
1915                 if (!pi.full_repaint && row.changed()) {
1916                         LYXERR(Debug::PAINTING, "Clear rect@("
1917                                << max(row_x, 0) << ", " << y - row.ascent() << ")="
1918                                << width() << " x " << row.height());
1919                         pi.pain.fillRectangle(row_x, y - row.ascent(),
1920                                               width(), row.height(), pi.background_color);
1921                 }
1922
1923                 // Instrumentation for testing row cache (see also
1924                 // 12 lines lower):
1925                 if (lyxerr.debugging(Debug::PAINTING)
1926                     && (row.selection() || pi.full_repaint || row.changed())) {
1927                         string const foreword = text_->isMainText() ? "main text redraw "
1928                                 : "inset text redraw: ";
1929                         LYXERR0(foreword << "pit=" << pit << " row=" << i
1930                                 << (row.selection() ? " row_selection": "")
1931                                 << (pi.full_repaint ? " full_repaint" : "")
1932                                 << (row.changed() ? " row.changed" : ""));
1933                 }
1934
1935                 // Backup full_repaint status and force full repaint
1936                 // for inner insets as the Row has been cleared out.
1937                 bool tmp = pi.full_repaint;
1938                 pi.full_repaint = true;
1939
1940                 rp.paintSelection();
1941                 rp.paintAppendix();
1942                 rp.paintDepthBar();
1943                 if (row.needsChangeBar())
1944                         rp.paintChangeBar();
1945                 if (i == 0)
1946                         rp.paintFirst();
1947                 if (i == nrows - 1)
1948                         rp.paintLast();
1949                 rp.paintText();
1950                 rp.paintTooLargeMarks(row_x + row.left_x() < 0,
1951                                       row_x + row.right_x() > bv_->workWidth());
1952                 // indicate bookmarks presence in margin
1953                 for (auto const & bp_p : bpl)
1954                         if (bp_p.second >= row.pos() && bp_p.second < row.endpos())
1955                                 rp.paintBookmark(bp_p.first);
1956
1957                 y += row.descent();
1958
1959 #if 0
1960                 // This debug code shows on screen which rows are repainted.
1961                 // FIXME: since the updates related to caret blinking restrict
1962                 // the painter to a small rectangle, the numbers are not
1963                 // updated when this happens. Change the code in
1964                 // GuiWorkArea::Private::show/hideCaret if this is important.
1965                 static int count = 0;
1966                 ++count;
1967                 FontInfo fi(sane_font);
1968                 fi.setSize(TINY_SIZE);
1969                 fi.setColor(Color_red);
1970                 pi.pain.text(row_x, y, convert<docstring>(count), fi);
1971 #endif
1972
1973                 // Restore full_repaint status.
1974                 pi.full_repaint = tmp;
1975
1976                 row.changed(false);
1977         }
1978
1979         //LYXERR(Debug::PAINTING, ".");
1980 }
1981
1982
1983 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
1984         Dimension & dim) const
1985 {
1986         DocIterator from = cur.bv().cursor();
1987         DocIterator to = from;
1988         text_->getWord(from.top(), to.top(), PREVIOUS_WORD);
1989
1990         // The vertical dimension of the word
1991         Font const font = displayFont(cur.pit(), from.pos());
1992         FontMetrics const & fm = theFontMetrics(font);
1993         // the +1's below are related to the extra pixels added in setRowHeight
1994         dim.asc = fm.maxAscent() + 1;
1995         dim.des = fm.maxDescent() + 1;
1996
1997         // get position on screen of the word start and end
1998         //FIXME: Is it necessary to explicitly set this to false?
1999         from.boundary(false);
2000         Point lxy = cur.bv().getPos(from);
2001         Point rxy = cur.bv().getPos(to);
2002         dim.wid = abs(rxy.x_ - lxy.x_);
2003
2004         // calculate position of word
2005         y = lxy.y_;
2006         x = min(rxy.x_, lxy.x_);
2007
2008         //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2009         //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2010 }
2011
2012 int defaultRowHeight()
2013 {
2014         return int(theFontMetrics(sane_font).maxHeight() *  1.2);
2015 }
2016
2017 } // namespace lyx