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/convert.h"
49 #include "support/debug.h"
50 #include "support/lassert.h"
60 using frontend::FontMetrics;
65 int numberOfLabelHfills(Paragraph const & par, Row const & row)
67 pos_type last = row.endpos() - 1;
68 pos_type first = row.pos();
70 // hfill *DO* count at the beginning of paragraphs!
72 while (first < last && par.isHfill(first))
76 last = min(last, par.beginOfBody());
78 for (pos_type p = first; p < last; ++p) {
85 // FIXME: this needs to be rewritten, probably by merging it into some
86 // code that, besides counting, sets the active status of the space
87 // inset in the row element.
88 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
89 pos_type const body_pos)
92 Row::const_iterator cit = row.begin();
93 Row::const_iterator const end = row.end();
94 for ( ; cit != end ; ++cit)
95 if (cit->pos >= body_pos
96 && cit->inset && pm.hfillExpansion(row, cit->pos))
104 /////////////////////////////////////////////////////////////////////
108 /////////////////////////////////////////////////////////////////////
111 TextMetrics::TextMetrics(BufferView * bv, Text * text)
112 : bv_(bv), text_(text)
115 max_width_ = bv_->workWidth();
116 dim_.wid = max_width_;
122 bool TextMetrics::contains(pit_type pit) const
124 return par_metrics_.find(pit) != par_metrics_.end();
128 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
130 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
135 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
137 ParMetricsCache::const_iterator it = par_metrics_.begin();
138 return make_pair(it->first, &it->second);
142 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
144 LBUFERR(!par_metrics_.empty());
145 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
146 return make_pair(it->first, &it->second);
150 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
152 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
153 if (pmc_it == par_metrics_.end()) {
154 pmc_it = par_metrics_.insert(
155 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
157 if (pmc_it->second.rows().empty() && redo)
159 return pmc_it->second;
163 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
165 LBUFERR(mi.base.textwidth > 0);
166 max_width_ = mi.base.textwidth;
167 // backup old dimension.
168 Dimension const old_dim = dim_;
171 dim_.wid = min_width;
172 pit_type const npar = text_->paragraphs().size();
174 // If there is more than one row, expand the text to
175 // the full allowable width.
176 dim_.wid = max_width_;
178 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
179 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
181 bool changed = false;
183 for (pit_type pit = 0; pit != npar; ++pit) {
184 changed |= redoParagraph(pit);
185 ParagraphMetrics const & pm = par_metrics_[pit];
187 if (dim_.wid < pm.width())
188 dim_.wid = pm.width();
191 dim_.asc = par_metrics_[0].ascent();
192 dim_.des = h - dim_.asc;
193 //lyxerr << "dim_.wid " << dim_.wid << endl;
194 //lyxerr << "dim_.asc " << dim_.asc << endl;
195 //lyxerr << "dim_.des " << dim_.des << endl;
197 changed |= dim_ != old_dim;
203 void TextMetrics::updatePosCache(pit_type pit) const
205 frontend::NullPainter np;
206 PainterInfo pi(bv_, np);
207 drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
211 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
213 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
217 int TextMetrics::rightMargin(pit_type const pit) const
219 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
223 void TextMetrics::applyOuterFont(Font & font) const
225 FontInfo lf(font_.fontInfo());
226 lf.reduce(bv_->buffer().params().getFont().fontInfo());
227 font.fontInfo().realize(lf);
231 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
233 LASSERT(pos >= 0, { static Font f; return f; });
235 ParagraphList const & pars = text_->paragraphs();
236 Paragraph const & par = pars[pit];
237 Layout const & layout = par.layout();
238 Buffer const & buffer = bv_->buffer();
240 BufferParams const & params = buffer.params();
241 pos_type const body_pos = par.beginOfBody();
243 // We specialize the 95% common case:
244 if (!par.getDepth()) {
245 Font f = par.getFontSettings(params, pos);
246 if (!text_->isMainText())
248 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
250 FontInfo const & lf = lab ? layout.labelfont : layout.font;
251 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
253 // In case the default family has been customized
254 if (lf.family() == INHERIT_FAMILY)
255 rlf.setFamily(params.getFont().fontInfo().family());
256 f.fontInfo().realize(rlf);
260 // The uncommon case need not be optimized as much
261 FontInfo const & layoutfont = pos < body_pos ?
262 layout.labelfont : layout.font;
264 Font font = par.getFontSettings(params, pos);
265 font.fontInfo().realize(layoutfont);
267 if (!text_->isMainText())
268 applyOuterFont(font);
270 // Realize against environment font information
271 // NOTE: the cast to pit_type should be removed when pit_type
272 // changes to a unsigned integer.
273 if (pit < pit_type(pars.size()))
274 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
276 // Realize with the fonts of lesser depth.
277 font.fontInfo().realize(params.getFont().fontInfo());
283 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
289 if (boundary && sl.pos() > 0)
292 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
296 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
298 // no RTL boundary at paragraph start
302 Font const & left_font = displayFont(pit, pos - 1);
304 return isRTLBoundary(pit, pos, left_font);
308 // isRTLBoundary returns false on a real end-of-line boundary,
309 // because otherwise the two boundary types get mixed up.
310 // This is the whole purpose of this being in TextMetrics.
311 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
312 Font const & font) const
314 if (// no RTL boundary at paragraph start
316 // if the metrics have not been calculated, then we are not
317 // on screen and can safely ignore issues about boundaries.
321 ParagraphMetrics & pm = par_metrics_[pit];
322 // no RTL boundary in empty paragraph
323 if (pm.rows().empty())
326 pos_type endpos = pm.getRow(pos - 1, false).endpos();
327 pos_type startpos = pm.getRow(pos, false).pos();
328 // no RTL boundary at line start:
329 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
331 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
334 Paragraph const & par = text_->getPar(pit);
335 // no RTL boundary at line break:
336 // abc|\n -> move right -> abc\n (and not: abc\n|
338 if (startpos == pos && endpos == pos && endpos != par.size()
339 && (par.isNewline(pos - 1)
340 || par.isEnvSeparator(pos - 1)
341 || par.isLineSeparator(pos - 1)
342 || par.isSeparator(pos - 1)))
345 bool left = font.isVisibleRightToLeft();
347 if (pos == par.size())
348 right = par.isRTL(bv_->buffer().params());
350 right = displayFont(pit, pos).isVisibleRightToLeft();
352 return left != right;
356 bool TextMetrics::redoParagraph(pit_type const pit)
358 Paragraph & par = text_->getPar(pit);
359 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
360 // redoParagraph() recursively inside parMetrics.
361 Dimension old_dim = parMetrics(pit, false).dim();
362 ParagraphMetrics & pm = par_metrics_[pit];
365 Buffer & buffer = bv_->buffer();
366 bool changed = false;
368 // Check whether there are InsetBibItems that need fixing
369 // FIXME: This check ought to be done somewhere else. It is the reason
370 // why text_ is not const. But then, where else to do it?
371 // Well, how can you end up with either (a) a biblio environment that
372 // has no InsetBibitem, (b) a biblio environment with more than one
373 // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
374 // environment? I think the answer is: when paragraphs are merged;
375 // when layout is set; when material is pasted.
376 if (par.brokenBiblio()) {
377 Cursor & cur = const_cast<Cursor &>(bv_->cursor());
378 // In some cases, we do not know how to record undo
379 if (&cur.inset() == &text_->inset())
380 cur.recordUndo(pit, pit);
382 int const moveCursor = par.fixBiblio(buffer);
384 // Is it necessary to update the cursor?
385 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
388 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
393 // Optimisation: this is used in the next two loops
394 // so better to calculate that once here.
395 int const right_margin = rightMargin(pm);
397 // iterator pointing to paragraph to resolve macros
398 DocIterator parPos = text_->macrocontextPosition();
402 LYXERR(Debug::INFO, "MacroContext not initialised!"
403 << " Going through the buffer again and hope"
404 << " the context is better then.");
405 // FIXME audit updateBuffer calls
406 // This should not be here, but it is not clear yet where else it
408 bv_->buffer().updateBuffer();
409 parPos = text_->macrocontextPosition();
410 LBUFERR(!parPos.empty());
415 par.setBeginOfBody();
416 Font const bufferfont = buffer.params().getFont();
417 CoordCache::Insets & insetCache = bv_->coordCache().insets();
418 InsetList::const_iterator ii = par.insetList().begin();
419 InsetList::const_iterator iend = par.insetList().end();
420 for (; ii != iend; ++ii) {
421 // FIXME Doesn't this HAVE to be non-empty?
422 // position already initialized?
423 if (!parPos.empty()) {
424 parPos.pos() = ii->pos;
426 // A macro template would normally not be visible
427 // by itself. But the tex macro semantics allow
428 // recursion, so we artifically take the context
429 // after the macro template to simulate this.
430 if (ii->inset->lyxCode() == MATHMACRO_CODE)
434 // If there is an end of paragraph marker, its size should be
435 // substracted to the available width. The logic here is
436 // almost the same as in breakRow, remember keep them in sync.
438 if (lyxrc.paragraph_markers && ii->pos + 1 == par.size()
439 && size_type(pit + 1) < text_->paragraphs().size()) {
440 Font f(text_->layoutFont(pit));
441 // ¶ U+00B6 PILCROW SIGN
442 eop = theFontMetrics(f).width(char_type(0x00B6));
445 // do the metric calculation
447 int const w = max_width_ - leftMargin(pit, ii->pos)
448 - right_margin - eop;
449 Font const & font = ii->inset->inheritFont() ?
450 displayFont(pit, ii->pos) : bufferfont;
451 MacroContext mc(&buffer, parPos);
452 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
453 ii->inset->metrics(mi, dim);
454 if (!insetCache.has(ii->inset) || insetCache.dim(ii->inset) != dim) {
455 insetCache.add(ii->inset, dim);
461 size_t row_index = 0;
462 bool need_new_row = false;
463 // maximum pixel width of a row
465 if (row_index == pm.rows().size())
466 pm.rows().push_back(Row());
467 Row & row = pm.rows()[row_index];
471 need_new_row = breakRow(row, right_margin);
474 if (row_index || row.endpos() < par.size()
475 || (row.right_boundary() && par.inInset().lyxCode() != CELL_CODE)) {
476 /* If there is more than one row or the row has been
477 * broken by a display inset or a newline, expand the text
478 * to the full allowable width. This setting here is
479 * needed for the computeRowMetrics() below. In the case
480 * of a display inset, we do nothing when inside a table
481 * cell, because the tabular code is not prepared for
482 * that, and it triggers when using a caption in a
483 * longtable (see bugs #9945 and #9757).
485 if (dim_.wid < max_width_)
486 dim_.wid = max_width_;
488 int const max_row_width = max(dim_.wid, row.width());
489 computeRowMetrics(row, max_row_width);
490 first = row.endpos();
493 pm.dim().wid = max(pm.dim().wid, row.width());
494 pm.dim().des += row.height();
495 } while (first < par.size() || need_new_row);
497 if (row_index < pm.rows().size())
498 pm.rows().resize(row_index);
500 // FIXME: It might be better to move this in another method
501 // specially tailored for the main text.
502 // Top and bottom margin of the document (only at top-level)
503 if (text_->isMainText()) {
504 // original value was 20px, which is 0.2in at 100dpi
505 int const margin = Length(0.2, Length::IN).inPixels(0);
507 pm.rows().front().dimension().asc += margin;
508 /* coverity thinks that we should update pm.dim().asc
509 * below, but all the rows heights are actually counted as
510 * part of the paragraph metric descent see loop above).
512 // coverity[copy_paste_error]
513 pm.dim().des += margin;
515 ParagraphList const & pars = text_->paragraphs();
516 if (pit + 1 == pit_type(pars.size())) {
517 pm.rows().back().dimension().des += margin;
518 pm.dim().des += margin;
522 // The space above and below the paragraph.
523 int const top = parTopSpacing(pit);
524 pm.rows().front().dimension().asc += top;
525 int const bottom = parBottomSpacing(pit);
526 pm.rows().back().dimension().des += bottom;
527 pm.dim().des += top + bottom;
529 pm.dim().asc += pm.rows()[0].ascent();
530 pm.dim().des -= pm.rows()[0].ascent();
532 changed |= old_dim.height() != pm.dim().height();
538 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
540 LyXAlignment align = par.getAlign(bv_->buffer().params());
542 // handle alignment inside tabular cells
543 Inset const & owner = text_->inset();
544 bool forced_block = false;
545 switch (owner.contentAlignment()) {
546 case LYX_ALIGN_BLOCK:
547 // In general block align is the default state, but here it is
548 // an explicit choice. Therefore it should not be overridden
552 case LYX_ALIGN_CENTER:
554 case LYX_ALIGN_RIGHT:
555 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
556 align = owner.contentAlignment();
559 // unchanged (use align)
563 // Display-style insets should always be on a centered row
564 if (Inset const * inset = par.getInset(row.pos())) {
565 switch (inset->display()) {
566 case Inset::AlignLeft:
567 align = LYX_ALIGN_BLOCK;
569 case Inset::AlignCenter:
570 align = LYX_ALIGN_CENTER;
573 // unchanged (use align)
575 case Inset::AlignRight:
576 align = LYX_ALIGN_RIGHT;
581 if (align == LYX_ALIGN_BLOCK) {
582 // If this row has been broken abruptly by a display inset, or
583 // it is the end of the paragraph, or the user requested we
584 // not justify stuff, then don't stretch.
585 // A forced block alignment can only be overridden the 'no
586 // justification on screen' setting.
587 if ((row.flushed() && !forced_block)
588 || !bv_->buffer().params().justification)
589 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
596 void TextMetrics::computeRowMetrics(Row & row, int width) const
601 Paragraph const & par = text_->getPar(row.pit());
603 int const w = width - row.right_margin - row.width();
604 // FIXME: put back this assertion when the crash on new doc is solved.
605 //LASSERT(w >= 0, /**/);
607 // is there a manual margin with a manual label
608 Layout const & layout = par.layout();
611 if (layout.margintype == MARGIN_MANUAL
612 && layout.labeltype == LABEL_MANUAL) {
613 /// We might have real hfills in the label part
614 nlh = numberOfLabelHfills(par, row);
616 // A manual label par (e.g. List) has an auto-hfill
617 // between the label text and the body of the
619 // But we don't want to do this auto hfill if the par
624 if (nlh && !par.getLabelWidthString().empty())
625 row.label_hfill = labelFill(row) / double(nlh);
628 // are there any hfills in the row?
629 ParagraphMetrics & pm = par_metrics_[row.pit()];
630 int nh = numberOfHfills(row, pm, par.beginOfBody());
634 // We don't have to look at the alignment if the row is already
635 // larger then the permitted width as then we force the
636 // LEFT_ALIGN'edness!
637 if (int(row.width()) >= max_width_)
641 // Common case : there is no hfill, and the alignment will be
643 switch (getAlign(par, row)) {
644 case LYX_ALIGN_BLOCK:
645 // Expand expanding characters by a total of w
646 if (!row.setExtraWidth(w) && row.isRTL()) {
647 // Justification failed and the text is RTL: align to the right
648 row.left_margin += w;
649 row.dimension().wid += w;
653 // a displayed inset that is flushed
654 if (Inset const * inset = par.getInset(row.pos())) {
655 row.left_margin += inset->indent(*bv_);
656 row.dimension().wid += inset->indent(*bv_);
659 case LYX_ALIGN_RIGHT:
660 if (Inset const * inset = par.getInset(row.pos())) {
661 int const new_w = max(w - inset->indent(*bv_), 0);
662 row.left_margin += new_w;
663 row.dimension().wid += new_w;
665 row.left_margin += w;
666 row.dimension().wid += w;
669 case LYX_ALIGN_CENTER:
670 row.dimension().wid += w / 2;
671 row.left_margin += w / 2;
674 case LYX_ALIGN_LAYOUT:
675 case LYX_ALIGN_SPECIAL:
676 case LYX_ALIGN_DECIMAL:
682 // Case nh > 0. There are hfill separators.
685 row.dimension().wid += w;
686 // Set size of hfill insets
687 pos_type const endpos = row.endpos();
688 pos_type body_pos = par.beginOfBody();
690 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
693 CoordCache::Insets & insetCache = bv_->coordCache().insets();
694 Row::iterator cit = row.begin();
695 Row::iterator const cend = row.end();
696 for ( ; cit != cend; ++cit) {
697 if (row.label_hfill && cit->endpos == body_pos
698 && cit->type == Row::SPACE)
699 cit->dim.wid -= int(row.label_hfill * (nlh - 1));
700 if (cit->inset && pm.hfillExpansion(row, cit->pos)) {
701 if (cit->pos >= body_pos) {
702 cit->dim.wid += hfill;
705 cit->dim.wid += hfill_rem;
707 cit->dim.wid += int(row.label_hfill);
708 // Cache the inset dimension.
709 insetCache.add(cit->inset, cit->dim);
715 int TextMetrics::labelFill(Row const & row) const
717 Paragraph const & par = text_->getPar(row.pit());
718 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
721 Row::const_iterator cit = row.begin();
722 Row::const_iterator const end = row.end();
723 // iterate over elements before main body (except the last one,
724 // which is extra space).
725 while (cit!= end && cit->endpos < par.beginOfBody()) {
730 docstring const & label = par.params().labelWidthString();
734 FontMetrics const & fm
735 = theFontMetrics(text_->labelFont(par));
737 return max(0, fm.width(label) - w);
742 // Not used, see TextMetrics::breakRow
743 // this needs special handling - only newlines count as a break point
744 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
746 pos_type const end = par.size();
749 if (par.isNewline(i))
757 int TextMetrics::labelEnd(pit_type const pit) const
759 // labelEnd is only needed if the layout fills a flushleft label.
760 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
762 // return the beginning of the body
763 return leftMargin(pit);
769 * Calling Text::getFont is slow. While rebreaking we scan a
770 * paragraph from left to right calling getFont for every char. This
771 * simple class address this problem by hidding an optimization trick
772 * (not mine btw -AB): the font is reused in the whole font span. The
773 * class handles transparently the "hidden" (not part of the fontlist)
774 * label font (as getFont does).
780 FontIterator(TextMetrics const & tm,
781 Paragraph const & par, pit_type pit, pos_type pos)
782 : tm_(tm), par_(par), pit_(pit), pos_(pos),
783 font_(tm.displayFont(pit, pos)),
784 endspan_(par.fontSpan(pos).last),
785 bodypos_(par.beginOfBody())
789 Font const & operator*() const { return font_; }
792 FontIterator & operator++()
795 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
796 font_ = tm_.displayFont(pit_, pos_);
797 endspan_ = par_.fontSpan(pos_).last;
803 Font * operator->() { return &font_; }
807 TextMetrics const & tm_;
809 Paragraph const & par_;
824 /** This is the function where the hard work is done. The code here is
825 * very sensitive to small changes :) Note that part of the
826 * intelligence is also in Row::shortenIfNeeded.
828 bool TextMetrics::breakRow(Row & row, int const right_margin) const
830 Paragraph const & par = text_->getPar(row.pit());
831 pos_type const end = par.size();
832 pos_type const pos = row.pos();
833 pos_type const body_pos = par.beginOfBody();
834 bool const is_rtl = text_->isRTL(par);
835 bool need_new_row = false;
838 row.left_margin = leftMargin(row.pit(), pos);
839 row.right_margin = right_margin;
840 row.needsChangeBar(false);
842 swap(row.left_margin, row.right_margin);
843 // Remember that the row width takes into account the left_margin
844 // but not the right_margin.
845 row.dimension().wid = row.left_margin;
846 // the width available for the row.
847 int const width = max_width_ - row.right_margin;
850 //FIXME: As long as leftMargin() is not correctly implemented for
851 // MARGIN_RIGHT_ADDRESS_BOX, we should also not do this here.
852 // Otherwise, long rows will be painted off the screen.
853 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX)
854 return addressBreakPoint(pos, par);
857 // check for possible inline completion
858 DocIterator const & ic_it = bv_->inlineCompletionPos();
859 pos_type ic_pos = -1;
860 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == row.pit())
861 ic_pos = ic_it.pos();
863 // Now we iterate through until we reach the right margin
864 // or the end of the par, then build a representation of the row.
866 FontIterator fi = FontIterator(*this, par, row.pit(), pos);
867 while (i < end && (i == pos || row.width() <= width)) {
868 char_type c = par.getChar(i);
869 // The most special cases are handled first.
870 if (par.isInset(i)) {
871 Inset const * ins = par.getInset(i);
872 Dimension dim = bv_->coordCache().insets().dim(ins);
873 row.add(i, ins, dim, *fi, par.lookupChange(i));
874 } else if (c == ' ' && i + 1 == body_pos) {
875 // There is a space at i, but it should not be
876 // added as a separator, because it is just
877 // before body_pos. Instead, insert some spacing to
879 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
880 // this is needed to make sure that the row width is correct
882 int const add = max(fm.width(par.layout().labelsep),
883 labelEnd(row.pit()) - row.width());
884 row.addSpace(i, add, *fi, par.lookupChange(i));
885 } else if (c == '\t')
886 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
887 *fi, par.lookupChange(i));
888 else if (c == 0x2028 || c == 0x2029) {
890 * U+2028 LINE SEPARATOR
891 * U+2029 PARAGRAPH SEPARATOR
893 * These are special unicode characters that break
894 * lines/pragraphs. Not handling them lead to trouble wrt
895 * Qt QTextLayout formatting. We add a visible character
896 * on screen so that the user can see that something is
900 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
901 // ¶ U+00B6 PILCROW SIGN
902 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
903 row.add(i, screen_char, *fi, par.lookupChange(i));
905 // FIXME: please someone fix the Hebrew/Arabic parenthesis mess!
906 // see also Paragraph::getUChar.
907 if (fi->language()->lang() == "hebrew") {
913 row.add(i, c, *fi, par.lookupChange(i));
916 // add inline completion width
917 // draw logically behind the previous character
918 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
919 docstring const comp = bv_->inlineCompletion();
920 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
924 f.fontInfo().setColor(Color_inlinecompletion);
925 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
927 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
928 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
931 // Handle some situations that abruptly terminate the row
933 // - Before a display inset
934 // - After a display inset
935 Inset const * inset = 0;
936 if (par.isNewline(i) || par.isEnvSeparator(i)
937 || (i + 1 < end && (inset = par.getInset(i + 1))
939 || (!row.empty() && row.back().inset
940 && row.back().inset->display())) {
942 need_new_row = par.isNewline(i);
953 // End of paragraph marker. The logic here is almost the
954 // same as in redoParagraph, remember keep them in sync.
955 ParagraphList const & pars = text_->paragraphs();
956 if (lyxrc.paragraph_markers && !need_new_row
957 && i == end && size_type(row.pit() + 1) < pars.size()) {
958 // add a virtual element for the end-of-paragraph
959 // marker; it is shown on screen, but does not exist
961 Font f(text_->layoutFont(row.pit()));
962 f.fontInfo().setColor(Color_paragraphmarker);
963 BufferParams const & bparams
964 = text_->inset().buffer().params();
965 f.setLanguage(par.getParLanguage(bparams));
966 // ¶ U+00B6 PILCROW SIGN
967 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, Change());
970 // Is there a end-of-paragaph change?
971 if (i == end && par.lookupChange(end).changed() && !need_new_row)
972 row.needsChangeBar(true);
974 // if the row is too large, try to cut at last separator. In case
975 // of success, reset indication that the row was broken abruptly.
976 int const next_width = max_width_ - leftMargin(row.pit(), row.endpos())
977 - rightMargin(row.pit());
979 if (row.shortenIfNeeded(body_pos, width, next_width))
981 row.right_boundary(!row.empty() && row.endpos() < end
982 && row.back().endpos == row.endpos());
983 // Last row in paragraph is flushed
984 if (row.endpos() == end)
987 // make sure that the RTL elements are in reverse ordering
988 row.reverseRTL(is_rtl);
989 //LYXERR0("breakrow: row is " << row);
994 int TextMetrics::parTopSpacing(pit_type const pit) const
996 Paragraph const & par = text_->getPar(pit);
997 Layout const & layout = par.layout();
1000 ParagraphList const & pars = text_->paragraphs();
1001 double const dh = defaultRowHeight();
1003 BufferParams const & bparams = bv_->buffer().params();
1004 Inset const & inset = text_->inset();
1005 // some parskips VERY EASY IMPLEMENTATION
1006 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1007 && !inset.getLayout().parbreakIsNewline()
1008 && !par.layout().parbreak_is_newline
1010 && ((layout.isParagraph() && par.getDepth() == 0)
1011 || (pars[pit - 1].layout().isParagraph()
1012 && pars[pit - 1].getDepth() == 0))) {
1013 asc += bparams.getDefSkip().inPixels(*bv_);
1016 if (par.params().startOfAppendix())
1019 // special code for the top label
1020 if (layout.labelIsAbove()
1021 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1022 && !par.labelString().empty()) {
1023 FontInfo labelfont = text_->labelFont(par);
1024 FontMetrics const & lfm = theFontMetrics(labelfont);
1025 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1026 * text_->spacing(par)
1027 + (layout.topsep + layout.labelbottomsep) * dh);
1030 // Add the layout spaces, for example before and after
1031 // a section, or between the items of a itemize or enumerate
1034 pit_type prev = text_->depthHook(pit, par.getDepth());
1035 Paragraph const & prevpar = pars[prev];
1036 double layoutasc = 0;
1038 && prevpar.layout() == layout
1039 && prevpar.getDepth() == par.getDepth()
1040 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1041 layoutasc = layout.itemsep * dh;
1042 } else if (pit != 0 && layout.topsep > 0)
1043 layoutasc = layout.topsep * dh;
1045 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1047 prev = text_->outerHook(pit);
1048 if (prev != pit_type(pars.size())) {
1049 asc += int(pars[prev].layout().parsep * dh);
1050 } else if (pit != 0) {
1051 Paragraph const & prevpar = pars[pit - 1];
1052 if (prevpar.getDepth() != 0 || prevpar.layout() == layout)
1053 asc += int(layout.parsep * dh);
1060 int TextMetrics::parBottomSpacing(pit_type const pit) const
1062 double layoutdesc = 0;
1063 ParagraphList const & pars = text_->paragraphs();
1064 double const dh = defaultRowHeight();
1066 // add the layout spaces, for example before and after
1067 // a section, or between the items of a itemize or enumerate
1069 pit_type nextpit = pit + 1;
1070 if (nextpit != pit_type(pars.size())) {
1071 pit_type cpit = pit;
1073 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1074 double usual = pars[cpit].layout().bottomsep * dh;
1076 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1077 if (pars[cpit].layout() != pars[nextpit].layout()
1078 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1079 unusual = pars[cpit].layout().bottomsep * dh;
1080 layoutdesc = max(unusual, usual);
1081 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1082 if (pars[cpit].layout() != pars[nextpit].layout()
1083 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1084 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1088 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1092 void TextMetrics::setRowHeight(Row & row) const
1094 Paragraph const & par = text_->getPar(row.pit());
1095 Layout const & layout = par.layout();
1096 double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1098 // Initial value for ascent (useful if row is empty).
1099 Font const font = displayFont(row.pit(), row.pos());
1100 FontMetrics const & fm = theFontMetrics(font);
1101 int maxasc = int(fm.maxAscent() * spacing_val);
1102 int maxdes = int(fm.maxDescent() * spacing_val);
1104 // Find the ascent/descent of the row contents
1105 Row::const_iterator cit = row.begin();
1106 Row::const_iterator cend = row.end();
1107 for ( ; cit != cend; ++cit) {
1109 maxasc = max(maxasc, cit->dim.ascent());
1110 maxdes = max(maxdes, cit->dim.descent());
1112 FontMetrics const & fm = theFontMetrics(cit->font);
1113 maxasc = max(maxasc, int(fm.maxAscent() * spacing_val));
1114 maxdes = max(maxdes, int(fm.maxDescent() * spacing_val));
1118 // This is nicer with box insets
1122 row.dimension().asc = maxasc;
1123 row.dimension().des = maxdes;
1127 // x is an absolute screen coord
1128 // returns the column near the specified x-coordinate of the row
1129 // x is set to the real beginning of this column
1130 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1131 bool & boundary) const
1133 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1134 /// For the main Text, it is possible that this pit is not
1135 /// yet in the CoordCache when moving cursor up.
1136 /// x Paragraph coordinate is always 0 for main text anyway.
1137 int const xo = origin_.x_;
1140 // Adapt to cursor row scroll offset if applicable.
1141 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1144 pos_type pos = row.pos();
1147 x = row.left_margin;
1148 else if (x <= row.left_margin) {
1149 pos = row.front().left_pos();
1150 x = row.left_margin;
1151 } else if (x >= row.width()) {
1152 pos = row.back().right_pos();
1155 double w = row.left_margin;
1156 Row::const_iterator cit = row.begin();
1157 Row::const_iterator cend = row.end();
1158 for ( ; cit != cend; ++cit) {
1159 if (w <= x && w + cit->full_width() > x) {
1160 int x_offset = int(x - w);
1161 pos = cit->x2pos(x_offset);
1162 x = int(x_offset + w);
1165 w += cit->full_width();
1167 if (cit == row.end()) {
1168 pos = row.back().right_pos();
1171 /** This tests for the case where the cursor is placed
1172 * just before a font direction change. See comment on
1173 * the boundary_ member in DocIterator.h to understand
1174 * how boundary helps here.
1176 else if (pos == cit->endpos
1177 && ((!cit->isRTL() && cit + 1 != row.end()
1178 && (cit + 1)->isRTL())
1179 || (cit->isRTL() && cit != row.begin()
1180 && !(cit - 1)->isRTL())))
1184 /** This tests for the case where the cursor is set at the end
1185 * of a row which has been broken due something else than a
1186 * separator (a display inset or a forced breaking of the
1187 * row). We know that there is a separator when the end of the
1188 * row is larger than the end of its last element.
1190 if (!row.empty() && pos == row.back().endpos
1191 && row.back().endpos == row.endpos()) {
1192 Inset const * inset = row.back().inset;
1193 if (inset && (inset->lyxCode() == NEWLINE_CODE
1194 || inset->lyxCode() == SEPARATOR_CODE))
1195 pos = row.back().pos;
1197 boundary = row.right_boundary();
1201 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1207 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1209 // We play safe and use parMetrics(pit) to make sure the
1210 // ParagraphMetrics will be redone and OK to use if needed.
1211 // Otherwise we would use an empty ParagraphMetrics in
1212 // upDownInText() while in selection mode.
1213 ParagraphMetrics const & pm = parMetrics(pit);
1215 LBUFERR(row < int(pm.rows().size()));
1217 Row const & r = pm.rows()[row];
1218 return getPosNearX(r, x, bound);
1222 void TextMetrics::newParMetricsDown()
1224 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1225 pit_type const pit = last.first + 1;
1226 if (pit == int(text_->paragraphs().size()))
1229 // do it and update its position.
1231 par_metrics_[pit].setPosition(last.second.position()
1232 + last.second.descent() + par_metrics_[pit].ascent());
1233 updatePosCache(pit);
1237 void TextMetrics::newParMetricsUp()
1239 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1240 if (first.first == 0)
1243 pit_type const pit = first.first - 1;
1244 // do it and update its position.
1246 par_metrics_[pit].setPosition(first.second.position()
1247 - first.second.ascent() - par_metrics_[pit].descent());
1248 updatePosCache(pit);
1251 // y is screen coordinate
1252 pit_type TextMetrics::getPitNearY(int y)
1254 LASSERT(!text_->paragraphs().empty(), return -1);
1255 LASSERT(!par_metrics_.empty(), return -1);
1256 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1258 // look for highest numbered paragraph with y coordinate less than given y
1261 ParMetricsCache::const_iterator it = par_metrics_.begin();
1262 ParMetricsCache::const_iterator et = par_metrics_.end();
1263 ParMetricsCache::const_iterator last = et;
1266 ParagraphMetrics const & pm = it->second;
1268 if (y < it->second.position() - int(pm.ascent())) {
1269 // We are looking for a position that is before the first paragraph in
1270 // the cache (which is in priciple off-screen, that is before the
1273 // We are already at the first paragraph in the inset.
1275 // OK, this is the paragraph we are looking for.
1276 pit = it->first - 1;
1281 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1283 if (y >= last->second.position() + int(pm_last.descent())) {
1284 // We are looking for a position that is after the last paragraph in
1285 // the cache (which is in priciple off-screen), that is before the
1287 pit = last->first + 1;
1288 if (pit == int(text_->paragraphs().size()))
1289 // We are already at the last paragraph in the inset.
1291 // OK, this is the paragraph we are looking for.
1292 newParMetricsDown();
1296 for (; it != et; ++it) {
1297 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1298 << " y: " << it->second.position());
1300 ParagraphMetrics const & pm = par_metrics_[it->first];
1302 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1304 yy = it->second.position();
1308 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1314 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1315 bool assert_in_view, bool up)
1317 ParagraphMetrics const & pm = par_metrics_[pit];
1319 int yy = pm.position() - pm.ascent();
1320 LBUFERR(!pm.rows().empty());
1321 RowList::const_iterator rit = pm.rows().begin();
1322 RowList::const_iterator rlast = pm.rows().end();
1324 for (; rit != rlast; yy += rit->height(), ++rit)
1325 if (yy + rit->height() > y)
1328 if (assert_in_view) {
1329 if (!up && yy + rit->height() > y) {
1330 if (rit != pm.rows().begin()) {
1333 } else if (pit != 0) {
1336 ParagraphMetrics const & pm2 = par_metrics_[pit];
1337 rit = pm2.rows().end();
1341 } else if (up && yy != y) {
1343 y = yy + rit->height();
1345 } else if (pit < int(text_->paragraphs().size()) - 1) {
1347 newParMetricsDown();
1348 ParagraphMetrics const & pm2 = par_metrics_[pit];
1349 rit = pm2.rows().begin();
1358 // x,y are absolute screen coordinates
1359 // sets cursor recursively descending into nested editable insets
1360 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1361 bool assert_in_view, bool up)
1363 if (lyxerr.debugging(Debug::WORKAREA)) {
1364 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1365 cur.bv().coordCache().dump();
1367 pit_type pit = getPitNearY(y);
1368 LASSERT(pit != -1, return 0);
1369 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1372 // Do we cover an inset?
1373 InsetList::InsetTable * it = checkInsetHit(pit, x, y);
1376 // No inset, set position in the text
1377 bool bound = false; // is modified by getPosNearX
1378 cur.pos() = getPosNearX(row, x, bound);
1379 cur.boundary(bound);
1380 cur.setCurrentFont();
1385 Inset * inset = it->inset;
1386 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1388 // Set position in front of inset
1389 cur.pos() = it->pos;
1390 cur.boundary(false);
1393 // Try to descend recursively inside the inset.
1394 Inset * edited = inset->editXY(cur, x, y);
1395 // FIXME: it is not clear that the test on position is needed
1396 // Remove it if/when semantics of editXY is clarified
1397 if (cur.text() == text_ && cur.pos() == it->pos) {
1398 // non-editable inset, set cursor after the inset if x is
1399 // nearer to that position (bug 9628)
1400 bool bound = false; // is modified by getPosNearX
1401 cur.pos() = getPosNearX(row, x, bound);
1402 cur.boundary(bound);
1403 cur.setCurrentFont();
1407 if (cur.top().text() == text_)
1408 cur.setCurrentFont();
1413 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1415 LASSERT(text_ == cur.text(), return);
1416 pit_type const pit = getPitNearY(y);
1417 LASSERT(pit != -1, return);
1419 ParagraphMetrics const & pm = par_metrics_[pit];
1421 int yy = pm.position() - pm.ascent();
1422 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1423 " pit: " << pit << " yy: " << yy);
1426 LBUFERR(pm.rows().size());
1427 for (; r < int(pm.rows().size()) - 1; ++r) {
1428 Row const & row = pm.rows()[r];
1429 if (int(yy + row.height()) > y)
1434 Row const & row = pm.rows()[r];
1436 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1440 pos_type const pos = getPosNearX(row, xx, bound);
1442 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1444 text_->setCursor(cur, pit, pos, true, bound);
1445 // remember new position.
1450 //takes screen x,y coordinates
1451 InsetList::InsetTable * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1453 Paragraph const & par = text_->paragraphs()[pit];
1454 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1456 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1458 for (auto const & it : par.insetList()) {
1459 LYXERR(Debug::DEBUG, "examining inset " << it.inset);
1461 if (insetCache.covers(it.inset, x, y)) {
1462 LYXERR(Debug::DEBUG, "Hit inset: " << it.inset);
1463 return const_cast<InsetList::InsetTable *>(&it);
1467 LYXERR(Debug::DEBUG, "No inset hit. ");
1472 //takes screen x,y coordinates
1473 Inset * TextMetrics::checkInsetHit(int x, int y)
1475 pit_type const pit = getPitNearY(y);
1476 LASSERT(pit != -1, return 0);
1477 InsetList::InsetTable * it = checkInsetHit(pit, x, y);
1486 int TextMetrics::cursorX(CursorSlice const & sl,
1487 bool boundary) const
1489 LASSERT(sl.text() == text_, return 0);
1491 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1492 if (pm.rows().empty())
1494 Row const & row = pm.getRow(sl.pos(), boundary);
1495 pos_type const pos = sl.pos();
1498 row.findElement(pos, boundary, x);
1504 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1506 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1507 ParagraphMetrics const & pm = parMetrics(sl.pit());
1508 if (pm.rows().empty())
1512 h -= parMetrics(0).rows()[0].ascent();
1513 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1514 h += parMetrics(pit).height();
1517 if (pos && boundary)
1519 size_t const rend = pm.pos2row(pos);
1520 for (size_t rit = 0; rit != rend; ++rit)
1521 h += pm.rows()[rit].height();
1522 h += pm.rows()[rend].ascent();
1527 // the cursor set functions have a special mechanism. When they
1528 // realize you left an empty paragraph, they will delete it.
1530 bool TextMetrics::cursorHome(Cursor & cur)
1532 LASSERT(text_ == cur.text(), return false);
1533 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1534 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1535 return text_->setCursor(cur, cur.pit(), row.pos());
1539 bool TextMetrics::cursorEnd(Cursor & cur)
1541 LASSERT(text_ == cur.text(), return false);
1542 // if not on the last row of the par, put the cursor before
1543 // the final space exept if I have a spanning inset or one string
1544 // is so long that we force a break.
1545 pos_type end = cur.textRow().endpos();
1547 // empty text, end-1 is no valid position
1549 bool boundary = false;
1550 if (end != cur.lastpos()) {
1551 if (!cur.paragraph().isLineSeparator(end-1)
1552 && !cur.paragraph().isNewline(end-1)
1553 && !cur.paragraph().isEnvSeparator(end-1))
1557 } else if (cur.paragraph().isEnvSeparator(end-1))
1559 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1563 void TextMetrics::deleteLineForward(Cursor & cur)
1565 LASSERT(text_ == cur.text(), return);
1566 if (cur.lastpos() == 0) {
1567 // Paragraph is empty, so we just go forward
1568 text_->cursorForward(cur);
1571 cur.selection(true); // to avoid deletion
1574 // What is this test for ??? (JMarc)
1575 if (!cur.selection())
1576 text_->deleteWordForward(cur);
1578 cap::cutSelection(cur, false);
1579 cur.checkBufferStructure();
1584 bool TextMetrics::isLastRow(Row const & row) const
1586 ParagraphList const & pars = text_->paragraphs();
1587 return row.endpos() >= pars[row.pit()].size()
1588 && row.pit() + 1 == pit_type(pars.size());
1592 bool TextMetrics::isFirstRow(Row const & row) const
1594 return row.pos() == 0 && row.pit() == 0;
1598 int TextMetrics::leftMargin(pit_type pit) const
1600 return leftMargin(pit, text_->paragraphs()[pit].size());
1604 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1606 ParagraphList const & pars = text_->paragraphs();
1608 LASSERT(pit >= 0, return 0);
1609 LASSERT(pit < int(pars.size()), return 0);
1610 Paragraph const & par = pars[pit];
1611 LASSERT(pos >= 0, return 0);
1612 LASSERT(pos <= par.size(), return 0);
1613 Buffer const & buffer = bv_->buffer();
1614 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1615 DocumentClass const & tclass = buffer.params().documentClass();
1616 Layout const & layout = par.layout();
1617 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1619 docstring parindent = layout.parindent;
1623 if (text_->isMainText()) {
1624 l_margin += bv_->leftMargin();
1625 l_margin += bfm.signedWidth(tclass.leftmargin());
1628 int depth = par.getDepth();
1630 // find the next level paragraph
1631 pit_type newpar = text_->outerHook(pit);
1632 if (newpar != pit_type(pars.size())) {
1633 if (pars[newpar].layout().isEnvironment()) {
1634 int nestmargin = depth * nestMargin();
1635 if (text_->isMainText())
1636 nestmargin += changebarMargin();
1637 l_margin = max(leftMargin(newpar), nestmargin);
1638 // Remove the parindent that has been added
1639 // if the paragraph was empty.
1640 if (pars[newpar].empty() &&
1641 buffer.params().paragraph_separation ==
1642 BufferParams::ParagraphIndentSeparation) {
1643 docstring pi = pars[newpar].layout().parindent;
1644 l_margin -= bfm.signedWidth(pi);
1647 if (tclass.isDefaultLayout(par.layout())
1648 || tclass.isPlainLayout(par.layout())) {
1649 if (pars[newpar].params().noindent())
1652 parindent = pars[newpar].layout().parindent;
1657 // This happens after sections or environments in standard classes.
1658 // We have to check the previous layout at same depth.
1659 if (buffer.params().paragraph_separation ==
1660 BufferParams::ParagraphSkipSeparation)
1662 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1663 pit_type prev = text_->depthHook(pit, par.getDepth());
1664 if (par.layout() == pars[prev].layout()) {
1666 && pars[pit - 1].layout().nextnoindent)
1668 } else if (pars[prev].layout().nextnoindent)
1672 FontInfo const labelfont = text_->labelFont(par);
1673 FontMetrics const & lfm = theFontMetrics(labelfont);
1675 switch (layout.margintype) {
1676 case MARGIN_DYNAMIC:
1677 if (!layout.leftmargin.empty()) {
1678 l_margin += bfm.signedWidth(layout.leftmargin);
1680 if (!par.labelString().empty()) {
1681 l_margin += lfm.signedWidth(layout.labelindent);
1682 l_margin += lfm.width(par.labelString());
1683 l_margin += lfm.width(layout.labelsep);
1687 case MARGIN_MANUAL: {
1688 l_margin += lfm.signedWidth(layout.labelindent);
1689 // The width of an empty par, even with manual label, should be 0
1690 if (!par.empty() && pos >= par.beginOfBody()) {
1691 if (!par.getLabelWidthString().empty()) {
1692 docstring labstr = par.getLabelWidthString();
1693 l_margin += lfm.width(labstr);
1694 l_margin += lfm.width(layout.labelsep);
1700 case MARGIN_STATIC: {
1701 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1702 / (par.getDepth() + 4);
1706 case MARGIN_FIRST_DYNAMIC:
1707 if (layout.labeltype == LABEL_MANUAL) {
1708 // if we are at position 0, we are never in the body
1709 if (pos > 0 && pos >= par.beginOfBody())
1710 l_margin += lfm.signedWidth(layout.leftmargin);
1712 l_margin += lfm.signedWidth(layout.labelindent);
1714 // Special case to fix problems with
1716 || (layout.labeltype == LABEL_STATIC
1717 && layout.latextype == LATEX_ENVIRONMENT
1718 && !text_->isFirstInSequence(pit))) {
1719 l_margin += lfm.signedWidth(layout.leftmargin);
1720 } else if (!layout.labelIsAbove()) {
1721 l_margin += lfm.signedWidth(layout.labelindent);
1722 l_margin += lfm.width(layout.labelsep);
1723 l_margin += lfm.width(par.labelString());
1727 case MARGIN_RIGHT_ADDRESS_BOX: {
1729 // The left margin depends on the widest row in this paragraph.
1730 // This code is wrong because it depends on the rows, but at the
1731 // same time this function is used in redoParagraph to construct
1733 ParagraphMetrics const & pm = par_metrics_[pit];
1734 RowList::const_iterator rit = pm.rows().begin();
1735 RowList::const_iterator end = pm.rows().end();
1736 int minfill = max_width_;
1737 for ( ; rit != end; ++rit)
1738 if (rit->fill() < minfill)
1739 minfill = rit->fill();
1740 l_margin += bfm.signedWidth(layout.leftmargin);
1741 l_margin += minfill;
1743 // also wrong, but much shorter.
1744 l_margin += max_width_ / 2;
1749 if (!par.params().leftIndent().zero())
1750 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1752 LyXAlignment align = par.getAlign(bv_->buffer().params());
1754 // set the correct parindent
1756 && (layout.labeltype == LABEL_NO_LABEL
1757 || layout.labeltype == LABEL_ABOVE
1758 || layout.labeltype == LABEL_CENTERED
1759 || (layout.labeltype == LABEL_STATIC
1760 && layout.latextype == LATEX_ENVIRONMENT
1761 && !text_->isFirstInSequence(pit)))
1762 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1763 && !par.params().noindent()
1764 // in some insets, paragraphs are never indented
1765 && !text_->inset().neverIndent()
1766 // display style insets are always centered, omit indentation
1769 && par.getInset(pos)->display())
1770 && (!(tclass.isDefaultLayout(par.layout())
1771 || tclass.isPlainLayout(par.layout()))
1772 || buffer.params().paragraph_separation
1773 == BufferParams::ParagraphIndentSeparation)) {
1774 /* use the parindent of the layout when the default
1775 * indentation is used otherwise use the indentation set in
1776 * the document settings
1778 if (buffer.params().getParIndent().empty())
1779 l_margin += bfm.signedWidth(parindent);
1781 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1788 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1790 if (par_metrics_.empty())
1796 ParMetricsCache::iterator it = par_metrics_.begin();
1797 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1798 y -= it->second.ascent();
1799 for (; it != pm_end; ++it) {
1800 ParagraphMetrics const & pmi = it->second;
1802 pit_type const pit = it->first;
1803 // Save the paragraph position in the cache.
1804 it->second.setPosition(y);
1805 drawParagraph(pi, pit, x, y);
1811 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1813 ParagraphMetrics const & pm = par_metrics_[pit];
1814 if (pm.rows().empty())
1816 size_t const nrows = pm.rows().size();
1818 // Use fast lane in nodraw stage.
1819 if (pi.pain.isNull()) {
1820 for (size_t i = 0; i != nrows; ++i) {
1822 Row const & row = pm.rows()[i];
1823 // Adapt to cursor row scroll offset if applicable.
1824 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1828 RowPainter rp(pi, *text_, row, row_x, y);
1830 rp.paintOnlyInsets();
1836 int const ww = bv_->workHeight();
1837 Cursor const & cur = bv_->cursor();
1838 DocIterator sel_beg = cur.selectionBegin();
1839 DocIterator sel_end = cur.selectionEnd();
1840 bool selection = cur.selection()
1841 // This is our text.
1842 && cur.text() == text_
1843 // if the anchor is outside, this is not our selection
1844 && cur.normalAnchor().text() == text_
1845 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1847 // We store the begin and end pos of the selection relative to this par
1848 DocIterator sel_beg_par = cur.selectionBegin();
1849 DocIterator sel_end_par = cur.selectionEnd();
1851 // We care only about visible selection.
1853 if (pit != sel_beg.pit()) {
1854 sel_beg_par.pit() = pit;
1855 sel_beg_par.pos() = 0;
1857 if (pit != sel_end.pit()) {
1858 sel_end_par.pit() = pit;
1859 sel_end_par.pos() = sel_end_par.lastpos();
1863 for (size_t i = 0; i != nrows; ++i) {
1865 Row const & row = pm.rows()[i];
1866 // Adapt to cursor row scroll offset if applicable.
1867 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1871 // It is not needed to draw on screen if we are not inside.
1872 bool const inside = (y + row.descent() >= 0
1873 && y - row.ascent() < ww);
1875 // Inset positions have already been set in nodraw stage.
1881 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
1883 row.setSelection(-1, -1);
1885 // The row knows nothing about the paragraph, so we have to check
1886 // whether this row is the first or last and update the margins.
1887 if (row.selection()) {
1888 if (row.sel_beg == 0)
1889 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
1890 if (row.sel_end == sel_end_par.lastpos())
1891 row.change(row.end_margin_sel, sel_end.pit() > pit);
1894 // has row changed since last paint?
1895 bool row_has_changed = row.changed()
1896 || bv_->hadHorizScrollOffset(text_, pit, row.pos());
1898 // Take this opportunity to spellcheck the row contents.
1899 if (row_has_changed && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
1900 text_->getPar(pit).spellCheck();
1903 RowPainter rp(pi, *text_, row, row_x, y);
1905 // Don't paint the row if a full repaint has not been requested
1906 // and if it has not changed.
1907 if (!pi.full_repaint && !row_has_changed) {
1908 // Paint only the insets if the text itself is
1910 rp.paintOnlyInsets();
1916 // Clear background of this row if paragraph background was not
1917 // already cleared because of a full repaint.
1918 if (!pi.full_repaint && row_has_changed) {
1919 LYXERR(Debug::PAINTING, "Clear rect@("
1920 << max(row_x, 0) << ", " << y - row.ascent() << ")="
1921 << width() << " x " << row.height());
1922 // FIXME: this is a hack. We know that at least this
1923 // amount of pixels can be cleared on right and left.
1924 // Doing so gets rid of caret ghosts when the cursor is at
1925 // the begining/end of row. However, it will not work if
1926 // the caret has a ridiculous width like 6. (see ticket
1928 pi.pain.fillRectangle(max(row_x, 0) - Inset::TEXT_TO_INSET_OFFSET,
1930 width() + 2 * Inset::TEXT_TO_INSET_OFFSET,
1931 row.height(), pi.background_color);
1934 // Instrumentation for testing row cache (see also
1936 if (lyxerr.debugging(Debug::PAINTING)
1937 && (row.selection() || pi.full_repaint || row_has_changed)) {
1938 string const foreword = text_->isMainText() ? "main text redraw "
1939 : "inset text redraw: ";
1940 LYXERR0(foreword << "pit=" << pit << " row=" << i
1941 << (row.selection() ? " row_selection": "")
1942 << (pi.full_repaint ? " full_repaint" : "")
1943 << (row_has_changed ? " row_has_changed" : ""));
1946 // Backup full_repaint status and force full repaint
1947 // for inner insets as the Row has been cleared out.
1948 bool tmp = pi.full_repaint;
1949 pi.full_repaint = true;
1951 rp.paintSelection();
1954 if (row.needsChangeBar())
1955 rp.paintChangeBar();
1956 if (i == 0 && !row.isRTL())
1958 if (i == nrows - 1 && row.isRTL())
1961 if (i == nrows - 1 && !row.isRTL())
1963 if (i == 0 && row.isRTL())
1965 rp.paintTooLargeMarks(row_x + row.left_x() < 0,
1966 row_x + row.right_x() > bv_->workWidth());
1970 // This debug code shows on screen which rows are repainted.
1971 // FIXME: since the updates related to caret blinking restrict
1972 // the painter to a small rectangle, the numbers are not
1973 // updated when this happens. Change the code in
1974 // GuiWorkArea::Private::show/hideCaret if this is important.
1975 static int count = 0;
1977 FontInfo fi(sane_font);
1978 fi.setSize(FONT_SIZE_TINY);
1979 fi.setColor(Color_red);
1980 pi.pain.text(row_x, y, convert<docstring>(count), fi);
1983 // Restore full_repaint status.
1984 pi.full_repaint = tmp;
1989 //LYXERR(Debug::PAINTING, ".");
1993 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
1994 Dimension & dim) const
1996 Cursor const & bvcur = cur.bv().cursor();
1998 // get word in front of cursor
1999 docstring word = text_->previousWord(bvcur.top());
2000 DocIterator wordStart = bvcur;
2001 wordStart.pos() -= word.length();
2003 // calculate dimensions of the word
2005 row.pit(bvcur.pit());
2006 row.pos(wordStart.pos());
2007 row.endpos(bvcur.pos());
2009 dim = row.dimension();
2011 // get position on screen of the word start and end
2012 //FIXME: Is it necessary to explicitly set this to false?
2013 wordStart.boundary(false);
2014 Point lxy = cur.bv().getPos(wordStart);
2015 Point rxy = cur.bv().getPos(bvcur);
2016 dim.wid = abs(rxy.x_ - lxy.x_);
2018 // calculate position of word
2020 x = min(rxy.x_, lxy.x_);
2022 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2023 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2026 int defaultRowHeight()
2028 return int(theFontMetrics(sane_font).maxHeight() * 1.2);