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/InsetText.h"
40 #include "mathed/MacroTable.h"
42 #include "frontends/FontMetrics.h"
43 #include "frontends/NullPainter.h"
45 #include "support/debug.h"
46 #include "support/lassert.h"
47 #include "support/Changer.h"
57 using frontend::FontMetrics;
62 int numberOfLabelHfills(Paragraph const & par, Row const & row)
64 pos_type last = row.endpos() - 1;
65 pos_type first = row.pos();
67 // hfill *DO* count at the beginning of paragraphs!
69 while (first < last && par.isHfill(first))
73 last = min(last, par.beginOfBody());
75 for (pos_type p = first; p < last; ++p) {
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)
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))
101 /////////////////////////////////////////////////////////////////////
105 /////////////////////////////////////////////////////////////////////
108 TextMetrics::TextMetrics(BufferView * bv, Text * text)
109 : bv_(bv), text_(text), dim_(bv_->workWidth(), 10, 10),
110 max_width_(dim_.wid), tight_(false)
114 bool TextMetrics::contains(pit_type pit) const
116 return par_metrics_.find(pit) != par_metrics_.end();
120 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
122 ParMetricsCache::const_iterator it = par_metrics_.begin();
123 return make_pair(it->first, &it->second);
127 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
129 LBUFERR(!par_metrics_.empty());
130 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
131 return make_pair(it->first, &it->second);
135 bool TextMetrics::isLastRow(Row const & row) const
137 ParagraphList const & pars = text_->paragraphs();
138 return row.endpos() >= pars[row.pit()].size()
139 && row.pit() + 1 == pit_type(pars.size());
143 bool TextMetrics::isFirstRow(Row const & row) const
145 return row.pos() == 0 && row.pit() == 0;
149 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
151 for (auto & pm_pair : par_metrics_)
152 if (pm_pair.first == pit)
153 for (Row & row : pm_pair.second.rows())
154 if (row.pos() == pos)
159 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
161 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
162 if (pmc_it == par_metrics_.end()) {
163 pmc_it = par_metrics_.insert(
164 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
166 if (pmc_it->second.rows().empty() && redo)
168 return pmc_it->second;
172 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
174 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
178 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit)
180 return parMetrics(pit, true);
184 void TextMetrics::newParMetricsDown()
186 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
187 pit_type const pit = last.first + 1;
188 if (pit == int(text_->paragraphs().size()))
191 // do it and update its position.
193 par_metrics_[pit].setPosition(last.second.position()
194 + last.second.descent() + par_metrics_[pit].ascent());
199 void TextMetrics::newParMetricsUp()
201 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
202 if (first.first == 0)
205 pit_type const pit = first.first - 1;
206 // do it and update its position.
208 par_metrics_[pit].setPosition(first.second.position()
209 - first.second.ascent() - par_metrics_[pit].descent());
214 bool TextMetrics::metrics(MetricsInfo const & mi, Dimension & dim, int min_width)
216 LBUFERR(mi.base.textwidth > 0);
217 max_width_ = mi.base.textwidth;
218 tight_ = mi.tight_insets;
219 // backup old dimension.
220 Dimension const old_dim = dim_;
223 dim_.wid = min_width;
224 pit_type const npar = text_->paragraphs().size();
225 if (npar > 1 && !tight_)
226 // If there is more than one row, expand the text to
227 // the full allowable width.
228 dim_.wid = max_width_;
230 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
231 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
233 bool changed = false;
235 for (pit_type pit = 0; pit != npar; ++pit) {
236 // create rows, but do not set alignment yet
237 changed |= redoParagraph(pit, false);
238 ParagraphMetrics const & pm = par_metrics_[pit];
240 if (dim_.wid < pm.width())
241 dim_.wid = pm.width();
244 // Now set alignment for all rows (the width might not have been known before).
245 for (pit_type pit = 0; pit != npar; ++pit) {
246 ParagraphMetrics & pm = par_metrics_[pit];
247 for (Row & row : pm.rows())
248 setRowAlignment(row, dim_.wid);
251 dim_.asc = par_metrics_[0].ascent();
252 dim_.des = h - dim_.asc;
253 //lyxerr << "dim_.wid " << dim_.wid << endl;
254 //lyxerr << "dim_.asc " << dim_.asc << endl;
255 //lyxerr << "dim_.des " << dim_.des << endl;
257 changed |= dim_ != old_dim;
263 void TextMetrics::updatePosCache(pit_type pit) const
265 frontend::NullPainter np;
266 PainterInfo pi(bv_, np);
267 drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
271 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
273 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
277 int TextMetrics::rightMargin(pit_type const pit) const
279 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
283 void TextMetrics::applyOuterFont(Font & font) const
285 FontInfo lf(font_.fontInfo());
286 lf.reduce(bv_->buffer().params().getFont().fontInfo());
287 font.fontInfo().realize(lf);
291 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
293 LASSERT(pos >= 0, { static Font f; return f; });
295 ParagraphList const & pars = text_->paragraphs();
296 Paragraph const & par = pars[pit];
297 Layout const & layout = par.layout();
298 Buffer const & buffer = bv_->buffer();
300 BufferParams const & params = buffer.params();
301 pos_type const body_pos = par.beginOfBody();
303 // We specialize the 95% common case:
304 if (!par.getDepth()) {
305 Font f = par.getFontSettings(params, pos);
306 if (!text_->isMainText())
308 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
310 FontInfo const & lf = lab ? layout.labelfont : layout.font;
311 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
313 // In case the default family has been customized
314 if (lf.family() == INHERIT_FAMILY)
315 rlf.setFamily(params.getFont().fontInfo().family());
316 f.fontInfo().realize(rlf);
320 // The uncommon case need not be optimized as much
321 FontInfo const & layoutfont = pos < body_pos ?
322 layout.labelfont : layout.font;
324 Font font = par.getFontSettings(params, pos);
325 font.fontInfo().realize(layoutfont);
327 if (!text_->isMainText())
328 applyOuterFont(font);
330 // Realize against environment font information
331 // NOTE: the cast to pit_type should be removed when pit_type
332 // changes to a unsigned integer.
333 if (pit < pit_type(pars.size()))
334 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
336 // Realize with the fonts of lesser depth.
337 font.fontInfo().realize(params.getFont().fontInfo());
343 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
349 if (boundary && sl.pos() > 0)
352 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
356 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
358 // no RTL boundary at paragraph start
362 Font const & left_font = displayFont(pit, pos - 1);
364 return isRTLBoundary(pit, pos, left_font);
368 // isRTLBoundary returns false on a real end-of-line boundary,
369 // because otherwise the two boundary types get mixed up.
370 // This is the whole purpose of this being in TextMetrics.
371 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
372 Font const & font) const
374 if (// no RTL boundary at paragraph start
376 // if the metrics have not been calculated, then we are not
377 // on screen and can safely ignore issues about boundaries.
381 ParagraphMetrics const & pm = par_metrics_[pit];
382 // no RTL boundary in empty paragraph
383 if (pm.rows().empty())
386 pos_type const endpos = pm.getRow(pos - 1, false).endpos();
387 pos_type const startpos = pm.getRow(pos, false).pos();
388 // no RTL boundary at line start:
389 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
391 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
394 Paragraph const & par = text_->getPar(pit);
395 // no RTL boundary at line break:
396 // abc|\n -> move right -> abc\n (and not: abc\n|
398 if (startpos == pos && endpos == pos && endpos != par.size()
399 && (par.isNewline(pos - 1)
400 || par.isEnvSeparator(pos - 1)
401 || par.isLineSeparator(pos - 1)
402 || par.isSeparator(pos - 1)))
405 bool const left = font.isVisibleRightToLeft();
407 if (pos == par.size())
408 right = par.isRTL(bv_->buffer().params());
410 right = displayFont(pit, pos).isVisibleRightToLeft();
412 return left != right;
416 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
418 Paragraph & par = text_->getPar(pit);
419 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
420 // redoParagraph() recursively inside parMetrics.
421 Dimension old_dim = parMetrics(pit, false).dim();
422 ParagraphMetrics & pm = par_metrics_[pit];
425 Buffer & buffer = bv_->buffer();
426 bool changed = false;
428 // Check whether there are InsetBibItems that need fixing
429 // FIXME: This check ought to be done somewhere else. It is the reason
430 // why text_ is not const. But then, where else to do it?
431 // Well, how can you end up with either (a) a biblio environment that
432 // has no InsetBibitem, (b) a biblio environment with more than one
433 // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
434 // environment? I think the answer is: when paragraphs are merged;
435 // when layout is set; when material is pasted.
436 if (par.brokenBiblio()) {
437 Cursor & cur = bv_->cursor();
438 // In some cases, we do not know how to record undo
439 if (&cur.inset() == &text_->inset())
440 cur.recordUndo(pit, pit);
442 int const moveCursor = par.fixBiblio(buffer);
444 // Is it necessary to update the cursor?
445 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
448 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
453 // Optimisation: this is used in the next two loops
454 // so better to calculate that once here.
455 int const right_margin = rightMargin(pm);
457 // iterator pointing to paragraph to resolve macros
458 DocIterator parPos = text_->macrocontextPosition();
462 LYXERR(Debug::INFO, "MacroContext not initialised!"
463 << " Going through the buffer again and hope"
464 << " the context is better then.");
465 // FIXME audit updateBuffer calls
466 // This should not be here, but it is not clear yet where else it
468 bv_->buffer().updateBuffer();
469 parPos = text_->macrocontextPosition();
470 LBUFERR(!parPos.empty());
475 par.setBeginOfBody();
476 Font const bufferfont = buffer.params().getFont();
477 CoordCache::Insets & insetCache = bv_->coordCache().insets();
478 for (auto const & e : par.insetList()) {
479 // FIXME Doesn't this HAVE to be non-empty?
480 // position already initialized?
481 if (!parPos.empty()) {
482 parPos.pos() = e.pos;
484 // A macro template would normally not be visible
485 // by itself. But the tex macro semantics allow
486 // recursion, so we artifically take the context
487 // after the macro template to simulate this.
488 if (e.inset->lyxCode() == MATHMACRO_CODE)
492 // If there is an end of paragraph marker, its size should be
493 // substracted to the available width. The logic here is
494 // almost the same as in breakRow, remember keep them in sync.
496 if (e.pos + 1 == par.size()
497 && (lyxrc.paragraph_markers || par.lookupChange(par.size()).changed())
498 && size_type(pit + 1) < text_->paragraphs().size()) {
499 Font f(text_->layoutFont(pit));
500 // ¶ U+00B6 PILCROW SIGN
501 eop = theFontMetrics(f).width(char_type(0x00B6));
504 // do the metric calculation
506 int const w = max_width_ - leftMargin(pit, e.pos)
507 - right_margin - eop;
508 Font const & font = e.inset->inheritFont() ?
509 displayFont(pit, e.pos) : bufferfont;
510 MacroContext mc(&buffer, parPos);
511 MetricsInfo mi(bv_, font.fontInfo(), w, mc, e.pos == 0, tight_);
512 e.inset->metrics(mi, dim);
513 if (!insetCache.has(e.inset) || insetCache.dim(e.inset) != dim) {
514 insetCache.add(e.inset, dim);
520 size_t row_index = 0;
521 bool need_new_row = false;
522 // maximum pixel width of a row
524 if (row_index == pm.rows().size())
525 pm.rows().push_back(Row());
527 pm.rows()[row_index] = Row();
528 Row & row = pm.rows()[row_index];
531 need_new_row = breakRow(row, right_margin);
534 if ((row_index || row.endpos() < par.size() || row.right_boundary())
536 /* If there is more than one row or the row has been
537 * broken by a display inset or a newline, expand the text
538 * to the full allowable width. This setting here is
539 * needed for the setRowAlignment() below.
540 * We do nothing when tight insets are requested.
542 if (dim_.wid < max_width_)
543 dim_.wid = max_width_;
546 setRowAlignment(row, max(dim_.wid, row.width()));
547 first = row.endpos();
550 pm.dim().wid = max(pm.dim().wid, row.width() + row.right_margin);
551 pm.dim().des += row.height();
552 } while (first < par.size() || need_new_row);
554 if (row_index < pm.rows().size())
555 pm.rows().resize(row_index);
557 // This type of margin can only be handled at the global paragraph level
558 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX) {
560 if (par.isRTL(buffer.params())) {
561 // globally align the paragraph to the left.
562 int minleft = max_width_;
563 for (Row const & row : pm.rows())
564 minleft = min(minleft, row.left_margin);
565 offset = right_margin - minleft;
567 // globally align the paragraph to the right.
569 for (Row const & row : pm.rows())
570 maxwid = max(maxwid, row.width());
571 offset = max_width_ - right_margin - maxwid;
574 for (Row & row : pm.rows()) {
575 row.left_margin += offset;
576 row.dim().wid += offset;
580 // The space above and below the paragraph.
581 int top = parTopSpacing(pit);
582 int bottom = parBottomSpacing(pit);
584 // Top and bottom margin of the document (only at top-level)
585 // FIXME: It might be better to move this in another method
586 // specially tailored for the main text.
587 if (text_->isMainText()) {
589 top += bv_->topMargin();
590 if (pit + 1 == pit_type(text_->paragraphs().size())) {
591 bottom += bv_->bottomMargin();
595 // Add the top/bottom space to rows and paragraph metrics
596 pm.rows().front().dim().asc += top;
597 pm.rows().back().dim().des += bottom;
598 pm.dim().des += top + bottom;
600 // Move the pm ascent to be the same as the first row ascent
601 pm.dim().asc += pm.rows().front().ascent();
602 pm.dim().des -= pm.rows().front().ascent();
604 changed |= old_dim.height() != pm.dim().height();
610 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
612 LyXAlignment align = par.getAlign(bv_->buffer().params());
614 // handle alignment inside tabular cells
615 Inset const & owner = text_->inset();
616 bool forced_block = false;
617 switch (owner.contentAlignment()) {
618 case LYX_ALIGN_BLOCK:
619 // In general block align is the default state, but here it is
620 // an explicit choice. Therefore it should not be overridden
624 case LYX_ALIGN_CENTER:
626 case LYX_ALIGN_RIGHT:
627 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
628 align = owner.contentAlignment();
631 // unchanged (use align)
635 // Display-style insets should always be on a centered row
636 if (Inset const * inset = par.getInset(row.pos())) {
637 if (inset->rowFlags() & Display) {
638 if (inset->rowFlags() & AlignLeft)
639 align = LYX_ALIGN_BLOCK;
640 else if (inset->rowFlags() & AlignRight)
641 align = LYX_ALIGN_RIGHT;
643 align = LYX_ALIGN_CENTER;
647 if (align == LYX_ALIGN_BLOCK) {
648 // If this row has been broken abruptly by a display inset, or
649 // it is the end of the paragraph, or the user requested we
650 // not justify stuff, then don't stretch.
651 // A forced block alignment can only be overridden the 'no
652 // justification on screen' setting.
653 if ((row.flushed() && !forced_block)
654 || !bv_->buffer().params().justification)
655 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
662 void TextMetrics::setRowAlignment(Row & row, int width) const
667 Paragraph const & par = text_->getPar(row.pit());
669 int const w = width - row.right_margin - row.width();
670 // FIXME: put back this assertion when the crash on new doc is solved.
671 //LASSERT(w >= 0, /**/);
673 // is there a manual margin with a manual label
674 Layout const & layout = par.layout();
677 if (layout.margintype == MARGIN_MANUAL
678 && layout.labeltype == LABEL_MANUAL) {
679 /// We might have real hfills in the label part
680 nlh = numberOfLabelHfills(par, row);
682 // A manual label par (e.g. List) has an auto-hfill
683 // between the label text and the body of the
685 // But we don't want to do this auto hfill if the par
690 if (nlh && !par.getLabelWidthString().empty())
691 row.label_hfill = labelFill(row) / double(nlh);
694 // are there any hfills in the row?
695 ParagraphMetrics const & pm = par_metrics_[row.pit()];
696 int nh = numberOfHfills(row, pm, par.beginOfBody());
700 // We don't have to look at the alignment if the row is already
701 // larger then the permitted width as then we force the
702 // LEFT_ALIGN'edness!
703 if (row.width() >= max_width_)
707 // Common case : there is no hfill, and the alignment will be
709 switch (getAlign(par, row)) {
710 case LYX_ALIGN_BLOCK:
711 // Expand expanding characters by a total of w
712 if (!row.setExtraWidth(w) && row.isRTL()) {
713 // Justification failed and the text is RTL: align to the right
714 row.left_margin += w;
719 // a displayed inset that is flushed
720 if (Inset const * inset = par.getInset(row.pos())) {
721 row.left_margin += inset->indent(*bv_);
722 row.dim().wid += inset->indent(*bv_);
725 case LYX_ALIGN_RIGHT:
726 if (Inset const * inset = par.getInset(row.pos())) {
727 int const new_w = max(w - inset->indent(*bv_), 0);
728 row.left_margin += new_w;
729 row.dim().wid += new_w;
731 row.left_margin += w;
735 case LYX_ALIGN_CENTER:
736 row.dim().wid += w / 2;
737 row.left_margin += w / 2;
740 case LYX_ALIGN_LAYOUT:
741 case LYX_ALIGN_SPECIAL:
742 case LYX_ALIGN_DECIMAL:
748 // Case nh > 0. There are hfill separators.
752 // Set size of hfill insets
753 pos_type const endpos = row.endpos();
754 pos_type body_pos = par.beginOfBody();
756 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
759 CoordCache::Insets & insetCache = bv_->coordCache().insets();
760 for (Row::Element & e : row) {
761 if (row.label_hfill && e.endpos == body_pos
762 && e.type == Row::SPACE)
763 e.dim.wid -= int(row.label_hfill * (nlh - 1));
764 if (e.inset && pm.hfillExpansion(row, e.pos)) {
765 if (e.pos >= body_pos) {
769 e.dim.wid += hfill_rem;
771 e.dim.wid += int(row.label_hfill);
772 // Cache the inset dimension.
773 insetCache.add(e.inset, e.dim);
779 int TextMetrics::labelFill(Row const & row) const
781 Paragraph const & par = text_->getPar(row.pit());
782 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
785 // iterate over elements before main body (except the last one,
786 // which is extra space).
787 for (Row::Element const & e : row) {
788 if (e.endpos >= par.beginOfBody())
793 docstring const & label = par.params().labelWidthString();
797 FontMetrics const & fm
798 = theFontMetrics(text_->labelFont(par));
800 return max(0, fm.width(label) - w);
804 int TextMetrics::labelEnd(pit_type const pit) const
806 // labelEnd is only needed if the layout fills a flushleft label.
807 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
809 // return the beginning of the body
810 return leftMargin(pit);
816 * Calling Text::getFont is slow. While rebreaking we scan a
817 * paragraph from left to right calling getFont for every char. This
818 * simple class address this problem by hidding an optimization trick
819 * (not mine btw -AB): the font is reused in the whole font span. The
820 * class handles transparently the "hidden" (not part of the fontlist)
821 * label font (as getFont does).
827 FontIterator(TextMetrics const & tm,
828 Paragraph const & par, pit_type pit, pos_type pos)
829 : tm_(tm), par_(par), pit_(pit), pos_(pos),
830 font_(tm.displayFont(pit, pos)),
831 endspan_(par.fontSpan(pos).last),
832 bodypos_(par.beginOfBody())
836 Font const & operator*() const { return font_; }
839 FontIterator & operator++()
842 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
843 font_ = tm_.displayFont(pit_, pos_);
844 endspan_ = par_.fontSpan(pos_).last;
850 Font * operator->() { return &font_; }
854 TextMetrics const & tm_;
856 Paragraph const & par_;
872 Row TextMetrics::tokenizeParagraph(pit_type const pit) const
876 Paragraph const & par = text_->getPar(pit);
877 Buffer const & buf = text_->inset().buffer();
878 BookmarksSection::BookmarkPosList bpl =
879 theSession().bookmarks().bookmarksInPar(buf.fileName(), par.id());
881 pos_type const end = par.size();
882 pos_type const body_pos = par.beginOfBody();
884 // check for possible inline completion
885 DocIterator const & ic_it = bv_->inlineCompletionPos();
886 pos_type ic_pos = -1;
887 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == pit)
888 ic_pos = ic_it.pos();
890 // Now we iterate through until we reach the right margin
891 // or the end of the par, then build a representation of the row.
893 FontIterator fi = FontIterator(*this, par, pit, 0);
894 // The real stopping condition is a few lines below.
896 // Firstly, check whether there is a bookmark here.
897 if (lyxrc.bookmarks_visibility == LyXRC::BMK_INLINE)
898 for (auto const & bp_p : bpl)
899 if (bp_p.second == i) {
901 f.fontInfo().setColor(Color_bookmark);
902 // ❶ U+2776 DINGBAT NEGATIVE CIRCLED DIGIT ONE
903 char_type const ch = 0x2775 + bp_p.first;
904 row.addVirtual(i, docstring(1, ch), f, Change());
907 // The stopping condition is here so that the display of a
908 // bookmark can take place at paragraph start too.
912 char_type c = par.getChar(i);
913 // The most special cases are handled first.
914 if (par.isInset(i)) {
915 Inset const * ins = par.getInset(i);
916 Dimension dim = bv_->coordCache().insets().dim(ins);
917 row.add(i, ins, dim, *fi, par.lookupChange(i));
918 } else if (c == ' ' && i + 1 == body_pos) {
919 // There is a space at i, but it should not be
920 // added as a separator, because it is just
921 // before body_pos. Instead, insert some spacing to
923 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
924 // this is needed to make sure that the row width is correct
926 int const add = max(fm.width(par.layout().labelsep),
927 labelEnd(pit) - row.width());
928 row.addSpace(i, add, *fi, par.lookupChange(i));
929 } else if (c == '\t')
930 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
931 *fi, par.lookupChange(i));
932 else if (c == 0x2028 || c == 0x2029) {
934 * U+2028 LINE SEPARATOR
935 * U+2029 PARAGRAPH SEPARATOR
937 * These are special unicode characters that break
938 * lines/pragraphs. Not handling them lead to trouble wrt
939 * Qt QTextLayout formatting. We add a visible character
940 * on screen so that the user can see that something is
944 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
945 // ¶ U+00B6 PILCROW SIGN
946 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
947 row.add(i, screen_char, *fi, par.lookupChange(i), i >= body_pos);
949 // row elements before body are unbreakable
950 row.add(i, c, *fi, par.lookupChange(i), i >= body_pos);
952 // add inline completion width
953 // draw logically behind the previous character
954 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
955 docstring const comp = bv_->inlineCompletion();
956 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
960 f.fontInfo().setColor(Color_inlinecompletion);
961 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
963 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
964 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
973 // End of paragraph marker. The logic here is almost the
974 // same as in redoParagraph, remember keep them in sync.
975 ParagraphList const & pars = text_->paragraphs();
976 Change const & change = par.lookupChange(i);
977 if ((lyxrc.paragraph_markers || change.changed())
978 && i == end && size_type(pit + 1) < pars.size()) {
979 // add a virtual element for the end-of-paragraph
980 // marker; it is shown on screen, but does not exist
982 Font f(text_->layoutFont(pit));
983 f.fontInfo().setColor(Color_paragraphmarker);
984 f.setLanguage(par.getParLanguage(buf.params()));
985 // ¶ U+00B6 PILCROW SIGN
986 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, change);
993 /** This is the function where the hard work is done. The code here is
994 * very sensitive to small changes :) Note that part of the
995 * intelligence is also in Row::shortenIfNeeded.
997 bool TextMetrics::breakRow(Row & row, int const right_margin) const
999 LATTEST(row.empty());//
1000 Paragraph const & par = text_->getPar(row.pit());//
1001 Buffer const & buf = text_->inset().buffer();//
1002 BookmarksSection::BookmarkPosList bpl =//
1003 theSession().bookmarks().bookmarksInPar(buf.fileName(), par.id());//
1005 pos_type const end = par.size();//
1006 pos_type const pos = row.pos();
1007 pos_type const body_pos = par.beginOfBody();//
1008 bool const is_rtl = text_->isRTL(row.pit());
1009 bool need_new_row = false;
1011 row.left_margin = leftMargin(row.pit(), pos);
1012 row.right_margin = right_margin;
1014 swap(row.left_margin, row.right_margin);
1015 // Remember that the row width takes into account the left_margin
1016 // but not the right_margin.
1017 row.dim().wid = row.left_margin;
1018 // the width available for the row.
1019 int const width = max_width_ - row.right_margin;
1021 // check for possible inline completion
1022 DocIterator const & ic_it = bv_->inlineCompletionPos();//
1023 pos_type ic_pos = -1;//
1024 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == row.pit())//
1025 ic_pos = ic_it.pos();//
1027 // Now we iterate through until we reach the right margin
1028 // or the end of the par, then build a representation of the row.
1029 pos_type i = pos;//---------------------------------------------------vvv
1030 FontIterator fi = FontIterator(*this, par, row.pit(), pos);
1031 // The real stopping condition is a few lines below.
1033 // Firstly, check whether there is a bookmark here.
1034 if (lyxrc.bookmarks_visibility == LyXRC::BMK_INLINE)
1035 for (auto const & bp_p : bpl)
1036 if (bp_p.second == i) {
1038 f.fontInfo().setColor(Color_bookmark);
1039 // ❶ U+2776 DINGBAT NEGATIVE CIRCLED DIGIT ONE
1040 char_type const ch = 0x2775 + bp_p.first;
1041 row.addVirtual(i, docstring(1, ch), f, Change());
1044 // The stopping condition is here so that the display of a
1045 // bookmark can take place at paragraph start too.
1046 if (i >= end || (i != pos && row.width() > width))//^width
1049 char_type c = par.getChar(i);
1050 // The most special cases are handled first.
1051 if (par.isInset(i)) {
1052 Inset const * ins = par.getInset(i);
1053 Dimension dim = bv_->coordCache().insets().dim(ins);
1054 row.add(i, ins, dim, *fi, par.lookupChange(i));
1055 } else if (c == ' ' && i + 1 == body_pos) {
1056 // There is a space at i, but it should not be
1057 // added as a separator, because it is just
1058 // before body_pos. Instead, insert some spacing to
1060 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
1061 // this is needed to make sure that the row width is correct
1063 int const add = max(fm.width(par.layout().labelsep),
1064 labelEnd(row.pit()) - row.width());
1065 row.addSpace(i, add, *fi, par.lookupChange(i));
1066 } else if (c == '\t')
1067 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
1068 *fi, par.lookupChange(i));
1069 else if (c == 0x2028 || c == 0x2029) {
1071 * U+2028 LINE SEPARATOR
1072 * U+2029 PARAGRAPH SEPARATOR
1074 * These are special unicode characters that break
1075 * lines/pragraphs. Not handling them lead to trouble wrt
1076 * Qt QTextLayout formatting. We add a visible character
1077 * on screen so that the user can see that something is
1081 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
1082 // ¶ U+00B6 PILCROW SIGN
1083 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
1084 row.add(i, screen_char, *fi, par.lookupChange(i), i >= body_pos);
1086 row.add(i, c, *fi, par.lookupChange(i), i >= body_pos);
1088 // add inline completion width
1089 // draw logically behind the previous character
1090 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
1091 docstring const comp = bv_->inlineCompletion();
1092 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
1096 f.fontInfo().setColor(Color_inlinecompletion);
1097 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
1099 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
1100 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
1101 }//---------------------------------------------------------------^^^
1103 // FIXME: Handle when breaking the rows
1104 // Handle some situations that abruptly terminate the row
1105 // - Before an inset with BreakBefore
1106 // - After an inset with BreakAfter
1107 Inset const * prevInset = !row.empty() ? row.back().inset : 0;
1108 Inset const * nextInset = (i + 1 < end) ? par.getInset(i + 1) : 0;
1109 if ((nextInset && nextInset->rowFlags() & BreakBefore)
1110 || (prevInset && prevInset->rowFlags() & BreakAfter)) {
1112 // Force a row creation after this one if it is ended by
1113 // an inset that either
1114 // - has row flag RowAfter that enforces that;
1115 // - or (1) did force the row breaking, (2) is at end of
1116 // paragraph and (3) the said paragraph has an end label.
1117 need_new_row = prevInset &&
1118 (prevInset->rowFlags() & AlwaysBreakAfter
1119 || (prevInset->rowFlags() & BreakAfter && i + 1 == end
1120 && text_->getEndLabel(row.pit()) != END_LABEL_NO_LABEL));
1128 //--------------------------------------------------------------------vvv
1132 // End of paragraph marker. The logic here is almost the
1133 // same as in redoParagraph, remember keep them in sync.
1134 ParagraphList const & pars = text_->paragraphs();
1135 Change const & change = par.lookupChange(i);
1136 if ((lyxrc.paragraph_markers || change.changed())
1137 && !need_new_row // not this
1138 && i == end && size_type(row.pit() + 1) < pars.size()) {
1139 // add a virtual element for the end-of-paragraph
1140 // marker; it is shown on screen, but does not exist
1141 // in the paragraph.
1142 Font f(text_->layoutFont(row.pit()));
1143 f.fontInfo().setColor(Color_paragraphmarker);
1144 f.setLanguage(par.getParLanguage(buf.params()));
1145 // ¶ U+00B6 PILCROW SIGN
1146 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, change);
1149 // Is there a end-of-paragaph change?
1150 if (i == end && par.lookupChange(end).changed() && !need_new_row)
1151 row.needsChangeBar(true);
1152 //--------------------------------------------------------------------^^^
1153 // FIXME : nothing below this
1155 // if the row is too large, try to cut at last separator. In case
1156 // of success, reset indication that the row was broken abruptly.
1157 int const next_width = max_width_ - leftMargin(row.pit(), row.endpos())
1158 - rightMargin(row.pit());
1160 if (row.shortenIfNeeded(width, next_width))
1162 row.right_boundary(!row.empty() && row.endpos() < end
1163 && row.back().endpos == row.endpos());
1164 // Last row in paragraph is flushed
1165 if (row.endpos() == end)
1168 // make sure that the RTL elements are in reverse ordering
1169 row.reverseRTL(is_rtl);
1170 //LYXERR0("breakrow: row is " << row);
1172 return need_new_row;
1175 int TextMetrics::parTopSpacing(pit_type const pit) const
1177 Paragraph const & par = text_->getPar(pit);
1178 Layout const & layout = par.layout();
1181 ParagraphList const & pars = text_->paragraphs();
1182 double const dh = defaultRowHeight();
1184 BufferParams const & bparams = bv_->buffer().params();
1185 Inset const & inset = text_->inset();
1186 // some parskips VERY EASY IMPLEMENTATION
1187 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1188 && !inset.getLayout().parbreakIsNewline()
1189 && !par.layout().parbreak_is_newline
1191 && ((layout.isParagraph() && par.getDepth() == 0)
1192 || (pars[pit - 1].layout().isParagraph()
1193 && pars[pit - 1].getDepth() == 0))) {
1194 asc += bparams.getDefSkip().inPixels(*bv_);
1197 if (par.params().startOfAppendix())
1200 // special code for the top label
1201 if (layout.labelIsAbove()
1202 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1203 && !par.labelString().empty()) {
1204 FontInfo labelfont = text_->labelFont(par);
1205 FontMetrics const & lfm = theFontMetrics(labelfont);
1206 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1207 * text_->spacing(par)
1208 + (layout.topsep + layout.labelbottomsep) * dh);
1211 // Add the layout spaces, for example before and after
1212 // a section, or between the items of a itemize or enumerate
1215 pit_type prev = text_->depthHook(pit, par.getDepth());
1216 Paragraph const & prevpar = pars[prev];
1217 double layoutasc = 0;
1219 && prevpar.layout() == layout
1220 && prevpar.getDepth() == par.getDepth()
1221 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1222 layoutasc = layout.itemsep * dh;
1223 } else if (pit != 0 && layout.topsep > 0)
1224 layoutasc = layout.topsep * dh;
1226 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1228 prev = text_->outerHook(pit);
1229 if (prev != pit_type(pars.size())) {
1230 asc += int(pars[prev].layout().parsep * dh);
1231 } else if (pit != 0) {
1232 Paragraph const & prevpar2 = pars[pit - 1];
1233 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1234 asc += int(layout.parsep * dh);
1241 int TextMetrics::parBottomSpacing(pit_type const pit) const
1243 double layoutdesc = 0;
1244 ParagraphList const & pars = text_->paragraphs();
1245 double const dh = defaultRowHeight();
1247 // add the layout spaces, for example before and after
1248 // a section, or between the items of a itemize or enumerate
1250 pit_type nextpit = pit + 1;
1251 if (nextpit != pit_type(pars.size())) {
1252 pit_type cpit = pit;
1254 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1255 double usual = pars[cpit].layout().bottomsep * dh;
1257 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1258 if (pars[cpit].layout() != pars[nextpit].layout()
1259 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1260 unusual = pars[cpit].layout().bottomsep * dh;
1261 layoutdesc = max(unusual, usual);
1262 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1263 if (pars[cpit].layout() != pars[nextpit].layout()
1264 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1265 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1269 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1273 void TextMetrics::setRowHeight(Row & row) const
1275 Paragraph const & par = text_->getPar(row.pit());
1276 Layout const & layout = par.layout();
1277 double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1279 // Initial value for ascent (useful if row is empty).
1280 Font const font = displayFont(row.pit(), row.pos());
1281 FontMetrics const & fm = theFontMetrics(font);
1282 int maxasc = int(fm.maxAscent() * spacing_val);
1283 int maxdes = int(fm.maxDescent() * spacing_val);
1285 // Take label string into account (useful if labelfont is large)
1286 if (row.pos() == 0 && layout.labelIsInline()) {
1287 FontInfo const labelfont = text_->labelFont(par);
1288 FontMetrics const & lfm = theFontMetrics(labelfont);
1289 maxasc = max(maxasc, int(lfm.maxAscent() * spacing_val));
1290 maxdes = max(maxdes, int(lfm.maxDescent() * spacing_val));
1293 // Find the ascent/descent of the row contents
1294 for (Row::Element const & e : row) {
1296 maxasc = max(maxasc, e.dim.ascent());
1297 maxdes = max(maxdes, e.dim.descent());
1299 FontMetrics const & fm2 = theFontMetrics(e.font);
1300 maxasc = max(maxasc, int(fm2.maxAscent() * spacing_val));
1301 maxdes = max(maxdes, int(fm2.maxDescent() * spacing_val));
1305 // This is nicer with box insets
1309 row.dim().asc = maxasc;
1310 row.dim().des = maxdes;
1312 // This is useful for selections
1313 row.contents_dim() = row.dim();
1317 // x is an absolute screen coord
1318 // returns the column near the specified x-coordinate of the row
1319 // x is set to the real beginning of this column
1320 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1321 bool & boundary) const
1323 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1324 /// For the main Text, it is possible that this pit is not
1325 /// yet in the CoordCache when moving cursor up.
1326 /// x Paragraph coordinate is always 0 for main text anyway.
1327 int const xo = origin_.x_;
1330 // Adapt to cursor row scroll offset if applicable.
1331 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1334 pos_type pos = row.pos();
1337 x = row.left_margin;
1338 else if (x <= row.left_margin) {
1339 pos = row.front().left_pos();
1340 x = row.left_margin;
1341 } else if (x >= row.width()) {
1342 pos = row.back().right_pos();
1345 double w = row.left_margin;
1346 Row::const_iterator cit = row.begin();
1347 Row::const_iterator cend = row.end();
1348 for ( ; cit != cend; ++cit) {
1349 if (w <= x && w + cit->full_width() > x) {
1350 int x_offset = int(x - w);
1351 pos = cit->x2pos(x_offset);
1352 x = int(x_offset + w);
1355 w += cit->full_width();
1357 if (cit == row.end()) {
1358 pos = row.back().right_pos();
1361 /** This tests for the case where the cursor is placed
1362 * just before a font direction change. See comment on
1363 * the boundary_ member in DocIterator.h to understand
1364 * how boundary helps here.
1366 else if (pos == cit->endpos
1367 && ((!cit->isRTL() && cit + 1 != row.end()
1368 && (cit + 1)->isRTL())
1369 || (cit->isRTL() && cit != row.begin()
1370 && !(cit - 1)->isRTL())))
1374 /** This tests for the case where the cursor is set at the end
1375 * of a row which has been broken due something else than a
1376 * separator (a display inset or a forced breaking of the
1377 * row). We know that there is a separator when the end of the
1378 * row is larger than the end of its last element.
1380 if (!row.empty() && pos == row.back().endpos
1381 && row.back().endpos == row.endpos()) {
1382 Inset const * inset = row.back().inset;
1383 if (inset && (inset->lyxCode() == NEWLINE_CODE
1384 || inset->lyxCode() == SEPARATOR_CODE))
1385 pos = row.back().pos;
1387 boundary = row.right_boundary();
1391 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1397 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1399 // We play safe and use parMetrics(pit) to make sure the
1400 // ParagraphMetrics will be redone and OK to use if needed.
1401 // Otherwise we would use an empty ParagraphMetrics in
1402 // upDownInText() while in selection mode.
1403 ParagraphMetrics const & pm = parMetrics(pit);
1405 LBUFERR(row < int(pm.rows().size()));
1407 Row const & r = pm.rows()[row];
1408 return getPosNearX(r, x, bound);
1412 // y is screen coordinate
1413 pit_type TextMetrics::getPitNearY(int y)
1415 LASSERT(!text_->paragraphs().empty(), return -1);
1416 LASSERT(!par_metrics_.empty(), return -1);
1417 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1419 // look for highest numbered paragraph with y coordinate less than given y
1422 ParMetricsCache::const_iterator it = par_metrics_.begin();
1423 ParMetricsCache::const_iterator et = par_metrics_.end();
1424 ParMetricsCache::const_iterator last = et;
1427 ParagraphMetrics const & pm = it->second;
1429 if (y < it->second.position() - pm.ascent()) {
1430 // We are looking for a position that is before the first paragraph in
1431 // the cache (which is in priciple off-screen, that is before the
1434 // We are already at the first paragraph in the inset.
1436 // OK, this is the paragraph we are looking for.
1437 pit = it->first - 1;
1442 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1444 if (y >= last->second.position() + pm_last.descent()) {
1445 // We are looking for a position that is after the last paragraph in
1446 // the cache (which is in priciple off-screen), that is before the
1448 pit = last->first + 1;
1449 if (pit == int(text_->paragraphs().size()))
1450 // We are already at the last paragraph in the inset.
1452 // OK, this is the paragraph we are looking for.
1453 newParMetricsDown();
1457 for (; it != et; ++it) {
1458 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1459 << " y: " << it->second.position());
1461 ParagraphMetrics const & pm2 = par_metrics_[it->first];
1463 if (it->first >= pit && it->second.position() - pm2.ascent() <= y) {
1465 yy = it->second.position();
1469 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1475 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1476 bool assert_in_view, bool up)
1478 ParagraphMetrics const & pm = par_metrics_[pit];
1480 int yy = pm.position() - pm.ascent();
1481 LBUFERR(!pm.rows().empty());
1482 RowList::const_iterator rit = pm.rows().begin();
1483 RowList::const_iterator rlast = pm.rows().end();
1485 for (; rit != rlast; yy += rit->height(), ++rit)
1486 if (yy + rit->height() > y)
1489 if (assert_in_view) {
1490 if (!up && yy + rit->height() > y) {
1491 if (rit != pm.rows().begin()) {
1494 } else if (pit != 0) {
1497 ParagraphMetrics const & pm2 = par_metrics_[pit];
1498 rit = pm2.rows().end();
1502 } else if (up && yy != y) {
1504 y = yy + rit->height();
1506 } else if (pit < int(text_->paragraphs().size()) - 1) {
1508 newParMetricsDown();
1509 ParagraphMetrics const & pm2 = par_metrics_[pit];
1510 rit = pm2.rows().begin();
1519 // x,y are absolute screen coordinates
1520 // sets cursor recursively descending into nested editable insets
1521 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1522 bool assert_in_view, bool up)
1524 if (lyxerr.debugging(Debug::WORKAREA)) {
1525 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1526 cur.bv().coordCache().dump();
1528 pit_type pit = getPitNearY(y);
1529 LASSERT(pit != -1, return 0);
1530 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1533 // Do we cover an inset?
1534 InsetList::Element * e = checkInsetHit(pit, x, y);
1537 // No inset, set position in the text
1538 bool bound = false; // is modified by getPosNearX
1539 cur.pos() = getPosNearX(row, x, bound);
1540 cur.boundary(bound);
1541 cur.setCurrentFont();
1546 Inset * inset = e->inset;
1547 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1549 // Set position in front of inset
1551 cur.boundary(false);
1554 // Try to descend recursively inside the inset.
1555 Inset * edited = inset->editXY(cur, x, y);
1556 // FIXME: it is not clear that the test on position is needed
1557 // Remove it if/when semantics of editXY is clarified
1558 if (cur.text() == text_ && cur.pos() == e->pos) {
1559 // non-editable inset, set cursor after the inset if x is
1560 // nearer to that position (bug 9628)
1561 bool bound = false; // is modified by getPosNearX
1562 cur.pos() = getPosNearX(row, x, bound);
1563 cur.boundary(bound);
1564 cur.setCurrentFont();
1568 if (cur.top().text() == text_)
1569 cur.setCurrentFont();
1574 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1576 LASSERT(text_ == cur.text(), return);
1577 pit_type const pit = getPitNearY(y);
1578 LASSERT(pit != -1, return);
1580 ParagraphMetrics const & pm = par_metrics_[pit];
1582 int yy = pm.position() - pm.rows().front().ascent();
1583 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1584 " pit: " << pit << " yy: " << yy);
1587 LBUFERR(pm.rows().size());
1588 for (; r < int(pm.rows().size()) - 1; ++r) {
1589 Row const & row = pm.rows()[r];
1590 if (yy + row.height() > y)
1595 Row const & row = pm.rows()[r];
1597 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1601 pos_type const pos = getPosNearX(row, xx, bound);
1603 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1605 text_->setCursor(cur, pit, pos, true, bound);
1606 // remember new position.
1611 //takes screen x,y coordinates
1612 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1614 Paragraph const & par = text_->paragraphs()[pit];
1615 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1617 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1619 for (InsetList::Element const & e : par.insetList()) {
1620 LYXERR(Debug::DEBUG, "examining inset " << e.inset);
1622 if (insetCache.covers(e.inset, x, y)) {
1623 LYXERR(Debug::DEBUG, "Hit inset: " << e.inset);
1624 return const_cast<InsetList::Element *>(&e);
1628 LYXERR(Debug::DEBUG, "No inset hit. ");
1633 //takes screen x,y coordinates
1634 Inset * TextMetrics::checkInsetHit(int x, int y)
1636 pit_type const pit = getPitNearY(y);
1637 LASSERT(pit != -1, return 0);
1638 InsetList::Element * e = checkInsetHit(pit, x, y);
1647 int TextMetrics::cursorX(CursorSlice const & sl,
1648 bool boundary) const
1650 LASSERT(sl.text() == text_, return 0);
1652 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1653 if (pm.rows().empty())
1655 Row const & row = pm.getRow(sl.pos(), boundary);
1656 pos_type const pos = sl.pos();
1659 row.findElement(pos, boundary, x);
1665 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1667 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1668 ParagraphMetrics const & pm = parMetrics(sl.pit());
1669 if (pm.rows().empty())
1673 h -= parMetrics(0).rows()[0].ascent();
1674 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1675 h += parMetrics(pit).height();
1678 if (pos && boundary)
1680 size_t const rend = pm.pos2row(pos);
1681 for (size_t rit = 0; rit != rend; ++rit)
1682 h += pm.rows()[rit].height();
1683 h += pm.rows()[rend].ascent();
1688 // the cursor set functions have a special mechanism. When they
1689 // realize you left an empty paragraph, they will delete it.
1691 bool TextMetrics::cursorHome(Cursor & cur)
1693 LASSERT(text_ == cur.text(), return false);
1694 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1695 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1696 return text_->setCursor(cur, cur.pit(), row.pos());
1700 bool TextMetrics::cursorEnd(Cursor & cur)
1702 LASSERT(text_ == cur.text(), return false);
1703 // if not on the last row of the par, put the cursor before
1704 // the final space exept if I have a spanning inset or one string
1705 // is so long that we force a break.
1706 pos_type end = cur.textRow().endpos();
1708 // empty text, end-1 is no valid position
1710 bool boundary = false;
1711 if (end != cur.lastpos()) {
1712 if (!cur.paragraph().isLineSeparator(end-1)
1713 && !cur.paragraph().isNewline(end-1)
1714 && !cur.paragraph().isEnvSeparator(end-1))
1718 } else if (cur.paragraph().isEnvSeparator(end-1))
1720 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1724 void TextMetrics::deleteLineForward(Cursor & cur)
1726 LASSERT(text_ == cur.text(), return);
1727 if (cur.lastpos() == 0) {
1728 // Paragraph is empty, so we just go forward
1729 text_->cursorForward(cur);
1732 cur.selection(true); // to avoid deletion
1735 // What is this test for ??? (JMarc)
1736 if (!cur.selection())
1737 text_->deleteWordForward(cur);
1739 cap::cutSelection(cur, false);
1740 cur.checkBufferStructure();
1745 int TextMetrics::leftMargin(pit_type pit) const
1747 // FIXME: what is the semantics? It depends on whether the
1748 // paragraph is empty!
1749 return leftMargin(pit, text_->paragraphs()[pit].size());
1753 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1755 ParagraphList const & pars = text_->paragraphs();
1757 LASSERT(pit >= 0, return 0);
1758 LASSERT(pit < int(pars.size()), return 0);
1759 Paragraph const & par = pars[pit];
1760 LASSERT(pos >= 0, return 0);
1761 // We do not really care whether pos > par.size(), since we do not
1762 // access the data. It can be actually useful, when querying the
1763 // margin without indentation (see leftMargin(pit_type).
1765 Buffer const & buffer = bv_->buffer();
1766 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1767 DocumentClass const & tclass = buffer.params().documentClass();
1768 Layout const & layout = par.layout();
1769 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1771 docstring parindent = layout.parindent;
1775 if (text_->isMainText()) {
1776 l_margin += bv_->leftMargin();
1777 l_margin += bfm.signedWidth(tclass.leftmargin());
1780 int depth = par.getDepth();
1782 // find the next level paragraph
1783 pit_type newpar = text_->outerHook(pit);
1784 if (newpar != pit_type(pars.size())) {
1785 if (pars[newpar].layout().isEnvironment()) {
1786 int nestmargin = depth * nestMargin();
1787 if (text_->isMainText())
1788 nestmargin += changebarMargin();
1789 l_margin = max(leftMargin(newpar), nestmargin);
1790 // Remove the parindent that has been added
1791 // if the paragraph was empty.
1792 if (pars[newpar].empty() &&
1793 buffer.params().paragraph_separation ==
1794 BufferParams::ParagraphIndentSeparation) {
1795 docstring pi = pars[newpar].layout().parindent;
1796 l_margin -= bfm.signedWidth(pi);
1799 if (tclass.isDefaultLayout(par.layout())
1800 || tclass.isPlainLayout(par.layout())) {
1801 if (pars[newpar].params().noindent())
1804 parindent = pars[newpar].layout().parindent;
1809 // This happens after sections or environments in standard classes.
1810 // We have to check the previous layout at same depth.
1811 if (buffer.params().paragraph_separation ==
1812 BufferParams::ParagraphSkipSeparation)
1814 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1815 pit_type prev = text_->depthHook(pit, par.getDepth());
1816 if (par.layout() == pars[prev].layout()) {
1818 && pars[pit - 1].layout().nextnoindent)
1820 } else if (pars[prev].layout().nextnoindent)
1824 FontInfo const labelfont = text_->labelFont(par);
1825 FontMetrics const & lfm = theFontMetrics(labelfont);
1827 switch (layout.margintype) {
1828 case MARGIN_DYNAMIC:
1829 if (!layout.leftmargin.empty()) {
1830 l_margin += bfm.signedWidth(layout.leftmargin);
1832 if (!par.labelString().empty()) {
1833 l_margin += lfm.signedWidth(layout.labelindent);
1834 l_margin += lfm.width(par.labelString());
1835 l_margin += lfm.width(layout.labelsep);
1839 case MARGIN_MANUAL: {
1840 l_margin += lfm.signedWidth(layout.labelindent);
1841 // The width of an empty par, even with manual label, should be 0
1842 if (!par.empty() && pos >= par.beginOfBody()) {
1843 if (!par.getLabelWidthString().empty()) {
1844 docstring labstr = par.getLabelWidthString();
1845 l_margin += lfm.width(labstr);
1846 l_margin += lfm.width(layout.labelsep);
1852 case MARGIN_STATIC: {
1853 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1854 / (par.getDepth() + 4);
1858 case MARGIN_FIRST_DYNAMIC:
1859 if (layout.labeltype == LABEL_MANUAL) {
1860 // if we are at position 0, we are never in the body
1861 if (pos > 0 && pos >= par.beginOfBody())
1862 l_margin += lfm.signedWidth(layout.leftmargin);
1864 l_margin += lfm.signedWidth(layout.labelindent);
1866 // Special case to fix problems with
1868 || (layout.labeltype == LABEL_STATIC
1869 && layout.latextype == LATEX_ENVIRONMENT
1870 && !text_->isFirstInSequence(pit))) {
1871 l_margin += lfm.signedWidth(layout.leftmargin);
1872 } else if (!layout.labelIsAbove()) {
1873 l_margin += lfm.signedWidth(layout.labelindent);
1874 l_margin += lfm.width(layout.labelsep);
1875 l_margin += lfm.width(par.labelString());
1879 case MARGIN_RIGHT_ADDRESS_BOX:
1880 // This is handled globally in redoParagraph().
1884 if (!par.params().leftIndent().zero())
1885 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1887 LyXAlignment align = par.getAlign(bv_->buffer().params());
1889 // set the correct parindent
1891 && (layout.labeltype == LABEL_NO_LABEL
1892 || layout.labeltype == LABEL_ABOVE
1893 || layout.labeltype == LABEL_CENTERED
1894 || (layout.labeltype == LABEL_STATIC
1895 && layout.latextype == LATEX_ENVIRONMENT
1896 && !text_->isFirstInSequence(pit)))
1897 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1898 && !par.params().noindent()
1899 // in some insets, paragraphs are never indented
1900 && !text_->inset().neverIndent()
1901 // display style insets do not need indentation
1904 && par.getInset(0)->rowFlags() & Display)
1905 && (!(tclass.isDefaultLayout(par.layout())
1906 || tclass.isPlainLayout(par.layout()))
1907 || buffer.params().paragraph_separation
1908 == BufferParams::ParagraphIndentSeparation)) {
1909 /* use the parindent of the layout when the default
1910 * indentation is used otherwise use the indentation set in
1911 * the document settings
1913 if (buffer.params().getParIndent().empty())
1914 l_margin += bfm.signedWidth(parindent);
1916 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1923 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1925 if (par_metrics_.empty())
1931 y -= par_metrics_.begin()->second.ascent();
1932 for (auto & pm_pair : par_metrics_) {
1933 pit_type const pit = pm_pair.first;
1934 ParagraphMetrics & pm = pm_pair.second;
1936 // Save the paragraph position in the cache.
1938 drawParagraph(pi, pit, x, y);
1944 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1946 ParagraphMetrics const & pm = par_metrics_[pit];
1947 if (pm.rows().empty())
1949 size_t const nrows = pm.rows().size();
1950 // Remember left and right margin for drawing math numbers
1951 Changer changeleft = changeVar(pi.leftx, x + leftMargin(pit));
1952 Changer changeright = changeVar(pi.rightx, x + width() - rightMargin(pit));
1954 // Use fast lane in nodraw stage.
1955 if (pi.pain.isNull()) {
1956 for (size_t i = 0; i != nrows; ++i) {
1958 Row const & row = pm.rows()[i];
1959 // Adapt to cursor row scroll offset if applicable.
1960 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1964 RowPainter rp(pi, *text_, row, row_x, y);
1966 rp.paintOnlyInsets();
1972 int const ww = bv_->workHeight();
1973 Cursor const & cur = bv_->cursor();
1974 DocIterator sel_beg = cur.selectionBegin();
1975 DocIterator sel_end = cur.selectionEnd();
1976 bool selection = cur.selection()
1977 // This is our text.
1978 && cur.text() == text_
1979 // if the anchor is outside, this is not our selection
1980 && cur.normalAnchor().text() == text_
1981 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1983 // We store the begin and end pos of the selection relative to this par
1984 DocIterator sel_beg_par = cur.selectionBegin();
1985 DocIterator sel_end_par = cur.selectionEnd();
1987 // We care only about visible selection.
1989 if (pit != sel_beg.pit()) {
1990 sel_beg_par.pit() = pit;
1991 sel_beg_par.pos() = 0;
1993 if (pit != sel_end.pit()) {
1994 sel_end_par.pit() = pit;
1995 sel_end_par.pos() = sel_end_par.lastpos();
1999 if (text_->isRTL(pit))
2000 swap(pi.leftx, pi.rightx);
2002 BookmarksSection::BookmarkPosList bpl =
2003 theSession().bookmarks().bookmarksInPar(bv_->buffer().fileName(), pm.par().id());
2005 for (size_t i = 0; i != nrows; ++i) {
2007 Row const & row = pm.rows()[i];
2008 // Adapt to cursor row scroll offset if applicable.
2009 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
2013 // It is not needed to draw on screen if we are not inside.
2014 bool const inside = (y + row.descent() >= 0
2015 && y - row.ascent() < ww);
2017 // Inset positions have already been set in nodraw stage.
2023 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2025 row.clearSelectionAndMargins();
2027 // The row knows nothing about the paragraph, so we have to check
2028 // whether this row is the first or last and update the margins.
2029 if (row.selection()) {
2030 if (row.sel_beg == 0)
2031 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
2032 if (row.sel_end == sel_end_par.lastpos())
2033 row.change(row.end_margin_sel, sel_end.pit() > pit);
2036 // Take this opportunity to spellcheck the row contents.
2037 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
2038 text_->getPar(pit).spellCheck();
2041 RowPainter rp(pi, *text_, row, row_x, y);
2043 // Don't paint the row if a full repaint has not been requested
2044 // and if it has not changed.
2045 if (!pi.full_repaint && !row.changed()) {
2046 // Paint only the insets if the text itself is
2048 rp.paintOnlyInsets();
2049 rp.paintTooLargeMarks(
2050 row_x + row.left_x() < bv_->leftMargin(),
2051 row_x + row.right_x() > bv_->workWidth() - bv_->rightMargin());
2057 // Clear background of this row if paragraph background was not
2058 // already cleared because of a full repaint.
2059 if (!pi.full_repaint && row.changed()) {
2060 LYXERR(Debug::PAINTING, "Clear rect@("
2061 << max(row_x, 0) << ", " << y - row.ascent() << ")="
2062 << width() << " x " << row.height());
2063 pi.pain.fillRectangle(row_x, y - row.ascent(),
2064 width(), row.height(), pi.background_color);
2067 // Instrumentation for testing row cache (see also
2069 if (lyxerr.debugging(Debug::PAINTING)
2070 && (row.selection() || pi.full_repaint || row.changed())) {
2071 string const foreword = text_->isMainText() ? "main text redraw "
2072 : "inset text redraw: ";
2073 LYXERR0(foreword << "pit=" << pit << " row=" << i
2074 << (row.selection() ? " row_selection": "")
2075 << (pi.full_repaint ? " full_repaint" : "")
2076 << (row.changed() ? " row.changed" : ""));
2079 // Backup full_repaint status and force full repaint
2080 // for inner insets as the Row has been cleared out.
2081 bool tmp = pi.full_repaint;
2082 pi.full_repaint = true;
2084 rp.paintSelection();
2087 if (row.needsChangeBar())
2088 rp.paintChangeBar();
2094 rp.paintTooLargeMarks(
2095 row_x + row.left_x() < bv_->leftMargin(),
2096 row_x + row.right_x() > bv_->workWidth() - bv_->rightMargin());
2097 // indicate bookmarks presence in margin
2098 if (lyxrc.bookmarks_visibility == LyXRC::BMK_MARGIN)
2099 for (auto const & bp_p : bpl)
2100 if (bp_p.second >= row.pos() && bp_p.second < row.endpos())
2101 rp.paintBookmark(bp_p.first);
2106 // This debug code shows on screen which rows are repainted.
2107 // FIXME: since the updates related to caret blinking restrict
2108 // the painter to a small rectangle, the numbers are not
2109 // updated when this happens. Change the code in
2110 // GuiWorkArea::Private::show/hideCaret if this is important.
2111 static int count = 0;
2113 FontInfo fi(sane_font);
2114 fi.setSize(TINY_SIZE);
2115 fi.setColor(Color_red);
2116 pi.pain.text(row_x, y, convert<docstring>(count), fi);
2119 // Restore full_repaint status.
2120 pi.full_repaint = tmp;
2125 //LYXERR(Debug::PAINTING, ".");
2129 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2130 Dimension & dim) const
2132 DocIterator from = cur.bv().cursor();
2133 DocIterator to = from;
2134 text_->getWord(from.top(), to.top(), PREVIOUS_WORD);
2136 // The vertical dimension of the word
2137 Font const font = displayFont(cur.pit(), from.pos());
2138 FontMetrics const & fm = theFontMetrics(font);
2139 // the +1's below are related to the extra pixels added in setRowHeight
2140 dim.asc = fm.maxAscent() + 1;
2141 dim.des = fm.maxDescent() + 1;
2143 // get position on screen of the word start and end
2144 //FIXME: Is it necessary to explicitly set this to false?
2145 from.boundary(false);
2146 Point lxy = cur.bv().getPos(from);
2147 Point rxy = cur.bv().getPos(to);
2148 dim.wid = abs(rxy.x_ - lxy.x_);
2150 // calculate position of word
2152 x = min(rxy.x_, lxy.x_);
2154 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2155 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2158 int defaultRowHeight()
2160 return int(theFontMetrics(sane_font).maxHeight() * 1.2);