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 "buffer_funcs.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
28 #include "CutAndPaste.h"
29 #include "InsetList.h"
33 #include "MetricsInfo.h"
34 #include "ParagraphParameters.h"
35 #include "RowPainter.h"
37 #include "TextClass.h"
40 #include "insets/InsetText.h"
42 #include "mathed/InsetMathMacroTemplate.h"
44 #include "frontends/FontMetrics.h"
45 #include "frontends/Painter.h"
46 #include "frontends/NullPainter.h"
48 #include "support/debug.h"
49 #include "support/lassert.h"
59 using frontend::FontMetrics;
64 int numberOfLabelHfills(Paragraph const & par, Row const & row)
66 pos_type last = row.endpos() - 1;
67 pos_type first = row.pos();
69 // hfill *DO* count at the beginning of paragraphs!
71 while (first < last && par.isHfill(first))
75 last = min(last, par.beginOfBody());
77 for (pos_type p = first; p < last; ++p) {
84 // FIXME: this needs to be rewritten, probably by merging it into some
85 // code that, besides counting, sets the active status of the space
86 // inset in the row element.
87 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
88 pos_type const body_pos)
91 Row::const_iterator cit = row.begin();
92 Row::const_iterator const end = row.end();
93 for ( ; cit != end ; ++cit)
94 if (cit->pos >= body_pos
95 && cit->inset && pm.hfillExpansion(row, cit->pos))
103 /////////////////////////////////////////////////////////////////////
107 /////////////////////////////////////////////////////////////////////
110 TextMetrics::TextMetrics(BufferView * bv, Text * text)
111 : bv_(bv), text_(text)
114 max_width_ = bv_->workWidth();
115 dim_.wid = max_width_;
121 bool TextMetrics::contains(pit_type pit) const
123 return par_metrics_.find(pit) != par_metrics_.end();
127 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
129 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
134 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
136 ParMetricsCache::const_iterator it = par_metrics_.begin();
137 return make_pair(it->first, &it->second);
141 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
143 LBUFERR(!par_metrics_.empty());
144 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
145 return make_pair(it->first, &it->second);
149 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
151 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
152 if (pmc_it == par_metrics_.end()) {
153 pmc_it = par_metrics_.insert(
154 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
156 if (pmc_it->second.rows().empty() && redo)
158 return pmc_it->second;
162 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
164 LBUFERR(mi.base.textwidth > 0);
165 max_width_ = mi.base.textwidth;
166 // backup old dimension.
167 Dimension const old_dim = dim_;
170 dim_.wid = min_width;
171 pit_type const npar = text_->paragraphs().size();
173 // If there is more than one row, expand the text to
174 // the full allowable width.
175 dim_.wid = max_width_;
177 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
178 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
180 bool changed = false;
182 for (pit_type pit = 0; pit != npar; ++pit) {
183 changed |= redoParagraph(pit);
184 ParagraphMetrics const & pm = par_metrics_[pit];
186 if (dim_.wid < pm.width())
187 dim_.wid = pm.width();
190 dim_.asc = par_metrics_[0].ascent();
191 dim_.des = h - dim_.asc;
192 //lyxerr << "dim_.wid " << dim_.wid << endl;
193 //lyxerr << "dim_.asc " << dim_.asc << endl;
194 //lyxerr << "dim_.des " << dim_.des << endl;
196 changed |= dim_ != old_dim;
202 void TextMetrics::updatePosCache(pit_type pit) const
204 frontend::NullPainter np;
205 PainterInfo pi(bv_, np);
206 drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
210 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
212 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
216 int TextMetrics::rightMargin(pit_type const pit) const
218 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
222 void TextMetrics::applyOuterFont(Font & font) const
224 FontInfo lf(font_.fontInfo());
225 lf.reduce(bv_->buffer().params().getFont().fontInfo());
226 font.fontInfo().realize(lf);
230 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
232 LASSERT(pos >= 0, { static Font f; return f; });
234 ParagraphList const & pars = text_->paragraphs();
235 Paragraph const & par = pars[pit];
236 Layout const & layout = par.layout();
237 Buffer const & buffer = bv_->buffer();
239 BufferParams const & params = buffer.params();
240 pos_type const body_pos = par.beginOfBody();
242 // We specialize the 95% common case:
243 if (!par.getDepth()) {
244 Font f = par.getFontSettings(params, pos);
245 if (!text_->isMainText())
247 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
249 FontInfo const & lf = lab ? layout.labelfont : layout.font;
250 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
252 // In case the default family has been customized
253 if (lf.family() == INHERIT_FAMILY)
254 rlf.setFamily(params.getFont().fontInfo().family());
255 f.fontInfo().realize(rlf);
259 // The uncommon case need not be optimized as much
260 FontInfo const & layoutfont = pos < body_pos ?
261 layout.labelfont : layout.font;
263 Font font = par.getFontSettings(params, pos);
264 font.fontInfo().realize(layoutfont);
266 if (!text_->isMainText())
267 applyOuterFont(font);
269 // Realize against environment font information
270 // NOTE: the cast to pit_type should be removed when pit_type
271 // changes to a unsigned integer.
272 if (pit < pit_type(pars.size()))
273 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
275 // Realize with the fonts of lesser depth.
276 font.fontInfo().realize(params.getFont().fontInfo());
282 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
288 if (boundary && sl.pos() > 0)
291 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
295 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
297 // no RTL boundary at paragraph start
301 Font const & left_font = displayFont(pit, pos - 1);
303 return isRTLBoundary(pit, pos, left_font);
307 // isRTLBoundary returns false on a real end-of-line boundary,
308 // because otherwise the two boundary types get mixed up.
309 // This is the whole purpose of this being in TextMetrics.
310 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
311 Font const & font) const
313 if (// no RTL boundary at paragraph start
315 // if the metrics have not been calculated, then we are not
316 // on screen and can safely ignore issues about boundaries.
320 ParagraphMetrics & pm = par_metrics_[pit];
321 // no RTL boundary in empty paragraph
322 if (pm.rows().empty())
325 pos_type endpos = pm.getRow(pos - 1, false).endpos();
326 pos_type startpos = pm.getRow(pos, false).pos();
327 // no RTL boundary at line start:
328 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
330 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
333 Paragraph const & par = text_->getPar(pit);
334 // no RTL boundary at line break:
335 // abc|\n -> move right -> abc\n (and not: abc\n|
337 if (startpos == pos && endpos == pos && endpos != par.size()
338 && (par.isNewline(pos - 1)
339 || par.isEnvSeparator(pos - 1)
340 || par.isLineSeparator(pos - 1)
341 || par.isSeparator(pos - 1)))
344 bool left = font.isVisibleRightToLeft();
346 if (pos == par.size())
347 right = par.isRTL(bv_->buffer().params());
349 right = displayFont(pit, pos).isVisibleRightToLeft();
351 return left != right;
355 bool TextMetrics::redoParagraph(pit_type const pit)
357 Paragraph & par = text_->getPar(pit);
358 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
359 // redoParagraph() recursively inside parMetrics.
360 Dimension old_dim = parMetrics(pit, false).dim();
361 ParagraphMetrics & pm = par_metrics_[pit];
364 Buffer & buffer = bv_->buffer();
365 bool changed = false;
367 // Check whether there are InsetBibItems that need fixing
368 // FIXME: This check ought to be done somewhere else. It is the reason
369 // why text_ is not const. But then, where else to do it?
370 // Well, how can you end up with either (a) a biblio environment that
371 // has no InsetBibitem or (b) a biblio environment with more than one
372 // InsetBibitem? I think the answer is: when paragraphs are merged;
373 // when layout is set; when material is pasted.
374 if (par.brokenBiblio()) {
375 Cursor & cur = const_cast<Cursor &>(bv_->cursor());
376 // In some cases, we do not know how to record undo
377 if (&cur.inset() == &text_->inset())
378 cur.recordUndo(pit, pit);
380 int const moveCursor = par.fixBiblio(buffer);
382 // Is it necessary to update the cursor?
383 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
386 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
391 // Optimisation: this is used in the next two loops
392 // so better to calculate that once here.
393 int const right_margin = rightMargin(pm);
395 // iterator pointing to paragraph to resolve macros
396 DocIterator parPos = text_->macrocontextPosition();
400 LYXERR(Debug::INFO, "MacroContext not initialised!"
401 << " Going through the buffer again and hope"
402 << " the context is better then.");
403 // FIXME audit updateBuffer calls
404 // This should not be here, but it is not clear yet where else it
406 bv_->buffer().updateBuffer();
407 parPos = text_->macrocontextPosition();
408 LBUFERR(!parPos.empty());
413 par.setBeginOfBody();
414 Font const bufferfont = buffer.params().getFont();
415 CoordCache::Insets & insetCache = bv_->coordCache().insets();
416 InsetList::const_iterator ii = par.insetList().begin();
417 InsetList::const_iterator iend = par.insetList().end();
418 for (; ii != iend; ++ii) {
419 // FIXME Doesn't this HAVE to be non-empty?
420 // position already initialized?
421 if (!parPos.empty()) {
422 parPos.pos() = ii->pos;
424 // A macro template would normally not be visible
425 // by itself. But the tex macro semantics allow
426 // recursion, so we artifically take the context
427 // after the macro template to simulate this.
428 if (ii->inset->lyxCode() == MATHMACRO_CODE)
432 // If there is an end of paragraph marker, its size should be
433 // substracted to the available width. The logic here is
434 // almost the same as in breakRow, remember keep them in sync.
436 if (lyxrc.paragraph_markers && ii->pos + 1 == par.size()
437 && size_type(pit + 1) < text_->paragraphs().size()) {
438 Font f(text_->layoutFont(pit));
439 // ¶ U+00B6 PILCROW SIGN
440 eop = theFontMetrics(f).width(char_type(0x00B6));
443 // do the metric calculation
445 int const w = max_width_ - leftMargin(pit, ii->pos)
446 - right_margin - eop;
447 Font const & font = ii->inset->inheritFont() ?
448 displayFont(pit, ii->pos) : bufferfont;
449 MacroContext mc(&buffer, parPos);
450 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
451 ii->inset->metrics(mi, dim);
452 if (!insetCache.has(ii->inset) || insetCache.dim(ii->inset) != dim) {
453 insetCache.add(ii->inset, dim);
459 size_t row_index = 0;
460 bool need_new_row = false;
461 // maximum pixel width of a row
463 if (row_index == pm.rows().size())
464 pm.rows().push_back(Row());
465 Row & row = pm.rows()[row_index];
469 need_new_row = breakRow(row, right_margin);
471 row.setChanged(false);
472 if (row_index || row.endpos() < par.size()
473 || (row.right_boundary() && par.inInset().lyxCode() != CELL_CODE)) {
474 /* If there is more than one row or the row has been
475 * broken by a display inset or a newline, expand the text
476 * to the full allowable width. This setting here is
477 * needed for the computeRowMetrics() below. In the case
478 * of a display inset, we do nothing when inside a table
479 * cell, because the tabular code is not prepared for
480 * that, and it triggers when using a caption in a
481 * longtable (see bugs #9945 and #9757).
483 if (dim_.wid < max_width_)
484 dim_.wid = max_width_;
486 int const max_row_width = max(dim_.wid, row.width());
487 computeRowMetrics(row, max_row_width);
488 first = row.endpos();
491 pm.dim().wid = max(pm.dim().wid, row.width());
492 pm.dim().des += row.height();
493 } while (first < par.size() || need_new_row);
495 if (row_index < pm.rows().size())
496 pm.rows().resize(row_index);
498 // FIXME: It might be better to move this in another method
499 // specially tailored for the main text.
500 // Top and bottom margin of the document (only at top-level)
501 if (text_->isMainText()) {
502 // original value was 20px, which is 0.2in at 100dpi
503 int const margin = Length(0.2, Length::IN).inPixels(0);
505 pm.rows().front().dimension().asc += margin;
506 /* coverity thinks that we should update pm.dim().asc
507 * below, but all the rows heights are actually counted as
508 * part of the paragraph metric descent see loop above).
510 // coverity[copy_paste_error]
511 pm.dim().des += margin;
513 ParagraphList const & pars = text_->paragraphs();
514 if (pit + 1 == pit_type(pars.size())) {
515 pm.rows().back().dimension().des += margin;
516 pm.dim().des += margin;
520 // The space above and below the paragraph.
521 int const top = parTopSpacing(pit);
522 pm.rows().front().dimension().asc += top;
523 int const bottom = parBottomSpacing(pit);
524 pm.rows().back().dimension().des += bottom;
525 pm.dim().des += top + bottom;
527 pm.dim().asc += pm.rows()[0].ascent();
528 pm.dim().des -= pm.rows()[0].ascent();
530 changed |= old_dim.height() != pm.dim().height();
536 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
538 LyXAlignment align = par.getAlign();
540 // handle alignment inside tabular cells
541 Inset const & owner = text_->inset();
542 bool forced_block = false;
543 switch (owner.contentAlignment()) {
544 case LYX_ALIGN_BLOCK:
545 // In general block align is the default state, but here it is
546 // an explicit choice. Therefore it should not be overridden
550 case LYX_ALIGN_CENTER:
552 case LYX_ALIGN_RIGHT:
553 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
554 align = owner.contentAlignment();
557 // unchanged (use align)
561 // Display-style insets should always be on a centered row
562 if (Inset const * inset = par.getInset(row.pos())) {
563 switch (inset->display()) {
564 case Inset::AlignLeft:
565 align = LYX_ALIGN_BLOCK;
567 case Inset::AlignCenter:
568 align = LYX_ALIGN_CENTER;
571 // unchanged (use align)
573 case Inset::AlignRight:
574 align = LYX_ALIGN_RIGHT;
579 if (align == LYX_ALIGN_BLOCK) {
580 // If this row has been broken abruptly by a display inset, or
581 // it is the end of the paragraph, or the user requested we
582 // not justify stuff, then don't stretch.
583 // A forced block alignment can only be overridden the 'no
584 // justification on screen' setting.
585 if ((row.flushed() && !forced_block)
586 || !bv_->buffer().params().justification)
587 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
594 void TextMetrics::computeRowMetrics(Row & row, int width) const
599 Paragraph const & par = text_->getPar(row.pit());
601 int const w = width - row.right_margin - row.width();
602 // FIXME: put back this assertion when the crash on new doc is solved.
603 //LASSERT(w >= 0, /**/);
605 // is there a manual margin with a manual label
606 Layout const & layout = par.layout();
609 if (layout.margintype == MARGIN_MANUAL
610 && layout.labeltype == LABEL_MANUAL) {
611 /// We might have real hfills in the label part
612 nlh = numberOfLabelHfills(par, row);
614 // A manual label par (e.g. List) has an auto-hfill
615 // between the label text and the body of the
617 // But we don't want to do this auto hfill if the par
622 if (nlh && !par.getLabelWidthString().empty())
623 row.label_hfill = labelFill(row) / double(nlh);
626 // are there any hfills in the row?
627 ParagraphMetrics & pm = par_metrics_[row.pit()];
628 int nh = numberOfHfills(row, pm, par.beginOfBody());
632 // We don't have to look at the alignment if the row is already
633 // larger then the permitted width as then we force the
634 // LEFT_ALIGN'edness!
635 if (int(row.width()) >= max_width_)
639 // Common case : there is no hfill, and the alignment will be
641 switch (getAlign(par, row)) {
642 case LYX_ALIGN_BLOCK:
643 // Expand expanding characters by a total of w
644 if (!row.setExtraWidth(w) && row.isRTL()) {
645 // Justification failed and the text is RTL: align to the right
646 row.left_margin += w;
647 row.dimension().wid += w;
651 // a displayed inset that is flushed
652 if (Inset const * inset = par.getInset(row.pos())) {
653 row.left_margin += inset->indent(*bv_);
654 row.dimension().wid += inset->indent(*bv_);
657 case LYX_ALIGN_RIGHT:
658 if (Inset const * inset = par.getInset(row.pos())) {
659 int const new_w = max(w - inset->indent(*bv_), 0);
660 row.left_margin += new_w;
661 row.dimension().wid += new_w;
663 row.left_margin += w;
664 row.dimension().wid += w;
667 case LYX_ALIGN_CENTER:
668 row.dimension().wid += w / 2;
669 row.left_margin += w / 2;
672 case LYX_ALIGN_LAYOUT:
673 case LYX_ALIGN_SPECIAL:
674 case LYX_ALIGN_DECIMAL:
680 // Case nh > 0. There are hfill separators.
683 row.dimension().wid += w;
684 // Set size of hfill insets
685 pos_type const endpos = row.endpos();
686 pos_type body_pos = par.beginOfBody();
688 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
691 CoordCache::Insets & insetCache = bv_->coordCache().insets();
692 Row::iterator cit = row.begin();
693 Row::iterator const cend = row.end();
694 for ( ; cit != cend; ++cit) {
695 if (row.label_hfill && cit->endpos == body_pos
696 && cit->type == Row::SPACE)
697 cit->dim.wid -= int(row.label_hfill * (nlh - 1));
698 if (cit->inset && pm.hfillExpansion(row, cit->pos)) {
699 if (cit->pos >= body_pos) {
700 cit->dim.wid += hfill;
703 cit->dim.wid += hfill_rem;
705 cit->dim.wid += int(row.label_hfill);
706 // Cache the inset dimension.
707 insetCache.add(cit->inset, cit->dim);
713 int TextMetrics::labelFill(Row const & row) const
715 Paragraph const & par = text_->getPar(row.pit());
716 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
719 Row::const_iterator cit = row.begin();
720 Row::const_iterator const end = row.end();
721 // iterate over elements before main body (except the last one,
722 // which is extra space).
723 while (cit!= end && cit->endpos < par.beginOfBody()) {
728 docstring const & label = par.params().labelWidthString();
732 FontMetrics const & fm
733 = theFontMetrics(text_->labelFont(par));
735 return max(0, fm.width(label) - w);
740 // Not used, see TextMetrics::breakRow
741 // this needs special handling - only newlines count as a break point
742 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
744 pos_type const end = par.size();
747 if (par.isNewline(i))
755 int TextMetrics::labelEnd(pit_type const pit) const
757 // labelEnd is only needed if the layout fills a flushleft label.
758 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
760 // return the beginning of the body
761 return leftMargin(pit);
767 * Calling Text::getFont is slow. While rebreaking we scan a
768 * paragraph from left to right calling getFont for every char. This
769 * simple class address this problem by hidding an optimization trick
770 * (not mine btw -AB): the font is reused in the whole font span. The
771 * class handles transparently the "hidden" (not part of the fontlist)
772 * label font (as getFont does).
778 FontIterator(TextMetrics const & tm,
779 Paragraph const & par, pit_type pit, pos_type pos)
780 : tm_(tm), par_(par), pit_(pit), pos_(pos),
781 font_(tm.displayFont(pit, pos)),
782 endspan_(par.fontSpan(pos).last),
783 bodypos_(par.beginOfBody())
787 Font const & operator*() const { return font_; }
790 FontIterator & operator++()
793 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
794 font_ = tm_.displayFont(pit_, pos_);
795 endspan_ = par_.fontSpan(pos_).last;
801 Font * operator->() { return &font_; }
805 TextMetrics const & tm_;
807 Paragraph const & par_;
822 /** This is the function where the hard work is done. The code here is
823 * very sensitive to small changes :) Note that part of the
824 * intelligence is also in Row::shortenIfNeeded.
826 bool TextMetrics::breakRow(Row & row, int const right_margin) const
828 Paragraph const & par = text_->getPar(row.pit());
829 pos_type const end = par.size();
830 pos_type const pos = row.pos();
831 pos_type const body_pos = par.beginOfBody();
832 bool const is_rtl = text_->isRTL(par);
833 bool need_new_row = false;
836 row.left_margin = leftMargin(row.pit(), pos);
837 row.right_margin = right_margin;
839 swap(row.left_margin, row.right_margin);
840 // Remember that the row width takes into account the left_margin
841 // but not the right_margin.
842 row.dimension().wid = row.left_margin;
843 // the width available for the row.
844 int const width = max_width_ - row.right_margin;
846 if (pos >= end || row.width() > width) {
852 //FIXME: As long as leftMargin() is not correctly implemented for
853 // MARGIN_RIGHT_ADDRESS_BOX, we should also not do this here.
854 // Otherwise, long rows will be painted off the screen.
855 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX)
856 return addressBreakPoint(pos, par);
859 // check for possible inline completion
860 DocIterator const & ic_it = bv_->inlineCompletionPos();
861 pos_type ic_pos = -1;
862 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == row.pit())
863 ic_pos = ic_it.pos();
865 // Now we iterate through until we reach the right margin
866 // or the end of the par, then build a representation of the row.
868 FontIterator fi = FontIterator(*this, par, row.pit(), pos);
870 // this can happen for an empty row after a newline
873 char_type c = par.getChar(i);
874 // The most special cases are handled first.
875 if (par.isInset(i)) {
876 Inset const * ins = par.getInset(i);
877 Dimension dim = bv_->coordCache().insets().dim(ins);
878 row.add(i, ins, dim, *fi, par.lookupChange(i));
879 } else if (c == ' ' && i + 1 == body_pos) {
880 // There is a space at i, but it should not be
881 // added as a separator, because it is just
882 // before body_pos. Instead, insert some spacing to
884 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
885 // this is needed to make sure that the row width is correct
887 int const add = max(fm.width(par.layout().labelsep),
888 labelEnd(row.pit()) - row.width());
889 row.addSpace(i, add, *fi, par.lookupChange(i));
890 } else if (c == '\t')
891 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
892 *fi, par.lookupChange(i));
893 else if (c == 0x2028 || c == 0x2029) {
895 * U+2028 LINE SEPARATOR
896 * U+2029 PARAGRAPH SEPARATOR
898 * These are special unicode characters that break
899 * lines/pragraphs. Not handling them lead to trouble wrt
900 * Qt QTextLayout formatting. We add a visible character
901 * on screen so that the user can see that something is
905 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
906 // ¶ U+00B6 PILCROW SIGN
907 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
908 row.add(i, screen_char, *fi, par.lookupChange(i));
910 // FIXME: please someone fix the Hebrew/Arabic parenthesis mess!
911 // see also Paragraph::getUChar.
912 if (fi->language()->lang() == "hebrew") {
918 row.add(i, c, *fi, par.lookupChange(i));
921 // add inline completion width
922 // draw logically behind the previous character
923 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
924 docstring const comp = bv_->inlineCompletion();
925 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
929 f.fontInfo().setColor(Color_inlinecompletion);
930 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
932 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
933 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
936 // Handle some situations that abruptly terminate the row
938 // - Before a display inset
939 // - After a display inset
940 Inset const * inset = 0;
941 if (par.isNewline(i) || par.isEnvSeparator(i)
942 || (i + 1 < end && (inset = par.getInset(i + 1))
944 || (!row.empty() && row.back().inset
945 && row.back().inset->display())) {
947 need_new_row = par.isNewline(i);
954 } while (i < end && row.width() <= width);
958 // End of paragraph marker. The logic here is almost the
959 // same as in redoParagraph, remember keep them in sync.
960 ParagraphList const & pars = text_->paragraphs();
961 if (lyxrc.paragraph_markers && !need_new_row
962 && i == end && size_type(row.pit() + 1) < pars.size()) {
963 // add a virtual element for the end-of-paragraph
964 // marker; it is shown on screen, but does not exist
966 Font f(text_->layoutFont(row.pit()));
967 f.fontInfo().setColor(Color_paragraphmarker);
968 BufferParams const & bparams
969 = text_->inset().buffer().params();
970 f.setLanguage(par.getParLanguage(bparams));
971 // ¶ U+00B6 PILCROW SIGN
972 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, Change());
975 // Is there a end-of-paragaph change?
976 if (i == end && par.lookupChange(end).changed() && !need_new_row)
977 row.needsChangeBar(true);
979 // if the row is too large, try to cut at last separator. In case
980 // of success, reset indication that the row was broken abruptly.
981 int const next_width = max_width_ - leftMargin(row.pit(), row.endpos())
982 - rightMargin(row.pit());
984 if (row.shortenIfNeeded(body_pos, width, next_width))
986 row.right_boundary(!row.empty() && row.endpos() < end
987 && row.back().endpos == row.endpos());
988 // Last row in paragraph is flushed
989 if (row.endpos() == end)
992 // make sure that the RTL elements are in reverse ordering
993 row.reverseRTL(is_rtl);
994 //LYXERR0("breakrow: row is " << row);
999 int TextMetrics::parTopSpacing(pit_type const pit) const
1001 Paragraph const & par = text_->getPar(pit);
1002 Layout const & layout = par.layout();
1005 ParagraphList const & pars = text_->paragraphs();
1006 double const dh = defaultRowHeight();
1008 BufferParams const & bparams = bv_->buffer().params();
1009 Inset const & inset = text_->inset();
1010 // some parskips VERY EASY IMPLEMENTATION
1011 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1012 && !inset.getLayout().parbreakIsNewline()
1013 && !par.layout().parbreak_is_newline
1015 && ((layout.isParagraph() && par.getDepth() == 0)
1016 || (pars[pit - 1].layout().isParagraph()
1017 && pars[pit - 1].getDepth() == 0))) {
1018 asc += bparams.getDefSkip().inPixels(*bv_);
1021 if (par.params().startOfAppendix())
1024 // special code for the top label
1025 if (layout.labelIsAbove()
1026 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1027 && !par.labelString().empty()) {
1028 FontInfo labelfont = text_->labelFont(par);
1029 FontMetrics const & lfm = theFontMetrics(labelfont);
1030 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1031 * text_->spacing(par)
1032 + (layout.topsep + layout.labelbottomsep) * dh);
1035 // Add the layout spaces, for example before and after
1036 // a section, or between the items of a itemize or enumerate
1039 pit_type prev = text_->depthHook(pit, par.getDepth());
1040 Paragraph const & prevpar = pars[prev];
1041 double layoutasc = 0;
1043 && prevpar.layout() == layout
1044 && prevpar.getDepth() == par.getDepth()
1045 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1046 layoutasc = layout.itemsep * dh;
1047 } else if (pit != 0 && layout.topsep > 0)
1048 layoutasc = layout.topsep * dh;
1050 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1052 prev = text_->outerHook(pit);
1053 if (prev != pit_type(pars.size())) {
1054 asc += int(pars[prev].layout().parsep * dh);
1055 } else if (pit != 0) {
1056 Paragraph const & prevpar = pars[pit - 1];
1057 if (prevpar.getDepth() != 0 || prevpar.layout() == layout)
1058 asc += int(layout.parsep * dh);
1065 int TextMetrics::parBottomSpacing(pit_type const pit) const
1067 double layoutdesc = 0;
1068 ParagraphList const & pars = text_->paragraphs();
1069 double const dh = defaultRowHeight();
1071 // add the layout spaces, for example before and after
1072 // a section, or between the items of a itemize or enumerate
1074 pit_type nextpit = pit + 1;
1075 if (nextpit != pit_type(pars.size())) {
1076 pit_type cpit = pit;
1078 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1079 double usual = pars[cpit].layout().bottomsep * dh;
1081 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1082 if (pars[cpit].layout() != pars[nextpit].layout()
1083 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1084 unusual = pars[cpit].layout().bottomsep * dh;
1085 layoutdesc = max(unusual, usual);
1086 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1087 if (pars[cpit].layout() != pars[nextpit].layout()
1088 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1089 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1093 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1097 void TextMetrics::setRowHeight(Row & row) const
1099 Paragraph const & par = text_->getPar(row.pit());
1100 Layout const & layout = par.layout();
1101 double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1103 // Initial value for ascent (useful if row is empty).
1104 Font const font = displayFont(row.pit(), row.pos());
1105 FontMetrics const & fm = theFontMetrics(font);
1106 int maxasc = int(fm.maxAscent() * spacing_val);
1107 int maxdes = int(fm.maxDescent() * spacing_val);
1109 // Find the ascent/descent of the row contents
1110 Row::const_iterator cit = row.begin();
1111 Row::const_iterator cend = row.end();
1112 for ( ; cit != cend; ++cit) {
1114 maxasc = max(maxasc, cit->dim.ascent());
1115 maxdes = max(maxdes, cit->dim.descent());
1117 FontMetrics const & fm = theFontMetrics(cit->font);
1118 maxasc = max(maxasc, int(fm.maxAscent() * spacing_val));
1119 maxdes = max(maxdes, int(fm.maxDescent() * spacing_val));
1123 // This is nicer with box insets
1127 row.dimension().asc = maxasc;
1128 row.dimension().des = maxdes;
1132 // x is an absolute screen coord
1133 // returns the column near the specified x-coordinate of the row
1134 // x is set to the real beginning of this column
1135 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1136 bool & boundary) const
1138 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1139 /// For the main Text, it is possible that this pit is not
1140 /// yet in the CoordCache when moving cursor up.
1141 /// x Paragraph coordinate is always 0 for main text anyway.
1142 int const xo = origin_.x_;
1145 // Adapt to cursor row scroll offset if applicable.
1146 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1149 pos_type pos = row.pos();
1152 x = row.left_margin;
1153 else if (x <= row.left_margin) {
1154 pos = row.front().left_pos();
1155 x = row.left_margin;
1156 } else if (x >= row.width()) {
1157 pos = row.back().right_pos();
1160 double w = row.left_margin;
1161 Row::const_iterator cit = row.begin();
1162 Row::const_iterator cend = row.end();
1163 for ( ; cit != cend; ++cit) {
1164 if (w <= x && w + cit->full_width() > x) {
1165 int x_offset = int(x - w);
1166 pos = cit->x2pos(x_offset);
1167 x = int(x_offset + w);
1170 w += cit->full_width();
1172 if (cit == row.end()) {
1173 pos = row.back().right_pos();
1176 /** This tests for the case where the cursor is placed
1177 * just before a font direction change. See comment on
1178 * the boundary_ member in DocIterator.h to understand
1179 * how boundary helps here.
1181 else if (pos == cit->endpos
1182 && ((!cit->isRTL() && cit + 1 != row.end()
1183 && (cit + 1)->isRTL())
1184 || (cit->isRTL() && cit != row.begin()
1185 && !(cit - 1)->isRTL())))
1189 /** This tests for the case where the cursor is set at the end
1190 * of a row which has been broken due something else than a
1191 * separator (a display inset or a forced breaking of the
1192 * row). We know that there is a separator when the end of the
1193 * row is larger than the end of its last element.
1195 if (!row.empty() && pos == row.back().endpos
1196 && row.back().endpos == row.endpos()) {
1197 Inset const * inset = row.back().inset;
1198 if (inset && (inset->lyxCode() == NEWLINE_CODE
1199 || inset->lyxCode() == SEPARATOR_CODE))
1200 pos = row.back().pos;
1202 boundary = row.right_boundary();
1206 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1212 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1214 // We play safe and use parMetrics(pit) to make sure the
1215 // ParagraphMetrics will be redone and OK to use if needed.
1216 // Otherwise we would use an empty ParagraphMetrics in
1217 // upDownInText() while in selection mode.
1218 ParagraphMetrics const & pm = parMetrics(pit);
1220 LBUFERR(row < int(pm.rows().size()));
1222 Row const & r = pm.rows()[row];
1223 return getPosNearX(r, x, bound);
1227 void TextMetrics::newParMetricsDown()
1229 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1230 pit_type const pit = last.first + 1;
1231 if (pit == int(text_->paragraphs().size()))
1234 // do it and update its position.
1236 par_metrics_[pit].setPosition(last.second.position()
1237 + last.second.descent() + par_metrics_[pit].ascent());
1238 updatePosCache(pit);
1242 void TextMetrics::newParMetricsUp()
1244 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1245 if (first.first == 0)
1248 pit_type const pit = first.first - 1;
1249 // do it and update its position.
1251 par_metrics_[pit].setPosition(first.second.position()
1252 - first.second.ascent() - par_metrics_[pit].descent());
1253 updatePosCache(pit);
1256 // y is screen coordinate
1257 pit_type TextMetrics::getPitNearY(int y)
1259 LASSERT(!text_->paragraphs().empty(), return -1);
1260 LASSERT(!par_metrics_.empty(), return -1);
1261 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1263 // look for highest numbered paragraph with y coordinate less than given y
1266 ParMetricsCache::const_iterator it = par_metrics_.begin();
1267 ParMetricsCache::const_iterator et = par_metrics_.end();
1268 ParMetricsCache::const_iterator last = et;
1271 ParagraphMetrics const & pm = it->second;
1273 if (y < it->second.position() - int(pm.ascent())) {
1274 // We are looking for a position that is before the first paragraph in
1275 // the cache (which is in priciple off-screen, that is before the
1278 // We are already at the first paragraph in the inset.
1280 // OK, this is the paragraph we are looking for.
1281 pit = it->first - 1;
1286 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1288 if (y >= last->second.position() + int(pm_last.descent())) {
1289 // We are looking for a position that is after the last paragraph in
1290 // the cache (which is in priciple off-screen), that is before the
1292 pit = last->first + 1;
1293 if (pit == int(text_->paragraphs().size()))
1294 // We are already at the last paragraph in the inset.
1296 // OK, this is the paragraph we are looking for.
1297 newParMetricsDown();
1301 for (; it != et; ++it) {
1302 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1303 << " y: " << it->second.position());
1305 ParagraphMetrics const & pm = par_metrics_[it->first];
1307 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1309 yy = it->second.position();
1313 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1319 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1320 bool assert_in_view, bool up)
1322 ParagraphMetrics const & pm = par_metrics_[pit];
1324 int yy = pm.position() - pm.ascent();
1325 LBUFERR(!pm.rows().empty());
1326 RowList::const_iterator rit = pm.rows().begin();
1327 RowList::const_iterator rlast = pm.rows().end();
1329 for (; rit != rlast; yy += rit->height(), ++rit)
1330 if (yy + rit->height() > y)
1333 if (assert_in_view) {
1334 if (!up && yy + rit->height() > y) {
1335 if (rit != pm.rows().begin()) {
1338 } else if (pit != 0) {
1341 ParagraphMetrics const & pm2 = par_metrics_[pit];
1342 rit = pm2.rows().end();
1346 } else if (up && yy != y) {
1348 y = yy + rit->height();
1350 } else if (pit < int(text_->paragraphs().size()) - 1) {
1352 newParMetricsDown();
1353 ParagraphMetrics const & pm2 = par_metrics_[pit];
1354 rit = pm2.rows().begin();
1363 // x,y are absolute screen coordinates
1364 // sets cursor recursively descending into nested editable insets
1365 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1366 bool assert_in_view, bool up)
1368 if (lyxerr.debugging(Debug::WORKAREA)) {
1369 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1370 cur.bv().coordCache().dump();
1372 pit_type pit = getPitNearY(y);
1373 LASSERT(pit != -1, return 0);
1374 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1377 // Do we cover an inset?
1378 InsetList::InsetTable * it = checkInsetHit(pit, x, y);
1381 // No inset, set position in the text
1382 bool bound = false; // is modified by getPosNearX
1383 cur.pos() = getPosNearX(row, x, bound);
1384 cur.boundary(bound);
1385 cur.setCurrentFont();
1390 Inset * inset = it->inset;
1391 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1393 // Set position in front of inset
1394 cur.pos() = it->pos;
1395 cur.boundary(false);
1398 // Try to descend recursively inside the inset.
1399 Inset * edited = inset->editXY(cur, x, y);
1400 // FIXME: it is not clear that the test on position is needed
1401 // Remove it if/when semantics of editXY is clarified
1402 if (cur.text() == text_ && cur.pos() == it->pos) {
1403 // non-editable inset, set cursor after the inset if x is
1404 // nearer to that position (bug 9628)
1405 bool bound = false; // is modified by getPosNearX
1406 cur.pos() = getPosNearX(row, x, bound);
1407 cur.boundary(bound);
1408 cur.setCurrentFont();
1412 if (cur.top().text() == text_)
1413 cur.setCurrentFont();
1418 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1420 LASSERT(text_ == cur.text(), return);
1421 pit_type const pit = getPitNearY(y);
1422 LASSERT(pit != -1, return);
1424 ParagraphMetrics const & pm = par_metrics_[pit];
1426 int yy = pm.position() - pm.ascent();
1427 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1428 " pit: " << pit << " yy: " << yy);
1431 LBUFERR(pm.rows().size());
1432 for (; r < int(pm.rows().size()) - 1; ++r) {
1433 Row const & row = pm.rows()[r];
1434 if (int(yy + row.height()) > y)
1439 Row const & row = pm.rows()[r];
1441 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1445 pos_type const pos = getPosNearX(row, xx, bound);
1447 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1449 text_->setCursor(cur, pit, pos, true, bound);
1450 // remember new position.
1455 //takes screen x,y coordinates
1456 InsetList::InsetTable * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1458 Paragraph const & par = text_->paragraphs()[pit];
1459 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1461 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1463 for (auto const & it : par.insetList()) {
1464 LYXERR(Debug::DEBUG, "examining inset " << it.inset);
1466 if (insetCache.covers(it.inset, x, y)) {
1467 LYXERR(Debug::DEBUG, "Hit inset: " << it.inset);
1468 return const_cast<InsetList::InsetTable *>(&it);
1472 LYXERR(Debug::DEBUG, "No inset hit. ");
1477 //takes screen x,y coordinates
1478 Inset * TextMetrics::checkInsetHit(int x, int y)
1480 pit_type const pit = getPitNearY(y);
1481 LASSERT(pit != -1, return 0);
1482 InsetList::InsetTable * it = checkInsetHit(pit, x, y);
1491 int TextMetrics::cursorX(CursorSlice const & sl,
1492 bool boundary) const
1494 LASSERT(sl.text() == text_, return 0);
1496 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1497 if (pm.rows().empty())
1499 Row const & row = pm.getRow(sl.pos(), boundary);
1500 pos_type const pos = sl.pos();
1503 row.findElement(pos, boundary, x);
1509 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1511 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1512 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1513 if (pm.rows().empty())
1517 h -= par_metrics_[0].rows()[0].ascent();
1518 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1519 h += par_metrics_[pit].height();
1522 if (pos && boundary)
1524 size_t const rend = pm.pos2row(pos);
1525 for (size_t rit = 0; rit != rend; ++rit)
1526 h += pm.rows()[rit].height();
1527 h += pm.rows()[rend].ascent();
1532 // the cursor set functions have a special mechanism. When they
1533 // realize you left an empty paragraph, they will delete it.
1535 bool TextMetrics::cursorHome(Cursor & cur)
1537 LASSERT(text_ == cur.text(), return false);
1538 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1539 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1540 return text_->setCursor(cur, cur.pit(), row.pos());
1544 bool TextMetrics::cursorEnd(Cursor & cur)
1546 LASSERT(text_ == cur.text(), return false);
1547 // if not on the last row of the par, put the cursor before
1548 // the final space exept if I have a spanning inset or one string
1549 // is so long that we force a break.
1550 pos_type end = cur.textRow().endpos();
1552 // empty text, end-1 is no valid position
1554 bool boundary = false;
1555 if (end != cur.lastpos()) {
1556 if (!cur.paragraph().isLineSeparator(end-1)
1557 && !cur.paragraph().isNewline(end-1)
1558 && !cur.paragraph().isEnvSeparator(end-1))
1562 } else if (cur.paragraph().isEnvSeparator(end-1))
1564 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1568 void TextMetrics::deleteLineForward(Cursor & cur)
1570 LASSERT(text_ == cur.text(), return);
1571 if (cur.lastpos() == 0) {
1572 // Paragraph is empty, so we just go forward
1573 text_->cursorForward(cur);
1576 cur.selection(true); // to avoid deletion
1579 // What is this test for ??? (JMarc)
1580 if (!cur.selection())
1581 text_->deleteWordForward(cur);
1583 cap::cutSelection(cur, true, false);
1584 cur.checkBufferStructure();
1589 bool TextMetrics::isLastRow(Row const & row) const
1591 ParagraphList const & pars = text_->paragraphs();
1592 return row.endpos() >= pars[row.pit()].size()
1593 && row.pit() + 1 == pit_type(pars.size());
1597 bool TextMetrics::isFirstRow(Row const & row) const
1599 return row.pos() == 0 && row.pit() == 0;
1603 int TextMetrics::leftMargin(pit_type pit) const
1605 return leftMargin(pit, text_->paragraphs()[pit].size());
1609 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1611 ParagraphList const & pars = text_->paragraphs();
1613 LASSERT(pit >= 0, return 0);
1614 LASSERT(pit < int(pars.size()), return 0);
1615 Paragraph const & par = pars[pit];
1616 LASSERT(pos >= 0, return 0);
1617 LASSERT(pos <= par.size(), return 0);
1618 Buffer const & buffer = bv_->buffer();
1619 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1620 DocumentClass const & tclass = buffer.params().documentClass();
1621 Layout const & layout = par.layout();
1622 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1624 docstring parindent = layout.parindent;
1628 if (text_->isMainText())
1629 l_margin += bv_->leftMargin();
1631 l_margin += bfm.signedWidth(tclass.leftmargin());
1633 int depth = par.getDepth();
1635 // find the next level paragraph
1636 pit_type newpar = text_->outerHook(pit);
1637 if (newpar != pit_type(pars.size())) {
1638 if (pars[newpar].layout().isEnvironment()) {
1639 int nestmargin = depth * nestMargin();
1640 if (text_->isMainText())
1641 nestmargin += changebarMargin();
1642 l_margin = max(leftMargin(newpar), nestmargin);
1643 // Remove the parindent that has been added
1644 // if the paragraph was empty.
1645 if (pars[newpar].empty() &&
1646 buffer.params().paragraph_separation ==
1647 BufferParams::ParagraphIndentSeparation) {
1648 docstring pi = pars[newpar].layout().parindent;
1649 l_margin -= bfm.signedWidth(pi);
1652 if (tclass.isDefaultLayout(par.layout())
1653 || tclass.isPlainLayout(par.layout())) {
1654 if (pars[newpar].params().noindent())
1657 parindent = pars[newpar].layout().parindent;
1662 // This happens after sections or environments in standard classes.
1663 // We have to check the previous layout at same depth.
1664 if (buffer.params().paragraph_separation ==
1665 BufferParams::ParagraphSkipSeparation)
1667 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1668 pit_type prev = text_->depthHook(pit, par.getDepth());
1669 if (par.layout() == pars[prev].layout()) {
1671 && pars[pit - 1].layout().nextnoindent)
1673 } else if (pars[prev].layout().nextnoindent)
1677 FontInfo const labelfont = text_->labelFont(par);
1678 FontMetrics const & lfm = theFontMetrics(labelfont);
1680 switch (layout.margintype) {
1681 case MARGIN_DYNAMIC:
1682 if (!layout.leftmargin.empty()) {
1683 l_margin += bfm.signedWidth(layout.leftmargin);
1685 if (!par.labelString().empty()) {
1686 l_margin += lfm.signedWidth(layout.labelindent);
1687 l_margin += lfm.width(par.labelString());
1688 l_margin += lfm.width(layout.labelsep);
1692 case MARGIN_MANUAL: {
1693 l_margin += lfm.signedWidth(layout.labelindent);
1694 // The width of an empty par, even with manual label, should be 0
1695 if (!par.empty() && pos >= par.beginOfBody()) {
1696 if (!par.getLabelWidthString().empty()) {
1697 docstring labstr = par.getLabelWidthString();
1698 l_margin += lfm.width(labstr);
1699 l_margin += lfm.width(layout.labelsep);
1705 case MARGIN_STATIC: {
1706 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1707 / (par.getDepth() + 4);
1711 case MARGIN_FIRST_DYNAMIC:
1712 if (layout.labeltype == LABEL_MANUAL) {
1713 // if we are at position 0, we are never in the body
1714 if (pos > 0 && pos >= par.beginOfBody())
1715 l_margin += lfm.signedWidth(layout.leftmargin);
1717 l_margin += lfm.signedWidth(layout.labelindent);
1719 // Special case to fix problems with
1721 || (layout.labeltype == LABEL_STATIC
1722 && layout.latextype == LATEX_ENVIRONMENT
1723 && !text_->isFirstInSequence(pit))) {
1724 l_margin += lfm.signedWidth(layout.leftmargin);
1725 } else if (!layout.labelIsAbove()) {
1726 l_margin += lfm.signedWidth(layout.labelindent);
1727 l_margin += lfm.width(layout.labelsep);
1728 l_margin += lfm.width(par.labelString());
1732 case MARGIN_RIGHT_ADDRESS_BOX: {
1734 // The left margin depends on the widest row in this paragraph.
1735 // This code is wrong because it depends on the rows, but at the
1736 // same time this function is used in redoParagraph to construct
1738 ParagraphMetrics const & pm = par_metrics_[pit];
1739 RowList::const_iterator rit = pm.rows().begin();
1740 RowList::const_iterator end = pm.rows().end();
1741 int minfill = max_width_;
1742 for ( ; rit != end; ++rit)
1743 if (rit->fill() < minfill)
1744 minfill = rit->fill();
1745 l_margin += bfm.signedWidth(layout.leftmargin);
1746 l_margin += minfill;
1748 // also wrong, but much shorter.
1749 l_margin += max_width_ / 2;
1754 if (!par.params().leftIndent().zero())
1755 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1757 LyXAlignment align = par.getAlign();
1759 // set the correct parindent
1761 && (layout.labeltype == LABEL_NO_LABEL
1762 || layout.labeltype == LABEL_ABOVE
1763 || layout.labeltype == LABEL_CENTERED
1764 || (layout.labeltype == LABEL_STATIC
1765 && layout.latextype == LATEX_ENVIRONMENT
1766 && !text_->isFirstInSequence(pit)))
1767 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1768 && !par.params().noindent()
1769 // in some insets, paragraphs are never indented
1770 && !text_->inset().neverIndent()
1771 // display style insets are always centered, omit indentation
1774 && par.getInset(pos)->display())
1775 && (!(tclass.isDefaultLayout(par.layout())
1776 || tclass.isPlainLayout(par.layout()))
1777 || buffer.params().paragraph_separation
1778 == BufferParams::ParagraphIndentSeparation)) {
1779 /* use the parindent of the layout when the default
1780 * indentation is used otherwise use the indentation set in
1781 * the document settings
1783 if (buffer.params().getParIndent().empty())
1784 l_margin += bfm.signedWidth(parindent);
1786 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1793 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1795 if (par_metrics_.empty())
1801 ParMetricsCache::iterator it = par_metrics_.begin();
1802 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1803 y -= it->second.ascent();
1804 for (; it != pm_end; ++it) {
1805 ParagraphMetrics const & pmi = it->second;
1807 pit_type const pit = it->first;
1808 // Save the paragraph position in the cache.
1809 it->second.setPosition(y);
1810 drawParagraph(pi, pit, x, y);
1816 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1818 ParagraphMetrics const & pm = par_metrics_[pit];
1819 if (pm.rows().empty())
1821 size_t const nrows = pm.rows().size();
1823 // Use fast lane in nodraw stage.
1824 if (pi.pain.isNull()) {
1825 for (size_t i = 0; i != nrows; ++i) {
1827 Row const & row = pm.rows()[i];
1828 // Adapt to cursor row scroll offset if applicable.
1829 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1833 RowPainter rp(pi, *text_, row, row_x, y);
1835 rp.paintOnlyInsets();
1841 int const ww = bv_->workHeight();
1842 Cursor const & cur = bv_->cursor();
1843 DocIterator sel_beg = cur.selectionBegin();
1844 DocIterator sel_end = cur.selectionEnd();
1845 bool selection = cur.selection()
1846 // This is our text.
1847 && cur.text() == text_
1848 // if the anchor is outside, this is not our selection
1849 && cur.normalAnchor().text() == text_
1850 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1852 // We store the begin and end pos of the selection relative to this par
1853 DocIterator sel_beg_par = cur.selectionBegin();
1854 DocIterator sel_end_par = cur.selectionEnd();
1856 // We care only about visible selection.
1858 if (pit != sel_beg.pit()) {
1859 sel_beg_par.pit() = pit;
1860 sel_beg_par.pos() = 0;
1862 if (pit != sel_end.pit()) {
1863 sel_end_par.pit() = pit;
1864 sel_end_par.pos() = sel_end_par.lastpos();
1868 for (size_t i = 0; i != nrows; ++i) {
1870 Row const & row = pm.rows()[i];
1871 // Adapt to cursor row scroll offset if applicable.
1872 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1876 // It is not needed to draw on screen if we are not inside.
1877 bool const inside = (y + row.descent() >= 0
1878 && y - row.ascent() < ww);
1880 // Inset positions have already been set in nodraw stage.
1886 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
1888 row.setSelection(-1, -1);
1890 // The row knows nothing about the paragraph, so we have to check
1891 // whether this row is the first or last and update the margins.
1892 if (row.selection()) {
1893 if (row.sel_beg == 0)
1894 row.begin_margin_sel = sel_beg.pit() < pit;
1895 if (row.sel_end == sel_end_par.lastpos())
1896 row.end_margin_sel = sel_end.pit() > pit;
1899 // Row signature; has row changed since last paint?
1900 row.setCrc(pm.computeRowSignature(row, *bv_));
1901 bool row_has_changed = row.changed()
1902 || bv_->hadHorizScrollOffset(text_, pit, row.pos())
1903 || bv_->needRepaint(text_, row);
1905 // Take this opportunity to spellcheck the row contents.
1906 if (row_has_changed && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
1907 text_->getPar(pit).spellCheck();
1910 RowPainter rp(pi, *text_, row, row_x, y);
1912 // Don't paint the row if a full repaint has not been requested
1913 // and if it has not changed.
1914 if (!pi.full_repaint && !row_has_changed) {
1915 // Paint only the insets if the text itself is
1917 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_has_changed) {
1925 LYXERR(Debug::PAINTING, "Clear rect@("
1926 << max(row_x, 0) << ", " << y - row.ascent() << ")="
1927 << width() << " x " << row.height());
1928 pi.pain.fillRectangle(max(row_x, 0), 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_has_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_has_changed ? " row_has_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();
1954 if (i == 0 && !row.isRTL())
1956 if (i == nrows - 1 && row.isRTL())
1959 if (i == nrows - 1 && !row.isRTL())
1961 if (i == 0 && row.isRTL())
1963 rp.paintTooLargeMarks(row_x + row.left_x() < 0,
1964 row_x + row.right_x() > bv_->workWidth());
1967 // Restore full_repaint status.
1968 pi.full_repaint = tmp;
1971 //LYXERR(Debug::PAINTING, ".");
1975 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
1976 Dimension & dim) const
1978 Cursor const & bvcur = cur.bv().cursor();
1980 // get word in front of cursor
1981 docstring word = text_->previousWord(bvcur.top());
1982 DocIterator wordStart = bvcur;
1983 wordStart.pos() -= word.length();
1985 // calculate dimensions of the word
1987 row.pit(bvcur.pit());
1988 row.pos(wordStart.pos());
1989 row.endpos(bvcur.pos());
1991 dim = row.dimension();
1993 // get position on screen of the word start and end
1994 //FIXME: Is it necessary to explicitly set this to false?
1995 wordStart.boundary(false);
1996 Point lxy = cur.bv().getPos(wordStart);
1997 Point rxy = cur.bv().getPos(bvcur);
1998 dim.wid = abs(rxy.x_ - lxy.x_);
2000 // calculate position of word
2002 x = min(rxy.x_, lxy.x_);
2004 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2005 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2008 int defaultRowHeight()
2010 return int(theFontMetrics(sane_font).maxHeight() * 1.2);