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"
24 #include "buffer_funcs.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "CoordCache.h"
29 #include "CutAndPaste.h"
30 #include "FuncRequest.h"
32 #include "InsetList.h"
36 #include "MetricsInfo.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.h"
39 #include "rowpainter.h"
41 #include "TextClass.h"
43 #include "WordLangTuple.h"
45 #include "insets/InsetText.h"
47 #include "mathed/MacroTable.h"
48 #include "mathed/MathMacroTemplate.h"
50 #include "frontends/FontMetrics.h"
51 #include "frontends/Painter.h"
53 #include "support/debug.h"
54 #include "support/docstring_list.h"
55 #include "support/lassert.h"
64 using frontend::FontMetrics;
66 static int numberOfSeparators(Paragraph const & par, Row const & row)
68 pos_type const first = max(row.pos(), par.beginOfBody());
69 pos_type const last = row.endpos() - 1;
71 for (pos_type p = first; p < last; ++p) {
72 if (par.isSeparator(p))
79 static int numberOfLabelHfills(Paragraph const & par, Row const & row)
81 pos_type last = row.endpos() - 1;
82 pos_type first = row.pos();
84 // hfill *DO* count at the beginning of paragraphs!
86 while (first < last && par.isHfill(first))
90 last = min(last, par.beginOfBody());
92 for (pos_type p = first; p < last; ++p) {
100 static int numberOfHfills(Paragraph const & par, Row const & row)
102 pos_type const last = row.endpos();
103 pos_type first = row.pos();
105 // hfill *DO* count at the beginning of paragraphs!
107 while (first < last && par.isHfill(first))
111 first = max(first, par.beginOfBody());
114 for (pos_type p = first; p < last; ++p) {
122 /////////////////////////////////////////////////////////////////////
126 /////////////////////////////////////////////////////////////////////
129 TextMetrics::TextMetrics(BufferView * bv, Text * text)
130 : bv_(bv), text_(text)
133 max_width_ = bv_->workWidth();
134 dim_.wid = max_width_;
138 //text_->updateBuffer(bv->buffer());
142 bool TextMetrics::contains(pit_type pit) const
144 return par_metrics_.find(pit) != par_metrics_.end();
148 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
150 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
155 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
157 ParMetricsCache::const_iterator it = par_metrics_.begin();
158 return make_pair(it->first, &it->second);
162 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
164 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
165 return make_pair(it->first, &it->second);
169 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
171 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
172 if (pmc_it == par_metrics_.end()) {
173 pmc_it = par_metrics_.insert(
174 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
176 if (pmc_it->second.rows().empty() && redo)
178 return pmc_it->second;
182 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
184 LASSERT(mi.base.textwidth > 0, /**/);
185 max_width_ = mi.base.textwidth;
186 // backup old dimension.
187 Dimension const old_dim = dim_;
190 dim_.wid = min_width;
191 pit_type const npar = text_->paragraphs().size();
193 // If there is more than one row, expand the text to
194 // the full allowable width.
195 dim_.wid = max_width_;
197 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
198 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
200 bool changed = false;
202 for (pit_type pit = 0; pit != npar; ++pit) {
203 changed |= redoParagraph(pit);
204 ParagraphMetrics const & pm = par_metrics_[pit];
206 if (dim_.wid < pm.width())
207 dim_.wid = pm.width();
210 dim_.asc = par_metrics_[0].ascent();
211 dim_.des = h - dim_.asc;
212 //lyxerr << "dim_.wid " << dim_.wid << endl;
213 //lyxerr << "dim_.asc " << dim_.asc << endl;
214 //lyxerr << "dim_.des " << dim_.des << endl;
216 changed |= dim_ != old_dim;
222 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
224 return main_text_? pm.rightMargin(*bv_) : 0;
228 int TextMetrics::rightMargin(pit_type const pit) const
230 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
234 void TextMetrics::applyOuterFont(Font & font) const
236 FontInfo lf(font_.fontInfo());
237 lf.reduce(bv_->buffer().params().getFont().fontInfo());
238 font.fontInfo().realize(lf);
242 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
244 LASSERT(pos >= 0, /**/);
246 ParagraphList const & pars = text_->paragraphs();
247 Paragraph const & par = pars[pit];
248 Layout const & layout = par.layout();
249 Buffer const & buffer = bv_->buffer();
251 BufferParams const & params = buffer.params();
252 pos_type const body_pos = par.beginOfBody();
254 // We specialize the 95% common case:
255 if (!par.getDepth()) {
256 Font f = par.getFontSettings(params, pos);
257 if (!text_->isMainText())
259 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
261 FontInfo const & lf = lab ? layout.labelfont : layout.font;
262 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
264 // In case the default family has been customized
265 if (lf.family() == INHERIT_FAMILY)
266 rlf.setFamily(params.getFont().fontInfo().family());
267 f.fontInfo().realize(rlf);
271 // The uncommon case need not be optimized as much
272 FontInfo const & layoutfont = pos < body_pos ?
273 layout.labelfont : layout.font;
275 Font font = par.getFontSettings(params, pos);
276 font.fontInfo().realize(layoutfont);
278 if (!text_->isMainText())
279 applyOuterFont(font);
281 // Realize against environment font information
282 // NOTE: the cast to pit_type should be removed when pit_type
283 // changes to a unsigned integer.
284 if (pit < pit_type(pars.size()))
285 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
287 // Realize with the fonts of lesser depth.
288 font.fontInfo().realize(params.getFont().fontInfo());
294 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
296 if (!lyxrc.rtl_support || !sl.text())
300 if (boundary && sl.pos() > 0)
303 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
307 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
309 // no RTL boundary at paragraph start
310 if (!lyxrc.rtl_support || pos == 0)
313 Font const & left_font = displayFont(pit, pos - 1);
315 return isRTLBoundary(pit, pos, left_font);
319 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
320 Font const & font) const
322 if (!lyxrc.rtl_support
323 // no RTL boundary at paragraph start
325 // if the metrics have not been calculated, then we are not
326 // on screen and can safely ignore issues about boundaries.
330 ParagraphMetrics & pm = par_metrics_[pit];
331 // no RTL boundary in empty paragraph
332 if (pm.rows().empty())
335 pos_type endpos = pm.getRow(pos - 1, false).endpos();
336 pos_type startpos = pm.getRow(pos, false).pos();
337 // no RTL boundary at line start:
338 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
340 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
343 Paragraph const & par = text_->getPar(pit);
344 // no RTL boundary at line break:
345 // abc|\n -> move right -> abc\n (and not: abc\n|
347 if (startpos == pos && endpos == pos && endpos != par.size()
348 && (par.isNewline(pos - 1)
349 || par.isLineSeparator(pos - 1)
350 || par.isSeparator(pos - 1)))
353 bool left = font.isVisibleRightToLeft();
355 if (pos == par.size())
356 right = par.isRTL(bv_->buffer().params());
358 right = displayFont(pit, pos).isVisibleRightToLeft();
360 return left != right;
364 bool TextMetrics::redoParagraph(pit_type const pit)
366 Paragraph & par = text_->getPar(pit);
367 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
368 // redoParagraph() recursively inside parMetrics.
369 Dimension old_dim = parMetrics(pit, false).dim();
370 ParagraphMetrics & pm = par_metrics_[pit];
373 Buffer & buffer = bv_->buffer();
374 main_text_ = (text_ == &buffer.text());
375 bool changed = false;
377 // FIXME: This check ought to be done somewhere else. It is the reason
378 // why text_ is not const. But then, where else to do it?
379 // Well, how can you end up with either (a) a biblio environment that
380 // has no InsetBibitem or (b) a biblio environment with more than one
381 // InsetBibitem? I think the answer is: when paragraphs are merged;
382 // when layout is set; when material is pasted.
383 int const moveCursor = par.checkBiblio(buffer);
385 const_cast<Cursor &>(bv_->cursor()).posForward();
386 else if (moveCursor < 0) {
387 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
388 if (cursor.pos() >= -moveCursor)
389 cursor.posBackward();
392 // Optimisation: this is used in the next two loops
393 // so better to calculate that once here.
394 int const right_margin = rightMargin(pm);
396 // iterator pointing to paragraph to resolve macros
397 DocIterator parPos = text_->macrocontextPosition();
401 LYXERR(Debug::INFO, "MacroContext not initialised!"
402 << " Going through the buffer again and hope"
403 << " the context is better then.");
404 bv_->buffer().updateBuffer();
405 parPos = text_->macrocontextPosition();
406 LASSERT(!parPos.empty(), /**/);
411 // FIXME: We should always use getFont(), see documentation of
412 // noFontChange() in Inset.h.
413 Font const bufferfont = buffer.params().getFont();
414 InsetList::const_iterator ii = par.insetList().begin();
415 InsetList::const_iterator iend = par.insetList().end();
416 for (; ii != iend; ++ii) {
417 // position already initialized?
418 if (!parPos.empty()) {
419 parPos.pos() = ii->pos;
421 // A macro template would normally not be visible
422 // by itself. But the tex macro semantics allow
423 // recursion, so we artifically take the context
424 // after the macro template to simulate this.
425 if (ii->inset->lyxCode() == MATHMACRO_CODE)
429 // do the metric calculation
431 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
433 Font const & font = ii->inset->noFontChange() ?
434 bufferfont : displayFont(pit, ii->pos);
435 MacroContext mc(&buffer, parPos);
436 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
437 ii->inset->metrics(mi, dim);
438 Dimension const old_dim = pm.insetDimension(ii->inset);
439 if (old_dim != dim) {
440 pm.setInsetDimension(ii->inset, dim);
445 par.setBeginOfBody();
447 size_t row_index = 0;
448 // maximum pixel width of a row
449 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
452 pos_type end = rowBreakPoint(width, pit, first);
453 if (row_index || end < par.size())
454 // If there is more than one row, expand the text to
455 // the full allowable width. This setting here is needed
456 // for the computeRowMetrics() below.
457 dim_.wid = max_width_;
459 dim = rowHeight(pit, first, end);
460 dim.wid = rowWidth(right_margin, pit, first, end);
461 if (row_index == pm.rows().size())
462 pm.rows().push_back(Row());
463 Row & row = pm.rows()[row_index];
464 row.setChanged(false);
467 row.setDimension(dim);
468 int const max_row_width = max(dim_.wid, dim.wid);
469 computeRowMetrics(pit, row, max_row_width);
473 pm.dim().wid = max(pm.dim().wid, dim.wid);
474 pm.dim().des += dim.height();
475 } while (first < par.size());
477 if (row_index < pm.rows().size())
478 pm.rows().resize(row_index);
480 // Make sure that if a par ends in newline, there is one more row
482 if (first > 0 && par.isNewline(first - 1)) {
483 Dimension dim = rowHeight(pit, first, first);
484 dim.wid = rowWidth(right_margin, pit, first, first);
485 if (row_index == pm.rows().size())
486 pm.rows().push_back(Row());
487 Row & row = pm.rows()[row_index];
488 row.setChanged(false);
491 row.setDimension(dim);
492 int const max_row_width = max(dim_.wid, dim.wid);
493 computeRowMetrics(pit, row, max_row_width);
494 pm.dim().des += dim.height();
497 pm.dim().asc += pm.rows()[0].ascent();
498 pm.dim().des -= pm.rows()[0].ascent();
500 changed |= old_dim.height() != pm.dim().height();
506 void TextMetrics::computeRowMetrics(pit_type const pit,
507 Row & row, int width) const
512 Paragraph const & par = text_->getPar(pit);
514 double w = width - row.width();
515 // FIXME: put back this assertion when the crash on new doc is solved.
516 //LASSERT(w >= 0, /**/);
518 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
519 //lyxerr << "row.width() " << row.width() << endl;
520 //lyxerr << "w " << w << endl;
522 bool const is_rtl = text_->isRTL(par);
524 row.x = rightMargin(pit);
526 row.x = leftMargin(max_width_, pit, row.pos());
528 // is there a manual margin with a manual label
529 Layout const & layout = par.layout();
531 if (layout.margintype == MARGIN_MANUAL
532 && layout.labeltype == LABEL_MANUAL) {
533 /// We might have real hfills in the label part
534 int nlh = numberOfLabelHfills(par, row);
536 // A manual label par (e.g. List) has an auto-hfill
537 // between the label text and the body of the
539 // But we don't want to do this auto hfill if the par
544 if (nlh && !par.getLabelWidthString().empty())
545 row.label_hfill = labelFill(pit, row) / double(nlh);
549 // are there any hfills in the row?
550 if (int const nh = numberOfHfills(par, row)) {
552 hfill = w / double(nh);
553 // we don't have to look at the alignment if it is ALIGN_LEFT and
554 // if the row is already larger then the permitted width as then
555 // we force the LEFT_ALIGN'edness!
556 } else if (int(row.width()) < max_width_) {
557 // is it block, flushleft or flushright?
558 // set x how you need it
560 if (par.params().align() == LYX_ALIGN_LAYOUT)
561 align = layout.align;
563 align = par.params().align();
565 // handle alignment inside tabular cells
566 Inset const & owner = text_->inset();
567 switch (owner.contentAlignment()) {
568 case LYX_ALIGN_CENTER:
570 case LYX_ALIGN_RIGHT:
571 if (align == LYX_ALIGN_NONE
572 || align == LYX_ALIGN_BLOCK)
573 align = owner.contentAlignment();
576 // unchanged (use align)
580 // Display-style insets should always be on a centered row
581 if (Inset const * inset = par.getInset(row.pos())) {
582 switch (inset->display()) {
583 case Inset::AlignLeft:
584 align = LYX_ALIGN_BLOCK;
586 case Inset::AlignCenter:
587 align = LYX_ALIGN_CENTER;
590 // unchanged (use align)
592 case Inset::AlignRight:
593 align = LYX_ALIGN_RIGHT;
599 case LYX_ALIGN_BLOCK: {
600 int const ns = numberOfSeparators(par, row);
601 bool disp_inset = false;
602 if (row.endpos() < par.size()) {
603 Inset const * in = par.getInset(row.endpos());
605 disp_inset = in->display();
607 // If we have separators, this is not the last row of a
608 // par, does not end in newline, and is not row above a
609 // display inset... then stretch it
611 && row.endpos() < par.size()
612 && !par.isNewline(row.endpos() - 1)
615 row.separator = w / ns;
616 //lyxerr << "row.separator " << row.separator << endl;
617 //lyxerr << "ns " << ns << endl;
623 case LYX_ALIGN_RIGHT:
626 case LYX_ALIGN_CENTER:
633 pos_type body_pos = par.beginOfBody();
634 pos_type end = row.endpos();
637 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
639 row.x += theFontMetrics(text_->labelFont(par)).
640 width(layout.labelsep);
642 row.x += row.label_hfill;
646 pos_type const endpos = row.endpos();
647 pos_type body_pos = par.beginOfBody();
649 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
652 ParagraphMetrics & pm = par_metrics_[pit];
653 InsetList::const_iterator ii = par.insetList().begin();
654 InsetList::const_iterator iend = par.insetList().end();
655 for ( ; ii != iend; ++ii) {
656 if (ii->pos >= endpos || ii->pos < row.pos()
657 || (ii->inset->lyxCode() != SPACE_CODE ||
658 !ii->inset->isStretchableSpace()))
660 Dimension dim = row.dimension();
661 if (pm.hfillExpansion(row, ii->pos))
662 dim.wid = int(ii->pos >= body_pos ?
663 max(hfill, 5.0) : row.label_hfill);
666 // Cache the inset dimension.
667 bv_->coordCache().insets().add(ii->inset, dim);
668 pm.setInsetDimension(ii->inset, dim);
673 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
675 Paragraph const & par = text_->getPar(pit);
677 pos_type last = par.beginOfBody();
678 LASSERT(last > 0, /**/);
680 // -1 because a label ends with a space that is in the label
683 // a separator at this end does not count
684 if (par.isLineSeparator(last))
688 for (pos_type i = row.pos(); i <= last; ++i)
689 w += singleWidth(pit, i);
691 docstring const & label = par.params().labelWidthString();
695 FontMetrics const & fm
696 = theFontMetrics(text_->labelFont(par));
698 return max(0, fm.width(label) - w);
702 // this needs special handling - only newlines count as a break point
703 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
705 pos_type const end = par.size();
708 if (par.isNewline(i))
715 int TextMetrics::labelEnd(pit_type const pit) const
717 // labelEnd is only needed if the layout fills a flushleft label.
718 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
720 // return the beginning of the body
721 return leftMargin(max_width_, pit);
727 * Calling Text::getFont is slow. While rebreaking we scan a
728 * paragraph from left to right calling getFont for every char. This
729 * simple class address this problem by hidding an optimization trick
730 * (not mine btw -AB): the font is reused in the whole font span. The
731 * class handles transparently the "hidden" (not part of the fontlist)
732 * label font (as getFont does).
738 FontIterator(TextMetrics const & tm,
739 Paragraph const & par, pit_type pit, pos_type pos)
740 : tm_(tm), par_(par), pit_(pit), pos_(pos),
741 font_(tm.displayFont(pit, pos)),
742 endspan_(par.fontSpan(pos).last),
743 bodypos_(par.beginOfBody())
747 Font const & operator*() const { return font_; }
750 FontIterator & operator++()
753 if (pos_ > endspan_ || pos_ == bodypos_) {
754 font_ = tm_.displayFont(pit_, pos_);
755 endspan_ = par_.fontSpan(pos_).last;
761 Font * operator->() { return &font_; }
765 TextMetrics const & tm_;
767 Paragraph const & par_;
782 pos_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
785 ParagraphMetrics const & pm = par_metrics_[pit];
786 Paragraph const & par = text_->getPar(pit);
787 pos_type const end = par.size();
788 if (pos == end || width < 0)
791 Layout const & layout = par.layout();
793 if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX)
794 return addressBreakPoint(pos, par);
796 pos_type const body_pos = par.beginOfBody();
798 // check for possible inline completion
799 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
800 pos_type inlineCompletionLPos = -1;
801 if (inlineCompletionPos.inTexted()
802 && inlineCompletionPos.text() == text_
803 && inlineCompletionPos.pit() == pit) {
804 // draw logically behind the previous character
805 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
808 // Now we iterate through until we reach the right margin
809 // or the end of the par, then choose the possible break
812 int label_end = labelEnd(pit);
813 int const left = leftMargin(max_width_, pit, pos);
816 // pixel width since last breakpoint
819 docstring const s(1, char_type(0x00B6));
821 int par_marker_width = theFontMetrics(f).width(s);
823 FontIterator fi = FontIterator(*this, par, pit, pos);
824 pos_type point = end;
827 ParagraphList const & pars_ = text_->paragraphs();
828 bool const draw_par_end_marker = lyxrc.paragraph_markers
829 && size_type(pit + 1) < pars_.size();
831 for ( ; i < end; ++i, ++fi) {
832 int thiswidth = pm.singleWidth(i, *fi);
834 if (draw_par_end_marker && i == end - 1)
835 // enlarge the last character to hold the end-of-par marker
836 thiswidth += par_marker_width;
838 // add inline completion width
839 if (inlineCompletionLPos == i) {
840 docstring const & completion = bv_->inlineCompletion();
841 if (completion.length() > 0)
842 thiswidth += theFontMetrics(*fi).width(completion);
845 // add the auto-hfill from label end to the body
846 if (body_pos && i == body_pos) {
847 FontMetrics const & fm = theFontMetrics(
848 text_->labelFont(par));
849 int add = fm.width(layout.labelsep);
850 if (par.isLineSeparator(i - 1))
851 add -= singleWidth(pit, i - 1);
853 add = max(add, label_end - x);
858 chunkwidth += thiswidth;
860 // break before a character that will fall off
861 // the right of the row
863 // if no break before, break here
864 if (point == end || chunkwidth >= width - left) {
870 // exit on last registered breakpoint:
874 if (par.isNewline(i)) {
878 Inset const * inset = 0;
881 if ((inset = par.getInset(i + 1)) && inset->display()) {
886 if ((inset = par.getInset(i)) && inset->display()) {
892 inset = par.getInset(i);
893 if (!inset || inset->isChar()) {
894 // some insets are line separators too
895 if (par.isLineSeparator(i)) {
896 // register breakpoint:
903 // maybe found one, but the par is short enough.
904 if (i == end && x < width)
907 // manual labels cannot be broken in LaTeX. But we
908 // want to make our on-screen rendering of footnotes
910 if (body_pos && point < body_pos)
917 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
918 pos_type const first, pos_type const end) const
920 // get the pure distance
921 ParagraphMetrics const & pm = par_metrics_[pit];
922 Paragraph const & par = text_->getPar(pit);
923 int w = leftMargin(max_width_, pit, first);
924 int label_end = labelEnd(pit);
926 // check for possible inline completion
927 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
928 pos_type inlineCompletionLPos = -1;
929 if (inlineCompletionPos.inTexted()
930 && inlineCompletionPos.text() == text_
931 && inlineCompletionPos.pit() == pit) {
932 // draw logically behind the previous character
933 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
936 pos_type const body_pos = par.beginOfBody();
940 FontIterator fi = FontIterator(*this, par, pit, i);
941 for ( ; i < end; ++i, ++fi) {
942 if (body_pos > 0 && i == body_pos) {
943 FontMetrics const & fm = theFontMetrics(
944 text_->labelFont(par));
945 w += fm.width(par.layout().labelsep);
946 if (par.isLineSeparator(i - 1))
947 w -= singleWidth(pit, i - 1);
948 w = max(w, label_end);
951 // a line separator at the end of a line (but not at the end of a
952 // paragraph) will not be drawn and should therefore not count for
954 if (!par.isLineSeparator(i) || i != end - 1 || end == par.size())
955 w += pm.singleWidth(i, *fi);
957 // add inline completion width
958 if (inlineCompletionLPos == i) {
959 docstring const & completion = bv_->inlineCompletion();
960 if (completion.length() > 0)
961 w += theFontMetrics(*fi).width(completion);
966 // count the paragraph end marker.
967 if (end == par.size() && lyxrc.paragraph_markers) {
968 ParagraphList const & pars_ = text_->paragraphs();
969 if (size_type(pit + 1) < pars_.size()) {
970 // enlarge the last character to hold the
972 docstring const s(1, char_type(0x00B6));
974 w += theFontMetrics(f).width(s);
978 if (body_pos > 0 && body_pos >= end) {
979 FontMetrics const & fm = theFontMetrics(
980 text_->labelFont(par));
981 w += fm.width(par.layout().labelsep);
982 if (end > 0 && par.isLineSeparator(end - 1))
983 w -= singleWidth(pit, end - 1);
984 w = max(w, label_end);
987 return w + right_margin;
991 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
992 pos_type const end, bool topBottomSpace) const
994 Paragraph const & par = text_->getPar(pit);
995 // get the maximum ascent and the maximum descent
996 double layoutasc = 0;
997 double layoutdesc = 0;
998 double const dh = defaultRowHeight();
1000 // ok, let us initialize the maxasc and maxdesc value.
1001 // Only the fontsize count. The other properties
1002 // are taken from the layoutfont. Nicer on the screen :)
1003 Layout const & layout = par.layout();
1005 // as max get the first character of this row then it can
1006 // increase but not decrease the height. Just some point to
1007 // start with so we don't have to do the assignment below too
1009 Buffer const & buffer = bv_->buffer();
1010 Font font = displayFont(pit, first);
1011 FontSize const tmpsize = font.fontInfo().size();
1012 font.fontInfo() = text_->layoutFont(pit);
1013 FontSize const size = font.fontInfo().size();
1014 font.fontInfo().setSize(tmpsize);
1016 FontInfo labelfont = text_->labelFont(par);
1018 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1019 FontMetrics const & fontmetrics = theFontMetrics(font);
1021 // these are minimum values
1022 double const spacing_val = layout.spacing.getValue()
1023 * text_->spacing(par);
1024 //lyxerr << "spacing_val = " << spacing_val << endl;
1025 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
1026 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
1028 // insets may be taller
1029 ParagraphMetrics const & pm = par_metrics_[pit];
1030 InsetList::const_iterator ii = par.insetList().begin();
1031 InsetList::const_iterator iend = par.insetList().end();
1032 for ( ; ii != iend; ++ii) {
1033 if (ii->pos >= first && ii->pos < end) {
1034 Dimension const & dim = pm.insetDimension(ii->inset);
1035 maxasc = max(maxasc, dim.ascent());
1036 maxdesc = max(maxdesc, dim.descent());
1040 // Check if any custom fonts are larger (Asger)
1041 // This is not completely correct, but we can live with the small,
1042 // cosmetic error for now.
1046 par.highestFontInRange(first, end, size);
1047 if (maxsize > font.fontInfo().size()) {
1048 // use standard paragraph font with the maximal size
1049 FontInfo maxfont = font.fontInfo();
1050 maxfont.setSize(maxsize);
1051 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
1052 maxasc = max(maxasc, maxfontmetrics.maxAscent());
1053 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
1056 // This is nicer with box insets:
1060 ParagraphList const & pars = text_->paragraphs();
1061 Inset const & inset = text_->inset();
1063 // is it a top line?
1064 if (first == 0 && topBottomSpace) {
1065 BufferParams const & bufparams = buffer.params();
1066 // some parskips VERY EASY IMPLEMENTATION
1067 if (bufparams.paragraph_separation
1068 == BufferParams::ParagraphSkipSeparation
1069 && inset.lyxCode() != ERT_CODE
1070 && inset.lyxCode() != LISTINGS_CODE
1072 && ((layout.isParagraph() && par.getDepth() == 0)
1073 || (pars[pit - 1].layout().isParagraph()
1074 && pars[pit - 1].getDepth() == 0)))
1076 maxasc += bufparams.getDefSkip().inPixels(*bv_);
1079 if (par.params().startOfAppendix())
1080 maxasc += int(3 * dh);
1082 // This is special code for the chapter, since the label of this
1083 // layout is printed in an extra row
1084 if (layout.counter == "chapter"
1085 && !par.params().labelString().empty()) {
1086 labeladdon = int(labelfont_metrics.maxHeight()
1087 * layout.spacing.getValue()
1088 * text_->spacing(par));
1091 // special code for the top label
1092 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1093 || layout.labeltype == LABEL_BIBLIO
1094 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1095 && text_->isFirstInSequence(pit)
1096 && !par.labelString().empty())
1099 labelfont_metrics.maxHeight()
1100 * layout.spacing.getValue()
1101 * text_->spacing(par)
1102 + (layout.topsep + layout.labelbottomsep) * dh);
1105 // Add the layout spaces, for example before and after
1106 // a section, or between the items of a itemize or enumerate
1109 pit_type prev = text_->depthHook(pit, par.getDepth());
1110 Paragraph const & prevpar = pars[prev];
1112 && prevpar.layout() == layout
1113 && prevpar.getDepth() == par.getDepth()
1114 && prevpar.getLabelWidthString()
1115 == par.getLabelWidthString()) {
1116 layoutasc = layout.itemsep * dh;
1117 } else if (pit != 0 || first != 0) {
1118 if (layout.topsep > 0)
1119 layoutasc = layout.topsep * dh;
1122 prev = text_->outerHook(pit);
1123 if (prev != pit_type(pars.size())) {
1124 maxasc += int(pars[prev].layout().parsep * dh);
1125 } else if (pit != 0) {
1126 Paragraph const & prevpar = pars[pit - 1];
1127 if (prevpar.getDepth() != 0 ||
1128 prevpar.layout() == layout) {
1129 maxasc += int(layout.parsep * dh);
1134 // is it a bottom line?
1135 if (end >= par.size() && topBottomSpace) {
1136 // add the layout spaces, for example before and after
1137 // a section, or between the items of a itemize or enumerate
1139 pit_type nextpit = pit + 1;
1140 if (nextpit != pit_type(pars.size())) {
1141 pit_type cpit = pit;
1145 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1146 usual = pars[cpit].layout().bottomsep * dh;
1147 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1148 if (pars[cpit].layout() != pars[nextpit].layout()
1149 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1151 unusual = pars[cpit].layout().bottomsep * dh;
1153 layoutdesc = max(unusual, usual);
1154 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1155 if (pars[cpit].layout() != pars[nextpit].layout()
1156 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1157 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1162 // incalculate the layout spaces
1163 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1164 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1166 // FIXME: the correct way is to do the following is to move the
1167 // following code in another method specially tailored for the
1168 // main Text. The following test is thus bogus.
1169 // Top and bottom margin of the document (only at top-level)
1170 if (main_text_ && topBottomSpace) {
1171 if (pit == 0 && first == 0)
1173 if (pit + 1 == pit_type(pars.size()) &&
1174 end == par.size() &&
1175 !(end > 0 && par.isNewline(end - 1)))
1179 return Dimension(0, maxasc + labeladdon, maxdesc);
1183 // x is an absolute screen coord
1184 // returns the column near the specified x-coordinate of the row
1185 // x is set to the real beginning of this column
1186 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1187 Row const & row, int & x, bool & boundary) const
1189 Buffer const & buffer = bv_->buffer();
1191 /// For the main Text, it is possible that this pit is not
1192 /// yet in the CoordCache when moving cursor up.
1193 /// x Paragraph coordinate is always 0 for main text anyway.
1194 int const xo = origin_.x_;
1196 Paragraph const & par = text_->getPar(pit);
1198 bidi.computeTables(par, buffer, row);
1200 pos_type vc = row.pos();
1201 pos_type end = row.endpos();
1203 Layout const & layout = par.layout();
1205 bool left_side = false;
1207 pos_type body_pos = par.beginOfBody();
1209 double tmpx = row.x;
1210 double last_tmpx = tmpx;
1213 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1216 // check for empty row
1222 // if the first character is a separator, we are in RTL
1223 // text. This character will not be painted on screen
1224 // and thus we should not count it and skip to the next.
1225 if (par.isSeparator(bidi.vis2log(vc)))
1228 while (vc < end && tmpx <= x) {
1229 c = bidi.vis2log(vc);
1231 if (body_pos > 0 && c == body_pos - 1) {
1232 FontMetrics const & fm = theFontMetrics(
1233 text_->labelFont(par));
1234 tmpx += row.label_hfill + fm.width(layout.labelsep);
1235 if (par.isLineSeparator(body_pos - 1))
1236 tmpx -= singleWidth(pit, body_pos - 1);
1239 tmpx += singleWidth(pit, c);
1240 if (par.isSeparator(c) && c >= body_pos)
1241 tmpx += row.separator;
1245 if ((tmpx + last_tmpx) / 2 > x) {
1250 LASSERT(vc <= end, /**/); // This shouldn't happen.
1253 // This (rtl_support test) is not needed, but gives
1254 // some speedup if rtl_support == false
1255 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1257 // If lastrow is false, we don't need to compute
1258 // the value of rtl.
1259 bool const rtl = lastrow ? text_->isRTL(par) : false;
1261 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1262 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1263 if (!par.isNewline(end - 1))
1265 } else if (vc == row.pos()) {
1266 c = bidi.vis2log(vc);
1267 if (bidi.level(c) % 2 == 1)
1270 c = bidi.vis2log(vc - 1);
1271 bool const rtl = (bidi.level(c) % 2 == 1);
1272 if (left_side == rtl) {
1274 boundary = isRTLBoundary(pit, c);
1278 // I believe this code is not needed anymore (Jug 20050717)
1280 // The following code is necessary because the cursor position past
1281 // the last char in a row is logically equivalent to that before
1282 // the first char in the next row. That's why insets causing row
1283 // divisions -- Newline and display-style insets -- must be treated
1284 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1285 // Newline inset, air gap below:
1286 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1287 if (bidi.level(end -1) % 2 == 0)
1288 tmpx -= singleWidth(pit, end - 1);
1290 tmpx += singleWidth(pit, end - 1);
1294 // Air gap above display inset:
1295 if (row.pos() < end && c >= end && end < par.size()
1296 && par.isInset(end) && par.getInset(end)->display()) {
1299 // Air gap below display inset:
1300 if (row.pos() < end && c >= end && par.isInset(end - 1)
1301 && par.getInset(end - 1)->display()) {
1307 pos_type const col = c - row.pos();
1309 if (!c || end == par.size())
1312 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1317 return min(col, end - 1 - row.pos());
1321 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1323 // We play safe and use parMetrics(pit) to make sure the
1324 // ParagraphMetrics will be redone and OK to use if needed.
1325 // Otherwise we would use an empty ParagraphMetrics in
1326 // upDownInText() while in selection mode.
1327 ParagraphMetrics const & pm = parMetrics(pit);
1329 LASSERT(row < int(pm.rows().size()), /**/);
1331 Row const & r = pm.rows()[row];
1332 return r.pos() + getColumnNearX(pit, r, x, bound);
1336 void TextMetrics::newParMetricsDown()
1338 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1339 pit_type const pit = last.first + 1;
1340 if (pit == int(text_->paragraphs().size()))
1343 // do it and update its position.
1345 par_metrics_[pit].setPosition(last.second.position()
1346 + last.second.descent() + par_metrics_[pit].ascent());
1350 void TextMetrics::newParMetricsUp()
1352 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1353 if (first.first == 0)
1356 pit_type const pit = first.first - 1;
1357 // do it and update its position.
1359 par_metrics_[pit].setPosition(first.second.position()
1360 - first.second.ascent() - par_metrics_[pit].descent());
1363 // y is screen coordinate
1364 pit_type TextMetrics::getPitNearY(int y)
1366 LASSERT(!text_->paragraphs().empty(), return -1);
1367 LASSERT(!par_metrics_.empty(), return -1);
1368 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1370 // look for highest numbered paragraph with y coordinate less than given y
1373 ParMetricsCache::const_iterator it = par_metrics_.begin();
1374 ParMetricsCache::const_iterator et = par_metrics_.end();
1375 ParMetricsCache::const_iterator last = et; last--;
1377 ParagraphMetrics const & pm = it->second;
1379 if (y < it->second.position() - int(pm.ascent())) {
1380 // We are looking for a position that is before the first paragraph in
1381 // the cache (which is in priciple off-screen, that is before the
1384 // We are already at the first paragraph in the inset.
1386 // OK, this is the paragraph we are looking for.
1387 pit = it->first - 1;
1392 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1394 if (y >= last->second.position() + int(pm_last.descent())) {
1395 // We are looking for a position that is after the last paragraph in
1396 // the cache (which is in priciple off-screen), that is before the
1398 pit = last->first + 1;
1399 if (pit == int(text_->paragraphs().size()))
1400 // We are already at the last paragraph in the inset.
1402 // OK, this is the paragraph we are looking for.
1403 newParMetricsDown();
1407 for (; it != et; ++it) {
1408 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1409 << " y: " << it->second.position());
1411 ParagraphMetrics const & pm = par_metrics_[it->first];
1413 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1415 yy = it->second.position();
1419 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1425 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1426 bool assert_in_view, bool up)
1428 ParagraphMetrics const & pm = par_metrics_[pit];
1430 int yy = pm.position() - pm.ascent();
1431 LASSERT(!pm.rows().empty(), /**/);
1432 RowList::const_iterator rit = pm.rows().begin();
1433 RowList::const_iterator rlast = pm.rows().end();
1435 for (; rit != rlast; yy += rit->height(), ++rit)
1436 if (yy + rit->height() > y)
1439 if (assert_in_view) {
1440 if (!up && yy + rit->height() > y) {
1441 if (rit != pm.rows().begin()) {
1444 } else if (pit != 0) {
1447 ParagraphMetrics const & pm2 = par_metrics_[pit];
1448 rit = pm2.rows().end();
1452 } else if (up && yy != y) {
1454 y = yy + rit->height();
1456 } else if (pit < int(text_->paragraphs().size()) - 1) {
1458 newParMetricsDown();
1459 ParagraphMetrics const & pm2 = par_metrics_[pit];
1460 rit = pm2.rows().begin();
1469 // x,y are absolute screen coordinates
1470 // sets cursor recursively descending into nested editable insets
1471 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1472 bool assert_in_view, bool up)
1474 if (lyxerr.debugging(Debug::WORKAREA)) {
1475 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1476 cur.bv().coordCache().dump();
1478 pit_type pit = getPitNearY(y);
1479 LASSERT(pit != -1, return 0);
1481 int yy = y; // is modified by getPitAndRowNearY
1482 Row const & row = getPitAndRowNearY(yy, pit, assert_in_view, up);
1484 bool bound = false; // is modified by getColumnNearX
1485 int xx = x; // is modified by getColumnNearX
1486 pos_type const pos = row.pos()
1487 + getColumnNearX(pit, row, xx, bound);
1490 cur.boundary(bound);
1493 // try to descend into nested insets
1494 Inset * inset = checkInsetHit(x, yy);
1495 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1497 // Either we deconst editXY or better we move current_font
1498 // and real_current_font to Cursor
1499 // FIXME: what is needed now that current_font and real_current_font
1501 cur.setCurrentFont();
1505 ParagraphList const & pars = text_->paragraphs();
1506 Inset const * inset_before = pos ? pars[pit].getInset(pos - 1) : 0;
1508 // This should be just before or just behind the
1509 // cursor position set above.
1510 LASSERT(inset == inset_before
1511 || inset == pars[pit].getInset(pos), /**/);
1513 // Make sure the cursor points to the position before
1515 if (inset == inset_before) {
1517 cur.boundary(false);
1520 // Try to descend recursively inside the inset.
1521 inset = inset->editXY(cur, x, yy);
1523 if (cur.top().text() == text_)
1524 cur.setCurrentFont();
1529 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1531 LASSERT(text_ == cur.text(), /**/);
1532 pit_type pit = getPitNearY(y);
1533 LASSERT(pit != -1, return);
1535 ParagraphMetrics const & pm = par_metrics_[pit];
1537 int yy = pm.position() - pm.ascent();
1538 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1539 " pit: " << pit << " yy: " << yy);
1542 LASSERT(pm.rows().size(), /**/);
1543 for (; r < int(pm.rows().size()) - 1; ++r) {
1544 Row const & row = pm.rows()[r];
1545 if (int(yy + row.height()) > y)
1550 Row const & row = pm.rows()[r];
1552 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1556 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1558 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1560 text_->setCursor(cur, pit, pos, true, bound);
1561 // remember new position.
1566 //takes screen x,y coordinates
1567 Inset * TextMetrics::checkInsetHit(int x, int y)
1569 pit_type pit = getPitNearY(y);
1570 LASSERT(pit != -1, return 0);
1572 Paragraph const & par = text_->paragraphs()[pit];
1573 ParagraphMetrics const & pm = par_metrics_[pit];
1575 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1577 InsetList::const_iterator iit = par.insetList().begin();
1578 InsetList::const_iterator iend = par.insetList().end();
1579 for (; iit != iend; ++iit) {
1580 Inset * inset = iit->inset;
1582 LYXERR(Debug::DEBUG, "examining inset " << inset);
1584 if (!bv_->coordCache().getInsets().has(inset)) {
1585 LYXERR(Debug::DEBUG, "inset has no cached position");
1589 Dimension const & dim = pm.insetDimension(inset);
1590 Point p = bv_->coordCache().getInsets().xy(inset);
1592 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1593 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1596 && x <= p.x_ + dim.wid
1597 && y >= p.y_ - dim.asc
1598 && y <= p.y_ + dim.des) {
1599 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1604 LYXERR(Debug::DEBUG, "No inset hit. ");
1609 int TextMetrics::cursorX(CursorSlice const & sl,
1610 bool boundary) const
1612 LASSERT(sl.text() == text_, /**/);
1613 pit_type const pit = sl.pit();
1614 Paragraph const & par = text_->paragraphs()[pit];
1615 ParagraphMetrics const & pm = par_metrics_[pit];
1616 if (pm.rows().empty())
1619 pos_type ppos = sl.pos();
1620 // Correct position in front of big insets
1621 bool const boundary_correction = ppos != 0 && boundary;
1622 if (boundary_correction)
1625 Row const & row = pm.getRow(sl.pos(), boundary);
1627 pos_type cursor_vpos = 0;
1629 Buffer const & buffer = bv_->buffer();
1632 bidi.computeTables(par, buffer, row);
1634 pos_type const row_pos = row.pos();
1635 pos_type const end = row.endpos();
1636 // Spaces at logical line breaks in bidi text must be skipped during
1637 // cursor positioning. However, they may appear visually in the middle
1638 // of a row; they must be skipped, wherever they are...
1639 // * logically "abc_[HEBREW_\nHEBREW]"
1640 // * visually "abc_[_WERBEH\nWERBEH]"
1641 pos_type skipped_sep_vpos = -1;
1644 cursor_vpos = row_pos;
1645 else if (ppos >= end)
1646 cursor_vpos = text_->isRTL(par) ? row_pos : end;
1647 else if (ppos > row_pos && ppos >= end)
1648 //FIXME: this code is never reached!
1649 // (see http://www.lyx.org/trac/changeset/8251)
1650 // Place cursor after char at (logical) position pos - 1
1651 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1652 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1654 // Place cursor before char at (logical) position ppos
1655 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1656 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1658 pos_type body_pos = par.beginOfBody();
1660 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1663 // check for possible inline completion in this row
1664 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1665 pos_type inlineCompletionVPos = -1;
1666 if (inlineCompletionPos.inTexted()
1667 && inlineCompletionPos.text() == text_
1668 && inlineCompletionPos.pit() == pit
1669 && inlineCompletionPos.pos() - 1 >= row_pos
1670 && inlineCompletionPos.pos() - 1 < end) {
1671 // draw logically behind the previous character
1672 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1675 // Use font span to speed things up, see below
1679 // If the last logical character is a separator, skip it, unless
1680 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1681 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1682 skipped_sep_vpos = bidi.log2vis(end - 1);
1684 if (lyxrc.paragraph_markers && text_->isRTL(par)) {
1685 ParagraphList const & pars_ = text_->paragraphs();
1686 if (size_type(pit + 1) < pars_.size()) {
1688 docstring const s = docstring(1, char_type(0x00B6));
1689 x += theFontMetrics(f).width(s);
1693 // Inline completion RTL special case row_pos == cursor_pos:
1694 // "__|b" => cursor_pos is right of __
1695 if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1696 font = displayFont(pit, row_pos + 1);
1697 docstring const & completion = bv_->inlineCompletion();
1698 if (font.isRightToLeft() && completion.length() > 0)
1699 x += theFontMetrics(font.fontInfo()).width(completion);
1702 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1703 // Skip the separator which is at the logical end of the row
1704 if (vpos == skipped_sep_vpos)
1706 pos_type pos = bidi.vis2log(vpos);
1707 if (body_pos > 0 && pos == body_pos - 1) {
1708 FontMetrics const & labelfm = theFontMetrics(
1709 text_->labelFont(par));
1710 x += row.label_hfill + labelfm.width(par.layout().labelsep);
1711 if (par.isLineSeparator(body_pos - 1))
1712 x -= singleWidth(pit, body_pos - 1);
1715 // Use font span to speed things up, see above
1716 if (pos < font_span.first || pos > font_span.last) {
1717 font_span = par.fontSpan(pos);
1718 font = displayFont(pit, pos);
1721 x += pm.singleWidth(pos, font);
1723 // Inline completion RTL case:
1724 // "a__|b", __ of b => non-boundary a-pos is right of __
1725 if (vpos + 1 == inlineCompletionVPos
1726 && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1727 font = displayFont(pit, vpos + 1);
1728 docstring const & completion = bv_->inlineCompletion();
1729 if (font.isRightToLeft() && completion.length() > 0)
1730 x += theFontMetrics(font.fontInfo()).width(completion);
1733 // Inline completion LTR case:
1734 // "b|__a", __ of b => non-boundary a-pos is in front of __
1735 if (vpos == inlineCompletionVPos
1736 && (vpos + 1 < cursor_vpos || boundary_correction)) {
1737 font = displayFont(pit, vpos);
1738 docstring const & completion = bv_->inlineCompletion();
1739 if (!font.isRightToLeft() && completion.length() > 0)
1740 x += theFontMetrics(font.fontInfo()).width(completion);
1743 if (par.isSeparator(pos) && pos >= body_pos)
1747 // see correction above
1748 if (boundary_correction) {
1749 if (isRTL(sl, boundary))
1750 x -= singleWidth(pit, ppos);
1752 x += singleWidth(pit, ppos);
1759 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1761 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1762 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1763 if (pm.rows().empty())
1767 h -= par_metrics_[0].rows()[0].ascent();
1768 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1769 h += par_metrics_[pit].height();
1772 if (pos && boundary)
1774 size_t const rend = pm.pos2row(pos);
1775 for (size_t rit = 0; rit != rend; ++rit)
1776 h += pm.rows()[rit].height();
1777 h += pm.rows()[rend].ascent();
1782 // the cursor set functions have a special mechanism. When they
1783 // realize you left an empty paragraph, they will delete it.
1785 bool TextMetrics::cursorHome(Cursor & cur)
1787 LASSERT(text_ == cur.text(), /**/);
1788 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1789 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1790 return text_->setCursor(cur, cur.pit(), row.pos());
1794 bool TextMetrics::cursorEnd(Cursor & cur)
1796 LASSERT(text_ == cur.text(), /**/);
1797 // if not on the last row of the par, put the cursor before
1798 // the final space exept if I have a spanning inset or one string
1799 // is so long that we force a break.
1800 pos_type end = cur.textRow().endpos();
1802 // empty text, end-1 is no valid position
1804 bool boundary = false;
1805 if (end != cur.lastpos()) {
1806 if (!cur.paragraph().isLineSeparator(end-1)
1807 && !cur.paragraph().isNewline(end-1))
1812 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1816 void TextMetrics::deleteLineForward(Cursor & cur)
1818 LASSERT(text_ == cur.text(), /**/);
1819 if (cur.lastpos() == 0) {
1820 // Paragraph is empty, so we just go forward
1821 text_->cursorForward(cur);
1824 cur.setSelection(true); // to avoid deletion
1827 // What is this test for ??? (JMarc)
1828 if (!cur.selection())
1829 text_->deleteWordForward(cur);
1831 cap::cutSelection(cur, true, false);
1832 cur.checkBufferStructure();
1837 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1839 ParagraphList const & pars = text_->paragraphs();
1840 return row.endpos() >= pars[pit].size()
1841 && pit + 1 == pit_type(pars.size());
1845 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1847 return row.pos() == 0 && pit == 0;
1851 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1853 LASSERT(pit >= 0, /**/);
1854 LASSERT(pit < int(text_->paragraphs().size()), /**/);
1855 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1859 int TextMetrics::leftMargin(int max_width,
1860 pit_type const pit, pos_type const pos) const
1862 ParagraphList const & pars = text_->paragraphs();
1864 LASSERT(pit >= 0, /**/);
1865 LASSERT(pit < int(pars.size()), /**/);
1866 Paragraph const & par = pars[pit];
1867 LASSERT(pos >= 0, /**/);
1868 LASSERT(pos <= par.size(), /**/);
1869 Buffer const & buffer = bv_->buffer();
1870 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1871 DocumentClass const & tclass = buffer.params().documentClass();
1872 Layout const & layout = par.layout();
1874 docstring parindent = layout.parindent;
1878 if (text_->isMainText())
1879 l_margin += bv_->leftMargin();
1881 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1882 tclass.leftmargin());
1884 if (par.getDepth() != 0) {
1885 // find the next level paragraph
1886 pit_type newpar = text_->outerHook(pit);
1887 if (newpar != pit_type(pars.size())) {
1888 if (pars[newpar].layout().isEnvironment()) {
1889 l_margin = leftMargin(max_width, newpar);
1891 if (tclass.isDefaultLayout(par.layout())
1892 || tclass.isPlainLayout(par.layout())) {
1893 if (pars[newpar].params().noindent())
1896 parindent = pars[newpar].layout().parindent;
1901 // This happens after sections in standard classes. The 1.3.x
1902 // code compared depths too, but it does not seem necessary
1904 if (tclass.isDefaultLayout(par.layout())
1905 && pit > 0 && pars[pit - 1].layout().nextnoindent)
1908 FontInfo const labelfont = text_->labelFont(par);
1909 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1911 switch (layout.margintype) {
1912 case MARGIN_DYNAMIC:
1913 if (!layout.leftmargin.empty()) {
1914 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1917 if (!par.labelString().empty()) {
1918 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1919 l_margin += labelfont_metrics.width(par.labelString());
1920 l_margin += labelfont_metrics.width(layout.labelsep);
1924 case MARGIN_MANUAL: {
1925 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1926 // The width of an empty par, even with manual label, should be 0
1927 if (!par.empty() && pos >= par.beginOfBody()) {
1928 if (!par.getLabelWidthString().empty()) {
1929 docstring labstr = par.getLabelWidthString();
1930 l_margin += labelfont_metrics.width(labstr);
1931 l_margin += labelfont_metrics.width(layout.labelsep);
1937 case MARGIN_STATIC: {
1938 l_margin += theFontMetrics(buffer.params().getFont()).
1939 signedWidth(layout.leftmargin) * 4 / (par.getDepth() + 4);
1943 case MARGIN_FIRST_DYNAMIC:
1944 if (layout.labeltype == LABEL_MANUAL) {
1945 // if we are at position 0, we are never in the body
1946 if (pos > 0 && pos >= par.beginOfBody())
1947 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1949 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1951 // Special case to fix problems with
1953 || (layout.labeltype == LABEL_STATIC
1954 && layout.latextype == LATEX_ENVIRONMENT
1955 && !text_->isFirstInSequence(pit))) {
1956 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1957 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
1958 && layout.labeltype != LABEL_BIBLIO
1959 && layout.labeltype !=
1960 LABEL_CENTERED_TOP_ENVIRONMENT) {
1961 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1962 l_margin += labelfont_metrics.width(layout.labelsep);
1963 l_margin += labelfont_metrics.width(par.labelString());
1967 case MARGIN_RIGHT_ADDRESS_BOX: {
1969 // ok, a terrible hack. The left margin depends on the widest
1970 // row in this paragraph.
1971 RowList::iterator rit = par.rows().begin();
1972 RowList::iterator end = par.rows().end();
1973 // FIXME: This is wrong.
1974 int minfill = max_width;
1975 for ( ; rit != end; ++rit)
1976 if (rit->fill() < minfill)
1977 minfill = rit->fill();
1978 l_margin += theFontMetrics(params.getFont()).signedWidth(layout.leftmargin);
1979 l_margin += minfill;
1981 // also wrong, but much shorter.
1982 l_margin += max_width / 2;
1987 if (!par.params().leftIndent().zero())
1988 l_margin += par.params().leftIndent().inPixels(max_width);
1992 if (par.params().align() == LYX_ALIGN_LAYOUT)
1993 align = layout.align;
1995 align = par.params().align();
1997 // set the correct parindent
1999 && (layout.labeltype == LABEL_NO_LABEL
2000 || layout.labeltype == LABEL_TOP_ENVIRONMENT
2001 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
2002 || (layout.labeltype == LABEL_STATIC
2003 && layout.latextype == LATEX_ENVIRONMENT
2004 && !text_->isFirstInSequence(pit)))
2005 && align == LYX_ALIGN_BLOCK
2006 && !par.params().noindent()
2007 // in some insets, paragraphs are never indented
2008 && !text_->inset().neverIndent()
2009 // display style insets are always centered, omit indentation
2012 && par.getInset(pos)->display())
2013 && (!(tclass.isDefaultLayout(par.layout())
2014 || tclass.isPlainLayout(par.layout()))
2015 || buffer.params().paragraph_separation
2016 == BufferParams::ParagraphIndentSeparation)
2019 // use the parindent of the layout when the default indentation is
2020 // used otherwise use the indentation set in the document settings
2021 if (buffer.params().getIndentation().asLyXCommand() == "default")
2022 l_margin += theFontMetrics(
2023 buffer.params().getFont()).signedWidth(parindent);
2025 l_margin += buffer.params().getIndentation().inPixels(*bv_);
2032 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
2034 ParagraphMetrics const & pm = par_metrics_[pit];
2036 return pm.singleWidth(pos, displayFont(pit, pos));
2040 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
2042 if (par_metrics_.empty())
2048 ParMetricsCache::iterator it = par_metrics_.begin();
2049 ParMetricsCache::iterator const pm_end = par_metrics_.end();
2050 y -= it->second.ascent();
2051 for (; it != pm_end; ++it) {
2052 ParagraphMetrics const & pmi = it->second;
2054 pit_type const pit = it->first;
2055 // Save the paragraph position in the cache.
2056 it->second.setPosition(y);
2057 drawParagraph(pi, pit, x, y);
2063 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
2065 BufferParams const & bparams = bv_->buffer().params();
2066 ParagraphMetrics const & pm = par_metrics_[pit];
2067 if (pm.rows().empty())
2071 bool const original_drawing_state = pi.pain.isDrawingEnabled();
2072 int const ww = bv_->workHeight();
2073 size_t const nrows = pm.rows().size();
2075 Cursor const & cur = bv_->cursor();
2076 DocIterator sel_beg = cur.selectionBegin();
2077 DocIterator sel_end = cur.selectionEnd();
2078 bool selection = cur.selection()
2079 // This is our text.
2080 && cur.text() == text_
2081 // if the anchor is outside, this is not our selection
2082 && cur.normalAnchor().text() == text_
2083 && pit >= sel_beg.pit() && pit <= sel_end.pit();
2085 // We store the begin and end pos of the selection relative to this par
2086 DocIterator sel_beg_par = cur.selectionBegin();
2087 DocIterator sel_end_par = cur.selectionEnd();
2089 // We care only about visible selection.
2091 if (pit != sel_beg.pit()) {
2092 sel_beg_par.pit() = pit;
2093 sel_beg_par.pos() = 0;
2095 if (pit != sel_end.pit()) {
2096 sel_end_par.pit() = pit;
2097 sel_end_par.pos() = sel_end_par.lastpos();
2101 for (size_t i = 0; i != nrows; ++i) {
2103 Row const & row = pm.rows()[i];
2107 bool const inside = (y + row.descent() >= 0
2108 && y - row.ascent() < ww);
2109 // It is not needed to draw on screen if we are not inside.
2110 pi.pain.setDrawingEnabled(inside && original_drawing_state);
2111 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
2114 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2116 row.setSelection(-1, -1);
2118 // The row knows nothing about the paragraph, so we have to check
2119 // whether this row is the first or last and update the margins.
2120 if (row.selection()) {
2121 if (row.sel_beg == 0)
2122 row.begin_margin_sel = sel_beg.pit() < pit;
2123 if (row.sel_end == sel_end_par.lastpos())
2124 row.end_margin_sel = sel_end.pit() > pit;
2127 // Row signature; has row changed since last paint?
2128 row.setCrc(pm.computeRowSignature(row, bparams));
2129 bool row_has_changed = row.changed();
2131 // Take this opportunity to spellcheck the row contents.
2132 if (row_has_changed && lyxrc.spellcheck_continuously) {
2134 // dummy variable, not used.
2135 static docstring_list suggestions;
2136 pos_type from = row.pos();
2137 pos_type to = row.endpos();
2138 while (from < row.endpos()) {
2139 text_->getPar(pit).spellCheck(from, to, wl, suggestions, false);
2144 // Don't paint the row if a full repaint has not been requested
2145 // and if it has not changed.
2146 if (!pi.full_repaint && !row_has_changed) {
2147 // Paint only the insets if the text itself is
2149 rp.paintOnlyInsets();
2154 // Clear background of this row if paragraph background was not
2155 // already cleared because of a full repaint.
2156 if (!pi.full_repaint && row_has_changed) {
2157 pi.pain.fillRectangle(x, y - row.ascent(),
2158 width(), row.height(), pi.background_color);
2161 if (row.selection())
2162 drawRowSelection(pi, x, row, cur, pit);
2164 // Instrumentation for testing row cache (see also
2166 if (lyxerr.debugging(Debug::PAINTING) && inside
2167 && (row.selection() || pi.full_repaint || row_has_changed)) {
2168 string const foreword = text_->isMainText() ?
2169 "main text redraw " : "inset text redraw: ";
2170 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
2171 << " row_selection=" << row.selection()
2172 << " full_repaint=" << pi.full_repaint
2173 << " row_has_changed=" << row_has_changed);
2176 // Backup full_repaint status and force full repaint
2177 // for inner insets as the Row has been cleared out.
2178 bool tmp = pi.full_repaint;
2179 pi.full_repaint = true;
2182 rp.paintChangeBar();
2183 bool const is_rtl = text_->isRTL(text_->getPar(pit));
2184 if (i == 0 && !is_rtl)
2186 if (i == nrows - 1 && is_rtl)
2189 if (i == nrows - 1 && !is_rtl)
2191 if (i == 0 && is_rtl)
2194 // Restore full_repaint status.
2195 pi.full_repaint = tmp;
2197 // Re-enable screen drawing for future use of the painter.
2198 pi.pain.setDrawingEnabled(original_drawing_state);
2200 //LYXERR(Debug::PAINTING, ".");
2204 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2205 Cursor const & curs, pit_type pit) const
2207 DocIterator beg = curs.selectionBegin();
2209 beg.pos() = row.sel_beg;
2211 DocIterator end = curs.selectionEnd();
2213 end.pos() = row.sel_end;
2215 bool const begin_boundary = beg.pos() >= row.endpos();
2216 bool const end_boundary = row.sel_end == row.endpos();
2218 DocIterator cur = beg;
2219 cur.boundary(begin_boundary);
2220 int x1 = cursorX(beg.top(), begin_boundary);
2221 int x2 = cursorX(end.top(), end_boundary);
2222 int const y1 = bv_->getPos(cur).y_ - row.ascent();
2223 int const y2 = y1 + row.height();
2225 int const rm = text_->isMainText() ? bv_->rightMargin() : 0;
2226 int const lm = text_->isMainText() ? bv_->leftMargin() : 0;
2229 if (row.begin_margin_sel) {
2230 if (text_->isRTL(beg.paragraph())) {
2231 pi.pain.fillRectangle(x + x1, y1, width() - rm - x1, y2 - y1,
2234 pi.pain.fillRectangle(x + lm, y1, x1 - lm, y2 - y1,
2239 if (row.end_margin_sel) {
2240 if (text_->isRTL(beg.paragraph())) {
2241 pi.pain.fillRectangle(x + lm, y1, x2 - lm, y2 - y1,
2244 pi.pain.fillRectangle(x + x2, y1, width() - rm - x2, y2 - y1,
2249 // if we are on a boundary from the beginning, it's probably
2250 // a RTL boundary and we jump to the other side directly as this
2251 // segement is 0-size and confuses the logic below
2253 cur.boundary(false);
2255 // go through row and draw from RTL boundary to RTL boundary
2257 bool draw_now = false;
2259 // simplified cursorForward code below which does not
2260 // descend into insets and which does not go into the
2261 // next line. Compare the logic with the original cursorForward
2263 // if left of boundary -> just jump to right side, but
2264 // for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2265 if (cur.boundary()) {
2266 cur.boundary(false);
2267 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2268 // in front of RTL boundary -> Stay on this side of the boundary
2269 // because: ab|cDDEEFFghi -> abc|DDEEFFghi
2278 if (cur.pos() == row.endpos())
2283 // the previous segment was just drawn, now the next starts
2284 x1 = cursorX(cur.top(), cur.boundary());
2287 if (!(cur < end) || draw_now) {
2288 x2 = cursorX(cur.top(), cur.boundary());
2289 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2292 // reset x1, so it is set again next round (which will be on the
2293 // right side of a boundary or at the selection end)
2300 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2301 Dimension & dim) const
2303 Cursor const & bvcur = cur.bv().cursor();
2305 // get word in front of cursor
2306 docstring word = text_->previousWord(bvcur.top());
2307 DocIterator wordStart = bvcur;
2308 wordStart.pos() -= word.length();
2310 // get position on screen of the word start and end
2311 //FIXME: Is it necessary to explicitly set this to false?
2312 wordStart.boundary(false);
2313 Point lxy = cur.bv().getPos(wordStart);
2314 Point rxy = cur.bv().getPos(bvcur);
2316 // calculate dimensions of the word
2317 dim = rowHeight(bvcur.pit(), wordStart.pos(), bvcur.pos(), false);
2318 dim.wid = abs(rxy.x_ - lxy.x_);
2320 // calculate position of word
2322 x = min(rxy.x_, lxy.x_);
2324 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2325 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2328 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2330 // ParagraphMetrics const & pm = par_metrics_[pit];
2331 // Row const & r = pm.rows()[row];
2337 int defaultRowHeight()
2339 return int(theFontMetrics(sane_font).maxHeight() * 1.2);