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.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * \author Jürgen Vigna
13 * \author Abdelrazak Younes
15 * Full author contact details are available in file CREDITS.
20 #include "TextMetrics.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CoordCache.h"
27 #include "CutAndPaste.h"
30 #include "MetricsInfo.h"
31 #include "ParagraphParameters.h"
32 #include "RowPainter.h"
35 #include "TextClass.h"
38 #include "insets/InsetSeparator.h"
39 #include "insets/InsetText.h"
41 #include "mathed/MacroTable.h"
43 #include "frontends/FontMetrics.h"
44 #include "frontends/NullPainter.h"
46 #include "support/debug.h"
47 #include "support/lassert.h"
48 #include "support/Changer.h"
58 using frontend::FontMetrics;
63 int numberOfLabelHfills(Paragraph const & par, Row const & row)
65 pos_type last = row.endpos() - 1;
66 pos_type first = row.pos();
68 // hfill *DO* count at the beginning of paragraphs!
70 while (first < last && par.isHfill(first))
74 last = min(last, par.beginOfBody());
76 for (pos_type p = first; p < last; ++p) {
83 // FIXME: this needs to be rewritten, probably by merging it into some
84 // code that, besides counting, sets the active status of the space
85 // inset in the row element.
86 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
87 pos_type const body_pos)
90 Row::const_iterator cit = row.begin();
91 Row::const_iterator const end = row.end();
92 for ( ; cit != end ; ++cit)
93 if (cit->pos >= body_pos
94 && cit->inset && pm.hfillExpansion(row, cit->pos))
102 /////////////////////////////////////////////////////////////////////
106 /////////////////////////////////////////////////////////////////////
109 TextMetrics::TextMetrics(BufferView * bv, Text * text)
110 : bv_(bv), text_(text), dim_(bv_->workWidth(), 10, 10),
111 max_width_(dim_.wid), tight_(false)
115 bool TextMetrics::contains(pit_type pit) const
117 return par_metrics_.find(pit) != par_metrics_.end();
121 void TextMetrics::forget(pit_type pit)
123 par_metrics_.erase(pit);
127 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
129 ParMetricsCache::const_iterator it = par_metrics_.begin();
130 return make_pair(it->first, &it->second);
134 pair<pit_type, ParagraphMetrics const *> TextMetrics::firstVisible() const
136 // This only works in the main text, I think (bottom > 0)
137 LASSERT(text_->isMainText(), return first());
138 auto it = find_if(par_metrics_.begin(), par_metrics_.end(),
139 [] (ParMetricsCache::value_type const & p) {
140 return p.second.hasPosition() && p.second.bottom() > 0;
142 return make_pair(it->first, &it->second);
145 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
147 LBUFERR(!par_metrics_.empty());
148 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
149 return make_pair(it->first, &it->second);
153 bool TextMetrics::isLastRow(Row const & row) const
155 ParagraphList const & pars = text_->paragraphs();
156 return row.endpos() >= pars[row.pit()].size()
157 && row.pit() + 1 == pit_type(pars.size());
161 bool TextMetrics::isFirstRow(Row const & row) const
163 return row.pos() == 0 && row.pit() == 0;
167 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
169 for (auto & pm_pair : par_metrics_)
170 if (pm_pair.first == pit)
171 for (Row & row : pm_pair.second.rows())
172 if (row.pos() == pos)
177 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
179 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
180 if (pmc_it == par_metrics_.end()) {
181 pmc_it = par_metrics_.insert(
182 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
184 if (pmc_it->second.rows().empty() && redo)
186 return pmc_it->second;
190 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
192 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
196 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit)
198 return parMetrics(pit, true);
202 void TextMetrics::newParMetricsDown()
204 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
205 pit_type const pit = last.first + 1;
206 if (pit == int(text_->paragraphs().size()))
209 // do it and update its position.
211 par_metrics_[pit].setPosition(last.second.bottom() + par_metrics_[pit].ascent());
216 void TextMetrics::newParMetricsUp()
218 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
219 if (first.first == 0)
222 pit_type const pit = first.first - 1;
223 // do it and update its position.
225 par_metrics_[pit].setPosition(first.second.top() - par_metrics_[pit].descent());
230 void TextMetrics::updateMetrics(pit_type const anchor_pit, int const anchor_ypos,
233 LASSERT(text_->isMainText(), return);
235 // Forget existing positions
236 for (auto & pm_pair : par_metrics_)
237 pm_pair.second.resetPosition();
239 if (!contains(anchor_pit))
240 // Rebreak anchor paragraph.
241 redoParagraph(anchor_pit);
242 ParagraphMetrics & anchor_pm = parMetrics(anchor_pit);
243 anchor_pm.setPosition(anchor_ypos);
245 // Redo paragraphs above anchor if necessary.
246 int y1 = anchor_ypos - anchor_pm.ascent();
247 // We are now just above the anchor paragraph.
248 pit_type pit1 = anchor_pit - 1;
249 for (; pit1 >= 0 && y1 > 0; --pit1) {
252 ParagraphMetrics & pm = parMetrics(pit1);
254 // Save the paragraph position in the cache.
259 // Redo paragraphs below the anchor if necessary.
260 int y2 = anchor_ypos + anchor_pm.descent();
261 // We are now just below the anchor paragraph.
262 pit_type pit2 = anchor_pit + 1;
263 pit_type const npit = pit_type(text_->paragraphs().size());
264 for (; pit2 < npit && y2 < bv_height; ++pit2) {
267 ParagraphMetrics & pm = parMetrics(pit2);
269 // Save the paragraph position in the cache.
274 LYXERR(Debug::PAINTING, "TextMetrics::updateMetrics "
275 << " anchor pit = " << anchor_pit
276 << " anchor ypos = " << anchor_ypos
279 << " pit1 = " << pit1
280 << " pit2 = " << pit2);
284 bool TextMetrics::metrics(MetricsInfo const & mi, Dimension & dim, int min_width)
286 LBUFERR(mi.base.textwidth > 0);
287 max_width_ = mi.base.textwidth;
288 tight_ = mi.tight_insets;
289 // backup old dimension.
290 Dimension const old_dim = dim_;
293 dim_.wid = min_width;
294 pit_type const npar = text_->paragraphs().size();
295 if (npar > 1 && !tight_)
296 // If there is more than one row, expand the text to
297 // the full allowable width.
298 dim_.wid = max_width_;
300 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
301 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
303 bool changed = false;
305 for (pit_type pit = 0; pit != npar; ++pit) {
306 // create rows, but do not set alignment yet
307 changed |= redoParagraph(pit, false);
308 ParagraphMetrics const & pm = par_metrics_[pit];
310 if (dim_.wid < pm.width())
311 dim_.wid = pm.width();
314 // Now set alignment for all rows (the width might not have been known before).
315 for (pit_type pit = 0; pit != npar; ++pit) {
316 ParagraphMetrics & pm = par_metrics_[pit];
317 for (Row & row : pm.rows())
318 setRowAlignment(row, dim_.wid);
321 dim_.asc = par_metrics_[0].ascent();
322 dim_.des = h - dim_.asc;
323 //lyxerr << "dim_.wid " << dim_.wid << endl;
324 //lyxerr << "dim_.asc " << dim_.asc << endl;
325 //lyxerr << "dim_.des " << dim_.des << endl;
327 changed |= dim_ != old_dim;
333 void TextMetrics::updatePosCache(pit_type pit) const
335 frontend::NullPainter np;
336 PainterInfo pi(bv_, np);
337 drawParagraph(pi, pit, origin_.x, par_metrics_[pit].position());
341 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
343 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
347 int TextMetrics::rightMargin(pit_type const pit) const
349 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
353 void TextMetrics::applyOuterFont(Font & font) const
355 FontInfo lf(font_.fontInfo());
356 lf.reduce(bv_->buffer().params().getFont().fontInfo());
357 font.fontInfo().realize(lf);
361 // This is an arbitrary magic value
362 static const pos_type force_label = -12345;
364 // if pos == force_label, this function will return the label font instead.
365 // This undocumented and only for use by labelDisplayFont()
366 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
368 LASSERT(pos >= 0 || pos == force_label, { static Font f; return f; });
370 ParagraphList const & pars = text_->paragraphs();
371 Paragraph const & par = pars[pit];
372 Layout const & layout = par.layout();
373 Buffer const & buffer = bv_->buffer();
375 BufferParams const & bparams = buffer.params();
376 bool const label = pos < par.beginOfBody() || pos == force_label;
378 Font f = (pos == force_label) ? Font(inherit_font, bparams.language)
379 : par.getFontSettings(bparams, pos);
380 FontInfo const & lf = label ? layout.labelfont : layout.font;
382 // We specialize the 95% common case:
383 if (!par.getDepth()) {
384 if (!text_->isMainText())
387 FontInfo rlf = label ? layout.reslabelfont : layout.resfont;
389 // In case the default family has been customized
390 if (lf.family() == INHERIT_FAMILY)
391 rlf.setFamily(bparams.getFont().fontInfo().family());
392 f.fontInfo().realize(rlf);
396 // The uncommon case need not be optimized as much.
397 // FIXME : the two code paths seem different in function.
398 f.fontInfo().realize(lf);
400 if (!text_->isMainText())
403 // Realize against environment font information
404 // NOTE: the cast to pit_type should be removed when pit_type
405 // changes to a unsigned integer.
406 if (pit < pit_type(pars.size()))
407 f.fontInfo().realize(text_->outerFont(pit).fontInfo());
409 // Realize with the fonts of lesser depth.
410 f.fontInfo().realize(bparams.getFont().fontInfo());
416 Font TextMetrics::labelDisplayFont(pit_type pit) const
418 return displayFont(pit, force_label);
422 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
428 if (boundary && sl.pos() > 0)
431 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
435 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
437 // no RTL boundary at paragraph start
441 Font const & left_font = displayFont(pit, pos - 1);
443 return isRTLBoundary(pit, pos, left_font);
447 // isRTLBoundary returns false on a real end-of-line boundary,
448 // because otherwise the two boundary types get mixed up.
449 // This is the whole purpose of this being in TextMetrics.
450 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
451 Font const & font) const
453 if (// no RTL boundary at paragraph start
455 // if the metrics have not been calculated, then we are not
456 // on screen and can safely ignore issues about boundaries.
460 ParagraphMetrics const & pm = par_metrics_[pit];
461 // no RTL boundary in empty paragraph
462 if (pm.rows().empty())
465 pos_type const endpos = pm.getRow(pos - 1, false).endpos();
466 pos_type const startpos = pm.getRow(pos, false).pos();
467 // no RTL boundary at line start:
468 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
470 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
473 Paragraph const & par = text_->getPar(pit);
474 // no RTL boundary at line break:
475 // abc|\n -> move right -> abc\n (and not: abc\n|
477 if (startpos == pos && endpos == pos && endpos != par.size()
478 && (par.isNewline(pos - 1)
479 || par.isEnvSeparator(pos - 1)
480 || par.isLineSeparator(pos - 1)
481 || par.isSeparator(pos - 1)))
484 bool const left = font.isVisibleRightToLeft();
486 if (pos == par.size())
487 right = par.isRTL(bv_->buffer().params());
489 right = displayFont(pit, pos).isVisibleRightToLeft();
491 return left != right;
495 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
497 Paragraph & par = text_->getPar(pit);
498 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
499 // redoParagraph() recursively inside parMetrics.
500 Dimension old_dim = parMetrics(pit, false).dim();
501 ParagraphMetrics & pm = par_metrics_[pit];
504 Buffer & buffer = bv_->buffer();
505 bool changed = false;
507 // Check whether there are InsetBibItems that need fixing
508 // FIXME: This check ought to be done somewhere else. It is the reason
509 // why text_ is not const. But then, where else to do it?
510 // Well, how can you end up with either (a) a biblio environment that
511 // has no InsetBibitem, (b) a biblio environment with more than one
512 // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
513 // environment? I think the answer is: when paragraphs are merged;
514 // when layout is set; when material is pasted.
515 if (par.brokenBiblio()) {
516 Cursor & cur = bv_->cursor();
517 // In some cases, we do not know how to record undo
518 if (&cur.inset() == &text_->inset())
519 cur.recordUndo(pit, pit);
521 int const moveCursor = par.fixBiblio(buffer);
523 // Is it necessary to update the cursor?
524 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
527 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
532 // Optimisation: this is used in the next two loops
533 // so better to calculate that once here.
534 int const right_margin = rightMargin(pm);
536 // iterator pointing to paragraph to resolve macros
537 DocIterator parPos = text_->macrocontextPosition();
541 LYXERR(Debug::INFO, "MacroContext not initialised!"
542 << " Going through the buffer again and hope"
543 << " the context is better then.");
544 // FIXME audit updateBuffer calls
545 // This should not be here, but it is not clear yet where else it
547 bv_->buffer().updateBuffer();
548 parPos = text_->macrocontextPosition();
549 LBUFERR(!parPos.empty());
554 par.setBeginOfBody();
555 Font const bufferfont = buffer.params().getFont();
556 CoordCache::Insets & insetCache = bv_->coordCache().insets();
557 map <Inset const *, int> extrawidths;
558 for (auto const & e : par.insetList()) {
559 // FIXME Doesn't this HAVE to be non-empty?
560 // position already initialized?
561 if (!parPos.empty()) {
562 parPos.pos() = e.pos;
564 // A macro template would normally not be visible
565 // by itself. But the tex macro semantics allow
566 // recursion, so we artifically take the context
567 // after the macro template to simulate this.
568 if (e.inset->lyxCode() == MATHMACRO_CODE)
572 // If there is an end of paragraph marker, its size should be
573 // substracted to the available width. The logic here is
574 // almost the same as in tokenizeParagraph, remember keep them in sync.
576 if (e.pos + 1 == par.size()
577 && (lyxrc.paragraph_markers || par.lookupChange(par.size()).changed())
578 && size_type(pit + 1) < text_->paragraphs().size()) {
579 Font f(text_->layoutFont(pit));
580 // ¶ U+00B6 PILCROW SIGN
581 eop = theFontMetrics(f).width(char_type(0x00B6));
584 // do the metric calculation
586 int const w = max_width_ - leftMargin(pit, e.pos)
587 - right_margin - eop;
588 Font const & font = e.inset->inheritFont() ?
589 displayFont(pit, e.pos) : bufferfont;
590 MacroContext mc(&buffer, parPos);
591 MetricsInfo mi(bv_, font.fontInfo(), w, mc, e.pos == 0, tight_);
592 mi.base.outer_font = displayFont(pit, e.pos).fontInfo();
593 e.inset->metrics(mi, dim);
594 /* FIXME: This is a hack. This allows InsetMathHull to state
595 * that it needs some elbow room beyond its width, in order to
596 * fit the numbering and/or the left margin (with left
597 * alignment), which are outside of the inset itself.
599 * To this end, InsetMathHull::metrics() sets a value in
600 * MetricsInfo::extrawidth and this value is added later to
601 * the width of the row that contains the inset (when this row
602 * is tight or shorter than the max allowed width).
604 * See ticket #12320 for details.
606 extrawidths[e.inset] = mi.extrawidth;
608 changed |= insetCache.add(e.inset, dim);
611 // Transform the paragraph into a single row containing all the elements.
612 Row const bigrow = tokenizeParagraph(pit);
613 // Split the row in several rows fitting in available width
614 pm.rows() = breakParagraph(bigrow);
616 // Add the needed extra width to the rows that contain the insets that request it
617 for (Row & row : pm.rows())
618 for (Row::Element & e : row)
619 if (e.type == Row::INSET && (row.width() < max_width_ || tight_))
620 row.dim().wid += extrawidths[e.inset];
622 /* If there is more than one row, expand the text to the full
623 * allowable width. This setting here is needed for the
624 * setRowAlignment() below. We do nothing when tight insets are
627 if (pm.rows().size() > 1 && !tight_ && dim_.wid < max_width_)
628 dim_.wid = max_width_;
630 // Compute height and alignment of the rows.
631 for (Row & row : pm.rows()) {
634 setRowAlignment(row, max(dim_.wid, row.width()));
636 pm.dim().wid = max(pm.dim().wid, row.width() + row.right_margin);
637 pm.dim().des += row.height();
640 // This type of margin can only be handled at the global paragraph level
641 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX) {
643 if (par.isRTL(buffer.params())) {
644 // globally align the paragraph to the left.
645 int minleft = max_width_;
646 for (Row const & row : pm.rows())
647 minleft = min(minleft, row.left_margin);
648 offset = right_margin - minleft;
650 // globally align the paragraph to the right.
652 for (Row const & row : pm.rows())
653 maxwid = max(maxwid, row.width());
654 offset = max_width_ - right_margin - maxwid;
657 for (Row & row : pm.rows()) {
658 row.left_margin += offset;
659 row.dim().wid += offset;
663 // The space above and below the paragraph.
664 int top = parTopSpacing(pit);
665 int bottom = parBottomSpacing(pit);
667 // Top and bottom margin of the document (only at top-level)
668 // FIXME: It might be better to move this in another method
669 // specially tailored for the main text.
670 if (text_->isMainText()) {
672 top += bv_->topMargin();
673 if (pit + 1 == pit_type(text_->paragraphs().size())) {
674 bottom += bv_->bottomMargin();
678 // Add the top/bottom space to rows and paragraph metrics
679 pm.rows().front().dim().asc += top;
680 pm.rows().back().dim().des += bottom;
681 pm.dim().des += top + bottom;
683 // Move the pm ascent to be the same as the first row ascent
684 pm.dim().asc += pm.rows().front().ascent();
685 pm.dim().des -= pm.rows().front().ascent();
687 changed |= old_dim.height() != pm.dim().height();
693 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
695 LyXAlignment align = par.getAlign(bv_->buffer().params());
697 // handle alignment inside tabular cells
698 Inset const & owner = text_->inset();
699 bool forced_block = false;
700 switch (owner.contentAlignment()) {
701 case LYX_ALIGN_BLOCK:
702 // In general block align is the default state, but here it is
703 // an explicit choice. Therefore it should not be overridden
707 case LYX_ALIGN_CENTER:
709 case LYX_ALIGN_RIGHT:
710 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
711 align = owner.contentAlignment();
714 // unchanged (use align)
718 // Display-style insets should always be on a centered row
719 if (Inset const * inset = par.getInset(row.pos())) {
720 if (inset->rowFlags() & Display) {
721 if (inset->rowFlags() & AlignLeft)
722 align = LYX_ALIGN_LEFT;
723 else if (inset->rowFlags() & AlignRight)
724 align = LYX_ALIGN_RIGHT;
726 align = LYX_ALIGN_CENTER;
730 if (align == LYX_ALIGN_BLOCK) {
731 // If this row has been broken abruptly by a display inset, or
732 // it is the end of the paragraph, or the user requested we
733 // not justify stuff, then don't stretch.
734 // A forced block alignment can only be overridden the 'no
735 // justification on screen' setting.
736 if ((row.flushed() && !forced_block)
737 || !bv_->buffer().params().justification)
738 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
745 void TextMetrics::setRowAlignment(Row & row, int width) const
750 Paragraph const & par = text_->getPar(row.pit());
752 int const w = width - row.right_margin - row.width();
753 // FIXME: put back this assertion when the crash on new doc is solved.
754 //LASSERT(w >= 0, /**/);
756 // is there a manual margin with a manual label
757 Layout const & layout = par.layout();
760 if (layout.margintype == MARGIN_MANUAL
761 && layout.labeltype == LABEL_MANUAL) {
762 /// We might have real hfills in the label part
763 nlh = numberOfLabelHfills(par, row);
765 // A manual label par (e.g. List) has an auto-hfill
766 // between the label text and the body of the
768 // But we don't want to do this auto hfill if the par
773 if (nlh && !par.getLabelWidthString().empty())
774 row.label_hfill = labelFill(row) / double(nlh);
777 // are there any hfills in the row?
778 ParagraphMetrics const & pm = par_metrics_[row.pit()];
779 int nh = numberOfHfills(row, pm, par.beginOfBody());
783 // We don't have to look at the alignment if the row is already
784 // larger then the permitted width as then we force the
785 // LEFT_ALIGN'edness!
786 if (row.width() >= max_width_)
790 // Common case : there is no hfill, and the alignment will be
792 switch (getAlign(par, row)) {
793 case LYX_ALIGN_BLOCK:
794 // Expand expanding characters by a total of w
795 if (!row.setExtraWidth(w) && row.isRTL()) {
796 // Justification failed and the text is RTL: align to the right
797 row.left_margin += w;
802 // a displayed inset that is flushed
803 if (Inset const * inset = par.getInset(row.pos())) {
804 row.left_margin += inset->indent(*bv_);
805 row.dim().wid += inset->indent(*bv_);
808 case LYX_ALIGN_RIGHT:
809 if (Inset const * inset = par.getInset(row.pos())) {
810 int const new_w = max(w - inset->indent(*bv_), 0);
811 row.left_margin += new_w;
812 row.dim().wid += new_w;
814 row.left_margin += w;
818 case LYX_ALIGN_CENTER:
819 row.dim().wid += w / 2;
820 row.left_margin += w / 2;
823 case LYX_ALIGN_LAYOUT:
824 case LYX_ALIGN_SPECIAL:
825 case LYX_ALIGN_DECIMAL:
831 // Case nh > 0. There are hfill separators.
835 // Set size of hfill insets
836 pos_type const endpos = row.endpos();
837 pos_type body_pos = par.beginOfBody();
839 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
842 CoordCache::Insets & insetCache = bv_->coordCache().insets();
843 for (Row::Element & e : row) {
844 if (row.label_hfill && e.endpos == body_pos
845 && e.type == Row::SPACE)
846 e.dim.wid -= int(row.label_hfill * (nlh - 1));
847 if (e.inset && pm.hfillExpansion(row, e.pos)) {
848 if (e.pos >= body_pos) {
852 e.dim.wid += hfill_rem;
854 e.dim.wid += int(row.label_hfill);
855 // Cache the inset dimension.
856 insetCache.add(e.inset, e.dim);
862 int TextMetrics::labelFill(Row const & row) const
864 Paragraph const & par = text_->getPar(row.pit());
865 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
868 // iterate over elements before main body (except the last one,
869 // which is extra space).
870 for (Row::Element const & e : row) {
871 if (e.endpos >= par.beginOfBody())
876 docstring const & label = par.params().labelWidthString();
880 FontMetrics const & fm
881 = theFontMetrics(text_->labelFont(par));
883 return max(0, fm.width(label) - w);
890 * Calling Text::getFont is slow. While rebreaking we scan a
891 * paragraph from left to right calling getFont for every char. This
892 * simple class address this problem by hidding an optimization trick
893 * (not mine btw -AB): the font is reused in the whole font span. The
894 * class handles transparently the "hidden" (not part of the fontlist)
895 * label font (as getFont does).
901 FontIterator(TextMetrics const & tm,
902 Paragraph const & par, pit_type pit, pos_type pos)
903 : tm_(tm), par_(par), pit_(pit), pos_(pos),
904 font_(tm.displayFont(pit, pos)),
905 endspan_(par.fontSpan(pos).last),
906 bodypos_(par.beginOfBody())
910 Font const & operator*() const { return font_; }
913 FontIterator & operator++()
916 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
917 font_ = tm_.displayFont(pit_, pos_);
918 endspan_ = par_.fontSpan(pos_).last;
924 Font * operator->() { return &font_; }
928 TextMetrics const & tm_;
930 Paragraph const & par_;
946 Row TextMetrics::tokenizeParagraph(pit_type const pit) const
950 Paragraph const & par = text_->getPar(pit);
951 Buffer const & buf = text_->inset().buffer();
952 BookmarksSection::BookmarkPosList bpl =
953 theSession().bookmarks().bookmarksInPar(buf.fileName(), par.id());
955 pos_type const end = par.size();
956 pos_type const body_pos = par.beginOfBody();
958 // check for possible inline completion
959 DocIterator const & ic_it = bv_->inlineCompletionPos();
960 pos_type ic_pos = -1;
961 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == pit)
962 ic_pos = ic_it.pos();
964 // Now we iterate through until we reach the right margin
965 // or the end of the par, then build a representation of the row.
967 FontIterator fi = FontIterator(*this, par, pit, 0);
968 // The real stopping condition is a few lines below.
970 // Firstly, check whether there is a bookmark here.
971 if (lyxrc.bookmarks_visibility == LyXRC::BMK_INLINE)
972 for (auto const & bp_p : bpl)
973 if (bp_p.second == i) {
975 f.fontInfo().setColor(Color_bookmark);
976 // ❶ U+2776 DINGBAT NEGATIVE CIRCLED DIGIT ONE
977 char_type const ch = 0x2775 + bp_p.first;
978 row.addVirtual(i, docstring(1, ch), f, Change());
981 // The stopping condition is here so that the display of a
982 // bookmark can take place at paragraph start too.
986 char_type c = par.getChar(i);
987 // The most special cases are handled first.
988 if (par.isInset(i)) {
989 Inset const * ins = par.getInset(i);
990 Dimension dim = bv_->coordCache().insets().dim(ins);
991 row.add(i, ins, dim, *fi, par.lookupChange(i));
992 } else if (c == ' ' && i + 1 == body_pos) {
993 // This space is an \item separator. Represent it with a
994 // special space element, which dimension will be computed
996 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
997 int const wid = fm.width(par.layout().labelsep);
998 row.addMarginSpace(i, wid, *fi, par.lookupChange(i));
999 } else if (c == '\t')
1000 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
1001 *fi, par.lookupChange(i));
1002 else if (c == 0x2028 || c == 0x2029) {
1004 * U+2028 LINE SEPARATOR
1005 * U+2029 PARAGRAPH SEPARATOR
1007 * These are special unicode characters that break
1008 * lines/pragraphs. Not handling them leads to trouble wrt
1009 * Qt QTextLayout formatting. We add a visible character
1010 * on screen so that the user can see that something is
1014 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
1015 // ¶ U+00B6 PILCROW SIGN
1016 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
1017 row.add(i, screen_char, *fi, par.lookupChange(i));
1019 // row elements before body are unbreakable
1020 row.add(i, c, *fi, par.lookupChange(i));
1022 // add inline completion width
1023 // draw logically behind the previous character
1024 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
1025 docstring const comp = bv_->inlineCompletion();
1026 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
1030 f.fontInfo().setColor(Color_inlinecompletion);
1031 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
1033 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
1034 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
1043 // End of paragraph marker, either if LyXRc requires it, or there
1044 // is an end of paragraph change. The logic here is almost the
1045 // same as in redoParagraph, remember keep them in sync.
1046 ParagraphList const & pars = text_->paragraphs();
1047 Change const & endchange = par.lookupChange(end);
1048 if (endchange.changed())
1049 row.needsChangeBar(true);
1050 if ((lyxrc.paragraph_markers || endchange.changed())
1051 && size_type(pit + 1) < pars.size()) {
1052 // add a virtual element for the end-of-paragraph
1053 // marker; it is shown on screen, but does not exist
1054 // in the paragraph.
1055 Font f(text_->layoutFont(pit));
1056 f.fontInfo().setColor(Color_paragraphmarker);
1057 f.setLanguage(par.getParLanguage(buf.params()));
1058 // ¶ U+00B6 PILCROW SIGN
1059 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, endchange);
1068 /** Helper template flexible_const_iterator<T>
1069 * A way to iterate over a const container, but insert fake elements in it.
1070 * In the case of a row, we will have to break some elements, which
1071 * create new ones. This class allows to abstract this.
1072 * Only the required parts are implemented for now.
1075 class flexible_const_iterator {
1076 typedef typename T::value_type value_type;
1080 flexible_const_iterator & operator++() {
1088 value_type operator*() const { return pile_.empty() ? *cit_ : pile_.back(); }
1090 value_type const * operator->() const { return pile_.empty() ? &*cit_ : &pile_.back(); }
1092 void put(value_type const & e) { pile_.push_back(e); }
1094 // Put a sequence of elements on the pile (in reverse order!)
1095 void put(vector<value_type> const & elts) {
1096 pile_.insert(pile_.end(), elts.rbegin(), elts.rend());
1099 // This should be private, but declaring the friend functions is too much work
1101 typename T::const_iterator cit_;
1102 // A vector that is used as like a pile to store the elements to
1103 // consider before incrementing the underlying iterator.
1104 vector<value_type> pile_;
1109 flexible_const_iterator<T> flexible_begin(T const & t)
1111 return { t.begin(), vector<typename T::value_type>() };
1116 flexible_const_iterator<T> flexible_end(T const & t)
1118 return { t.end(), vector<typename T::value_type>() };
1122 // Equality is only possible if respective piles are empty
1124 bool operator==(flexible_const_iterator<T> const & t1,
1125 flexible_const_iterator<T> const & t2)
1127 return t1.cit_ == t2.cit_ && t1.pile_.empty() && t2.pile_.empty();
1131 Row newRow(TextMetrics const & tm, pit_type pit, pos_type pos, bool is_rtl)
1136 nrow.left_margin = tm.leftMargin(pit, pos);
1137 nrow.right_margin = tm.rightMargin(pit);
1138 nrow.setRTL(is_rtl);
1140 swap(nrow.left_margin, nrow.right_margin);
1141 // Remember that the row width takes into account the left_margin
1142 // but not the right_margin.
1143 nrow.dim().wid = nrow.left_margin;
1148 void cleanupRow(Row & row, bool at_end)
1151 row.endpos(row.pos());
1155 row.endpos(row.back().endpos);
1156 // remove trailing spaces on row break
1157 if (!at_end && !row.flushed())
1159 // boundary exists when there was no space at the end of row
1160 row.end_boundary(!at_end && row.back().endpos == row.endpos());
1161 // make sure that the RTL elements are in reverse ordering
1166 // Implement the priorities described in RowFlags.h.
1167 bool needsRowBreak(int f1, int f2)
1169 if (f1 & AlwaysBreakAfter /*|| f2 & AlwaysBreakBefore*/)
1171 if (f1 & NoBreakAfter || f2 & NoBreakBefore)
1173 if (f1 & BreakAfter || f2 & BreakBefore)
1182 RowList TextMetrics::breakParagraph(Row const & bigrow) const
1185 bool const is_rtl = text_->isRTL(bigrow.pit());
1186 bool const end_label = text_->getEndLabel(bigrow.pit()) != END_LABEL_NO_LABEL;
1187 int const next_width = max_width_ - leftMargin(bigrow.pit(), bigrow.endpos())
1188 - rightMargin(bigrow.pit());
1191 flexible_const_iterator<Row> fcit = flexible_begin(bigrow);
1192 flexible_const_iterator<Row> const end = flexible_end(bigrow);
1194 bool const row_empty = rows.empty() || rows.back().empty();
1195 // The row flags of previous element, if there is one.
1196 // Otherwise we use NoBreakAfter to avoid an empty row before
1197 // e.g. a displayed equation.
1198 int const f1 = row_empty ? NoBreakAfter : rows.back().back().row_flags;
1199 // The row flags of next element, if there is one.
1200 // Otherwise we use NoBreakBefore (see above), unless the
1201 // paragraph has an end label (for which an empty row is OK).
1202 int const f2 = (fcit == end) ? (end_label ? Inline : NoBreakBefore)
1204 if (rows.empty() || needsRowBreak(f1, f2)) {
1205 if (!rows.empty()) {
1206 // Flush row as requested by row flags
1207 rows.back().flushed((f1 & Flush) || (f2 & FlushBefore));
1208 cleanupRow(rows.back(), false);
1210 pos_type pos = rows.empty() ? 0 : rows.back().endpos();
1211 rows.push_back(newRow(*this, bigrow.pit(), pos, is_rtl));
1212 // the width available for the row.
1213 width = max_width_ - rows.back().right_margin;
1216 // The stopping condition is here because we may need a new
1217 // empty row at the end.
1221 // Next element to consider is either the top of the temporary
1222 // pile, or the place when we were in main row
1223 Row::Element elt = *fcit;
1225 elt.splitAt(width - rows.back().width(), next_width, Row::FIT, tail);
1226 Row & rb = rows.back();
1227 if (elt.type == Row::MARGINSPACE)
1228 elt.dim.wid = max(elt.dim.wid, leftMargin(bigrow.pit()) - rb.width());
1231 if (rb.width() > width) {
1232 // Keep the tail for later; this ought to be rare, but play safe.
1235 // if the row is too large, try to cut at last separator.
1236 tail = rb.shortenIfNeeded(width, next_width);
1239 // Go to next element
1242 // Handle later the elements returned by splitAt or shortenIfNeeded.
1246 if (!rows.empty()) {
1247 // Last row in paragraph is flushed
1248 rows.back().flushed(true);
1249 cleanupRow(rows.back(), true);
1250 // Is there an end-of-paragraph change?
1251 if (bigrow.needsChangeBar())
1252 rows.back().needsChangeBar(true);
1259 int TextMetrics::parTopSpacing(pit_type const pit) const
1261 Paragraph const & par = text_->getPar(pit);
1262 Layout const & layout = par.layout();
1265 ParagraphList const & pars = text_->paragraphs();
1266 double const dh = defaultRowHeight();
1268 BufferParams const & bparams = bv_->buffer().params();
1269 Inset const & inset = text_->inset();
1270 // some parskips VERY EASY IMPLEMENTATION
1271 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1272 && !inset.getLayout().parbreakIsNewline()
1273 && !par.layout().parbreak_is_newline
1275 && ((layout.isParagraph() && par.getDepth() == 0)
1276 || (pars[pit - 1].layout().isParagraph()
1277 && pars[pit - 1].getDepth() == 0))) {
1278 asc += bparams.getDefSkip().inPixels(*bv_);
1281 if (par.params().startOfAppendix())
1284 // special code for the top label
1285 if (layout.labelIsAbove()
1286 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1287 && !par.labelString().empty()) {
1288 FontInfo labelfont = text_->labelFont(par);
1289 FontMetrics const & lfm = theFontMetrics(labelfont);
1290 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1291 * text_->spacing(par)
1292 + (layout.topsep + layout.labelbottomsep) * dh);
1295 // Add the layout spaces, for example before and after
1296 // a section, or between the items of a itemize or enumerate
1299 pit_type prev = text_->depthHook(pit, par.getDepth());
1300 Paragraph const & prevpar = pars[prev];
1301 double layoutasc = 0;
1303 && prevpar.layout() == layout
1304 && prevpar.getDepth() == par.getDepth()
1305 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1306 layoutasc = layout.itemsep * dh;
1307 } else if (pit != 0 && layout.topsep > 0)
1308 // combine the separation between different layouts (with same depth)
1309 layoutasc = max(0.0,
1310 prevpar.getDepth() != par.getDepth() ? layout.topsep
1311 : layout.topsep - prevpar.layout().bottomsep) * dh;
1313 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1315 prev = text_->outerHook(pit);
1316 if (prev != pit_type(pars.size())) {
1317 asc += int(pars[prev].layout().parsep * dh);
1318 } else if (pit != 0) {
1319 Paragraph const & prevpar2 = pars[pit - 1];
1320 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1321 asc += int(layout.parsep * dh);
1328 int TextMetrics::parBottomSpacing(pit_type const pit) const
1330 double layoutdesc = 0;
1331 ParagraphList const & pars = text_->paragraphs();
1332 double const dh = defaultRowHeight();
1334 // add the layout spaces, for example before and after
1335 // a section, or between the items of a itemize or enumerate
1337 pit_type nextpit = pit + 1;
1338 if (nextpit != pit_type(pars.size())) {
1339 pit_type cpit = pit;
1341 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1342 double usual = pars[cpit].layout().bottomsep * dh;
1344 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1345 if (pars[cpit].layout() != pars[nextpit].layout()
1346 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1347 unusual = pars[cpit].layout().bottomsep * dh;
1348 layoutdesc = max(unusual, usual);
1349 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1350 if (pars[cpit].layout() != pars[nextpit].layout()
1351 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1352 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1356 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1360 void TextMetrics::setRowHeight(Row & row) const
1362 Paragraph const & par = text_->getPar(row.pit());
1363 Layout const & layout = par.layout();
1364 // leading space (line spacing) factor based on current paragraph
1365 double spacing_val = layout.spacing.getValue() * text_->spacing(par);
1367 // if this is the first row but not the first paragraph, take into
1368 // account the spacing of the previous paragraph.
1369 if (row.pos() == 0 && row.pit() > 0) {
1370 // for the first row in the paragraph,
1371 // use previous paragraphs line spacing if it is larger
1372 Paragraph const & previousPar = text_->getPar(row.pit() - 1);
1373 Layout const & previousLayout = previousPar.layout();
1374 // leading space factor based on previous paragraph
1375 double const previous_spacing_val
1376 = previousLayout.spacing.getValue() * text_->spacing(previousPar);
1377 if (previous_spacing_val > spacing_val)
1378 spacing_val = previous_spacing_val;
1381 // Initial value for ascent (useful if row is empty).
1382 Font const font = displayFont(row.pit(), row.pos());
1383 FontMetrics const & fm = theFontMetrics(font);
1384 int maxasc = int(fm.maxAscent()
1385 // add leading space
1386 + fm.maxHeight() * (spacing_val - 1));
1387 int maxdes = int(fm.maxDescent());
1389 // Take label string into account (useful if labelfont is large)
1390 if (row.pos() == 0 && layout.labelIsInline()) {
1391 FontInfo const labelfont = text_->labelFont(par);
1392 FontMetrics const & lfm = theFontMetrics(labelfont);
1393 maxasc = max(maxasc, int(lfm.maxAscent()
1394 // add leading space
1395 + lfm.maxHeight() * (spacing_val - 1)));
1396 maxdes = max(maxdes, int(lfm.maxDescent()));
1399 // Find the ascent/descent of the row contents
1400 for (Row::Element const & e : row) {
1402 maxasc = max(maxasc, e.dim.ascent());
1403 maxdes = max(maxdes, e.dim.descent());
1405 FontMetrics const & fm2 = theFontMetrics(e.font);
1406 maxasc = max(maxasc, int(fm2.maxAscent()
1407 // add leading space
1408 + fm2.maxHeight() * (spacing_val - 1)));
1409 maxdes = max(maxdes, int(fm2.maxDescent()));
1413 // This is nicer with box insets
1417 row.dim().asc = maxasc;
1418 row.dim().des = maxdes;
1420 // This is useful for selections
1421 row.contents_dim() = row.dim();
1425 // x is an absolute screen coord
1426 // returns the column near the specified x-coordinate of the row
1427 // x is set to the real beginning of this column
1428 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1429 bool & boundary) const
1431 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1432 /// For the main Text, it is possible that this pit is not
1433 /// yet in the CoordCache when moving cursor up.
1434 /// x Paragraph coordinate is always 0 for main text anyway.
1435 int const xo = origin_.x;
1438 // Adapt to cursor row scroll offset if applicable.
1439 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1442 pos_type pos = row.pos();
1445 x = row.left_margin;
1446 else if (x <= row.left_margin) {
1447 pos = row.front().left_pos();
1448 x = row.left_margin;
1449 } else if (x >= row.width()) {
1450 pos = row.back().right_pos();
1453 double w = row.left_margin;
1454 Row::const_iterator cit = row.begin();
1455 Row::const_iterator cend = row.end();
1456 for ( ; cit != cend; ++cit) {
1457 if (w <= x && w + cit->full_width() > x) {
1458 int x_offset = int(x - w);
1459 pos = cit->x2pos(x_offset);
1460 x = int(x_offset + w);
1463 w += cit->full_width();
1465 if (cit == row.end()) {
1466 pos = row.back().right_pos();
1469 /** This tests for the case where the cursor is placed
1470 * just before a font direction change. See comment on
1471 * the boundary_ member in DocIterator.h to understand
1472 * how boundary helps here.
1474 else if (pos == cit->endpos
1475 && ((!cit->isRTL() && cit + 1 != row.end()
1476 && (cit + 1)->isRTL())
1477 || (cit->isRTL() && cit != row.begin()
1478 && !(cit - 1)->isRTL())))
1482 /** This tests for the case where the cursor is set at the end
1483 * of a row which has been broken due something else than a
1484 * separator (a display inset or a forced breaking of the
1485 * row). We know that there is a separator when the end of the
1486 * row is larger than the end of its last element.
1488 if (!row.empty() && pos == row.back().endpos
1489 && row.back().endpos == row.endpos()) {
1490 Inset const * inset = row.back().inset;
1491 if (inset && (inset->lyxCode() == NEWLINE_CODE
1492 || inset->lyxCode() == SEPARATOR_CODE))
1493 pos = row.back().pos;
1495 boundary = row.end_boundary();
1499 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1505 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1507 // We play safe and use parMetrics(pit) to make sure the
1508 // ParagraphMetrics will be redone and OK to use if needed.
1509 // Otherwise we would use an empty ParagraphMetrics in
1510 // upDownInText() while in selection mode.
1511 ParagraphMetrics const & pm = parMetrics(pit);
1513 LBUFERR(row < int(pm.rows().size()));
1515 Row const & r = pm.rows()[row];
1516 return getPosNearX(r, x, bound);
1520 // y is screen coordinate
1521 pit_type TextMetrics::getPitNearY(int y)
1523 LASSERT(!text_->paragraphs().empty(), return -1);
1524 LASSERT(!par_metrics_.empty(), return -1);
1525 LYXERR(Debug::PAINTING, "y: " << y << " cache size: " << par_metrics_.size());
1527 // look for highest numbered paragraph with y coordinate less than given y
1530 ParMetricsCache::const_iterator it = par_metrics_.begin();
1531 ParMetricsCache::const_iterator et = par_metrics_.end();
1532 ParMetricsCache::const_iterator last = et;
1535 if (y < it->second.top()) {
1536 // We are looking for a position that is before the first paragraph in
1537 // the cache (which is in priciple off-screen, that is before the
1540 // We are already at the first paragraph in the inset.
1542 // OK, this is the paragraph we are looking for.
1543 pit = it->first - 1;
1548 if (y >= par_metrics_[last->first].bottom()) {
1549 // We are looking for a position that is after the last paragraph in
1550 // the cache (which is in priciple off-screen), that is before the
1552 pit = last->first + 1;
1553 if (pit == int(text_->paragraphs().size()))
1554 // We are already at the last paragraph in the inset.
1556 // OK, this is the paragraph we are looking for.
1557 newParMetricsDown();
1561 for (; it != et; ++it) {
1562 // LYXERR(Debug::PAINTING, "examining: pit: " << it->first
1563 // << " y: " << it->second.position());
1565 if (it->first >= pit && it->second.top() <= y) {
1567 yy = it->second.position();
1571 LYXERR(Debug::PAINTING, "found best y: " << yy << " for pit: " << pit);
1577 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1578 bool assert_in_view, bool up)
1580 ParagraphMetrics const & pm = par_metrics_[pit];
1583 LBUFERR(!pm.rows().empty());
1584 RowList::const_iterator rit = pm.rows().begin();
1585 RowList::const_iterator rlast = pm.rows().end();
1587 for (; rit != rlast; yy += rit->height(), ++rit)
1588 if (yy + rit->height() > y)
1591 if (assert_in_view) {
1592 if (!up && yy + rit->height() > y) {
1593 if (rit != pm.rows().begin()) {
1596 } else if (pit != 0) {
1599 ParagraphMetrics const & pm2 = par_metrics_[pit];
1600 rit = pm2.rows().end();
1604 } else if (up && yy != y) {
1606 y = yy + rit->height();
1608 } else if (pit < int(text_->paragraphs().size()) - 1) {
1610 newParMetricsDown();
1611 ParagraphMetrics const & pm2 = par_metrics_[pit];
1612 rit = pm2.rows().begin();
1621 // x,y are absolute screen coordinates
1622 // sets cursor recursively descending into nested editable insets
1623 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1624 bool assert_in_view, bool up)
1626 if (lyxerr.debugging(Debug::WORKAREA)) {
1627 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1628 cur.bv().coordCache().dump();
1630 pit_type pit = getPitNearY(y);
1631 LASSERT(pit != -1, return 0);
1632 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1635 // Do we cover an inset?
1636 InsetList::Element * e = checkInsetHit(pit, x, y);
1639 // No inset, set position in the text
1640 bool bound = false; // is modified by getPosNearX
1641 cur.pos() = getPosNearX(row, x, bound);
1642 cur.boundary(bound);
1643 cur.setCurrentFont();
1648 Inset * inset = e->inset;
1649 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1651 // Set position in front of inset
1653 cur.boundary(false);
1656 // Try to descend recursively inside the inset.
1657 Inset * edited = inset->editXY(cur, x, y);
1658 // FIXME: it is not clear that the test on position is needed
1659 // Remove it if/when semantics of editXY is clarified
1660 if (cur.text() == text_ && cur.pos() == e->pos) {
1661 // non-editable inset, set cursor after the inset if x is
1662 // nearer to that position (bug 9628)
1663 bool bound = false; // is modified by getPosNearX
1664 cur.pos() = getPosNearX(row, x, bound);
1665 cur.boundary(bound);
1666 cur.setCurrentFont();
1670 if (cur.top().text() == text_)
1671 cur.setCurrentFont();
1676 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1678 LASSERT(text_ == cur.text(), return);
1679 pit_type const pit = getPitNearY(y);
1680 LASSERT(pit != -1, return);
1682 ParagraphMetrics const & pm = par_metrics_[pit];
1684 int yy = pm.position() - pm.rows().front().ascent();
1685 LYXERR(Debug::PAINTING, "x: " << x << " y: " << y <<
1686 " pit: " << pit << " yy: " << yy);
1689 LBUFERR(pm.rows().size());
1690 for (; r < int(pm.rows().size()) - 1; ++r) {
1691 Row const & row = pm.rows()[r];
1692 if (yy + row.height() > y)
1697 Row const & row = pm.rows()[r];
1699 LYXERR(Debug::PAINTING, "row " << r << " from pos: " << row.pos());
1703 pos_type const pos = getPosNearX(row, xx, bound);
1705 LYXERR(Debug::PAINTING, "setting cursor pit: " << pit << " pos: " << pos);
1707 text_->setCursor(cur, pit, pos, true, bound);
1708 // remember new position.
1713 //takes screen x,y coordinates
1714 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1716 Paragraph const & par = text_->paragraphs()[pit];
1717 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1719 LYXERR(Debug::PAINTING, "x: " << x << " y: " << y << " pit: " << pit);
1721 for (InsetList::Element const & e : par.insetList()) {
1722 LYXERR(Debug::PAINTING, "examining inset " << e.inset);
1724 if (insetCache.covers(e.inset, x, y)) {
1725 LYXERR(Debug::PAINTING, "Hit inset: " << e.inset);
1726 return const_cast<InsetList::Element *>(&e);
1730 LYXERR(Debug::PAINTING, "No inset hit. ");
1735 //takes screen x,y coordinates
1736 Inset * TextMetrics::checkInsetHit(int x, int y)
1738 pit_type const pit = getPitNearY(y);
1739 LASSERT(pit != -1, return 0);
1740 InsetList::Element * e = checkInsetHit(pit, x, y);
1749 int TextMetrics::cursorX(CursorSlice const & sl,
1750 bool boundary) const
1752 LASSERT(sl.text() == text_, return 0);
1754 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1755 if (pm.rows().empty())
1757 Row const & row = pm.getRow(sl.pos(), boundary);
1758 pos_type const pos = sl.pos();
1761 row.findElement(pos, boundary, x);
1767 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1769 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1770 ParagraphMetrics const & pm = parMetrics(sl.pit());
1771 if (pm.rows().empty())
1775 h -= parMetrics(0).rows()[0].ascent();
1776 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1777 h += parMetrics(pit).height();
1780 if (pos && boundary)
1782 size_t const rend = pm.pos2row(pos);
1783 for (size_t rit = 0; rit != rend; ++rit)
1784 h += pm.rows()[rit].height();
1785 h += pm.rows()[rend].ascent();
1790 // the cursor set functions have a special mechanism. When they
1791 // realize you left an empty paragraph, they will delete it.
1793 bool TextMetrics::cursorHome(Cursor & cur)
1795 LASSERT(text_ == cur.text(), return false);
1796 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1797 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1798 return text_->setCursor(cur, cur.pit(), row.pos());
1802 bool TextMetrics::cursorEnd(Cursor & cur)
1804 LASSERT(text_ == cur.text(), return false);
1805 // if not on the last row of the par, put the cursor before
1806 // the final space exept if I have a spanning inset or one string
1807 // is so long that we force a break.
1808 pos_type end = cur.textRow().endpos();
1810 // empty text, end-1 is no valid position
1812 bool boundary = false;
1813 if (end != cur.lastpos()) {
1814 if (!cur.paragraph().isLineSeparator(end-1)
1815 && !cur.paragraph().isNewline(end-1)
1816 && !cur.paragraph().isEnvSeparator(end-1))
1820 } else if (cur.paragraph().isEnvSeparator(end-1))
1822 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1826 void TextMetrics::deleteLineForward(Cursor & cur)
1828 LASSERT(text_ == cur.text(), return);
1829 if (cur.lastpos() == 0) {
1830 // Paragraph is empty, so we just go forward
1831 text_->cursorForward(cur);
1834 cur.selection(true); // to avoid deletion
1837 // What is this test for ??? (JMarc)
1838 if (!cur.selection())
1839 text_->deleteWordForward(cur);
1841 cap::cutSelection(cur, false);
1842 cur.checkBufferStructure();
1847 int TextMetrics::leftMargin(pit_type pit) const
1849 // FIXME: what is the semantics? It depends on whether the
1850 // paragraph is empty!
1851 return leftMargin(pit, text_->paragraphs()[pit].size());
1855 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1857 ParagraphList const & pars = text_->paragraphs();
1859 LASSERT(pit >= 0, return 0);
1860 LASSERT(pit < int(pars.size()), return 0);
1861 Paragraph const & par = pars[pit];
1862 LASSERT(pos >= 0, return 0);
1863 // We do not really care whether pos > par.size(), since we do not
1864 // access the data. It can be actually useful, when querying the
1865 // margin without indentation (see leftMargin(pit_type).
1867 Buffer const & buffer = bv_->buffer();
1868 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1869 DocumentClass const & tclass = buffer.params().documentClass();
1870 Layout const & layout = par.layout();
1871 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1873 docstring parindent = layout.parindent;
1877 if (text_->isMainText()) {
1878 l_margin += bv_->leftMargin();
1879 l_margin += bfm.signedWidth(tclass.leftmargin());
1882 int depth = par.getDepth();
1884 // find the next level paragraph
1885 pit_type newpar = text_->outerHook(pit);
1886 if (newpar != pit_type(pars.size())) {
1887 if (pars[newpar].layout().isEnvironment()) {
1888 int nestmargin = depth * nestMargin();
1889 if (text_->isMainText())
1890 nestmargin += changebarMargin();
1891 l_margin = max(leftMargin(newpar), nestmargin);
1892 // Remove the parindent that has been added
1893 // if the paragraph was empty.
1894 if (pars[newpar].empty() &&
1895 buffer.params().paragraph_separation ==
1896 BufferParams::ParagraphIndentSeparation) {
1897 docstring pi = pars[newpar].layout().parindent;
1898 l_margin -= bfm.signedWidth(pi);
1901 if (tclass.isDefaultLayout(par.layout())
1902 || tclass.isPlainLayout(par.layout())) {
1903 if (pars[newpar].params().noindent())
1906 parindent = pars[newpar].layout().parindent;
1911 // Check for reasons to remove indentation.
1912 // First, at document level.
1913 if (buffer.params().paragraph_separation ==
1914 BufferParams::ParagraphSkipSeparation)
1916 // This happens after sections or environments in standard classes.
1917 // We have to check the previous layout at same depth.
1918 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1919 pit_type prev = text_->depthHook(pit, par.getDepth());
1920 if (par.layout() == pars[prev].layout()) {
1922 && pars[pit - 1].layout().nextnoindent)
1924 } else if (pars[prev].layout().nextnoindent)
1927 // The previous paragraph may have ended with a separator inset.
1929 Paragraph const & ppar = pars[pit - 1];
1930 if (ppar.size() > 0) {
1931 auto * in = dynamic_cast<InsetSeparator const *>(ppar.getInset(ppar.size() - 1));
1932 if (in != nullptr && in->nextnoindent())
1937 FontInfo const labelfont = text_->labelFont(par);
1938 FontMetrics const & lfm = theFontMetrics(labelfont);
1940 switch (layout.margintype) {
1941 case MARGIN_DYNAMIC:
1942 if (!layout.leftmargin.empty()) {
1943 l_margin += bfm.signedWidth(layout.leftmargin);
1945 if (!par.labelString().empty()) {
1946 l_margin += lfm.signedWidth(layout.labelindent);
1947 l_margin += lfm.width(par.labelString());
1948 l_margin += lfm.width(layout.labelsep);
1952 case MARGIN_MANUAL: {
1953 l_margin += lfm.signedWidth(layout.labelindent);
1954 // The width of an empty par, even with manual label, should be 0
1955 if (!par.empty() && pos >= par.beginOfBody()) {
1956 if (!par.getLabelWidthString().empty()) {
1957 docstring labstr = par.getLabelWidthString();
1958 l_margin += lfm.width(labstr);
1959 l_margin += lfm.width(layout.labelsep);
1965 case MARGIN_STATIC: {
1966 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1967 / (par.getDepth() + 4);
1971 case MARGIN_FIRST_DYNAMIC:
1972 if (layout.labeltype == LABEL_MANUAL) {
1973 // if we are at position 0, we are never in the body
1974 if (pos > 0 && pos >= par.beginOfBody())
1975 l_margin += lfm.signedWidth(layout.leftmargin);
1977 l_margin += lfm.signedWidth(layout.labelindent);
1979 // Special case to fix problems with
1981 || (layout.labeltype == LABEL_STATIC
1982 && layout.latextype == LATEX_ENVIRONMENT
1983 && !text_->isFirstInSequence(pit))) {
1984 l_margin += lfm.signedWidth(layout.leftmargin);
1985 } else if (!layout.labelIsAbove()) {
1986 l_margin += lfm.signedWidth(layout.labelindent);
1987 l_margin += lfm.width(layout.labelsep);
1988 l_margin += lfm.width(par.labelString());
1992 case MARGIN_RIGHT_ADDRESS_BOX:
1993 // This is handled globally in redoParagraph().
1997 if (!par.params().leftIndent().zero())
1998 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
2000 LyXAlignment align = par.getAlign(bv_->buffer().params());
2002 // set the correct parindent
2004 && (layout.labeltype == LABEL_NO_LABEL
2005 || layout.labeltype == LABEL_ABOVE
2006 || layout.labeltype == LABEL_CENTERED
2007 || (layout.labeltype == LABEL_STATIC
2008 && layout.latextype == LATEX_ENVIRONMENT
2009 && !text_->isFirstInSequence(pit)))
2010 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
2011 && !par.params().noindent()
2012 // in some insets, paragraphs are never indented
2013 && !text_->inset().neverIndent()
2014 // display style insets do not need indentation
2017 && par.getInset(0)->rowFlags() & Display)
2018 && (!(tclass.isDefaultLayout(par.layout())
2019 || tclass.isPlainLayout(par.layout()))
2020 || buffer.params().paragraph_separation
2021 == BufferParams::ParagraphIndentSeparation)) {
2022 /* use the parindent of the layout when the default
2023 * indentation is used otherwise use the indentation set in
2024 * the document settings
2026 if (buffer.params().getParIndent().empty())
2027 l_margin += bfm.signedWidth(parindent);
2029 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
2036 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
2038 if (par_metrics_.empty())
2044 y -= par_metrics_.begin()->second.ascent();
2045 for (auto & pm_pair : par_metrics_) {
2046 pit_type const pit = pm_pair.first;
2047 ParagraphMetrics & pm = pm_pair.second;
2049 // Save the paragraph position in the cache.
2051 drawParagraph(pi, pit, x, y);
2057 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
2059 ParagraphMetrics const & pm = par_metrics_[pit];
2060 if (pm.rows().empty())
2062 size_t const nrows = pm.rows().size();
2063 int const wh = bv_->workHeight();
2064 // Remember left and right margin for drawing math numbers
2065 Changer changeleft, changeright;
2066 if (text_->isRTL(pit)) {
2067 changeleft = changeVar(pi.leftx, x + rightMargin(pit));
2068 changeright = changeVar(pi.rightx, x + width() - leftMargin(pit));
2070 changeleft = changeVar(pi.leftx, x + leftMargin(pit));
2071 changeright = changeVar(pi.rightx, x + width() - rightMargin(pit));
2074 // Use fast lane in nodraw stage.
2075 if (pi.pain.isNull()) {
2076 for (size_t i = 0; i != nrows; ++i) {
2078 Row const & row = pm.rows()[i];
2079 // Adapt to cursor row scroll offset if applicable.
2080 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
2084 // It is not needed to draw on screen if we are not inside
2085 bool const inside = (y + row.descent() >= 0 && y - row.ascent() < wh);
2087 RowPainter rp(pi, *text_, row, row_x, y);
2088 rp.paintOnlyInsets();
2095 Cursor const & cur = bv_->cursor();
2096 DocIterator sel_beg = cur.selectionBegin();
2097 DocIterator sel_end = cur.selectionEnd();
2098 bool selection = cur.selection()
2099 // This is our text.
2100 && cur.text() == text_
2101 // if the anchor is outside, this is not our selection
2102 && cur.normalAnchor().text() == text_
2103 && pit >= sel_beg.pit() && pit <= sel_end.pit();
2105 // We store the begin and end pos of the selection relative to this par
2106 DocIterator sel_beg_par = cur.selectionBegin();
2107 DocIterator sel_end_par = cur.selectionEnd();
2109 // We care only about visible selection.
2111 if (pit != sel_beg.pit()) {
2112 sel_beg_par.pit() = pit;
2113 sel_beg_par.pos() = 0;
2115 if (pit != sel_end.pit()) {
2116 sel_end_par.pit() = pit;
2117 sel_end_par.pos() = sel_end_par.lastpos();
2121 BookmarksSection::BookmarkPosList bpl =
2122 theSession().bookmarks().bookmarksInPar(bv_->buffer().fileName(), pm.id());
2124 for (size_t i = 0; i != nrows; ++i) {
2126 Row const & row = pm.rows()[i];
2127 // Adapt to cursor row scroll offset if applicable.
2128 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
2132 // It is not needed to draw on screen if we are not inside.
2133 bool const inside = (y + row.descent() >= 0
2134 && y - row.ascent() < wh);
2136 // Inset positions have already been set in nodraw stage.
2142 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2144 row.clearSelectionAndMargins();
2146 // The row knows nothing about the paragraph, so we have to check
2147 // whether this row is the first or last and update the margins.
2148 if (row.selection()) {
2149 if (row.sel_beg == 0)
2150 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
2151 if (row.sel_end == sel_end_par.lastpos())
2152 row.change(row.end_margin_sel, sel_end.pit() > pit);
2155 // Take this opportunity to spellcheck the row contents.
2156 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
2157 text_->getPar(pit).spellCheck();
2160 RowPainter rp(pi, *text_, row, row_x, y);
2162 // Don't paint the row if a full repaint has not been requested
2163 // and if it has not changed.
2164 if (!pi.full_repaint && !row.changed()) {
2165 // Paint only the insets if the text itself is
2167 rp.paintOnlyInsets();
2168 rp.paintTooLargeMarks(
2169 row_x + row.left_x() < bv_->leftMargin(),
2170 row_x + row.right_x() > bv_->workWidth() - bv_->rightMargin());
2176 // Clear background of this row if paragraph background was not
2177 // already cleared because of a full repaint.
2178 if (!pi.full_repaint && row.changed()) {
2179 LYXERR(Debug::PAINTING, "Clear rect@("
2180 << x << ", " << y - row.ascent() << ")="
2181 << width() << " x " << row.height());
2182 pi.pain.fillRectangle(x, y - row.ascent(),
2183 width(), row.height(), pi.background_color);
2186 // Instrumentation for testing row cache (see also
2188 if (lyxerr.debugging(Debug::PAINTING)
2189 && (row.selection() || pi.full_repaint || row.changed())) {
2190 string const foreword = text_->isMainText() ? "main text redraw "
2191 : "inset text redraw: ";
2192 LYXERR0(foreword << "pit=" << pit << " row=" << i
2193 << (row.selection() ? " row_selection": "")
2194 << (pi.full_repaint ? " full_repaint" : "")
2195 << (row.changed() ? " row.changed" : ""));
2198 // Backup full_repaint status and force full repaint
2199 // for inner insets as the Row has been cleared out.
2200 bool tmp = pi.full_repaint;
2201 pi.full_repaint = true;
2203 rp.paintSelection();
2206 if (row.needsChangeBar())
2207 rp.paintChangeBar();
2213 rp.paintTooLargeMarks(
2214 row_x + row.left_x() < bv_->leftMargin(),
2215 row_x + row.right_x() > bv_->workWidth() - bv_->rightMargin());
2216 // indicate bookmarks presence in margin
2217 if (lyxrc.bookmarks_visibility == LyXRC::BMK_MARGIN)
2218 for (auto const & bp_p : bpl)
2219 if (bp_p.second >= row.pos() && bp_p.second < row.endpos())
2220 rp.paintBookmark(bp_p.first);
2225 // This debug code shows on screen which rows are repainted.
2226 // FIXME: since the updates related to caret blinking restrict
2227 // the painter to a small rectangle, the numbers are not
2228 // updated when this happens. Change the code in
2229 // GuiWorkArea::Private::show/hideCaret if this is important.
2230 static int count = 0;
2232 FontInfo fi(sane_font);
2233 fi.setSize(TINY_SIZE);
2234 fi.setColor(Color_red);
2235 pi.pain.text(row_x, y, convert<docstring>(count), fi);
2238 // Restore full_repaint status.
2239 pi.full_repaint = tmp;
2244 //LYXERR(Debug::PAINTING, ".");
2248 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2249 Dimension & dim) const
2251 DocIterator from = cur.bv().cursor();
2252 DocIterator to = from;
2253 text_->getWord(from.top(), to.top(), PREVIOUS_WORD);
2255 // The vertical dimension of the word
2256 Font const font = displayFont(cur.pit(), from.pos());
2257 FontMetrics const & fm = theFontMetrics(font);
2258 // the +1's below are related to the extra pixels added in setRowHeight
2259 dim.asc = fm.maxAscent() + 1;
2260 dim.des = fm.maxDescent() + 1;
2262 // get position on screen of the word start and end
2263 //FIXME: Is it necessary to explicitly set this to false?
2264 from.boundary(false);
2265 Point lxy = cur.bv().getPos(from);
2266 Point rxy = cur.bv().getPos(to);
2267 dim.wid = abs(rxy.x - lxy.x);
2269 // calculate position of word
2271 x = min(rxy.x, lxy.x);
2273 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x=" << lxy.x << " rxy.x=" << rxy.x << " word=" << word << std::endl;
2274 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2277 int defaultRowHeight()
2279 return int(theFontMetrics(sane_font).maxHeight() * 1.2);