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)
112 max_width_ = bv_->workWidth();
113 dim_.wid = max_width_;
119 bool TextMetrics::contains(pit_type pit) const
121 return par_metrics_.find(pit) != par_metrics_.end();
125 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
127 ParMetricsCache::const_iterator it = par_metrics_.begin();
128 return make_pair(it->first, &it->second);
132 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
134 LBUFERR(!par_metrics_.empty());
135 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
136 return make_pair(it->first, &it->second);
140 bool TextMetrics::isLastRow(Row const & row) const
142 ParagraphList const & pars = text_->paragraphs();
143 return row.endpos() >= pars[row.pit()].size()
144 && row.pit() + 1 == pit_type(pars.size());
148 bool TextMetrics::isFirstRow(Row const & row) const
150 return row.pos() == 0 && row.pit() == 0;
154 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
156 for (auto & pm_pair : par_metrics_)
157 if (pm_pair.first == pit)
158 for (Row & row : pm_pair.second.rows())
159 if (row.pos() == pos)
164 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
166 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
167 if (pmc_it == par_metrics_.end()) {
168 pmc_it = par_metrics_.insert(
169 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
171 if (pmc_it->second.rows().empty() && redo)
173 return pmc_it->second;
177 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
179 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
183 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit)
185 return parMetrics(pit, true);
189 void TextMetrics::newParMetricsDown()
191 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
192 pit_type const pit = last.first + 1;
193 if (pit == int(text_->paragraphs().size()))
196 // do it and update its position.
198 par_metrics_[pit].setPosition(last.second.position()
199 + last.second.descent() + par_metrics_[pit].ascent());
204 void TextMetrics::newParMetricsUp()
206 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
207 if (first.first == 0)
210 pit_type const pit = first.first - 1;
211 // do it and update its position.
213 par_metrics_[pit].setPosition(first.second.position()
214 - first.second.ascent() - par_metrics_[pit].descent());
219 bool TextMetrics::metrics(MetricsInfo const & mi, Dimension & dim, int min_width,
220 bool const expand_on_multipars)
222 LBUFERR(mi.base.textwidth > 0);
223 max_width_ = mi.base.textwidth;
224 // backup old dimension.
225 Dimension const old_dim = dim_;
228 dim_.wid = min_width;
229 pit_type const npar = text_->paragraphs().size();
230 if (npar > 1 && expand_on_multipars)
231 // If there is more than one row, expand the text to
232 // the full allowable width.
233 dim_.wid = max_width_;
235 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
236 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
238 bool changed = false;
240 for (pit_type pit = 0; pit != npar; ++pit) {
241 // create rows, but do not set alignment yet
242 changed |= redoParagraph(pit, false);
243 ParagraphMetrics const & pm = par_metrics_[pit];
245 if (dim_.wid < pm.width())
246 dim_.wid = pm.width();
249 // Now set alignment for all rows (the width might not have been known before).
250 for (pit_type pit = 0; pit != npar; ++pit) {
251 ParagraphMetrics & pm = par_metrics_[pit];
252 for (Row & row : pm.rows())
253 setRowAlignment(row, dim_.wid);
256 dim_.asc = par_metrics_[0].ascent();
257 dim_.des = h - dim_.asc;
258 //lyxerr << "dim_.wid " << dim_.wid << endl;
259 //lyxerr << "dim_.asc " << dim_.asc << endl;
260 //lyxerr << "dim_.des " << dim_.des << endl;
262 changed |= dim_ != old_dim;
268 void TextMetrics::updatePosCache(pit_type pit) const
270 frontend::NullPainter np;
271 PainterInfo pi(bv_, np);
272 drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
276 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
278 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
282 int TextMetrics::rightMargin(pit_type const pit) const
284 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
288 void TextMetrics::applyOuterFont(Font & font) const
290 FontInfo lf(font_.fontInfo());
291 lf.reduce(bv_->buffer().params().getFont().fontInfo());
292 font.fontInfo().realize(lf);
296 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
298 LASSERT(pos >= 0, { static Font f; return f; });
300 ParagraphList const & pars = text_->paragraphs();
301 Paragraph const & par = pars[pit];
302 Layout const & layout = par.layout();
303 Buffer const & buffer = bv_->buffer();
305 BufferParams const & params = buffer.params();
306 pos_type const body_pos = par.beginOfBody();
308 // We specialize the 95% common case:
309 if (!par.getDepth()) {
310 Font f = par.getFontSettings(params, pos);
311 if (!text_->isMainText())
313 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
315 FontInfo const & lf = lab ? layout.labelfont : layout.font;
316 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
318 // In case the default family has been customized
319 if (lf.family() == INHERIT_FAMILY)
320 rlf.setFamily(params.getFont().fontInfo().family());
321 f.fontInfo().realize(rlf);
325 // The uncommon case need not be optimized as much
326 FontInfo const & layoutfont = pos < body_pos ?
327 layout.labelfont : layout.font;
329 Font font = par.getFontSettings(params, pos);
330 font.fontInfo().realize(layoutfont);
332 if (!text_->isMainText())
333 applyOuterFont(font);
335 // Realize against environment font information
336 // NOTE: the cast to pit_type should be removed when pit_type
337 // changes to a unsigned integer.
338 if (pit < pit_type(pars.size()))
339 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
341 // Realize with the fonts of lesser depth.
342 font.fontInfo().realize(params.getFont().fontInfo());
348 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
354 if (boundary && sl.pos() > 0)
357 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
361 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
363 // no RTL boundary at paragraph start
367 Font const & left_font = displayFont(pit, pos - 1);
369 return isRTLBoundary(pit, pos, left_font);
373 // isRTLBoundary returns false on a real end-of-line boundary,
374 // because otherwise the two boundary types get mixed up.
375 // This is the whole purpose of this being in TextMetrics.
376 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
377 Font const & font) const
379 if (// no RTL boundary at paragraph start
381 // if the metrics have not been calculated, then we are not
382 // on screen and can safely ignore issues about boundaries.
386 ParagraphMetrics const & pm = par_metrics_[pit];
387 // no RTL boundary in empty paragraph
388 if (pm.rows().empty())
391 pos_type const endpos = pm.getRow(pos - 1, false).endpos();
392 pos_type const startpos = pm.getRow(pos, false).pos();
393 // no RTL boundary at line start:
394 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
396 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
399 Paragraph const & par = text_->getPar(pit);
400 // no RTL boundary at line break:
401 // abc|\n -> move right -> abc\n (and not: abc\n|
403 if (startpos == pos && endpos == pos && endpos != par.size()
404 && (par.isNewline(pos - 1)
405 || par.isEnvSeparator(pos - 1)
406 || par.isLineSeparator(pos - 1)
407 || par.isSeparator(pos - 1)))
410 bool const left = font.isVisibleRightToLeft();
412 if (pos == par.size())
413 right = par.isRTL(bv_->buffer().params());
415 right = displayFont(pit, pos).isVisibleRightToLeft();
417 return left != right;
421 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
423 Paragraph & par = text_->getPar(pit);
424 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
425 // redoParagraph() recursively inside parMetrics.
426 Dimension old_dim = parMetrics(pit, false).dim();
427 ParagraphMetrics & pm = par_metrics_[pit];
430 Buffer & buffer = bv_->buffer();
431 bool changed = false;
433 // Check whether there are InsetBibItems that need fixing
434 // FIXME: This check ought to be done somewhere else. It is the reason
435 // why text_ is not const. But then, where else to do it?
436 // Well, how can you end up with either (a) a biblio environment that
437 // has no InsetBibitem, (b) a biblio environment with more than one
438 // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
439 // environment? I think the answer is: when paragraphs are merged;
440 // when layout is set; when material is pasted.
441 if (par.brokenBiblio()) {
442 Cursor & cur = const_cast<Cursor &>(bv_->cursor());
443 // In some cases, we do not know how to record undo
444 if (&cur.inset() == &text_->inset())
445 cur.recordUndo(pit, pit);
447 int const moveCursor = par.fixBiblio(buffer);
449 // Is it necessary to update the cursor?
450 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
453 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
458 // Optimisation: this is used in the next two loops
459 // so better to calculate that once here.
460 int const right_margin = rightMargin(pm);
462 // iterator pointing to paragraph to resolve macros
463 DocIterator parPos = text_->macrocontextPosition();
467 LYXERR(Debug::INFO, "MacroContext not initialised!"
468 << " Going through the buffer again and hope"
469 << " the context is better then.");
470 // FIXME audit updateBuffer calls
471 // This should not be here, but it is not clear yet where else it
473 bv_->buffer().updateBuffer();
474 parPos = text_->macrocontextPosition();
475 LBUFERR(!parPos.empty());
480 par.setBeginOfBody();
481 Font const bufferfont = buffer.params().getFont();
482 CoordCache::Insets & insetCache = bv_->coordCache().insets();
483 for (auto const & e : par.insetList()) {
484 // FIXME Doesn't this HAVE to be non-empty?
485 // position already initialized?
486 if (!parPos.empty()) {
487 parPos.pos() = e.pos;
489 // A macro template would normally not be visible
490 // by itself. But the tex macro semantics allow
491 // recursion, so we artifically take the context
492 // after the macro template to simulate this.
493 if (e.inset->lyxCode() == MATHMACRO_CODE)
497 // If there is an end of paragraph marker, its size should be
498 // substracted to the available width. The logic here is
499 // almost the same as in breakRow, remember keep them in sync.
501 if (lyxrc.paragraph_markers && e.pos + 1 == par.size()
502 && size_type(pit + 1) < text_->paragraphs().size()) {
503 Font f(text_->layoutFont(pit));
504 // ¶ U+00B6 PILCROW SIGN
505 eop = theFontMetrics(f).width(char_type(0x00B6));
508 // do the metric calculation
510 int const w = max_width_ - leftMargin(pit, e.pos)
511 - right_margin - eop;
512 Font const & font = e.inset->inheritFont() ?
513 displayFont(pit, e.pos) : bufferfont;
514 MacroContext mc(&buffer, parPos);
515 MetricsInfo mi(bv_, font.fontInfo(), w, mc, e.pos == 0);
516 e.inset->metrics(mi, dim);
517 if (!insetCache.has(e.inset) || insetCache.dim(e.inset) != dim) {
518 insetCache.add(e.inset, dim);
524 size_t row_index = 0;
525 bool need_new_row = false;
526 // maximum pixel width of a row
528 if (row_index == pm.rows().size())
529 pm.rows().push_back(Row());
531 pm.rows()[row_index] = Row();
532 Row & row = pm.rows()[row_index];
535 need_new_row = breakRow(row, right_margin);
538 if ((row_index || row.endpos() < par.size() || row.right_boundary())
539 && par.inInset().lyxCode() != CELL_CODE) {
540 /* If there is more than one row or the row has been
541 * broken by a display inset or a newline, expand the text
542 * to the full allowable width. This setting here is
543 * needed for the setRowAlignment() below.
544 * We do nothing when inside a table cell.
546 if (dim_.wid < max_width_)
547 dim_.wid = max_width_;
550 setRowAlignment(row, max(dim_.wid, row.width()));
551 first = row.endpos();
554 pm.dim().wid = max(pm.dim().wid, row.width() + row.right_margin);
555 pm.dim().des += row.height();
556 } while (first < par.size() || need_new_row);
558 if (row_index < pm.rows().size())
559 pm.rows().resize(row_index);
561 // This type of margin can only be handled at the global paragraph level
562 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX) {
564 if (par.isRTL(buffer.params())) {
565 // globally align the paragraph to the left.
566 int minleft = max_width_;
567 for (Row const & row : pm.rows())
568 minleft = min(minleft, row.left_margin);
569 offset = right_margin - minleft;
571 // globally align the paragraph to the right.
573 for (Row const & row : pm.rows())
574 maxwid = max(maxwid, row.width());
575 offset = max_width_ - right_margin - maxwid;
578 for (Row & row : pm.rows()) {
579 row.left_margin += offset;
580 row.dim().wid += offset;
584 // The space above and below the paragraph.
585 int const top = parTopSpacing(pit);
586 pm.rows().front().dim().asc += top;
587 int const bottom = parBottomSpacing(pit);
588 pm.rows().back().dim().des += bottom;
589 pm.dim().des += top + bottom;
591 pm.dim().asc += pm.rows()[0].ascent();
592 pm.dim().des -= pm.rows()[0].ascent();
594 // Top and bottom margin of the document (only at top-level)
595 // FIXME: It might be better to move this in another method
596 // specially tailored for the main text.
597 if (text_->isMainText()) {
599 pm.dim().asc += bv_->topMargin();
600 ParagraphList const & pars = text_->paragraphs();
601 if (pit + 1 == pit_type(pars.size())) {
602 pm.dim().des += bv_->bottomMargin();
606 changed |= old_dim.height() != pm.dim().height();
612 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
614 LyXAlignment align = par.getAlign(bv_->buffer().params());
616 // handle alignment inside tabular cells
617 Inset const & owner = text_->inset();
618 bool forced_block = false;
619 switch (owner.contentAlignment()) {
620 case LYX_ALIGN_BLOCK:
621 // In general block align is the default state, but here it is
622 // an explicit choice. Therefore it should not be overridden
626 case LYX_ALIGN_CENTER:
628 case LYX_ALIGN_RIGHT:
629 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
630 align = owner.contentAlignment();
633 // unchanged (use align)
637 // Display-style insets should always be on a centered row
638 if (Inset const * inset = par.getInset(row.pos())) {
639 if (inset->rowFlags() & Inset::Display) {
640 if (inset->rowFlags() & Inset::AlignLeft)
641 align = LYX_ALIGN_BLOCK;
642 else if (inset->rowFlags() & Inset::AlignRight)
643 align = LYX_ALIGN_RIGHT;
645 align = LYX_ALIGN_CENTER;
649 if (align == LYX_ALIGN_BLOCK) {
650 // If this row has been broken abruptly by a display inset, or
651 // it is the end of the paragraph, or the user requested we
652 // not justify stuff, then don't stretch.
653 // A forced block alignment can only be overridden the 'no
654 // justification on screen' setting.
655 if ((row.flushed() && !forced_block)
656 || !bv_->buffer().params().justification)
657 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
664 void TextMetrics::setRowAlignment(Row & row, int width) const
669 Paragraph const & par = text_->getPar(row.pit());
671 int const w = width - row.right_margin - row.width();
672 // FIXME: put back this assertion when the crash on new doc is solved.
673 //LASSERT(w >= 0, /**/);
675 // is there a manual margin with a manual label
676 Layout const & layout = par.layout();
679 if (layout.margintype == MARGIN_MANUAL
680 && layout.labeltype == LABEL_MANUAL) {
681 /// We might have real hfills in the label part
682 nlh = numberOfLabelHfills(par, row);
684 // A manual label par (e.g. List) has an auto-hfill
685 // between the label text and the body of the
687 // But we don't want to do this auto hfill if the par
692 if (nlh && !par.getLabelWidthString().empty())
693 row.label_hfill = labelFill(row) / double(nlh);
696 // are there any hfills in the row?
697 ParagraphMetrics const & pm = par_metrics_[row.pit()];
698 int nh = numberOfHfills(row, pm, par.beginOfBody());
702 // We don't have to look at the alignment if the row is already
703 // larger then the permitted width as then we force the
704 // LEFT_ALIGN'edness!
705 if (int(row.width()) >= max_width_)
709 // Common case : there is no hfill, and the alignment will be
711 switch (getAlign(par, row)) {
712 case LYX_ALIGN_BLOCK:
713 // Expand expanding characters by a total of w
714 if (!row.setExtraWidth(w) && row.isRTL()) {
715 // Justification failed and the text is RTL: align to the right
716 row.left_margin += w;
721 // a displayed inset that is flushed
722 if (Inset const * inset = par.getInset(row.pos())) {
723 row.left_margin += inset->indent(*bv_);
724 row.dim().wid += inset->indent(*bv_);
727 case LYX_ALIGN_RIGHT:
728 if (Inset const * inset = par.getInset(row.pos())) {
729 int const new_w = max(w - inset->indent(*bv_), 0);
730 row.left_margin += new_w;
731 row.dim().wid += new_w;
733 row.left_margin += w;
737 case LYX_ALIGN_CENTER:
738 row.dim().wid += w / 2;
739 row.left_margin += w / 2;
742 case LYX_ALIGN_LAYOUT:
743 case LYX_ALIGN_SPECIAL:
744 case LYX_ALIGN_DECIMAL:
750 // Case nh > 0. There are hfill separators.
754 // Set size of hfill insets
755 pos_type const endpos = row.endpos();
756 pos_type body_pos = par.beginOfBody();
758 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
761 CoordCache::Insets & insetCache = bv_->coordCache().insets();
762 for (Row::Element & e : row) {
763 if (row.label_hfill && e.endpos == body_pos
764 && e.type == Row::SPACE)
765 e.dim.wid -= int(row.label_hfill * (nlh - 1));
766 if (e.inset && pm.hfillExpansion(row, e.pos)) {
767 if (e.pos >= body_pos) {
771 e.dim.wid += hfill_rem;
773 e.dim.wid += int(row.label_hfill);
774 // Cache the inset dimension.
775 insetCache.add(e.inset, e.dim);
781 int TextMetrics::labelFill(Row const & row) const
783 Paragraph const & par = text_->getPar(row.pit());
784 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
787 // iterate over elements before main body (except the last one,
788 // which is extra space).
789 for (Row::Element const & e : row) {
790 if (e.endpos >= par.beginOfBody())
795 docstring const & label = par.params().labelWidthString();
799 FontMetrics const & fm
800 = theFontMetrics(text_->labelFont(par));
802 return max(0, fm.width(label) - w);
806 int TextMetrics::labelEnd(pit_type const pit) const
808 // labelEnd is only needed if the layout fills a flushleft label.
809 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
811 // return the beginning of the body
812 return leftMargin(pit);
818 * Calling Text::getFont is slow. While rebreaking we scan a
819 * paragraph from left to right calling getFont for every char. This
820 * simple class address this problem by hidding an optimization trick
821 * (not mine btw -AB): the font is reused in the whole font span. The
822 * class handles transparently the "hidden" (not part of the fontlist)
823 * label font (as getFont does).
829 FontIterator(TextMetrics const & tm,
830 Paragraph const & par, pit_type pit, pos_type pos)
831 : tm_(tm), par_(par), pit_(pit), pos_(pos),
832 font_(tm.displayFont(pit, pos)),
833 endspan_(par.fontSpan(pos).last),
834 bodypos_(par.beginOfBody())
838 Font const & operator*() const { return font_; }
841 FontIterator & operator++()
844 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
845 font_ = tm_.displayFont(pit_, pos_);
846 endspan_ = par_.fontSpan(pos_).last;
852 Font * operator->() { return &font_; }
856 TextMetrics const & tm_;
858 Paragraph const & par_;
873 /** This is the function where the hard work is done. The code here is
874 * very sensitive to small changes :) Note that part of the
875 * intelligence is also in Row::shortenIfNeeded.
877 bool TextMetrics::breakRow(Row & row, int const right_margin) const
879 LATTEST(row.empty());
880 Paragraph const & par = text_->getPar(row.pit());
881 Buffer const & buf = text_->inset().buffer();
882 BookmarksSection::BookmarkPosList bpl =
883 theSession().bookmarks().bookmarksInPar(buf.fileName(), par.id());
885 pos_type const end = par.size();
886 pos_type const pos = row.pos();
887 pos_type const body_pos = par.beginOfBody();
888 bool const is_rtl = text_->isRTL(row.pit());
889 bool need_new_row = false;
891 row.left_margin = leftMargin(row.pit(), pos);
892 row.right_margin = right_margin;
894 swap(row.left_margin, row.right_margin);
895 // Remember that the row width takes into account the left_margin
896 // but not the right_margin.
897 row.dim().wid = row.left_margin;
898 // the width available for the row.
899 int const width = max_width_ - row.right_margin;
901 // check for possible inline completion
902 DocIterator const & ic_it = bv_->inlineCompletionPos();
903 pos_type ic_pos = -1;
904 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == row.pit())
905 ic_pos = ic_it.pos();
907 // Now we iterate through until we reach the right margin
908 // or the end of the par, then build a representation of the row.
910 FontIterator fi = FontIterator(*this, par, row.pit(), pos);
911 // The real stopping condition is a few lines below.
913 // Firstly, check whether there is a bookmark here.
914 for (auto const & bp_p : bpl)
915 if (bp_p.second == i) {
917 f.fontInfo().setColor(Color_bookmark);
918 // ❶ U+2776 DINGBAT NEGATIVE CIRCLED DIGIT ONE
919 char_type const ch = 0x2775 + bp_p.first;
920 row.addVirtual(i, docstring(1, ch), f, Change());
923 // The stopping condition is here so that the display of a
924 // bookmark can take place at paragraph start too.
925 if (i >= end || (i != pos && row.width() > width))
928 char_type c = par.getChar(i);
929 // The most special cases are handled first.
930 if (par.isInset(i)) {
931 Inset const * ins = par.getInset(i);
932 Dimension dim = bv_->coordCache().insets().dim(ins);
933 row.add(i, ins, dim, *fi, par.lookupChange(i));
934 } else if (c == ' ' && i + 1 == body_pos) {
935 // There is a space at i, but it should not be
936 // added as a separator, because it is just
937 // before body_pos. Instead, insert some spacing to
939 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
940 // this is needed to make sure that the row width is correct
942 int const add = max(fm.width(par.layout().labelsep),
943 labelEnd(row.pit()) - row.width());
944 row.addSpace(i, add, *fi, par.lookupChange(i));
945 } else if (c == '\t')
946 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
947 *fi, par.lookupChange(i));
948 else if (c == 0x2028 || c == 0x2029) {
950 * U+2028 LINE SEPARATOR
951 * U+2029 PARAGRAPH SEPARATOR
953 * These are special unicode characters that break
954 * lines/pragraphs. Not handling them lead to trouble wrt
955 * Qt QTextLayout formatting. We add a visible character
956 * on screen so that the user can see that something is
960 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
961 // ¶ U+00B6 PILCROW SIGN
962 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
963 row.add(i, screen_char, *fi, par.lookupChange(i));
965 row.add(i, c, *fi, par.lookupChange(i));
967 // add inline completion width
968 // draw logically behind the previous character
969 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
970 docstring const comp = bv_->inlineCompletion();
971 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
975 f.fontInfo().setColor(Color_inlinecompletion);
976 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
978 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
979 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
982 // Handle some situations that abruptly terminate the row
983 // - Before an inset with BreakBefore
984 // - After an inset with BreakAfter
985 Inset const * prevInset = !row.empty() ? row.back().inset : 0;
986 Inset const * nextInset = (i + 1 < end) ? par.getInset(i + 1) : 0;
987 if ((nextInset && nextInset->rowFlags() & Inset::BreakBefore)
988 || (prevInset && prevInset->rowFlags() & Inset::BreakAfter)) {
990 // Force a row creation after this one if it is ended by
991 // an inset that either
992 // - has row flag RowAfter that enforces that;
993 // - or (1) did force the row breaking, (2) is at end of
994 // paragraph and (3) the said paragraph has an end label.
995 need_new_row = prevInset &&
996 (prevInset->rowFlags() & Inset::RowAfter
997 || (prevInset->rowFlags() & Inset::BreakAfter && i + 1 == end
998 && text_->getEndLabel(row.pit()) != END_LABEL_NO_LABEL));
1009 // End of paragraph marker. The logic here is almost the
1010 // same as in redoParagraph, remember keep them in sync.
1011 ParagraphList const & pars = text_->paragraphs();
1012 Change const & change = par.lookupChange(i);
1013 if ((lyxrc.paragraph_markers || change.changed())
1015 && i == end && size_type(row.pit() + 1) < pars.size()) {
1016 // add a virtual element for the end-of-paragraph
1017 // marker; it is shown on screen, but does not exist
1018 // in the paragraph.
1019 Font f(text_->layoutFont(row.pit()));
1020 f.fontInfo().setColor(Color_paragraphmarker);
1021 f.setLanguage(par.getParLanguage(buf.params()));
1022 // ¶ U+00B6 PILCROW SIGN
1023 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, change);
1026 // Is there a end-of-paragaph change?
1027 if (i == end && par.lookupChange(end).changed() && !need_new_row)
1028 row.needsChangeBar(true);
1030 // if the row is too large, try to cut at last separator. In case
1031 // of success, reset indication that the row was broken abruptly.
1032 int const next_width = max_width_ - leftMargin(row.pit(), row.endpos())
1033 - rightMargin(row.pit());
1035 if (row.shortenIfNeeded(body_pos, width, next_width))
1037 row.right_boundary(!row.empty() && row.endpos() < end
1038 && row.back().endpos == row.endpos());
1039 // Last row in paragraph is flushed
1040 if (row.endpos() == end)
1043 // make sure that the RTL elements are in reverse ordering
1044 row.reverseRTL(is_rtl);
1045 //LYXERR0("breakrow: row is " << row);
1047 return need_new_row;
1050 int TextMetrics::parTopSpacing(pit_type const pit) const
1052 Paragraph const & par = text_->getPar(pit);
1053 Layout const & layout = par.layout();
1056 ParagraphList const & pars = text_->paragraphs();
1057 double const dh = defaultRowHeight();
1059 BufferParams const & bparams = bv_->buffer().params();
1060 Inset const & inset = text_->inset();
1061 // some parskips VERY EASY IMPLEMENTATION
1062 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1063 && !inset.getLayout().parbreakIsNewline()
1064 && !par.layout().parbreak_is_newline
1066 && ((layout.isParagraph() && par.getDepth() == 0)
1067 || (pars[pit - 1].layout().isParagraph()
1068 && pars[pit - 1].getDepth() == 0))) {
1069 asc += bparams.getDefSkip().inPixels(*bv_);
1072 if (par.params().startOfAppendix())
1075 // special code for the top label
1076 if (layout.labelIsAbove()
1077 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1078 && !par.labelString().empty()) {
1079 FontInfo labelfont = text_->labelFont(par);
1080 FontMetrics const & lfm = theFontMetrics(labelfont);
1081 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1082 * text_->spacing(par)
1083 + (layout.topsep + layout.labelbottomsep) * dh);
1086 // Add the layout spaces, for example before and after
1087 // a section, or between the items of a itemize or enumerate
1090 pit_type prev = text_->depthHook(pit, par.getDepth());
1091 Paragraph const & prevpar = pars[prev];
1092 double layoutasc = 0;
1094 && prevpar.layout() == layout
1095 && prevpar.getDepth() == par.getDepth()
1096 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1097 layoutasc = layout.itemsep * dh;
1098 } else if (pit != 0 && layout.topsep > 0)
1099 layoutasc = layout.topsep * dh;
1101 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1103 prev = text_->outerHook(pit);
1104 if (prev != pit_type(pars.size())) {
1105 asc += int(pars[prev].layout().parsep * dh);
1106 } else if (pit != 0) {
1107 Paragraph const & prevpar2 = pars[pit - 1];
1108 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1109 asc += int(layout.parsep * dh);
1116 int TextMetrics::parBottomSpacing(pit_type const pit) const
1118 double layoutdesc = 0;
1119 ParagraphList const & pars = text_->paragraphs();
1120 double const dh = defaultRowHeight();
1122 // add the layout spaces, for example before and after
1123 // a section, or between the items of a itemize or enumerate
1125 pit_type nextpit = pit + 1;
1126 if (nextpit != pit_type(pars.size())) {
1127 pit_type cpit = pit;
1129 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1130 double usual = pars[cpit].layout().bottomsep * dh;
1132 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1133 if (pars[cpit].layout() != pars[nextpit].layout()
1134 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1135 unusual = pars[cpit].layout().bottomsep * dh;
1136 layoutdesc = max(unusual, usual);
1137 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1138 if (pars[cpit].layout() != pars[nextpit].layout()
1139 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1140 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1144 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1148 void TextMetrics::setRowHeight(Row & row) const
1150 Paragraph const & par = text_->getPar(row.pit());
1151 Layout const & layout = par.layout();
1152 double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1154 // Initial value for ascent (useful if row is empty).
1155 Font const font = displayFont(row.pit(), row.pos());
1156 FontMetrics const & fm = theFontMetrics(font);
1157 int maxasc = int(fm.maxAscent() * spacing_val);
1158 int maxdes = int(fm.maxDescent() * spacing_val);
1160 // Take label string into account (useful if labelfont is large)
1161 if (row.pos() == 0 && layout.labelIsInline()) {
1162 FontInfo const labelfont = text_->labelFont(par);
1163 FontMetrics const & lfm = theFontMetrics(labelfont);
1164 maxasc = max(maxasc, int(lfm.maxAscent() * spacing_val));
1165 maxdes = max(maxdes, int(lfm.maxDescent() * spacing_val));
1168 // Find the ascent/descent of the row contents
1169 for (Row::Element const & e : row) {
1171 maxasc = max(maxasc, e.dim.ascent());
1172 maxdes = max(maxdes, e.dim.descent());
1174 FontMetrics const & fm2 = theFontMetrics(e.font);
1175 maxasc = max(maxasc, int(fm2.maxAscent() * spacing_val));
1176 maxdes = max(maxdes, int(fm2.maxDescent() * spacing_val));
1180 // This is nicer with box insets
1184 row.dim().asc = maxasc;
1185 row.dim().des = maxdes;
1189 // x is an absolute screen coord
1190 // returns the column near the specified x-coordinate of the row
1191 // x is set to the real beginning of this column
1192 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1193 bool & boundary) const
1195 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1196 /// For the main Text, it is possible that this pit is not
1197 /// yet in the CoordCache when moving cursor up.
1198 /// x Paragraph coordinate is always 0 for main text anyway.
1199 int const xo = origin_.x_;
1202 // Adapt to cursor row scroll offset if applicable.
1203 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1206 pos_type pos = row.pos();
1209 x = row.left_margin;
1210 else if (x <= row.left_margin) {
1211 pos = row.front().left_pos();
1212 x = row.left_margin;
1213 } else if (x >= row.width()) {
1214 pos = row.back().right_pos();
1217 double w = row.left_margin;
1218 Row::const_iterator cit = row.begin();
1219 Row::const_iterator cend = row.end();
1220 for ( ; cit != cend; ++cit) {
1221 if (w <= x && w + cit->full_width() > x) {
1222 int x_offset = int(x - w);
1223 pos = cit->x2pos(x_offset);
1224 x = int(x_offset + w);
1227 w += cit->full_width();
1229 if (cit == row.end()) {
1230 pos = row.back().right_pos();
1233 /** This tests for the case where the cursor is placed
1234 * just before a font direction change. See comment on
1235 * the boundary_ member in DocIterator.h to understand
1236 * how boundary helps here.
1238 else if (pos == cit->endpos
1239 && ((!cit->isRTL() && cit + 1 != row.end()
1240 && (cit + 1)->isRTL())
1241 || (cit->isRTL() && cit != row.begin()
1242 && !(cit - 1)->isRTL())))
1246 /** This tests for the case where the cursor is set at the end
1247 * of a row which has been broken due something else than a
1248 * separator (a display inset or a forced breaking of the
1249 * row). We know that there is a separator when the end of the
1250 * row is larger than the end of its last element.
1252 if (!row.empty() && pos == row.back().endpos
1253 && row.back().endpos == row.endpos()) {
1254 Inset const * inset = row.back().inset;
1255 if (inset && (inset->lyxCode() == NEWLINE_CODE
1256 || inset->lyxCode() == SEPARATOR_CODE))
1257 pos = row.back().pos;
1259 boundary = row.right_boundary();
1263 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1269 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1271 // We play safe and use parMetrics(pit) to make sure the
1272 // ParagraphMetrics will be redone and OK to use if needed.
1273 // Otherwise we would use an empty ParagraphMetrics in
1274 // upDownInText() while in selection mode.
1275 ParagraphMetrics const & pm = parMetrics(pit);
1277 LBUFERR(row < int(pm.rows().size()));
1279 Row const & r = pm.rows()[row];
1280 return getPosNearX(r, x, bound);
1284 // y is screen coordinate
1285 pit_type TextMetrics::getPitNearY(int y)
1287 LASSERT(!text_->paragraphs().empty(), return -1);
1288 LASSERT(!par_metrics_.empty(), return -1);
1289 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1291 // look for highest numbered paragraph with y coordinate less than given y
1294 ParMetricsCache::const_iterator it = par_metrics_.begin();
1295 ParMetricsCache::const_iterator et = par_metrics_.end();
1296 ParMetricsCache::const_iterator last = et;
1299 ParagraphMetrics const & pm = it->second;
1301 if (y < it->second.position() - int(pm.ascent())) {
1302 // We are looking for a position that is before the first paragraph in
1303 // the cache (which is in priciple off-screen, that is before the
1306 // We are already at the first paragraph in the inset.
1308 // OK, this is the paragraph we are looking for.
1309 pit = it->first - 1;
1314 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1316 if (y >= last->second.position() + int(pm_last.descent())) {
1317 // We are looking for a position that is after the last paragraph in
1318 // the cache (which is in priciple off-screen), that is before the
1320 pit = last->first + 1;
1321 if (pit == int(text_->paragraphs().size()))
1322 // We are already at the last paragraph in the inset.
1324 // OK, this is the paragraph we are looking for.
1325 newParMetricsDown();
1329 for (; it != et; ++it) {
1330 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1331 << " y: " << it->second.position());
1333 ParagraphMetrics const & pm2 = par_metrics_[it->first];
1335 if (it->first >= pit && int(it->second.position()) - int(pm2.ascent()) <= y) {
1337 yy = it->second.position();
1341 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1347 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1348 bool assert_in_view, bool up)
1350 ParagraphMetrics const & pm = par_metrics_[pit];
1352 int yy = pm.position() - pm.rows().front().ascent();
1353 LBUFERR(!pm.rows().empty());
1354 RowList::const_iterator rit = pm.rows().begin();
1355 RowList::const_iterator rlast = pm.rows().end();
1357 for (; rit != rlast; yy += rit->height(), ++rit)
1358 if (yy + rit->height() > y)
1361 if (assert_in_view) {
1362 if (!up && yy + rit->height() > y) {
1363 if (rit != pm.rows().begin()) {
1366 } else if (pit != 0) {
1369 ParagraphMetrics const & pm2 = par_metrics_[pit];
1370 rit = pm2.rows().end();
1374 } else if (up && yy != y) {
1376 y = yy + rit->height();
1378 } else if (pit < int(text_->paragraphs().size()) - 1) {
1380 newParMetricsDown();
1381 ParagraphMetrics const & pm2 = par_metrics_[pit];
1382 rit = pm2.rows().begin();
1391 // x,y are absolute screen coordinates
1392 // sets cursor recursively descending into nested editable insets
1393 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1394 bool assert_in_view, bool up)
1396 if (lyxerr.debugging(Debug::WORKAREA)) {
1397 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1398 cur.bv().coordCache().dump();
1400 pit_type pit = getPitNearY(y);
1401 LASSERT(pit != -1, return 0);
1402 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1405 // Do we cover an inset?
1406 InsetList::Element * e = checkInsetHit(pit, x, y);
1409 // No inset, set position in the text
1410 bool bound = false; // is modified by getPosNearX
1411 cur.pos() = getPosNearX(row, x, bound);
1412 cur.boundary(bound);
1413 cur.setCurrentFont();
1418 Inset * inset = e->inset;
1419 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1421 // Set position in front of inset
1423 cur.boundary(false);
1426 // Try to descend recursively inside the inset.
1427 Inset * edited = inset->editXY(cur, x, y);
1428 // FIXME: it is not clear that the test on position is needed
1429 // Remove it if/when semantics of editXY is clarified
1430 if (cur.text() == text_ && cur.pos() == e->pos) {
1431 // non-editable inset, set cursor after the inset if x is
1432 // nearer to that position (bug 9628)
1433 bool bound = false; // is modified by getPosNearX
1434 cur.pos() = getPosNearX(row, x, bound);
1435 cur.boundary(bound);
1436 cur.setCurrentFont();
1440 if (cur.top().text() == text_)
1441 cur.setCurrentFont();
1446 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1448 LASSERT(text_ == cur.text(), return);
1449 pit_type const pit = getPitNearY(y);
1450 LASSERT(pit != -1, return);
1452 ParagraphMetrics const & pm = par_metrics_[pit];
1454 int yy = pm.position() - pm.rows().front().ascent();
1455 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1456 " pit: " << pit << " yy: " << yy);
1459 LBUFERR(pm.rows().size());
1460 for (; r < int(pm.rows().size()) - 1; ++r) {
1461 Row const & row = pm.rows()[r];
1462 if (int(yy + row.height()) > y)
1467 Row const & row = pm.rows()[r];
1469 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1473 pos_type const pos = getPosNearX(row, xx, bound);
1475 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1477 text_->setCursor(cur, pit, pos, true, bound);
1478 // remember new position.
1483 //takes screen x,y coordinates
1484 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1486 Paragraph const & par = text_->paragraphs()[pit];
1487 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1489 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1491 for (InsetList::Element const & e : par.insetList()) {
1492 LYXERR(Debug::DEBUG, "examining inset " << e.inset);
1494 if (insetCache.covers(e.inset, x, y)) {
1495 LYXERR(Debug::DEBUG, "Hit inset: " << e.inset);
1496 return const_cast<InsetList::Element *>(&e);
1500 LYXERR(Debug::DEBUG, "No inset hit. ");
1505 //takes screen x,y coordinates
1506 Inset * TextMetrics::checkInsetHit(int x, int y)
1508 pit_type const pit = getPitNearY(y);
1509 LASSERT(pit != -1, return 0);
1510 InsetList::Element * e = checkInsetHit(pit, x, y);
1519 int TextMetrics::cursorX(CursorSlice const & sl,
1520 bool boundary) const
1522 LASSERT(sl.text() == text_, return 0);
1524 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1525 if (pm.rows().empty())
1527 Row const & row = pm.getRow(sl.pos(), boundary);
1528 pos_type const pos = sl.pos();
1531 row.findElement(pos, boundary, x);
1537 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1539 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1540 ParagraphMetrics const & pm = parMetrics(sl.pit());
1541 if (pm.rows().empty())
1545 h -= parMetrics(0).rows()[0].ascent();
1546 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1547 h += parMetrics(pit).height();
1550 if (pos && boundary)
1552 size_t const rend = pm.pos2row(pos);
1553 for (size_t rit = 0; rit != rend; ++rit)
1554 h += pm.rows()[rit].height();
1555 h += pm.rows()[rend].ascent();
1560 // the cursor set functions have a special mechanism. When they
1561 // realize you left an empty paragraph, they will delete it.
1563 bool TextMetrics::cursorHome(Cursor & cur)
1565 LASSERT(text_ == cur.text(), return false);
1566 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1567 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1568 return text_->setCursor(cur, cur.pit(), row.pos());
1572 bool TextMetrics::cursorEnd(Cursor & cur)
1574 LASSERT(text_ == cur.text(), return false);
1575 // if not on the last row of the par, put the cursor before
1576 // the final space exept if I have a spanning inset or one string
1577 // is so long that we force a break.
1578 pos_type end = cur.textRow().endpos();
1580 // empty text, end-1 is no valid position
1582 bool boundary = false;
1583 if (end != cur.lastpos()) {
1584 if (!cur.paragraph().isLineSeparator(end-1)
1585 && !cur.paragraph().isNewline(end-1)
1586 && !cur.paragraph().isEnvSeparator(end-1))
1590 } else if (cur.paragraph().isEnvSeparator(end-1))
1592 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1596 void TextMetrics::deleteLineForward(Cursor & cur)
1598 LASSERT(text_ == cur.text(), return);
1599 if (cur.lastpos() == 0) {
1600 // Paragraph is empty, so we just go forward
1601 text_->cursorForward(cur);
1604 cur.selection(true); // to avoid deletion
1607 // What is this test for ??? (JMarc)
1608 if (!cur.selection())
1609 text_->deleteWordForward(cur);
1611 cap::cutSelection(cur, false);
1612 cur.checkBufferStructure();
1617 int TextMetrics::leftMargin(pit_type pit) const
1619 // the + 1 is useful when the paragraph is empty
1620 return leftMargin(pit, text_->paragraphs()[pit].size() + 1);
1624 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1626 ParagraphList const & pars = text_->paragraphs();
1628 LASSERT(pit >= 0, return 0);
1629 LASSERT(pit < int(pars.size()), return 0);
1630 Paragraph const & par = pars[pit];
1631 LASSERT(pos >= 0, return 0);
1632 // We do not really care whether pos > par.size(), since we do not
1633 // access the data. It can be actially useful, when querying the
1634 // margin without indentation (see leftMargin(pit_type).
1636 Buffer const & buffer = bv_->buffer();
1637 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1638 DocumentClass const & tclass = buffer.params().documentClass();
1639 Layout const & layout = par.layout();
1640 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1642 docstring parindent = layout.parindent;
1646 if (text_->isMainText()) {
1647 l_margin += bv_->leftMargin();
1648 l_margin += bfm.signedWidth(tclass.leftmargin());
1651 int depth = par.getDepth();
1653 // find the next level paragraph
1654 pit_type newpar = text_->outerHook(pit);
1655 if (newpar != pit_type(pars.size())) {
1656 if (pars[newpar].layout().isEnvironment()) {
1657 int nestmargin = depth * nestMargin();
1658 if (text_->isMainText())
1659 nestmargin += changebarMargin();
1660 l_margin = max(leftMargin(newpar), nestmargin);
1661 // Remove the parindent that has been added
1662 // if the paragraph was empty.
1663 if (pars[newpar].empty() &&
1664 buffer.params().paragraph_separation ==
1665 BufferParams::ParagraphIndentSeparation) {
1666 docstring pi = pars[newpar].layout().parindent;
1667 l_margin -= bfm.signedWidth(pi);
1670 if (tclass.isDefaultLayout(par.layout())
1671 || tclass.isPlainLayout(par.layout())) {
1672 if (pars[newpar].params().noindent())
1675 parindent = pars[newpar].layout().parindent;
1680 // This happens after sections or environments in standard classes.
1681 // We have to check the previous layout at same depth.
1682 if (buffer.params().paragraph_separation ==
1683 BufferParams::ParagraphSkipSeparation)
1685 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1686 pit_type prev = text_->depthHook(pit, par.getDepth());
1687 if (par.layout() == pars[prev].layout()) {
1689 && pars[pit - 1].layout().nextnoindent)
1691 } else if (pars[prev].layout().nextnoindent)
1695 FontInfo const labelfont = text_->labelFont(par);
1696 FontMetrics const & lfm = theFontMetrics(labelfont);
1698 switch (layout.margintype) {
1699 case MARGIN_DYNAMIC:
1700 if (!layout.leftmargin.empty()) {
1701 l_margin += bfm.signedWidth(layout.leftmargin);
1703 if (!par.labelString().empty()) {
1704 l_margin += lfm.signedWidth(layout.labelindent);
1705 l_margin += lfm.width(par.labelString());
1706 l_margin += lfm.width(layout.labelsep);
1710 case MARGIN_MANUAL: {
1711 l_margin += lfm.signedWidth(layout.labelindent);
1712 // The width of an empty par, even with manual label, should be 0
1713 if (!par.empty() && pos >= par.beginOfBody()) {
1714 if (!par.getLabelWidthString().empty()) {
1715 docstring labstr = par.getLabelWidthString();
1716 l_margin += lfm.width(labstr);
1717 l_margin += lfm.width(layout.labelsep);
1723 case MARGIN_STATIC: {
1724 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1725 / (par.getDepth() + 4);
1729 case MARGIN_FIRST_DYNAMIC:
1730 if (layout.labeltype == LABEL_MANUAL) {
1731 // if we are at position 0, we are never in the body
1732 if (pos > 0 && pos >= par.beginOfBody())
1733 l_margin += lfm.signedWidth(layout.leftmargin);
1735 l_margin += lfm.signedWidth(layout.labelindent);
1737 // Special case to fix problems with
1739 || (layout.labeltype == LABEL_STATIC
1740 && layout.latextype == LATEX_ENVIRONMENT
1741 && !text_->isFirstInSequence(pit))) {
1742 l_margin += lfm.signedWidth(layout.leftmargin);
1743 } else if (!layout.labelIsAbove()) {
1744 l_margin += lfm.signedWidth(layout.labelindent);
1745 l_margin += lfm.width(layout.labelsep);
1746 l_margin += lfm.width(par.labelString());
1750 case MARGIN_RIGHT_ADDRESS_BOX:
1751 // This is handled globally in redoParagraph().
1755 if (!par.params().leftIndent().zero())
1756 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1758 LyXAlignment align = par.getAlign(bv_->buffer().params());
1760 // set the correct parindent
1762 && (layout.labeltype == LABEL_NO_LABEL
1763 || layout.labeltype == LABEL_ABOVE
1764 || layout.labeltype == LABEL_CENTERED
1765 || (layout.labeltype == LABEL_STATIC
1766 && layout.latextype == LATEX_ENVIRONMENT
1767 && !text_->isFirstInSequence(pit)))
1768 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1769 && !par.params().noindent()
1770 // in some insets, paragraphs are never indented
1771 && !text_->inset().neverIndent()
1772 // display style insets do not need indentation
1775 && par.getInset(0)->rowFlags() & Inset::Display)
1776 && (!(tclass.isDefaultLayout(par.layout())
1777 || tclass.isPlainLayout(par.layout()))
1778 || buffer.params().paragraph_separation
1779 == BufferParams::ParagraphIndentSeparation)) {
1780 /* use the parindent of the layout when the default
1781 * indentation is used otherwise use the indentation set in
1782 * the document settings
1784 if (buffer.params().getParIndent().empty())
1785 l_margin += bfm.signedWidth(parindent);
1787 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1794 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1796 if (par_metrics_.empty())
1802 y -= par_metrics_.begin()->second.ascent();
1803 for (auto & pm_pair : par_metrics_) {
1804 pit_type const pit = pm_pair.first;
1805 ParagraphMetrics & pm = pm_pair.second;
1807 // Save the paragraph position in the cache.
1809 drawParagraph(pi, pit, x, y);
1815 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1817 ParagraphMetrics const & pm = par_metrics_[pit];
1818 if (pm.rows().empty())
1820 size_t const nrows = pm.rows().size();
1821 // Remember left and right margin for drawing math numbers
1822 Changer changeleft = changeVar(pi.leftx, x + leftMargin(pit));
1823 Changer changeright = changeVar(pi.rightx, x + width() - rightMargin(pit));
1825 // Use fast lane in nodraw stage.
1826 if (pi.pain.isNull()) {
1827 for (size_t i = 0; i != nrows; ++i) {
1829 Row const & row = pm.rows()[i];
1830 // Adapt to cursor row scroll offset if applicable.
1831 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1835 RowPainter rp(pi, *text_, row, row_x, y);
1837 rp.paintOnlyInsets();
1843 int const ww = bv_->workHeight();
1844 Cursor const & cur = bv_->cursor();
1845 DocIterator sel_beg = cur.selectionBegin();
1846 DocIterator sel_end = cur.selectionEnd();
1847 bool selection = cur.selection()
1848 // This is our text.
1849 && cur.text() == text_
1850 // if the anchor is outside, this is not our selection
1851 && cur.normalAnchor().text() == text_
1852 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1854 // We store the begin and end pos of the selection relative to this par
1855 DocIterator sel_beg_par = cur.selectionBegin();
1856 DocIterator sel_end_par = cur.selectionEnd();
1858 // We care only about visible selection.
1860 if (pit != sel_beg.pit()) {
1861 sel_beg_par.pit() = pit;
1862 sel_beg_par.pos() = 0;
1864 if (pit != sel_end.pit()) {
1865 sel_end_par.pit() = pit;
1866 sel_end_par.pos() = sel_end_par.lastpos();
1870 if (text_->isRTL(pit))
1871 swap(pi.leftx, pi.rightx);
1873 for (size_t i = 0; i != nrows; ++i) {
1875 Row const & row = pm.rows()[i];
1876 // Adapt to cursor row scroll offset if applicable.
1877 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1881 // It is not needed to draw on screen if we are not inside.
1882 bool const inside = (y + row.descent() >= 0
1883 && y - row.ascent() < ww);
1885 // Inset positions have already been set in nodraw stage.
1891 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
1893 row.clearSelectionAndMargins();
1895 // The row knows nothing about the paragraph, so we have to check
1896 // whether this row is the first or last and update the margins.
1897 if (row.selection()) {
1898 if (row.sel_beg == 0)
1899 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
1900 if (row.sel_end == sel_end_par.lastpos())
1901 row.change(row.end_margin_sel, sel_end.pit() > pit);
1904 // Take this opportunity to spellcheck the row contents.
1905 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
1906 text_->getPar(pit).spellCheck();
1909 RowPainter rp(pi, *text_, row, row_x, y);
1911 // Don't paint the row if a full repaint has not been requested
1912 // and if it has not changed.
1913 if (!pi.full_repaint && !row.changed()) {
1914 // Paint only the insets if the text itself is
1916 rp.paintOnlyInsets();
1922 // Clear background of this row if paragraph background was not
1923 // already cleared because of a full repaint.
1924 if (!pi.full_repaint && row.changed()) {
1925 LYXERR(Debug::PAINTING, "Clear rect@("
1926 << max(row_x, 0) << ", " << y - row.ascent() << ")="
1927 << width() << " x " << row.height());
1928 pi.pain.fillRectangle(row_x, y - row.ascent(),
1929 width(), row.height(), pi.background_color);
1932 // Instrumentation for testing row cache (see also
1934 if (lyxerr.debugging(Debug::PAINTING)
1935 && (row.selection() || pi.full_repaint || row.changed())) {
1936 string const foreword = text_->isMainText() ? "main text redraw "
1937 : "inset text redraw: ";
1938 LYXERR0(foreword << "pit=" << pit << " row=" << i
1939 << (row.selection() ? " row_selection": "")
1940 << (pi.full_repaint ? " full_repaint" : "")
1941 << (row.changed() ? " row.changed" : ""));
1944 // Backup full_repaint status and force full repaint
1945 // for inner insets as the Row has been cleared out.
1946 bool tmp = pi.full_repaint;
1947 pi.full_repaint = true;
1949 rp.paintSelection();
1952 if (row.needsChangeBar())
1953 rp.paintChangeBar();
1959 rp.paintTooLargeMarks(row_x + row.left_x() < 0,
1960 row_x + row.right_x() > bv_->workWidth());
1964 // This debug code shows on screen which rows are repainted.
1965 // FIXME: since the updates related to caret blinking restrict
1966 // the painter to a small rectangle, the numbers are not
1967 // updated when this happens. Change the code in
1968 // GuiWorkArea::Private::show/hideCaret if this is important.
1969 static int count = 0;
1971 FontInfo fi(sane_font);
1972 fi.setSize(TINY_SIZE);
1973 fi.setColor(Color_red);
1974 pi.pain.text(row_x, y, convert<docstring>(count), fi);
1977 // Restore full_repaint status.
1978 pi.full_repaint = tmp;
1983 //LYXERR(Debug::PAINTING, ".");
1987 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
1988 Dimension & dim) const
1990 DocIterator from = cur.bv().cursor();
1991 DocIterator to = from;
1992 text_->getWord(from.top(), to.top(), PREVIOUS_WORD);
1994 // The vertical dimension of the word
1995 Font const font = displayFont(cur.pit(), from.pos());
1996 FontMetrics const & fm = theFontMetrics(font);
1997 // the +1's below are related to the extra pixels added in setRowHeight
1998 dim.asc = fm.maxAscent() + 1;
1999 dim.des = fm.maxDescent() + 1;
2001 // get position on screen of the word start and end
2002 //FIXME: Is it necessary to explicitly set this to false?
2003 from.boundary(false);
2004 Point lxy = cur.bv().getPos(from);
2005 Point rxy = cur.bv().getPos(to);
2006 dim.wid = abs(rxy.x_ - lxy.x_);
2008 // calculate position of word
2010 x = min(rxy.x_, lxy.x_);
2012 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2013 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2016 int defaultRowHeight()
2018 return int(theFontMetrics(sane_font).maxHeight() * 1.2);