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"
34 #include "TextClass.h"
37 #include "insets/InsetText.h"
39 #include "mathed/MacroTable.h"
41 #include "frontends/FontMetrics.h"
42 #include "frontends/NullPainter.h"
44 #include "support/debug.h"
45 #include "support/lassert.h"
46 #include "support/Changer.h"
56 using frontend::FontMetrics;
61 int numberOfLabelHfills(Paragraph const & par, Row const & row)
63 pos_type last = row.endpos() - 1;
64 pos_type first = row.pos();
66 // hfill *DO* count at the beginning of paragraphs!
68 while (first < last && par.isHfill(first))
72 last = min(last, par.beginOfBody());
74 for (pos_type p = first; p < last; ++p) {
81 // FIXME: this needs to be rewritten, probably by merging it into some
82 // code that, besides counting, sets the active status of the space
83 // inset in the row element.
84 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
85 pos_type const body_pos)
88 Row::const_iterator cit = row.begin();
89 Row::const_iterator const end = row.end();
90 for ( ; cit != end ; ++cit)
91 if (cit->pos >= body_pos
92 && cit->inset && pm.hfillExpansion(row, cit->pos))
100 /////////////////////////////////////////////////////////////////////
104 /////////////////////////////////////////////////////////////////////
107 TextMetrics::TextMetrics(BufferView * bv, Text * text)
108 : bv_(bv), text_(text)
111 max_width_ = bv_->workWidth();
112 dim_.wid = max_width_;
118 bool TextMetrics::contains(pit_type pit) const
120 return par_metrics_.find(pit) != par_metrics_.end();
124 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
126 ParMetricsCache::const_iterator it = par_metrics_.begin();
127 return make_pair(it->first, &it->second);
131 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
133 LBUFERR(!par_metrics_.empty());
134 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
135 return make_pair(it->first, &it->second);
139 bool TextMetrics::isLastRow(Row const & row) const
141 ParagraphList const & pars = text_->paragraphs();
142 return row.endpos() >= pars[row.pit()].size()
143 && row.pit() + 1 == pit_type(pars.size());
147 bool TextMetrics::isFirstRow(Row const & row) const
149 return row.pos() == 0 && row.pit() == 0;
153 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
155 for (auto & pm_pair : par_metrics_)
156 if (pm_pair.first == pit)
157 for (Row & row : pm_pair.second.rows())
158 if (row.pos() == pos)
163 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
165 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
166 if (pmc_it == par_metrics_.end()) {
167 pmc_it = par_metrics_.insert(
168 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
170 if (pmc_it->second.rows().empty() && redo)
172 return pmc_it->second;
176 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
178 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
182 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit)
184 return parMetrics(pit, true);
188 void TextMetrics::newParMetricsDown()
190 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
191 pit_type const pit = last.first + 1;
192 if (pit == int(text_->paragraphs().size()))
195 // do it and update its position.
197 par_metrics_[pit].setPosition(last.second.position()
198 + last.second.descent() + par_metrics_[pit].ascent());
203 void TextMetrics::newParMetricsUp()
205 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
206 if (first.first == 0)
209 pit_type const pit = first.first - 1;
210 // do it and update its position.
212 par_metrics_[pit].setPosition(first.second.position()
213 - first.second.ascent() - par_metrics_[pit].descent());
218 bool TextMetrics::metrics(MetricsInfo const & mi, Dimension & dim, int min_width,
219 bool const expand_on_multipars)
221 LBUFERR(mi.base.textwidth > 0);
222 max_width_ = mi.base.textwidth;
223 // backup old dimension.
224 Dimension const old_dim = dim_;
227 dim_.wid = min_width;
228 pit_type const npar = text_->paragraphs().size();
229 if (npar > 1 && expand_on_multipars)
230 // If there is more than one row, expand the text to
231 // the full allowable width.
232 dim_.wid = max_width_;
234 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
235 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
237 bool changed = false;
239 for (pit_type pit = 0; pit != npar; ++pit) {
240 // create rows, but do not set alignment yet
241 changed |= redoParagraph(pit, false);
242 ParagraphMetrics const & pm = par_metrics_[pit];
244 if (dim_.wid < pm.width())
245 dim_.wid = pm.width();
248 // Now set alignment for all rows (the width might not have been known before).
249 for (pit_type pit = 0; pit != npar; ++pit) {
250 ParagraphMetrics & pm = par_metrics_[pit];
251 for (Row & row : pm.rows())
252 setRowAlignment(row, dim_.wid);
255 dim_.asc = par_metrics_[0].ascent();
256 dim_.des = h - dim_.asc;
257 //lyxerr << "dim_.wid " << dim_.wid << endl;
258 //lyxerr << "dim_.asc " << dim_.asc << endl;
259 //lyxerr << "dim_.des " << dim_.des << endl;
261 changed |= dim_ != old_dim;
267 void TextMetrics::updatePosCache(pit_type pit) const
269 frontend::NullPainter np;
270 PainterInfo pi(bv_, np);
271 drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
275 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
277 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
281 int TextMetrics::rightMargin(pit_type const pit) const
283 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
287 void TextMetrics::applyOuterFont(Font & font) const
289 FontInfo lf(font_.fontInfo());
290 lf.reduce(bv_->buffer().params().getFont().fontInfo());
291 font.fontInfo().realize(lf);
295 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
297 LASSERT(pos >= 0, { static Font f; return f; });
299 ParagraphList const & pars = text_->paragraphs();
300 Paragraph const & par = pars[pit];
301 Layout const & layout = par.layout();
302 Buffer const & buffer = bv_->buffer();
304 BufferParams const & params = buffer.params();
305 pos_type const body_pos = par.beginOfBody();
307 // We specialize the 95% common case:
308 if (!par.getDepth()) {
309 Font f = par.getFontSettings(params, pos);
310 if (!text_->isMainText())
312 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
314 FontInfo const & lf = lab ? layout.labelfont : layout.font;
315 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
317 // In case the default family has been customized
318 if (lf.family() == INHERIT_FAMILY)
319 rlf.setFamily(params.getFont().fontInfo().family());
320 f.fontInfo().realize(rlf);
324 // The uncommon case need not be optimized as much
325 FontInfo const & layoutfont = pos < body_pos ?
326 layout.labelfont : layout.font;
328 Font font = par.getFontSettings(params, pos);
329 font.fontInfo().realize(layoutfont);
331 if (!text_->isMainText())
332 applyOuterFont(font);
334 // Realize against environment font information
335 // NOTE: the cast to pit_type should be removed when pit_type
336 // changes to a unsigned integer.
337 if (pit < pit_type(pars.size()))
338 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
340 // Realize with the fonts of lesser depth.
341 font.fontInfo().realize(params.getFont().fontInfo());
347 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
353 if (boundary && sl.pos() > 0)
356 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
360 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
362 // no RTL boundary at paragraph start
366 Font const & left_font = displayFont(pit, pos - 1);
368 return isRTLBoundary(pit, pos, left_font);
372 // isRTLBoundary returns false on a real end-of-line boundary,
373 // because otherwise the two boundary types get mixed up.
374 // This is the whole purpose of this being in TextMetrics.
375 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
376 Font const & font) const
378 if (// no RTL boundary at paragraph start
380 // if the metrics have not been calculated, then we are not
381 // on screen and can safely ignore issues about boundaries.
385 ParagraphMetrics const & pm = par_metrics_[pit];
386 // no RTL boundary in empty paragraph
387 if (pm.rows().empty())
390 pos_type const endpos = pm.getRow(pos - 1, false).endpos();
391 pos_type const startpos = pm.getRow(pos, false).pos();
392 // no RTL boundary at line start:
393 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
395 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
398 Paragraph const & par = text_->getPar(pit);
399 // no RTL boundary at line break:
400 // abc|\n -> move right -> abc\n (and not: abc\n|
402 if (startpos == pos && endpos == pos && endpos != par.size()
403 && (par.isNewline(pos - 1)
404 || par.isEnvSeparator(pos - 1)
405 || par.isLineSeparator(pos - 1)
406 || par.isSeparator(pos - 1)))
409 bool const left = font.isVisibleRightToLeft();
411 if (pos == par.size())
412 right = par.isRTL(bv_->buffer().params());
414 right = displayFont(pit, pos).isVisibleRightToLeft();
416 return left != right;
420 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
422 Paragraph & par = text_->getPar(pit);
423 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
424 // redoParagraph() recursively inside parMetrics.
425 Dimension old_dim = parMetrics(pit, false).dim();
426 ParagraphMetrics & pm = par_metrics_[pit];
429 Buffer & buffer = bv_->buffer();
430 bool changed = false;
432 // Check whether there are InsetBibItems that need fixing
433 // FIXME: This check ought to be done somewhere else. It is the reason
434 // why text_ is not const. But then, where else to do it?
435 // Well, how can you end up with either (a) a biblio environment that
436 // has no InsetBibitem, (b) a biblio environment with more than one
437 // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
438 // environment? I think the answer is: when paragraphs are merged;
439 // when layout is set; when material is pasted.
440 if (par.brokenBiblio()) {
441 Cursor & cur = const_cast<Cursor &>(bv_->cursor());
442 // In some cases, we do not know how to record undo
443 if (&cur.inset() == &text_->inset())
444 cur.recordUndo(pit, pit);
446 int const moveCursor = par.fixBiblio(buffer);
448 // Is it necessary to update the cursor?
449 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
452 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
457 // Optimisation: this is used in the next two loops
458 // so better to calculate that once here.
459 int const right_margin = rightMargin(pm);
461 // iterator pointing to paragraph to resolve macros
462 DocIterator parPos = text_->macrocontextPosition();
466 LYXERR(Debug::INFO, "MacroContext not initialised!"
467 << " Going through the buffer again and hope"
468 << " the context is better then.");
469 // FIXME audit updateBuffer calls
470 // This should not be here, but it is not clear yet where else it
472 bv_->buffer().updateBuffer();
473 parPos = text_->macrocontextPosition();
474 LBUFERR(!parPos.empty());
479 par.setBeginOfBody();
480 Font const bufferfont = buffer.params().getFont();
481 CoordCache::Insets & insetCache = bv_->coordCache().insets();
482 for (auto const & e : par.insetList()) {
483 // FIXME Doesn't this HAVE to be non-empty?
484 // position already initialized?
485 if (!parPos.empty()) {
486 parPos.pos() = e.pos;
488 // A macro template would normally not be visible
489 // by itself. But the tex macro semantics allow
490 // recursion, so we artifically take the context
491 // after the macro template to simulate this.
492 if (e.inset->lyxCode() == MATHMACRO_CODE)
496 // If there is an end of paragraph marker, its size should be
497 // substracted to the available width. The logic here is
498 // almost the same as in breakRow, remember keep them in sync.
500 if (lyxrc.paragraph_markers && e.pos + 1 == par.size()
501 && size_type(pit + 1) < text_->paragraphs().size()) {
502 Font f(text_->layoutFont(pit));
503 // ¶ U+00B6 PILCROW SIGN
504 eop = theFontMetrics(f).width(char_type(0x00B6));
507 // do the metric calculation
509 int const w = max_width_ - leftMargin(pit, e.pos)
510 - right_margin - eop;
511 Font const & font = e.inset->inheritFont() ?
512 displayFont(pit, e.pos) : bufferfont;
513 MacroContext mc(&buffer, parPos);
514 MetricsInfo mi(bv_, font.fontInfo(), w, mc, e.pos == 0);
515 e.inset->metrics(mi, dim);
516 if (!insetCache.has(e.inset) || insetCache.dim(e.inset) != dim) {
517 insetCache.add(e.inset, dim);
523 size_t row_index = 0;
524 bool need_new_row = false;
525 // maximum pixel width of a row
527 if (row_index == pm.rows().size())
528 pm.rows().push_back(Row());
530 pm.rows()[row_index] = Row();
531 Row & row = pm.rows()[row_index];
534 need_new_row = breakRow(row, right_margin);
537 if ((row_index || row.endpos() < par.size() || row.right_boundary())
538 && par.inInset().lyxCode() != CELL_CODE) {
539 /* If there is more than one row or the row has been
540 * broken by a display inset or a newline, expand the text
541 * to the full allowable width. This setting here is
542 * needed for the setRowAlignment() below.
543 * We do nothing when inside a table cell.
545 if (dim_.wid < max_width_)
546 dim_.wid = max_width_;
549 setRowAlignment(row, max(dim_.wid, row.width()));
550 first = row.endpos();
553 pm.dim().wid = max(pm.dim().wid, row.width() + row.right_margin);
554 pm.dim().des += row.height();
555 } while (first < par.size() || need_new_row);
557 if (row_index < pm.rows().size())
558 pm.rows().resize(row_index);
560 // This type of margin can only be handled at the global paragraph level
561 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX) {
563 if (par.isRTL(buffer.params())) {
564 // globally align the paragraph to the left.
565 int minleft = max_width_;
566 for (Row const & row : pm.rows())
567 minleft = min(minleft, row.left_margin);
568 offset = right_margin - minleft;
570 // globally align the paragraph to the right.
572 for (Row const & row : pm.rows())
573 maxwid = max(maxwid, row.width());
574 offset = max_width_ - right_margin - maxwid;
577 for (Row & row : pm.rows()) {
578 row.left_margin += offset;
579 row.dim().wid += offset;
583 // The space above and below the paragraph.
584 int top = parTopSpacing(pit);
585 int bottom = parBottomSpacing(pit);
587 // Top and bottom margin of the document (only at top-level)
588 // FIXME: It might be better to move this in another method
589 // specially tailored for the main text.
590 if (text_->isMainText()) {
592 top += bv_->topMargin();
593 if (pit + 1 == pit_type(text_->paragraphs().size())) {
594 bottom += bv_->bottomMargin();
598 // Add the top/bottom space to rows and paragraph metrics
599 pm.rows().front().dim().asc += top;
600 pm.rows().back().dim().des += bottom;
601 pm.dim().des += top + bottom;
603 // Move the pm ascent to be the same as the first row ascent
604 pm.dim().asc += pm.rows().front().ascent();
605 pm.dim().des -= pm.rows().front().ascent();
607 changed |= old_dim.height() != pm.dim().height();
613 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
615 LyXAlignment align = par.getAlign(bv_->buffer().params());
617 // handle alignment inside tabular cells
618 Inset const & owner = text_->inset();
619 bool forced_block = false;
620 switch (owner.contentAlignment()) {
621 case LYX_ALIGN_BLOCK:
622 // In general block align is the default state, but here it is
623 // an explicit choice. Therefore it should not be overridden
627 case LYX_ALIGN_CENTER:
629 case LYX_ALIGN_RIGHT:
630 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
631 align = owner.contentAlignment();
634 // unchanged (use align)
638 // Display-style insets should always be on a centered row
639 if (Inset const * inset = par.getInset(row.pos())) {
640 if (inset->rowFlags() & Inset::Display) {
641 if (inset->rowFlags() & Inset::AlignLeft)
642 align = LYX_ALIGN_BLOCK;
643 else if (inset->rowFlags() & Inset::AlignRight)
644 align = LYX_ALIGN_RIGHT;
646 align = LYX_ALIGN_CENTER;
650 if (align == LYX_ALIGN_BLOCK) {
651 // If this row has been broken abruptly by a display inset, or
652 // it is the end of the paragraph, or the user requested we
653 // not justify stuff, then don't stretch.
654 // A forced block alignment can only be overridden the 'no
655 // justification on screen' setting.
656 if ((row.flushed() && !forced_block)
657 || !bv_->buffer().params().justification)
658 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
665 void TextMetrics::setRowAlignment(Row & row, int width) const
670 Paragraph const & par = text_->getPar(row.pit());
672 int const w = width - row.right_margin - row.width();
673 // FIXME: put back this assertion when the crash on new doc is solved.
674 //LASSERT(w >= 0, /**/);
676 // is there a manual margin with a manual label
677 Layout const & layout = par.layout();
680 if (layout.margintype == MARGIN_MANUAL
681 && layout.labeltype == LABEL_MANUAL) {
682 /// We might have real hfills in the label part
683 nlh = numberOfLabelHfills(par, row);
685 // A manual label par (e.g. List) has an auto-hfill
686 // between the label text and the body of the
688 // But we don't want to do this auto hfill if the par
693 if (nlh && !par.getLabelWidthString().empty())
694 row.label_hfill = labelFill(row) / double(nlh);
697 // are there any hfills in the row?
698 ParagraphMetrics const & pm = par_metrics_[row.pit()];
699 int nh = numberOfHfills(row, pm, par.beginOfBody());
703 // We don't have to look at the alignment if the row is already
704 // larger then the permitted width as then we force the
705 // LEFT_ALIGN'edness!
706 if (int(row.width()) >= max_width_)
710 // Common case : there is no hfill, and the alignment will be
712 switch (getAlign(par, row)) {
713 case LYX_ALIGN_BLOCK:
714 // Expand expanding characters by a total of w
715 if (!row.setExtraWidth(w) && row.isRTL()) {
716 // Justification failed and the text is RTL: align to the right
717 row.left_margin += w;
722 // a displayed inset that is flushed
723 if (Inset const * inset = par.getInset(row.pos())) {
724 row.left_margin += inset->indent(*bv_);
725 row.dim().wid += inset->indent(*bv_);
728 case LYX_ALIGN_RIGHT:
729 if (Inset const * inset = par.getInset(row.pos())) {
730 int const new_w = max(w - inset->indent(*bv_), 0);
731 row.left_margin += new_w;
732 row.dim().wid += new_w;
734 row.left_margin += w;
738 case LYX_ALIGN_CENTER:
739 row.dim().wid += w / 2;
740 row.left_margin += w / 2;
743 case LYX_ALIGN_LAYOUT:
744 case LYX_ALIGN_SPECIAL:
745 case LYX_ALIGN_DECIMAL:
751 // Case nh > 0. There are hfill separators.
755 // Set size of hfill insets
756 pos_type const endpos = row.endpos();
757 pos_type body_pos = par.beginOfBody();
759 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
762 CoordCache::Insets & insetCache = bv_->coordCache().insets();
763 for (Row::Element & e : row) {
764 if (row.label_hfill && e.endpos == body_pos
765 && e.type == Row::SPACE)
766 e.dim.wid -= int(row.label_hfill * (nlh - 1));
767 if (e.inset && pm.hfillExpansion(row, e.pos)) {
768 if (e.pos >= body_pos) {
772 e.dim.wid += hfill_rem;
774 e.dim.wid += int(row.label_hfill);
775 // Cache the inset dimension.
776 insetCache.add(e.inset, e.dim);
782 int TextMetrics::labelFill(Row const & row) const
784 Paragraph const & par = text_->getPar(row.pit());
785 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
788 // iterate over elements before main body (except the last one,
789 // which is extra space).
790 for (Row::Element const & e : row) {
791 if (e.endpos >= par.beginOfBody())
796 docstring const & label = par.params().labelWidthString();
800 FontMetrics const & fm
801 = theFontMetrics(text_->labelFont(par));
803 return max(0, fm.width(label) - w);
807 int TextMetrics::labelEnd(pit_type const pit) const
809 // labelEnd is only needed if the layout fills a flushleft label.
810 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
812 // return the beginning of the body
813 return leftMargin(pit);
819 * Calling Text::getFont is slow. While rebreaking we scan a
820 * paragraph from left to right calling getFont for every char. This
821 * simple class address this problem by hidding an optimization trick
822 * (not mine btw -AB): the font is reused in the whole font span. The
823 * class handles transparently the "hidden" (not part of the fontlist)
824 * label font (as getFont does).
830 FontIterator(TextMetrics const & tm,
831 Paragraph const & par, pit_type pit, pos_type pos)
832 : tm_(tm), par_(par), pit_(pit), pos_(pos),
833 font_(tm.displayFont(pit, pos)),
834 endspan_(par.fontSpan(pos).last),
835 bodypos_(par.beginOfBody())
839 Font const & operator*() const { return font_; }
842 FontIterator & operator++()
845 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
846 font_ = tm_.displayFont(pit_, pos_);
847 endspan_ = par_.fontSpan(pos_).last;
853 Font * operator->() { return &font_; }
857 TextMetrics const & tm_;
859 Paragraph const & par_;
874 /** This is the function where the hard work is done. The code here is
875 * very sensitive to small changes :) Note that part of the
876 * intelligence is also in Row::shortenIfNeeded.
878 bool TextMetrics::breakRow(Row & row, int const right_margin) const
880 LATTEST(row.empty());
881 Paragraph const & par = text_->getPar(row.pit());
882 pos_type const end = par.size();
883 pos_type const pos = row.pos();
884 pos_type const body_pos = par.beginOfBody();
885 bool const is_rtl = text_->isRTL(row.pit());
886 bool need_new_row = false;
888 row.left_margin = leftMargin(row.pit(), pos);
889 row.right_margin = right_margin;
891 swap(row.left_margin, row.right_margin);
892 // Remember that the row width takes into account the left_margin
893 // but not the right_margin.
894 row.dim().wid = row.left_margin;
895 // the width available for the row.
896 int const width = max_width_ - row.right_margin;
898 // check for possible inline completion
899 DocIterator const & ic_it = bv_->inlineCompletionPos();
900 pos_type ic_pos = -1;
901 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == row.pit())
902 ic_pos = ic_it.pos();
904 // Now we iterate through until we reach the right margin
905 // or the end of the par, then build a representation of the row.
907 FontIterator fi = FontIterator(*this, par, row.pit(), pos);
908 while (i < end && (i == pos || row.width() <= width)) {
909 char_type c = par.getChar(i);
910 // The most special cases are handled first.
911 if (par.isInset(i)) {
912 Inset const * ins = par.getInset(i);
913 Dimension dim = bv_->coordCache().insets().dim(ins);
914 row.add(i, ins, dim, *fi, par.lookupChange(i));
915 } else if (c == ' ' && i + 1 == body_pos) {
916 // There is a space at i, but it should not be
917 // added as a separator, because it is just
918 // before body_pos. Instead, insert some spacing to
920 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
921 // this is needed to make sure that the row width is correct
923 int const add = max(fm.width(par.layout().labelsep),
924 labelEnd(row.pit()) - row.width());
925 row.addSpace(i, add, *fi, par.lookupChange(i));
926 } else if (c == '\t')
927 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
928 *fi, par.lookupChange(i));
929 else if (c == 0x2028 || c == 0x2029) {
931 * U+2028 LINE SEPARATOR
932 * U+2029 PARAGRAPH SEPARATOR
934 * These are special unicode characters that break
935 * lines/pragraphs. Not handling them lead to trouble wrt
936 * Qt QTextLayout formatting. We add a visible character
937 * on screen so that the user can see that something is
941 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
942 // ¶ U+00B6 PILCROW SIGN
943 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
944 row.add(i, screen_char, *fi, par.lookupChange(i));
946 row.add(i, c, *fi, par.lookupChange(i));
948 // add inline completion width
949 // draw logically behind the previous character
950 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
951 docstring const comp = bv_->inlineCompletion();
952 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
956 f.fontInfo().setColor(Color_inlinecompletion);
957 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
959 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
960 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
963 // Handle some situations that abruptly terminate the row
964 // - Before an inset with BreakBefore
965 // - After an inset with BreakAfter
966 Inset const * prevInset = !row.empty() ? row.back().inset : 0;
967 Inset const * nextInset = (i + 1 < end) ? par.getInset(i + 1) : 0;
968 if ((nextInset && nextInset->rowFlags() & Inset::BreakBefore)
969 || (prevInset && prevInset->rowFlags() & Inset::BreakAfter)) {
971 // Force a row creation after this one if it is ended by
972 // an inset that either
973 // - has row flag RowAfter that enforces that;
974 // - or (1) did force the row breaking, (2) is at end of
975 // paragraph and (3) the said paragraph has an end label.
976 need_new_row = prevInset &&
977 (prevInset->rowFlags() & Inset::RowAfter
978 || (prevInset->rowFlags() & Inset::BreakAfter && i + 1 == end
979 && text_->getEndLabel(row.pit()) != END_LABEL_NO_LABEL));
990 // End of paragraph marker. The logic here is almost the
991 // same as in redoParagraph, remember keep them in sync.
992 ParagraphList const & pars = text_->paragraphs();
993 Change const & change = par.lookupChange(i);
994 if ((lyxrc.paragraph_markers || change.changed())
996 && i == end && size_type(row.pit() + 1) < pars.size()) {
997 // add a virtual element for the end-of-paragraph
998 // marker; it is shown on screen, but does not exist
1000 Font f(text_->layoutFont(row.pit()));
1001 f.fontInfo().setColor(Color_paragraphmarker);
1002 BufferParams const & bparams
1003 = text_->inset().buffer().params();
1004 f.setLanguage(par.getParLanguage(bparams));
1005 // ¶ U+00B6 PILCROW SIGN
1006 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, change);
1009 // Is there a end-of-paragaph change?
1010 if (i == end && par.lookupChange(end).changed() && !need_new_row)
1011 row.needsChangeBar(true);
1013 // if the row is too large, try to cut at last separator. In case
1014 // of success, reset indication that the row was broken abruptly.
1015 int const next_width = max_width_ - leftMargin(row.pit(), row.endpos())
1016 - rightMargin(row.pit());
1018 if (row.shortenIfNeeded(body_pos, width, next_width))
1020 row.right_boundary(!row.empty() && row.endpos() < end
1021 && row.back().endpos == row.endpos());
1022 // Last row in paragraph is flushed
1023 if (row.endpos() == end)
1026 // make sure that the RTL elements are in reverse ordering
1027 row.reverseRTL(is_rtl);
1028 //LYXERR0("breakrow: row is " << row);
1030 return need_new_row;
1033 int TextMetrics::parTopSpacing(pit_type const pit) const
1035 Paragraph const & par = text_->getPar(pit);
1036 Layout const & layout = par.layout();
1039 ParagraphList const & pars = text_->paragraphs();
1040 double const dh = defaultRowHeight();
1042 BufferParams const & bparams = bv_->buffer().params();
1043 Inset const & inset = text_->inset();
1044 // some parskips VERY EASY IMPLEMENTATION
1045 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1046 && !inset.getLayout().parbreakIsNewline()
1047 && !par.layout().parbreak_is_newline
1049 && ((layout.isParagraph() && par.getDepth() == 0)
1050 || (pars[pit - 1].layout().isParagraph()
1051 && pars[pit - 1].getDepth() == 0))) {
1052 asc += bparams.getDefSkip().inPixels(*bv_);
1055 if (par.params().startOfAppendix())
1058 // special code for the top label
1059 if (layout.labelIsAbove()
1060 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1061 && !par.labelString().empty()) {
1062 FontInfo labelfont = text_->labelFont(par);
1063 FontMetrics const & lfm = theFontMetrics(labelfont);
1064 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1065 * text_->spacing(par)
1066 + (layout.topsep + layout.labelbottomsep) * dh);
1069 // Add the layout spaces, for example before and after
1070 // a section, or between the items of a itemize or enumerate
1073 pit_type prev = text_->depthHook(pit, par.getDepth());
1074 Paragraph const & prevpar = pars[prev];
1075 double layoutasc = 0;
1077 && prevpar.layout() == layout
1078 && prevpar.getDepth() == par.getDepth()
1079 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1080 layoutasc = layout.itemsep * dh;
1081 } else if (pit != 0 && layout.topsep > 0)
1082 layoutasc = layout.topsep * dh;
1084 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1086 prev = text_->outerHook(pit);
1087 if (prev != pit_type(pars.size())) {
1088 asc += int(pars[prev].layout().parsep * dh);
1089 } else if (pit != 0) {
1090 Paragraph const & prevpar2 = pars[pit - 1];
1091 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1092 asc += int(layout.parsep * dh);
1099 int TextMetrics::parBottomSpacing(pit_type const pit) const
1101 double layoutdesc = 0;
1102 ParagraphList const & pars = text_->paragraphs();
1103 double const dh = defaultRowHeight();
1105 // add the layout spaces, for example before and after
1106 // a section, or between the items of a itemize or enumerate
1108 pit_type nextpit = pit + 1;
1109 if (nextpit != pit_type(pars.size())) {
1110 pit_type cpit = pit;
1112 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1113 double usual = pars[cpit].layout().bottomsep * dh;
1115 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1116 if (pars[cpit].layout() != pars[nextpit].layout()
1117 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1118 unusual = pars[cpit].layout().bottomsep * dh;
1119 layoutdesc = max(unusual, usual);
1120 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1121 if (pars[cpit].layout() != pars[nextpit].layout()
1122 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1123 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1127 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1131 void TextMetrics::setRowHeight(Row & row) const
1133 Paragraph const & par = text_->getPar(row.pit());
1134 Layout const & layout = par.layout();
1135 double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1137 // Initial value for ascent (useful if row is empty).
1138 Font const font = displayFont(row.pit(), row.pos());
1139 FontMetrics const & fm = theFontMetrics(font);
1140 int maxasc = int(fm.maxAscent() * spacing_val);
1141 int maxdes = int(fm.maxDescent() * spacing_val);
1143 // Take label string into account (useful if labelfont is large)
1144 if (row.pos() == 0 && layout.labelIsInline()) {
1145 FontInfo const labelfont = text_->labelFont(par);
1146 FontMetrics const & lfm = theFontMetrics(labelfont);
1147 maxasc = max(maxasc, int(lfm.maxAscent() * spacing_val));
1148 maxdes = max(maxdes, int(lfm.maxDescent() * spacing_val));
1151 // Find the ascent/descent of the row contents
1152 for (Row::Element const & e : row) {
1154 maxasc = max(maxasc, e.dim.ascent());
1155 maxdes = max(maxdes, e.dim.descent());
1157 FontMetrics const & fm2 = theFontMetrics(e.font);
1158 maxasc = max(maxasc, int(fm2.maxAscent() * spacing_val));
1159 maxdes = max(maxdes, int(fm2.maxDescent() * spacing_val));
1163 // This is nicer with box insets
1167 row.dim().asc = maxasc;
1168 row.dim().des = maxdes;
1170 // This is useful for selections
1171 row.contents_dim() = row.dim();
1175 // x is an absolute screen coord
1176 // returns the column near the specified x-coordinate of the row
1177 // x is set to the real beginning of this column
1178 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1179 bool & boundary) const
1181 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1182 /// For the main Text, it is possible that this pit is not
1183 /// yet in the CoordCache when moving cursor up.
1184 /// x Paragraph coordinate is always 0 for main text anyway.
1185 int const xo = origin_.x_;
1188 // Adapt to cursor row scroll offset if applicable.
1189 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1192 pos_type pos = row.pos();
1195 x = row.left_margin;
1196 else if (x <= row.left_margin) {
1197 pos = row.front().left_pos();
1198 x = row.left_margin;
1199 } else if (x >= row.width()) {
1200 pos = row.back().right_pos();
1203 double w = row.left_margin;
1204 Row::const_iterator cit = row.begin();
1205 Row::const_iterator cend = row.end();
1206 for ( ; cit != cend; ++cit) {
1207 if (w <= x && w + cit->full_width() > x) {
1208 int x_offset = int(x - w);
1209 pos = cit->x2pos(x_offset);
1210 x = int(x_offset + w);
1213 w += cit->full_width();
1215 if (cit == row.end()) {
1216 pos = row.back().right_pos();
1219 /** This tests for the case where the cursor is placed
1220 * just before a font direction change. See comment on
1221 * the boundary_ member in DocIterator.h to understand
1222 * how boundary helps here.
1224 else if (pos == cit->endpos
1225 && ((!cit->isRTL() && cit + 1 != row.end()
1226 && (cit + 1)->isRTL())
1227 || (cit->isRTL() && cit != row.begin()
1228 && !(cit - 1)->isRTL())))
1232 /** This tests for the case where the cursor is set at the end
1233 * of a row which has been broken due something else than a
1234 * separator (a display inset or a forced breaking of the
1235 * row). We know that there is a separator when the end of the
1236 * row is larger than the end of its last element.
1238 if (!row.empty() && pos == row.back().endpos
1239 && row.back().endpos == row.endpos()) {
1240 Inset const * inset = row.back().inset;
1241 if (inset && (inset->lyxCode() == NEWLINE_CODE
1242 || inset->lyxCode() == SEPARATOR_CODE))
1243 pos = row.back().pos;
1245 boundary = row.right_boundary();
1249 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1255 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1257 // We play safe and use parMetrics(pit) to make sure the
1258 // ParagraphMetrics will be redone and OK to use if needed.
1259 // Otherwise we would use an empty ParagraphMetrics in
1260 // upDownInText() while in selection mode.
1261 ParagraphMetrics const & pm = parMetrics(pit);
1263 LBUFERR(row < int(pm.rows().size()));
1265 Row const & r = pm.rows()[row];
1266 return getPosNearX(r, x, bound);
1270 // y is screen coordinate
1271 pit_type TextMetrics::getPitNearY(int y)
1273 LASSERT(!text_->paragraphs().empty(), return -1);
1274 LASSERT(!par_metrics_.empty(), return -1);
1275 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1277 // look for highest numbered paragraph with y coordinate less than given y
1280 ParMetricsCache::const_iterator it = par_metrics_.begin();
1281 ParMetricsCache::const_iterator et = par_metrics_.end();
1282 ParMetricsCache::const_iterator last = et;
1285 ParagraphMetrics const & pm = it->second;
1287 if (y < it->second.position() - int(pm.ascent())) {
1288 // We are looking for a position that is before the first paragraph in
1289 // the cache (which is in priciple off-screen, that is before the
1292 // We are already at the first paragraph in the inset.
1294 // OK, this is the paragraph we are looking for.
1295 pit = it->first - 1;
1300 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1302 if (y >= last->second.position() + int(pm_last.descent())) {
1303 // We are looking for a position that is after the last paragraph in
1304 // the cache (which is in priciple off-screen), that is before the
1306 pit = last->first + 1;
1307 if (pit == int(text_->paragraphs().size()))
1308 // We are already at the last paragraph in the inset.
1310 // OK, this is the paragraph we are looking for.
1311 newParMetricsDown();
1315 for (; it != et; ++it) {
1316 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1317 << " y: " << it->second.position());
1319 ParagraphMetrics const & pm2 = par_metrics_[it->first];
1321 if (it->first >= pit && int(it->second.position()) - int(pm2.ascent()) <= y) {
1323 yy = it->second.position();
1327 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1333 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1334 bool assert_in_view, bool up)
1336 ParagraphMetrics const & pm = par_metrics_[pit];
1338 int yy = pm.position() - pm.ascent();
1339 LBUFERR(!pm.rows().empty());
1340 RowList::const_iterator rit = pm.rows().begin();
1341 RowList::const_iterator rlast = pm.rows().end();
1343 for (; rit != rlast; yy += rit->height(), ++rit)
1344 if (yy + rit->height() > y)
1347 if (assert_in_view) {
1348 if (!up && yy + rit->height() > y) {
1349 if (rit != pm.rows().begin()) {
1352 } else if (pit != 0) {
1355 ParagraphMetrics const & pm2 = par_metrics_[pit];
1356 rit = pm2.rows().end();
1360 } else if (up && yy != y) {
1362 y = yy + rit->height();
1364 } else if (pit < int(text_->paragraphs().size()) - 1) {
1366 newParMetricsDown();
1367 ParagraphMetrics const & pm2 = par_metrics_[pit];
1368 rit = pm2.rows().begin();
1377 // x,y are absolute screen coordinates
1378 // sets cursor recursively descending into nested editable insets
1379 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1380 bool assert_in_view, bool up)
1382 if (lyxerr.debugging(Debug::WORKAREA)) {
1383 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1384 cur.bv().coordCache().dump();
1386 pit_type pit = getPitNearY(y);
1387 LASSERT(pit != -1, return 0);
1388 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1391 // Do we cover an inset?
1392 InsetList::Element * e = checkInsetHit(pit, x, y);
1395 // No inset, set position in the text
1396 bool bound = false; // is modified by getPosNearX
1397 cur.pos() = getPosNearX(row, x, bound);
1398 cur.boundary(bound);
1399 cur.setCurrentFont();
1404 Inset * inset = e->inset;
1405 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1407 // Set position in front of inset
1409 cur.boundary(false);
1412 // Try to descend recursively inside the inset.
1413 Inset * edited = inset->editXY(cur, x, y);
1414 // FIXME: it is not clear that the test on position is needed
1415 // Remove it if/when semantics of editXY is clarified
1416 if (cur.text() == text_ && cur.pos() == e->pos) {
1417 // non-editable inset, set cursor after the inset if x is
1418 // nearer to that position (bug 9628)
1419 bool bound = false; // is modified by getPosNearX
1420 cur.pos() = getPosNearX(row, x, bound);
1421 cur.boundary(bound);
1422 cur.setCurrentFont();
1426 if (cur.top().text() == text_)
1427 cur.setCurrentFont();
1432 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1434 LASSERT(text_ == cur.text(), return);
1435 pit_type const pit = getPitNearY(y);
1436 LASSERT(pit != -1, return);
1438 ParagraphMetrics const & pm = par_metrics_[pit];
1440 int yy = pm.position() - pm.rows().front().ascent();
1441 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1442 " pit: " << pit << " yy: " << yy);
1445 LBUFERR(pm.rows().size());
1446 for (; r < int(pm.rows().size()) - 1; ++r) {
1447 Row const & row = pm.rows()[r];
1448 if (int(yy + row.height()) > y)
1453 Row const & row = pm.rows()[r];
1455 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1459 pos_type const pos = getPosNearX(row, xx, bound);
1461 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1463 text_->setCursor(cur, pit, pos, true, bound);
1464 // remember new position.
1469 //takes screen x,y coordinates
1470 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1472 Paragraph const & par = text_->paragraphs()[pit];
1473 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1475 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1477 for (InsetList::Element const & e : par.insetList()) {
1478 LYXERR(Debug::DEBUG, "examining inset " << e.inset);
1480 if (insetCache.covers(e.inset, x, y)) {
1481 LYXERR(Debug::DEBUG, "Hit inset: " << e.inset);
1482 return const_cast<InsetList::Element *>(&e);
1486 LYXERR(Debug::DEBUG, "No inset hit. ");
1491 //takes screen x,y coordinates
1492 Inset * TextMetrics::checkInsetHit(int x, int y)
1494 pit_type const pit = getPitNearY(y);
1495 LASSERT(pit != -1, return 0);
1496 InsetList::Element * e = checkInsetHit(pit, x, y);
1505 int TextMetrics::cursorX(CursorSlice const & sl,
1506 bool boundary) const
1508 LASSERT(sl.text() == text_, return 0);
1510 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1511 if (pm.rows().empty())
1513 Row const & row = pm.getRow(sl.pos(), boundary);
1514 pos_type const pos = sl.pos();
1517 row.findElement(pos, boundary, x);
1523 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1525 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1526 ParagraphMetrics const & pm = parMetrics(sl.pit());
1527 if (pm.rows().empty())
1531 h -= parMetrics(0).rows()[0].ascent();
1532 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1533 h += parMetrics(pit).height();
1536 if (pos && boundary)
1538 size_t const rend = pm.pos2row(pos);
1539 for (size_t rit = 0; rit != rend; ++rit)
1540 h += pm.rows()[rit].height();
1541 h += pm.rows()[rend].ascent();
1546 // the cursor set functions have a special mechanism. When they
1547 // realize you left an empty paragraph, they will delete it.
1549 bool TextMetrics::cursorHome(Cursor & cur)
1551 LASSERT(text_ == cur.text(), return false);
1552 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1553 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1554 return text_->setCursor(cur, cur.pit(), row.pos());
1558 bool TextMetrics::cursorEnd(Cursor & cur)
1560 LASSERT(text_ == cur.text(), return false);
1561 // if not on the last row of the par, put the cursor before
1562 // the final space exept if I have a spanning inset or one string
1563 // is so long that we force a break.
1564 pos_type end = cur.textRow().endpos();
1566 // empty text, end-1 is no valid position
1568 bool boundary = false;
1569 if (end != cur.lastpos()) {
1570 if (!cur.paragraph().isLineSeparator(end-1)
1571 && !cur.paragraph().isNewline(end-1)
1572 && !cur.paragraph().isEnvSeparator(end-1))
1576 } else if (cur.paragraph().isEnvSeparator(end-1))
1578 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1582 void TextMetrics::deleteLineForward(Cursor & cur)
1584 LASSERT(text_ == cur.text(), return);
1585 if (cur.lastpos() == 0) {
1586 // Paragraph is empty, so we just go forward
1587 text_->cursorForward(cur);
1590 cur.selection(true); // to avoid deletion
1593 // What is this test for ??? (JMarc)
1594 if (!cur.selection())
1595 text_->deleteWordForward(cur);
1597 cap::cutSelection(cur, false);
1598 cur.checkBufferStructure();
1603 int TextMetrics::leftMargin(pit_type pit) const
1605 // FIXME: what is the semantics? It depends on whether the
1606 // paragraph is empty!
1607 return leftMargin(pit, text_->paragraphs()[pit].size());
1611 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1613 ParagraphList const & pars = text_->paragraphs();
1615 LASSERT(pit >= 0, return 0);
1616 LASSERT(pit < int(pars.size()), return 0);
1617 Paragraph const & par = pars[pit];
1618 LASSERT(pos >= 0, return 0);
1619 // We do not really care whether pos > par.size(), since we do not
1620 // access the data. It can be actually useful, when querying the
1621 // margin without indentation (see leftMargin(pit_type).
1623 Buffer const & buffer = bv_->buffer();
1624 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1625 DocumentClass const & tclass = buffer.params().documentClass();
1626 Layout const & layout = par.layout();
1627 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1629 docstring parindent = layout.parindent;
1633 if (text_->isMainText()) {
1634 l_margin += bv_->leftMargin();
1635 l_margin += bfm.signedWidth(tclass.leftmargin());
1638 int depth = par.getDepth();
1640 // find the next level paragraph
1641 pit_type newpar = text_->outerHook(pit);
1642 if (newpar != pit_type(pars.size())) {
1643 if (pars[newpar].layout().isEnvironment()) {
1644 int nestmargin = depth * nestMargin();
1645 if (text_->isMainText())
1646 nestmargin += changebarMargin();
1647 l_margin = max(leftMargin(newpar), nestmargin);
1648 // Remove the parindent that has been added
1649 // if the paragraph was empty.
1650 if (pars[newpar].empty() &&
1651 buffer.params().paragraph_separation ==
1652 BufferParams::ParagraphIndentSeparation) {
1653 docstring pi = pars[newpar].layout().parindent;
1654 l_margin -= bfm.signedWidth(pi);
1657 if (tclass.isDefaultLayout(par.layout())
1658 || tclass.isPlainLayout(par.layout())) {
1659 if (pars[newpar].params().noindent())
1662 parindent = pars[newpar].layout().parindent;
1667 // This happens after sections or environments in standard classes.
1668 // We have to check the previous layout at same depth.
1669 if (buffer.params().paragraph_separation ==
1670 BufferParams::ParagraphSkipSeparation)
1672 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1673 pit_type prev = text_->depthHook(pit, par.getDepth());
1674 if (par.layout() == pars[prev].layout()) {
1676 && pars[pit - 1].layout().nextnoindent)
1678 } else if (pars[prev].layout().nextnoindent)
1682 FontInfo const labelfont = text_->labelFont(par);
1683 FontMetrics const & lfm = theFontMetrics(labelfont);
1685 switch (layout.margintype) {
1686 case MARGIN_DYNAMIC:
1687 if (!layout.leftmargin.empty()) {
1688 l_margin += bfm.signedWidth(layout.leftmargin);
1690 if (!par.labelString().empty()) {
1691 l_margin += lfm.signedWidth(layout.labelindent);
1692 l_margin += lfm.width(par.labelString());
1693 l_margin += lfm.width(layout.labelsep);
1697 case MARGIN_MANUAL: {
1698 l_margin += lfm.signedWidth(layout.labelindent);
1699 // The width of an empty par, even with manual label, should be 0
1700 if (!par.empty() && pos >= par.beginOfBody()) {
1701 if (!par.getLabelWidthString().empty()) {
1702 docstring labstr = par.getLabelWidthString();
1703 l_margin += lfm.width(labstr);
1704 l_margin += lfm.width(layout.labelsep);
1710 case MARGIN_STATIC: {
1711 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1712 / (par.getDepth() + 4);
1716 case MARGIN_FIRST_DYNAMIC:
1717 if (layout.labeltype == LABEL_MANUAL) {
1718 // if we are at position 0, we are never in the body
1719 if (pos > 0 && pos >= par.beginOfBody())
1720 l_margin += lfm.signedWidth(layout.leftmargin);
1722 l_margin += lfm.signedWidth(layout.labelindent);
1724 // Special case to fix problems with
1726 || (layout.labeltype == LABEL_STATIC
1727 && layout.latextype == LATEX_ENVIRONMENT
1728 && !text_->isFirstInSequence(pit))) {
1729 l_margin += lfm.signedWidth(layout.leftmargin);
1730 } else if (!layout.labelIsAbove()) {
1731 l_margin += lfm.signedWidth(layout.labelindent);
1732 l_margin += lfm.width(layout.labelsep);
1733 l_margin += lfm.width(par.labelString());
1737 case MARGIN_RIGHT_ADDRESS_BOX:
1738 // This is handled globally in redoParagraph().
1742 if (!par.params().leftIndent().zero())
1743 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1745 LyXAlignment align = par.getAlign(bv_->buffer().params());
1747 // set the correct parindent
1749 && (layout.labeltype == LABEL_NO_LABEL
1750 || layout.labeltype == LABEL_ABOVE
1751 || layout.labeltype == LABEL_CENTERED
1752 || (layout.labeltype == LABEL_STATIC
1753 && layout.latextype == LATEX_ENVIRONMENT
1754 && !text_->isFirstInSequence(pit)))
1755 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1756 && !par.params().noindent()
1757 // in some insets, paragraphs are never indented
1758 && !text_->inset().neverIndent()
1759 // display style insets do not need indentation
1762 && par.getInset(0)->rowFlags() & Inset::Display)
1763 && (!(tclass.isDefaultLayout(par.layout())
1764 || tclass.isPlainLayout(par.layout()))
1765 || buffer.params().paragraph_separation
1766 == BufferParams::ParagraphIndentSeparation)) {
1767 /* use the parindent of the layout when the default
1768 * indentation is used otherwise use the indentation set in
1769 * the document settings
1771 if (buffer.params().getParIndent().empty())
1772 l_margin += bfm.signedWidth(parindent);
1774 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1781 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1783 if (par_metrics_.empty())
1789 y -= par_metrics_.begin()->second.ascent();
1790 for (auto & pm_pair : par_metrics_) {
1791 pit_type const pit = pm_pair.first;
1792 ParagraphMetrics & pm = pm_pair.second;
1794 // Save the paragraph position in the cache.
1796 drawParagraph(pi, pit, x, y);
1802 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1804 ParagraphMetrics const & pm = par_metrics_[pit];
1805 if (pm.rows().empty())
1807 size_t const nrows = pm.rows().size();
1808 // Remember left and right margin for drawing math numbers
1809 Changer changeleft = changeVar(pi.leftx, x + leftMargin(pit));
1810 Changer changeright = changeVar(pi.rightx, x + width() - rightMargin(pit));
1812 // Use fast lane in nodraw stage.
1813 if (pi.pain.isNull()) {
1814 for (size_t i = 0; i != nrows; ++i) {
1816 Row const & row = pm.rows()[i];
1817 // Adapt to cursor row scroll offset if applicable.
1818 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1822 RowPainter rp(pi, *text_, row, row_x, y);
1824 rp.paintOnlyInsets();
1830 int const ww = bv_->workHeight();
1831 Cursor const & cur = bv_->cursor();
1832 DocIterator sel_beg = cur.selectionBegin();
1833 DocIterator sel_end = cur.selectionEnd();
1834 bool selection = cur.selection()
1835 // This is our text.
1836 && cur.text() == text_
1837 // if the anchor is outside, this is not our selection
1838 && cur.normalAnchor().text() == text_
1839 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1841 // We store the begin and end pos of the selection relative to this par
1842 DocIterator sel_beg_par = cur.selectionBegin();
1843 DocIterator sel_end_par = cur.selectionEnd();
1845 // We care only about visible selection.
1847 if (pit != sel_beg.pit()) {
1848 sel_beg_par.pit() = pit;
1849 sel_beg_par.pos() = 0;
1851 if (pit != sel_end.pit()) {
1852 sel_end_par.pit() = pit;
1853 sel_end_par.pos() = sel_end_par.lastpos();
1857 if (text_->isRTL(pit))
1858 swap(pi.leftx, pi.rightx);
1860 for (size_t i = 0; i != nrows; ++i) {
1862 Row const & row = pm.rows()[i];
1863 // Adapt to cursor row scroll offset if applicable.
1864 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1868 // It is not needed to draw on screen if we are not inside.
1869 bool const inside = (y + row.descent() >= 0
1870 && y - row.ascent() < ww);
1872 // Inset positions have already been set in nodraw stage.
1878 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
1880 row.clearSelectionAndMargins();
1882 // The row knows nothing about the paragraph, so we have to check
1883 // whether this row is the first or last and update the margins.
1884 if (row.selection()) {
1885 if (row.sel_beg == 0)
1886 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
1887 if (row.sel_end == sel_end_par.lastpos())
1888 row.change(row.end_margin_sel, sel_end.pit() > pit);
1891 // Take this opportunity to spellcheck the row contents.
1892 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
1893 text_->getPar(pit).spellCheck();
1896 RowPainter rp(pi, *text_, row, row_x, y);
1898 // Don't paint the row if a full repaint has not been requested
1899 // and if it has not changed.
1900 if (!pi.full_repaint && !row.changed()) {
1901 // Paint only the insets if the text itself is
1903 rp.paintOnlyInsets();
1909 // Clear background of this row if paragraph background was not
1910 // already cleared because of a full repaint.
1911 if (!pi.full_repaint && row.changed()) {
1912 LYXERR(Debug::PAINTING, "Clear rect@("
1913 << max(row_x, 0) << ", " << y - row.ascent() << ")="
1914 << width() << " x " << row.height());
1915 pi.pain.fillRectangle(row_x, y - row.ascent(),
1916 width(), row.height(), pi.background_color);
1919 // Instrumentation for testing row cache (see also
1921 if (lyxerr.debugging(Debug::PAINTING)
1922 && (row.selection() || pi.full_repaint || row.changed())) {
1923 string const foreword = text_->isMainText() ? "main text redraw "
1924 : "inset text redraw: ";
1925 LYXERR0(foreword << "pit=" << pit << " row=" << i
1926 << (row.selection() ? " row_selection": "")
1927 << (pi.full_repaint ? " full_repaint" : "")
1928 << (row.changed() ? " row.changed" : ""));
1931 // Backup full_repaint status and force full repaint
1932 // for inner insets as the Row has been cleared out.
1933 bool tmp = pi.full_repaint;
1934 pi.full_repaint = true;
1936 rp.paintSelection();
1939 if (row.needsChangeBar())
1940 rp.paintChangeBar();
1946 rp.paintTooLargeMarks(row_x + row.left_x() < 0,
1947 row_x + row.right_x() > bv_->workWidth());
1951 // This debug code shows on screen which rows are repainted.
1952 // FIXME: since the updates related to caret blinking restrict
1953 // the painter to a small rectangle, the numbers are not
1954 // updated when this happens. Change the code in
1955 // GuiWorkArea::Private::show/hideCaret if this is important.
1956 static int count = 0;
1958 FontInfo fi(sane_font);
1959 fi.setSize(TINY_SIZE);
1960 fi.setColor(Color_red);
1961 pi.pain.text(row_x, y, convert<docstring>(count), fi);
1964 // Restore full_repaint status.
1965 pi.full_repaint = tmp;
1970 //LYXERR(Debug::PAINTING, ".");
1974 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
1975 Dimension & dim) const
1977 DocIterator from = cur.bv().cursor();
1978 DocIterator to = from;
1979 text_->getWord(from.top(), to.top(), PREVIOUS_WORD);
1981 // The vertical dimension of the word
1982 Font const font = displayFont(cur.pit(), from.pos());
1983 FontMetrics const & fm = theFontMetrics(font);
1984 // the +1's below are related to the extra pixels added in setRowHeight
1985 dim.asc = fm.maxAscent() + 1;
1986 dim.des = fm.maxDescent() + 1;
1988 // get position on screen of the word start and end
1989 //FIXME: Is it necessary to explicitly set this to false?
1990 from.boundary(false);
1991 Point lxy = cur.bv().getPos(from);
1992 Point rxy = cur.bv().getPos(to);
1993 dim.wid = abs(rxy.x_ - lxy.x_);
1995 // calculate position of word
1997 x = min(rxy.x_, lxy.x_);
1999 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2000 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2003 int defaultRowHeight()
2005 return int(theFontMetrics(sane_font).maxHeight() * 1.2);