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"
31 #include "InsetList.h"
35 #include "MetricsInfo.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "rowpainter.h"
40 #include "TextClass.h"
42 #include "WordLangTuple.h"
44 #include "insets/InsetText.h"
46 #include "mathed/MacroTable.h"
47 #include "mathed/MathMacroTemplate.h"
49 #include "frontends/FontMetrics.h"
50 #include "frontends/Painter.h"
52 #include "support/debug.h"
53 #include "support/docstring_list.h"
54 #include "support/lassert.h"
63 using frontend::FontMetrics;
65 static int numberOfSeparators(Paragraph const & par, Row const & row)
67 pos_type const first = max(row.pos(), par.beginOfBody());
68 pos_type const last = row.endpos() - 1;
70 for (pos_type p = first; p < last; ++p) {
71 if (par.isSeparator(p))
78 static int numberOfLabelHfills(Paragraph const & par, Row const & row)
80 pos_type last = row.endpos() - 1;
81 pos_type first = row.pos();
83 // hfill *DO* count at the beginning of paragraphs!
85 while (first < last && par.isHfill(first))
89 last = min(last, par.beginOfBody());
91 for (pos_type p = first; p < last; ++p) {
99 static int numberOfHfills(Paragraph const & par, Row const & row)
101 pos_type const last = row.endpos();
102 pos_type first = row.pos();
104 // hfill *DO* count at the beginning of paragraphs!
106 while (first < last && par.isHfill(first))
110 first = max(first, par.beginOfBody());
113 for (pos_type p = first; p < last; ++p) {
121 /////////////////////////////////////////////////////////////////////
125 /////////////////////////////////////////////////////////////////////
128 TextMetrics::TextMetrics(BufferView * bv, Text * text)
129 : bv_(bv), text_(text)
132 max_width_ = bv_->workWidth();
133 dim_.wid = max_width_;
139 bool TextMetrics::contains(pit_type pit) const
141 return par_metrics_.find(pit) != par_metrics_.end();
145 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
147 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
152 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
154 ParMetricsCache::const_iterator it = par_metrics_.begin();
155 return make_pair(it->first, &it->second);
159 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
161 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
162 return make_pair(it->first, &it->second);
166 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
168 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
169 if (pmc_it == par_metrics_.end()) {
170 pmc_it = par_metrics_.insert(
171 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
173 if (pmc_it->second.rows().empty() && redo)
175 return pmc_it->second;
179 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
181 LASSERT(mi.base.textwidth > 0, /**/);
182 max_width_ = mi.base.textwidth;
183 // backup old dimension.
184 Dimension const old_dim = dim_;
187 dim_.wid = min_width;
188 pit_type const npar = text_->paragraphs().size();
190 // If there is more than one row, expand the text to
191 // the full allowable width.
192 dim_.wid = max_width_;
194 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
195 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
197 bool changed = false;
199 for (pit_type pit = 0; pit != npar; ++pit) {
200 changed |= redoParagraph(pit);
201 ParagraphMetrics const & pm = par_metrics_[pit];
203 if (dim_.wid < pm.width())
204 dim_.wid = pm.width();
207 dim_.asc = par_metrics_[0].ascent();
208 dim_.des = h - dim_.asc;
209 //lyxerr << "dim_.wid " << dim_.wid << endl;
210 //lyxerr << "dim_.asc " << dim_.asc << endl;
211 //lyxerr << "dim_.des " << dim_.des << endl;
213 changed |= dim_ != old_dim;
219 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
221 return main_text_? pm.rightMargin(*bv_) : 0;
225 int TextMetrics::rightMargin(pit_type const pit) const
227 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
231 void TextMetrics::applyOuterFont(Font & font) const
233 FontInfo lf(font_.fontInfo());
234 lf.reduce(bv_->buffer().params().getFont().fontInfo());
235 font.fontInfo().realize(lf);
239 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
241 LASSERT(pos >= 0, /**/);
243 ParagraphList const & pars = text_->paragraphs();
244 Paragraph const & par = pars[pit];
245 Layout const & layout = par.layout();
246 Buffer const & buffer = bv_->buffer();
248 BufferParams const & params = buffer.params();
249 pos_type const body_pos = par.beginOfBody();
251 // We specialize the 95% common case:
252 if (!par.getDepth()) {
253 Font f = par.getFontSettings(params, pos);
254 if (!text_->isMainText())
256 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
258 FontInfo const & lf = lab ? layout.labelfont : layout.font;
259 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
261 // In case the default family has been customized
262 if (lf.family() == INHERIT_FAMILY)
263 rlf.setFamily(params.getFont().fontInfo().family());
264 f.fontInfo().realize(rlf);
268 // The uncommon case need not be optimized as much
269 FontInfo const & layoutfont = pos < body_pos ?
270 layout.labelfont : layout.font;
272 Font font = par.getFontSettings(params, pos);
273 font.fontInfo().realize(layoutfont);
275 if (!text_->isMainText())
276 applyOuterFont(font);
278 // Realize against environment font information
279 // NOTE: the cast to pit_type should be removed when pit_type
280 // changes to a unsigned integer.
281 if (pit < pit_type(pars.size()))
282 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
284 // Realize with the fonts of lesser depth.
285 font.fontInfo().realize(params.getFont().fontInfo());
291 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
293 if (!lyxrc.rtl_support || !sl.text())
297 if (boundary && sl.pos() > 0)
300 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
304 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
306 // no RTL boundary at paragraph start
307 if (!lyxrc.rtl_support || pos == 0)
310 Font const & left_font = displayFont(pit, pos - 1);
312 return isRTLBoundary(pit, pos, left_font);
316 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
317 Font const & font) const
319 if (!lyxrc.rtl_support
320 // no RTL boundary at paragraph start
322 // if the metrics have not been calculated, then we are not
323 // on screen and can safely ignore issues about boundaries.
327 ParagraphMetrics & pm = par_metrics_[pit];
328 // no RTL boundary in empty paragraph
329 if (pm.rows().empty())
332 pos_type endpos = pm.getRow(pos - 1, false).endpos();
333 pos_type startpos = pm.getRow(pos, false).pos();
334 // no RTL boundary at line start:
335 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
337 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
340 Paragraph const & par = text_->getPar(pit);
341 // no RTL boundary at line break:
342 // abc|\n -> move right -> abc\n (and not: abc\n|
344 if (startpos == pos && endpos == pos && endpos != par.size()
345 && (par.isNewline(pos - 1)
346 || par.isLineSeparator(pos - 1)
347 || par.isSeparator(pos - 1)))
350 bool left = font.isVisibleRightToLeft();
352 if (pos == par.size())
353 right = par.isRTL(bv_->buffer().params());
355 right = displayFont(pit, pos).isVisibleRightToLeft();
357 return left != right;
361 bool TextMetrics::redoParagraph(pit_type const pit)
363 Paragraph & par = text_->getPar(pit);
364 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
365 // redoParagraph() recursively inside parMetrics.
366 Dimension old_dim = parMetrics(pit, false).dim();
367 ParagraphMetrics & pm = par_metrics_[pit];
370 Buffer & buffer = bv_->buffer();
371 main_text_ = (text_ == &buffer.text());
372 bool changed = false;
374 // FIXME: This check ought to be done somewhere else. It is the reason
375 // why text_ is not const. But then, where else to do it?
376 // Well, how can you end up with either (a) a biblio environment that
377 // has no InsetBibitem or (b) a biblio environment with more than one
378 // InsetBibitem? I think the answer is: when paragraphs are merged;
379 // when layout is set; when material is pasted.
380 int const moveCursor = par.checkBiblio(buffer);
382 const_cast<Cursor &>(bv_->cursor()).posForward();
383 else if (moveCursor < 0) {
384 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
385 if (cursor.pos() >= -moveCursor)
386 cursor.posBackward();
389 // Optimisation: this is used in the next two loops
390 // so better to calculate that once here.
391 int const right_margin = rightMargin(pm);
393 // iterator pointing to paragraph to resolve macros
394 DocIterator parPos = text_->macrocontextPosition();
398 LYXERR(Debug::INFO, "MacroContext not initialised!"
399 << " Going through the buffer again and hope"
400 << " the context is better then.");
401 // FIXME audit updateBuffer calls
402 // This should not be here, but it is not clear yet where else it
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 ParagraphList const & pars = text_->paragraphs();
1057 Inset const & inset = text_->inset();
1059 // is it a top line?
1060 if (first == 0 && topBottomSpace) {
1061 BufferParams const & bufparams = buffer.params();
1062 // some parskips VERY EASY IMPLEMENTATION
1063 if (bufparams.paragraph_separation
1064 == BufferParams::ParagraphSkipSeparation
1065 && inset.lyxCode() != ERT_CODE
1066 && inset.lyxCode() != LISTINGS_CODE
1068 && ((layout.isParagraph() && par.getDepth() == 0)
1069 || (pars[pit - 1].layout().isParagraph()
1070 && pars[pit - 1].getDepth() == 0)))
1072 maxasc += bufparams.getDefSkip().inPixels(*bv_);
1075 if (par.params().startOfAppendix())
1076 maxasc += int(3 * dh);
1078 // This is special code for the chapter, since the label of this
1079 // layout is printed in an extra row
1080 if (layout.counter == "chapter"
1081 && !par.params().labelString().empty()) {
1082 labeladdon = int(labelfont_metrics.maxHeight()
1083 * layout.spacing.getValue()
1084 * text_->spacing(par));
1087 // special code for the top label
1088 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1089 || layout.labeltype == LABEL_BIBLIO
1090 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1091 && text_->isFirstInSequence(pit)
1092 && !par.labelString().empty())
1095 labelfont_metrics.maxHeight()
1096 * layout.spacing.getValue()
1097 * text_->spacing(par)
1098 + (layout.topsep + layout.labelbottomsep) * dh);
1101 // Add the layout spaces, for example before and after
1102 // a section, or between the items of a itemize or enumerate
1105 pit_type prev = text_->depthHook(pit, par.getDepth());
1106 Paragraph const & prevpar = pars[prev];
1108 && prevpar.layout() == layout
1109 && prevpar.getDepth() == par.getDepth()
1110 && prevpar.getLabelWidthString()
1111 == par.getLabelWidthString()) {
1112 layoutasc = layout.itemsep * dh;
1113 } else if (pit != 0 || first != 0) {
1114 if (layout.topsep > 0)
1115 layoutasc = layout.topsep * dh;
1118 prev = text_->outerHook(pit);
1119 if (prev != pit_type(pars.size())) {
1120 maxasc += int(pars[prev].layout().parsep * dh);
1121 } else if (pit != 0) {
1122 Paragraph const & prevpar = pars[pit - 1];
1123 if (prevpar.getDepth() != 0 ||
1124 prevpar.layout() == layout) {
1125 maxasc += int(layout.parsep * dh);
1130 // is it a bottom line?
1131 if (end >= par.size() && topBottomSpace) {
1132 // add the layout spaces, for example before and after
1133 // a section, or between the items of a itemize or enumerate
1135 pit_type nextpit = pit + 1;
1136 if (nextpit != pit_type(pars.size())) {
1137 pit_type cpit = pit;
1141 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1142 usual = pars[cpit].layout().bottomsep * dh;
1143 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1144 if (pars[cpit].layout() != pars[nextpit].layout()
1145 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1147 unusual = pars[cpit].layout().bottomsep * dh;
1149 layoutdesc = max(unusual, usual);
1150 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1151 if (pars[cpit].layout() != pars[nextpit].layout()
1152 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1153 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1158 // incalculate the layout spaces
1159 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1160 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1162 // FIXME: the correct way is to do the following is to move the
1163 // following code in another method specially tailored for the
1164 // main Text. The following test is thus bogus.
1165 // Top and bottom margin of the document (only at top-level)
1166 if (main_text_ && topBottomSpace) {
1167 if (pit == 0 && first == 0)
1169 if (pit + 1 == pit_type(pars.size()) &&
1170 end == par.size() &&
1171 !(end > 0 && par.isNewline(end - 1)))
1175 return Dimension(0, maxasc + labeladdon, maxdesc);
1179 // x is an absolute screen coord
1180 // returns the column near the specified x-coordinate of the row
1181 // x is set to the real beginning of this column
1182 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1183 Row const & row, int & x, bool & boundary) const
1185 Buffer const & buffer = bv_->buffer();
1187 /// For the main Text, it is possible that this pit is not
1188 /// yet in the CoordCache when moving cursor up.
1189 /// x Paragraph coordinate is always 0 for main text anyway.
1190 int const xo = origin_.x_;
1192 Paragraph const & par = text_->getPar(pit);
1194 bidi.computeTables(par, buffer, row);
1196 pos_type vc = row.pos();
1197 pos_type end = row.endpos();
1199 Layout const & layout = par.layout();
1201 bool left_side = false;
1203 pos_type body_pos = par.beginOfBody();
1205 double tmpx = row.x;
1206 double last_tmpx = tmpx;
1209 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1212 // check for empty row
1218 // This (rtl_support test) is not needed, but gives
1219 // some speedup if rtl_support == false
1220 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1222 // If lastrow is false, we don't need to compute
1223 // the value of rtl.
1224 bool const rtl = lastrow ? text_->isRTL(par) : false;
1226 // if the first character is a separator, and we are in RTL
1227 // text, this character will not be painted on screen
1228 // and thus we should not count it and skip to the next.
1229 if (rtl && par.isSeparator(bidi.vis2log(vc)))
1232 while (vc < end && tmpx <= x) {
1233 c = bidi.vis2log(vc);
1235 if (body_pos > 0 && c == body_pos - 1) {
1236 FontMetrics const & fm = theFontMetrics(
1237 text_->labelFont(par));
1238 tmpx += row.label_hfill + fm.width(layout.labelsep);
1239 if (par.isLineSeparator(body_pos - 1))
1240 tmpx -= singleWidth(pit, body_pos - 1);
1243 tmpx += singleWidth(pit, c);
1244 if (par.isSeparator(c) && c >= body_pos)
1245 tmpx += row.separator;
1249 if ((tmpx + last_tmpx) / 2 > x) {
1254 LASSERT(vc <= end, /**/); // This shouldn't happen.
1259 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1260 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1261 if (!par.isNewline(end - 1))
1263 } else if (vc == row.pos()) {
1264 c = bidi.vis2log(vc);
1265 if (bidi.level(c) % 2 == 1)
1268 c = bidi.vis2log(vc - 1);
1269 bool const rtl = (bidi.level(c) % 2 == 1);
1270 if (left_side == rtl) {
1272 boundary = isRTLBoundary(pit, c);
1276 // I believe this code is not needed anymore (Jug 20050717)
1278 // The following code is necessary because the cursor position past
1279 // the last char in a row is logically equivalent to that before
1280 // the first char in the next row. That's why insets causing row
1281 // divisions -- Newline and display-style insets -- must be treated
1282 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1283 // Newline inset, air gap below:
1284 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1285 if (bidi.level(end -1) % 2 == 0)
1286 tmpx -= singleWidth(pit, end - 1);
1288 tmpx += singleWidth(pit, end - 1);
1292 // Air gap above display inset:
1293 if (row.pos() < end && c >= end && end < par.size()
1294 && par.isInset(end) && par.getInset(end)->display()) {
1297 // Air gap below display inset:
1298 if (row.pos() < end && c >= end && par.isInset(end - 1)
1299 && par.getInset(end - 1)->display()) {
1305 pos_type const col = c - row.pos();
1307 if (!c || end == par.size())
1310 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1315 return min(col, end - 1 - row.pos());
1319 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1321 // We play safe and use parMetrics(pit) to make sure the
1322 // ParagraphMetrics will be redone and OK to use if needed.
1323 // Otherwise we would use an empty ParagraphMetrics in
1324 // upDownInText() while in selection mode.
1325 ParagraphMetrics const & pm = parMetrics(pit);
1327 LASSERT(row < int(pm.rows().size()), /**/);
1329 Row const & r = pm.rows()[row];
1330 return r.pos() + getColumnNearX(pit, r, x, bound);
1334 void TextMetrics::newParMetricsDown()
1336 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1337 pit_type const pit = last.first + 1;
1338 if (pit == int(text_->paragraphs().size()))
1341 // do it and update its position.
1343 par_metrics_[pit].setPosition(last.second.position()
1344 + last.second.descent() + par_metrics_[pit].ascent());
1348 void TextMetrics::newParMetricsUp()
1350 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1351 if (first.first == 0)
1354 pit_type const pit = first.first - 1;
1355 // do it and update its position.
1357 par_metrics_[pit].setPosition(first.second.position()
1358 - first.second.ascent() - par_metrics_[pit].descent());
1361 // y is screen coordinate
1362 pit_type TextMetrics::getPitNearY(int y)
1364 LASSERT(!text_->paragraphs().empty(), return -1);
1365 LASSERT(!par_metrics_.empty(), return -1);
1366 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1368 // look for highest numbered paragraph with y coordinate less than given y
1371 ParMetricsCache::const_iterator it = par_metrics_.begin();
1372 ParMetricsCache::const_iterator et = par_metrics_.end();
1373 ParMetricsCache::const_iterator last = et; last--;
1375 ParagraphMetrics const & pm = it->second;
1377 if (y < it->second.position() - int(pm.ascent())) {
1378 // We are looking for a position that is before the first paragraph in
1379 // the cache (which is in priciple off-screen, that is before the
1382 // We are already at the first paragraph in the inset.
1384 // OK, this is the paragraph we are looking for.
1385 pit = it->first - 1;
1390 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1392 if (y >= last->second.position() + int(pm_last.descent())) {
1393 // We are looking for a position that is after the last paragraph in
1394 // the cache (which is in priciple off-screen), that is before the
1396 pit = last->first + 1;
1397 if (pit == int(text_->paragraphs().size()))
1398 // We are already at the last paragraph in the inset.
1400 // OK, this is the paragraph we are looking for.
1401 newParMetricsDown();
1405 for (; it != et; ++it) {
1406 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1407 << " y: " << it->second.position());
1409 ParagraphMetrics const & pm = par_metrics_[it->first];
1411 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1413 yy = it->second.position();
1417 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1423 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1424 bool assert_in_view, bool up)
1426 ParagraphMetrics const & pm = par_metrics_[pit];
1428 int yy = pm.position() - pm.ascent();
1429 LASSERT(!pm.rows().empty(), /**/);
1430 RowList::const_iterator rit = pm.rows().begin();
1431 RowList::const_iterator rlast = pm.rows().end();
1433 for (; rit != rlast; yy += rit->height(), ++rit)
1434 if (yy + rit->height() > y)
1437 if (assert_in_view) {
1438 if (!up && yy + rit->height() > y) {
1439 if (rit != pm.rows().begin()) {
1442 } else if (pit != 0) {
1445 ParagraphMetrics const & pm2 = par_metrics_[pit];
1446 rit = pm2.rows().end();
1450 } else if (up && yy != y) {
1452 y = yy + rit->height();
1454 } else if (pit < int(text_->paragraphs().size()) - 1) {
1456 newParMetricsDown();
1457 ParagraphMetrics const & pm2 = par_metrics_[pit];
1458 rit = pm2.rows().begin();
1467 // x,y are absolute screen coordinates
1468 // sets cursor recursively descending into nested editable insets
1469 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1470 bool assert_in_view, bool up)
1472 if (lyxerr.debugging(Debug::WORKAREA)) {
1473 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1474 cur.bv().coordCache().dump();
1476 pit_type pit = getPitNearY(y);
1477 LASSERT(pit != -1, return 0);
1479 int yy = y; // is modified by getPitAndRowNearY
1480 Row const & row = getPitAndRowNearY(yy, pit, assert_in_view, up);
1482 bool bound = false; // is modified by getColumnNearX
1483 int xx = x; // is modified by getColumnNearX
1484 pos_type const pos = row.pos()
1485 + getColumnNearX(pit, row, xx, bound);
1488 cur.boundary(bound);
1491 // try to descend into nested insets
1492 Inset * inset = checkInsetHit(x, yy);
1493 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1495 // Either we deconst editXY or better we move current_font
1496 // and real_current_font to Cursor
1497 // FIXME: what is needed now that current_font and real_current_font
1499 cur.setCurrentFont();
1503 ParagraphList const & pars = text_->paragraphs();
1504 Inset const * inset_before = pos ? pars[pit].getInset(pos - 1) : 0;
1506 // This should be just before or just behind the
1507 // cursor position set above.
1508 LASSERT(inset == inset_before
1509 || inset == pars[pit].getInset(pos), /**/);
1511 // Make sure the cursor points to the position before
1513 if (inset == inset_before) {
1515 cur.boundary(false);
1518 // Try to descend recursively inside the inset.
1519 inset = inset->editXY(cur, x, yy);
1521 if (cur.top().text() == text_)
1522 cur.setCurrentFont();
1527 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1529 LASSERT(text_ == cur.text(), /**/);
1530 pit_type pit = getPitNearY(y);
1531 LASSERT(pit != -1, return);
1533 ParagraphMetrics const & pm = par_metrics_[pit];
1535 int yy = pm.position() - pm.ascent();
1536 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1537 " pit: " << pit << " yy: " << yy);
1540 LASSERT(pm.rows().size(), /**/);
1541 for (; r < int(pm.rows().size()) - 1; ++r) {
1542 Row const & row = pm.rows()[r];
1543 if (int(yy + row.height()) > y)
1548 Row const & row = pm.rows()[r];
1550 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1554 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1556 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1558 text_->setCursor(cur, pit, pos, true, bound);
1559 // remember new position.
1564 //takes screen x,y coordinates
1565 Inset * TextMetrics::checkInsetHit(int x, int y)
1567 pit_type pit = getPitNearY(y);
1568 LASSERT(pit != -1, return 0);
1570 Paragraph const & par = text_->paragraphs()[pit];
1571 ParagraphMetrics const & pm = par_metrics_[pit];
1573 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1575 InsetList::const_iterator iit = par.insetList().begin();
1576 InsetList::const_iterator iend = par.insetList().end();
1577 for (; iit != iend; ++iit) {
1578 Inset * inset = iit->inset;
1580 LYXERR(Debug::DEBUG, "examining inset " << inset);
1582 if (!bv_->coordCache().getInsets().has(inset)) {
1583 LYXERR(Debug::DEBUG, "inset has no cached position");
1587 Dimension const & dim = pm.insetDimension(inset);
1588 Point p = bv_->coordCache().getInsets().xy(inset);
1590 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1591 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1594 && x <= p.x_ + dim.wid
1595 && y >= p.y_ - dim.asc
1596 && y <= p.y_ + dim.des) {
1597 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1602 LYXERR(Debug::DEBUG, "No inset hit. ");
1607 int TextMetrics::cursorX(CursorSlice const & sl,
1608 bool boundary) const
1610 LASSERT(sl.text() == text_, /**/);
1611 pit_type const pit = sl.pit();
1612 Paragraph const & par = text_->paragraphs()[pit];
1613 ParagraphMetrics const & pm = par_metrics_[pit];
1614 if (pm.rows().empty())
1617 pos_type ppos = sl.pos();
1618 // Correct position in front of big insets
1619 bool const boundary_correction = ppos != 0 && boundary;
1620 if (boundary_correction)
1623 Row const & row = pm.getRow(sl.pos(), boundary);
1625 pos_type cursor_vpos = 0;
1627 Buffer const & buffer = bv_->buffer();
1630 bidi.computeTables(par, buffer, row);
1632 pos_type const row_pos = row.pos();
1633 pos_type const end = row.endpos();
1634 // Spaces at logical line breaks in bidi text must be skipped during
1635 // cursor positioning. However, they may appear visually in the middle
1636 // of a row; they must be skipped, wherever they are...
1637 // * logically "abc_[HEBREW_\nHEBREW]"
1638 // * visually "abc_[_WERBEH\nWERBEH]"
1639 pos_type skipped_sep_vpos = -1;
1642 cursor_vpos = row_pos;
1643 else if (ppos >= end)
1644 cursor_vpos = text_->isRTL(par) ? row_pos : end;
1645 else if (ppos > row_pos && ppos >= end)
1646 //FIXME: this code is never reached!
1647 // (see http://www.lyx.org/trac/changeset/8251)
1648 // Place cursor after char at (logical) position pos - 1
1649 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1650 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1652 // Place cursor before char at (logical) position ppos
1653 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1654 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1656 pos_type body_pos = par.beginOfBody();
1658 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1661 // check for possible inline completion in this row
1662 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1663 pos_type inlineCompletionVPos = -1;
1664 if (inlineCompletionPos.inTexted()
1665 && inlineCompletionPos.text() == text_
1666 && inlineCompletionPos.pit() == pit
1667 && inlineCompletionPos.pos() - 1 >= row_pos
1668 && inlineCompletionPos.pos() - 1 < end) {
1669 // draw logically behind the previous character
1670 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1673 // Use font span to speed things up, see below
1677 // If the last logical character is a separator, skip it, unless
1678 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1679 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1680 skipped_sep_vpos = bidi.log2vis(end - 1);
1682 if (lyxrc.paragraph_markers && text_->isRTL(par)) {
1683 ParagraphList const & pars_ = text_->paragraphs();
1684 if (size_type(pit + 1) < pars_.size()) {
1686 docstring const s = docstring(1, char_type(0x00B6));
1687 x += theFontMetrics(f).width(s);
1691 // Inline completion RTL special case row_pos == cursor_pos:
1692 // "__|b" => cursor_pos is right of __
1693 if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1694 font = displayFont(pit, row_pos + 1);
1695 docstring const & completion = bv_->inlineCompletion();
1696 if (font.isRightToLeft() && completion.length() > 0)
1697 x += theFontMetrics(font.fontInfo()).width(completion);
1700 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1701 // Skip the separator which is at the logical end of the row
1702 if (vpos == skipped_sep_vpos)
1704 pos_type pos = bidi.vis2log(vpos);
1705 if (body_pos > 0 && pos == body_pos - 1) {
1706 FontMetrics const & labelfm = theFontMetrics(
1707 text_->labelFont(par));
1708 x += row.label_hfill + labelfm.width(par.layout().labelsep);
1709 if (par.isLineSeparator(body_pos - 1))
1710 x -= singleWidth(pit, body_pos - 1);
1713 // Use font span to speed things up, see above
1714 if (pos < font_span.first || pos > font_span.last) {
1715 font_span = par.fontSpan(pos);
1716 font = displayFont(pit, pos);
1719 x += pm.singleWidth(pos, font);
1721 // Inline completion RTL case:
1722 // "a__|b", __ of b => non-boundary a-pos is right of __
1723 if (vpos + 1 == inlineCompletionVPos
1724 && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1725 font = displayFont(pit, vpos + 1);
1726 docstring const & completion = bv_->inlineCompletion();
1727 if (font.isRightToLeft() && completion.length() > 0)
1728 x += theFontMetrics(font.fontInfo()).width(completion);
1731 // Inline completion LTR case:
1732 // "b|__a", __ of b => non-boundary a-pos is in front of __
1733 if (vpos == inlineCompletionVPos
1734 && (vpos + 1 < cursor_vpos || boundary_correction)) {
1735 font = displayFont(pit, vpos);
1736 docstring const & completion = bv_->inlineCompletion();
1737 if (!font.isRightToLeft() && completion.length() > 0)
1738 x += theFontMetrics(font.fontInfo()).width(completion);
1741 if (par.isSeparator(pos) && pos >= body_pos)
1745 // see correction above
1746 if (boundary_correction) {
1747 if (isRTL(sl, boundary))
1748 x -= singleWidth(pit, ppos);
1750 x += singleWidth(pit, ppos);
1757 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1759 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1760 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1761 if (pm.rows().empty())
1765 h -= par_metrics_[0].rows()[0].ascent();
1766 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1767 h += par_metrics_[pit].height();
1770 if (pos && boundary)
1772 size_t const rend = pm.pos2row(pos);
1773 for (size_t rit = 0; rit != rend; ++rit)
1774 h += pm.rows()[rit].height();
1775 h += pm.rows()[rend].ascent();
1780 // the cursor set functions have a special mechanism. When they
1781 // realize you left an empty paragraph, they will delete it.
1783 bool TextMetrics::cursorHome(Cursor & cur)
1785 LASSERT(text_ == cur.text(), /**/);
1786 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1787 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1788 return text_->setCursor(cur, cur.pit(), row.pos());
1792 bool TextMetrics::cursorEnd(Cursor & cur)
1794 LASSERT(text_ == cur.text(), /**/);
1795 // if not on the last row of the par, put the cursor before
1796 // the final space exept if I have a spanning inset or one string
1797 // is so long that we force a break.
1798 pos_type end = cur.textRow().endpos();
1800 // empty text, end-1 is no valid position
1802 bool boundary = false;
1803 if (end != cur.lastpos()) {
1804 if (!cur.paragraph().isLineSeparator(end-1)
1805 && !cur.paragraph().isNewline(end-1))
1810 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1814 void TextMetrics::deleteLineForward(Cursor & cur)
1816 LASSERT(text_ == cur.text(), /**/);
1817 if (cur.lastpos() == 0) {
1818 // Paragraph is empty, so we just go forward
1819 text_->cursorForward(cur);
1822 cur.setSelection(true); // to avoid deletion
1825 // What is this test for ??? (JMarc)
1826 if (!cur.selection())
1827 text_->deleteWordForward(cur);
1829 cap::cutSelection(cur, true, false);
1830 cur.checkBufferStructure();
1835 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1837 ParagraphList const & pars = text_->paragraphs();
1838 return row.endpos() >= pars[pit].size()
1839 && pit + 1 == pit_type(pars.size());
1843 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1845 return row.pos() == 0 && pit == 0;
1849 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1851 LASSERT(pit >= 0, /**/);
1852 LASSERT(pit < int(text_->paragraphs().size()), /**/);
1853 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1857 int TextMetrics::leftMargin(int max_width,
1858 pit_type const pit, pos_type const pos) const
1860 ParagraphList const & pars = text_->paragraphs();
1862 LASSERT(pit >= 0, /**/);
1863 LASSERT(pit < int(pars.size()), /**/);
1864 Paragraph const & par = pars[pit];
1865 LASSERT(pos >= 0, /**/);
1866 LASSERT(pos <= par.size(), /**/);
1867 Buffer const & buffer = bv_->buffer();
1868 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1869 DocumentClass const & tclass = buffer.params().documentClass();
1870 Layout const & layout = par.layout();
1872 docstring parindent = layout.parindent;
1876 if (text_->isMainText())
1877 l_margin += bv_->leftMargin();
1879 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1880 tclass.leftmargin());
1882 if (par.getDepth() != 0) {
1883 // find the next level paragraph
1884 pit_type newpar = text_->outerHook(pit);
1885 if (newpar != pit_type(pars.size())) {
1886 if (pars[newpar].layout().isEnvironment()) {
1887 l_margin = leftMargin(max_width, newpar);
1889 if (tclass.isDefaultLayout(par.layout())
1890 || tclass.isPlainLayout(par.layout())) {
1891 if (pars[newpar].params().noindent())
1894 parindent = pars[newpar].layout().parindent;
1899 // This happens after sections in standard classes. The 1.3.x
1900 // code compared depths too, but it does not seem necessary
1902 if (tclass.isDefaultLayout(par.layout())
1903 && pit > 0 && pars[pit - 1].layout().nextnoindent)
1906 FontInfo const labelfont = text_->labelFont(par);
1907 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1909 switch (layout.margintype) {
1910 case MARGIN_DYNAMIC:
1911 if (!layout.leftmargin.empty()) {
1912 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1915 if (!par.labelString().empty()) {
1916 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1917 l_margin += labelfont_metrics.width(par.labelString());
1918 l_margin += labelfont_metrics.width(layout.labelsep);
1922 case MARGIN_MANUAL: {
1923 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1924 // The width of an empty par, even with manual label, should be 0
1925 if (!par.empty() && pos >= par.beginOfBody()) {
1926 if (!par.getLabelWidthString().empty()) {
1927 docstring labstr = par.getLabelWidthString();
1928 l_margin += labelfont_metrics.width(labstr);
1929 l_margin += labelfont_metrics.width(layout.labelsep);
1935 case MARGIN_STATIC: {
1936 l_margin += theFontMetrics(buffer.params().getFont()).
1937 signedWidth(layout.leftmargin) * 4 / (par.getDepth() + 4);
1941 case MARGIN_FIRST_DYNAMIC:
1942 if (layout.labeltype == LABEL_MANUAL) {
1943 // if we are at position 0, we are never in the body
1944 if (pos > 0 && pos >= par.beginOfBody())
1945 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1947 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1949 // Special case to fix problems with
1951 || (layout.labeltype == LABEL_STATIC
1952 && layout.latextype == LATEX_ENVIRONMENT
1953 && !text_->isFirstInSequence(pit))) {
1954 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1955 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
1956 && layout.labeltype != LABEL_BIBLIO
1957 && layout.labeltype !=
1958 LABEL_CENTERED_TOP_ENVIRONMENT) {
1959 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1960 l_margin += labelfont_metrics.width(layout.labelsep);
1961 l_margin += labelfont_metrics.width(par.labelString());
1965 case MARGIN_RIGHT_ADDRESS_BOX: {
1967 // ok, a terrible hack. The left margin depends on the widest
1968 // row in this paragraph.
1969 RowList::iterator rit = par.rows().begin();
1970 RowList::iterator end = par.rows().end();
1971 // FIXME: This is wrong.
1972 int minfill = max_width;
1973 for ( ; rit != end; ++rit)
1974 if (rit->fill() < minfill)
1975 minfill = rit->fill();
1976 l_margin += theFontMetrics(params.getFont()).signedWidth(layout.leftmargin);
1977 l_margin += minfill;
1979 // also wrong, but much shorter.
1980 l_margin += max_width / 2;
1985 if (!par.params().leftIndent().zero())
1986 l_margin += par.params().leftIndent().inPixels(max_width);
1990 if (par.params().align() == LYX_ALIGN_LAYOUT)
1991 align = layout.align;
1993 align = par.params().align();
1995 // set the correct parindent
1997 && (layout.labeltype == LABEL_NO_LABEL
1998 || layout.labeltype == LABEL_TOP_ENVIRONMENT
1999 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
2000 || (layout.labeltype == LABEL_STATIC
2001 && layout.latextype == LATEX_ENVIRONMENT
2002 && !text_->isFirstInSequence(pit)))
2003 && align == LYX_ALIGN_BLOCK
2004 && !par.params().noindent()
2005 // in some insets, paragraphs are never indented
2006 && !text_->inset().neverIndent()
2007 // display style insets are always centered, omit indentation
2010 && par.getInset(pos)->display())
2011 && (!(tclass.isDefaultLayout(par.layout())
2012 || tclass.isPlainLayout(par.layout()))
2013 || buffer.params().paragraph_separation
2014 == BufferParams::ParagraphIndentSeparation)
2017 // use the parindent of the layout when the default indentation is
2018 // used otherwise use the indentation set in the document settings
2019 if (buffer.params().getIndentation().asLyXCommand() == "default")
2020 l_margin += theFontMetrics(
2021 buffer.params().getFont()).signedWidth(parindent);
2023 l_margin += buffer.params().getIndentation().inPixels(*bv_);
2030 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
2032 ParagraphMetrics const & pm = par_metrics_[pit];
2034 return pm.singleWidth(pos, displayFont(pit, pos));
2038 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
2040 if (par_metrics_.empty())
2046 ParMetricsCache::iterator it = par_metrics_.begin();
2047 ParMetricsCache::iterator const pm_end = par_metrics_.end();
2048 y -= it->second.ascent();
2049 for (; it != pm_end; ++it) {
2050 ParagraphMetrics const & pmi = it->second;
2052 pit_type const pit = it->first;
2053 // Save the paragraph position in the cache.
2054 it->second.setPosition(y);
2055 drawParagraph(pi, pit, x, y);
2061 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
2063 BufferParams const & bparams = bv_->buffer().params();
2064 ParagraphMetrics const & pm = par_metrics_[pit];
2065 if (pm.rows().empty())
2069 bool const original_drawing_state = pi.pain.isDrawingEnabled();
2070 int const ww = bv_->workHeight();
2071 size_t const nrows = pm.rows().size();
2073 Cursor const & cur = bv_->cursor();
2074 DocIterator sel_beg = cur.selectionBegin();
2075 DocIterator sel_end = cur.selectionEnd();
2076 bool selection = cur.selection()
2077 // This is our text.
2078 && cur.text() == text_
2079 // if the anchor is outside, this is not our selection
2080 && cur.normalAnchor().text() == text_
2081 && pit >= sel_beg.pit() && pit <= sel_end.pit();
2083 // We store the begin and end pos of the selection relative to this par
2084 DocIterator sel_beg_par = cur.selectionBegin();
2085 DocIterator sel_end_par = cur.selectionEnd();
2087 // We care only about visible selection.
2089 if (pit != sel_beg.pit()) {
2090 sel_beg_par.pit() = pit;
2091 sel_beg_par.pos() = 0;
2093 if (pit != sel_end.pit()) {
2094 sel_end_par.pit() = pit;
2095 sel_end_par.pos() = sel_end_par.lastpos();
2099 for (size_t i = 0; i != nrows; ++i) {
2101 Row const & row = pm.rows()[i];
2105 bool const inside = (y + row.descent() >= 0
2106 && y - row.ascent() < ww);
2107 // It is not needed to draw on screen if we are not inside.
2108 pi.pain.setDrawingEnabled(inside && original_drawing_state);
2109 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
2112 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2114 row.setSelection(-1, -1);
2116 // The row knows nothing about the paragraph, so we have to check
2117 // whether this row is the first or last and update the margins.
2118 if (row.selection()) {
2119 if (row.sel_beg == 0)
2120 row.begin_margin_sel = sel_beg.pit() < pit;
2121 if (row.sel_end == sel_end_par.lastpos())
2122 row.end_margin_sel = sel_end.pit() > pit;
2125 // Row signature; has row changed since last paint?
2126 row.setCrc(pm.computeRowSignature(row, bparams));
2127 bool row_has_changed = row.changed();
2129 // Take this opportunity to spellcheck the row contents.
2130 if (row_has_changed && lyxrc.spellcheck_continuously) {
2132 // dummy variable, not used.
2133 static docstring_list suggestions;
2134 pos_type from = row.pos();
2135 pos_type to = row.endpos();
2136 while (from < row.endpos()) {
2137 text_->getPar(pit).spellCheck(from, to, wl, suggestions, false);
2142 // Don't paint the row if a full repaint has not been requested
2143 // and if it has not changed.
2144 if (!pi.full_repaint && !row_has_changed) {
2145 // Paint only the insets if the text itself is
2147 rp.paintOnlyInsets();
2152 // Clear background of this row if paragraph background was not
2153 // already cleared because of a full repaint.
2154 if (!pi.full_repaint && row_has_changed) {
2155 pi.pain.fillRectangle(x, y - row.ascent(),
2156 width(), row.height(), pi.background_color);
2159 if (row.selection())
2160 drawRowSelection(pi, x, row, cur, pit);
2162 // Instrumentation for testing row cache (see also
2164 if (lyxerr.debugging(Debug::PAINTING) && inside
2165 && (row.selection() || pi.full_repaint || row_has_changed)) {
2166 string const foreword = text_->isMainText() ?
2167 "main text redraw " : "inset text redraw: ";
2168 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
2169 << " row_selection=" << row.selection()
2170 << " full_repaint=" << pi.full_repaint
2171 << " row_has_changed=" << row_has_changed);
2174 // Backup full_repaint status and force full repaint
2175 // for inner insets as the Row has been cleared out.
2176 bool tmp = pi.full_repaint;
2177 pi.full_repaint = true;
2180 rp.paintChangeBar();
2181 bool const is_rtl = text_->isRTL(text_->getPar(pit));
2182 if (i == 0 && !is_rtl)
2184 if (i == nrows - 1 && is_rtl)
2187 if (i == nrows - 1 && !is_rtl)
2189 if (i == 0 && is_rtl)
2192 // Restore full_repaint status.
2193 pi.full_repaint = tmp;
2195 // Re-enable screen drawing for future use of the painter.
2196 pi.pain.setDrawingEnabled(original_drawing_state);
2198 //LYXERR(Debug::PAINTING, ".");
2202 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2203 Cursor const & curs, pit_type pit) const
2205 DocIterator beg = curs.selectionBegin();
2207 beg.pos() = row.sel_beg;
2209 DocIterator end = curs.selectionEnd();
2211 end.pos() = row.sel_end;
2213 bool const begin_boundary = beg.pos() >= row.endpos();
2214 bool const end_boundary = row.sel_end == row.endpos();
2216 DocIterator cur = beg;
2217 cur.boundary(begin_boundary);
2218 int x1 = cursorX(beg.top(), begin_boundary);
2219 int x2 = cursorX(end.top(), end_boundary);
2220 int const y1 = bv_->getPos(cur).y_ - row.ascent();
2221 int const y2 = y1 + row.height();
2223 int const rm = text_->isMainText() ? bv_->rightMargin() : 0;
2224 int const lm = text_->isMainText() ? bv_->leftMargin() : 0;
2227 if (row.begin_margin_sel) {
2228 if (text_->isRTL(beg.paragraph())) {
2229 pi.pain.fillRectangle(x + x1, y1, width() - rm - x1, y2 - y1,
2232 pi.pain.fillRectangle(x + lm, y1, x1 - lm, y2 - y1,
2237 if (row.end_margin_sel) {
2238 if (text_->isRTL(beg.paragraph())) {
2239 pi.pain.fillRectangle(x + lm, y1, x2 - lm, y2 - y1,
2242 pi.pain.fillRectangle(x + x2, y1, width() - rm - x2, y2 - y1,
2247 // if we are on a boundary from the beginning, it's probably
2248 // a RTL boundary and we jump to the other side directly as this
2249 // segement is 0-size and confuses the logic below
2251 cur.boundary(false);
2253 // go through row and draw from RTL boundary to RTL boundary
2255 bool draw_now = false;
2257 // simplified cursorForward code below which does not
2258 // descend into insets and which does not go into the
2259 // next line. Compare the logic with the original cursorForward
2261 // if left of boundary -> just jump to right side, but
2262 // for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2263 if (cur.boundary()) {
2264 cur.boundary(false);
2265 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2266 // in front of RTL boundary -> Stay on this side of the boundary
2267 // because: ab|cDDEEFFghi -> abc|DDEEFFghi
2276 if (cur.pos() == row.endpos())
2281 // the previous segment was just drawn, now the next starts
2282 x1 = cursorX(cur.top(), cur.boundary());
2285 if (!(cur < end) || draw_now) {
2286 x2 = cursorX(cur.top(), cur.boundary());
2287 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2290 // reset x1, so it is set again next round (which will be on the
2291 // right side of a boundary or at the selection end)
2298 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2299 Dimension & dim) const
2301 Cursor const & bvcur = cur.bv().cursor();
2303 // get word in front of cursor
2304 docstring word = text_->previousWord(bvcur.top());
2305 DocIterator wordStart = bvcur;
2306 wordStart.pos() -= word.length();
2308 // get position on screen of the word start and end
2309 //FIXME: Is it necessary to explicitly set this to false?
2310 wordStart.boundary(false);
2311 Point lxy = cur.bv().getPos(wordStart);
2312 Point rxy = cur.bv().getPos(bvcur);
2314 // calculate dimensions of the word
2315 dim = rowHeight(bvcur.pit(), wordStart.pos(), bvcur.pos(), false);
2316 dim.wid = abs(rxy.x_ - lxy.x_);
2318 // calculate position of word
2320 x = min(rxy.x_, lxy.x_);
2322 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2323 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2326 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2328 // ParagraphMetrics const & pm = par_metrics_[pit];
2329 // Row const & r = pm.rows()[row];
2335 int defaultRowHeight()
2337 return int(theFontMetrics(sane_font).maxHeight() * 1.2);