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 "paragraph_funcs.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
40 #include "rowpainter.h"
42 #include "TextClass.h"
45 #include "mathed/MacroTable.h"
46 #include "mathed/MathMacroTemplate.h"
48 #include "frontends/FontMetrics.h"
49 #include "frontends/Painter.h"
51 #include "support/debug.h"
53 #include "support/lassert.h"
60 using frontend::FontMetrics;
62 static int numberOfSeparators(Paragraph const & par, Row const & row)
64 pos_type const first = max(row.pos(), par.beginOfBody());
65 pos_type const last = row.endpos() - 1;
67 for (pos_type p = first; p < last; ++p) {
68 if (par.isSeparator(p))
75 static int numberOfLabelHfills(Paragraph const & par, Row const & row)
77 pos_type last = row.endpos() - 1;
78 pos_type first = row.pos();
80 // hfill *DO* count at the beginning of paragraphs!
82 while (first < last && par.isHfill(first))
86 last = min(last, par.beginOfBody());
88 for (pos_type p = first; p < last; ++p) {
96 static int numberOfHfills(Paragraph const & par, Row const & row)
98 pos_type const last = row.endpos();
99 pos_type first = row.pos();
101 // hfill *DO* count at the beginning of paragraphs!
103 while (first < last && par.isHfill(first))
107 first = max(first, par.beginOfBody());
110 for (pos_type p = first; p < last; ++p) {
118 /////////////////////////////////////////////////////////////////////
122 /////////////////////////////////////////////////////////////////////
125 TextMetrics::TextMetrics(BufferView * bv, Text * text)
126 : bv_(bv), text_(text)
129 max_width_ = bv_->workWidth();
130 dim_.wid = max_width_;
134 //text_->updateLabels(bv->buffer());
138 bool TextMetrics::contains(pit_type pit) const
140 return par_metrics_.find(pit) != par_metrics_.end();
144 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
146 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
151 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
153 ParMetricsCache::const_iterator it = par_metrics_.begin();
154 return make_pair(it->first, &it->second);
158 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
160 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
161 return make_pair(it->first, &it->second);
165 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
167 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
168 if (pmc_it == par_metrics_.end()) {
169 pmc_it = par_metrics_.insert(
170 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
172 if (pmc_it->second.rows().empty() && redo)
174 return pmc_it->second;
178 int TextMetrics::parPosition(pit_type pit) const
180 if (pit < par_metrics_.begin()->first)
182 if (pit > par_metrics_.rbegin()->first)
185 return par_metrics_[pit].position();
189 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
191 LASSERT(mi.base.textwidth > 0, /**/);
192 max_width_ = mi.base.textwidth;
193 // backup old dimension.
194 Dimension const old_dim = dim_;
197 dim_.wid = min_width;
198 pit_type const npar = text_->paragraphs().size();
200 // If there is more than one row, expand the text to
201 // the full allowable width.
202 dim_.wid = max_width_;
204 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
205 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
207 bool changed = false;
209 for (pit_type pit = 0; pit != npar; ++pit) {
210 changed |= redoParagraph(pit);
211 ParagraphMetrics const & pm = par_metrics_[pit];
213 if (dim_.wid < pm.width())
214 dim_.wid = pm.width();
217 dim_.asc = par_metrics_[0].ascent();
218 dim_.des = h - dim_.asc;
219 //lyxerr << "dim_.wid " << dim_.wid << endl;
220 //lyxerr << "dim_.asc " << dim_.asc << endl;
221 //lyxerr << "dim_.des " << dim_.des << endl;
223 changed |= dim_ != old_dim;
229 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
231 return main_text_? pm.rightMargin(*bv_) : 0;
235 int TextMetrics::rightMargin(pit_type const pit) const
237 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
241 void TextMetrics::applyOuterFont(Font & font) const
244 lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
245 lf.fontInfo().realize(font.fontInfo());
246 lf.setLanguage(font.language());
251 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
253 LASSERT(pos >= 0, /**/);
255 ParagraphList const & pars = text_->paragraphs();
256 Paragraph const & par = pars[pit];
257 Layout const & layout = par.layout();
258 Buffer const & buffer = bv_->buffer();
260 BufferParams const & params = buffer.params();
261 pos_type const body_pos = par.beginOfBody();
263 // We specialize the 95% common case:
264 if (!par.getDepth()) {
265 Font f = par.getFontSettings(params, pos);
266 if (!text_->isMainText(buffer))
268 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
270 FontInfo const & lf = lab ? layout.labelfont : layout.font;
271 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
273 // In case the default family has been customized
274 if (lf.family() == INHERIT_FAMILY)
275 rlf.setFamily(params.getFont().fontInfo().family());
276 f.fontInfo().realize(rlf);
280 // The uncommon case need not be optimized as much
281 FontInfo const & layoutfont = pos < body_pos ?
282 layout.labelfont : layout.font;
284 Font font = par.getFontSettings(params, pos);
285 font.fontInfo().realize(layoutfont);
287 if (!text_->isMainText(buffer))
288 applyOuterFont(font);
290 // Realize against environment font information
291 // NOTE: the cast to pit_type should be removed when pit_type
292 // changes to a unsigned integer.
293 if (pit < pit_type(pars.size()))
294 font.fontInfo().realize(outerFont(pit, pars).fontInfo());
296 // Realize with the fonts of lesser depth.
297 font.fontInfo().realize(params.getFont().fontInfo());
303 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
305 if (!lyxrc.rtl_support || !sl.text())
309 if (boundary && sl.pos() > 0)
312 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
316 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
318 if (!lyxrc.rtl_support)
321 // no RTL boundary at line start
325 Font const & left_font = displayFont(pit, pos - 1);
327 return isRTLBoundary(pit, pos, left_font);
331 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
332 Font const & font) const
334 if (!lyxrc.rtl_support)
337 Paragraph const & par = text_->getPar(pit);
338 bool left = font.isVisibleRightToLeft();
340 if (pos == par.size())
341 right = par.isRTL(bv_->buffer().params());
343 right = displayFont(pit, pos).isVisibleRightToLeft();
344 return left != right;
348 bool TextMetrics::redoParagraph(pit_type const pit)
350 Paragraph & par = text_->getPar(pit);
351 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
352 // redoParagraph() recursively inside parMetrics.
353 Dimension old_dim = parMetrics(pit, false).dim();
354 ParagraphMetrics & pm = par_metrics_[pit];
357 Buffer & buffer = bv_->buffer();
358 main_text_ = (text_ == &buffer.text());
359 bool changed = false;
361 // FIXME: This check ought to be done somewhere else. It is the reason
362 // why text_ is not const. But then, where else to do it?
363 // Well, how can you end up with either (a) a biblio environment that
364 // has no InsetBibitem or (b) a biblio environment with more than one
365 // InsetBibitem? I think the answer is: when paragraphs are merged;
366 // when layout is set; when material is pasted.
367 int const moveCursor = par.checkBiblio(buffer);
369 const_cast<Cursor &>(bv_->cursor()).posForward();
370 else if (moveCursor < 0) {
371 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
372 if (cursor.pos() >= -moveCursor)
373 cursor.posBackward();
376 // Optimisation: this is used in the next two loops
377 // so better to calculate that once here.
378 int const right_margin = rightMargin(pm);
380 // iterator pointing to paragraph to resolve macros
381 DocIterator parPos = text_->macrocontextPosition();
385 LYXERR(Debug::INFO, "MacroContext not initialised!"
386 << " Going through the buffer again and hope"
387 << " the context is better then.");
388 bv_->buffer().updateLabels();
389 parPos = text_->macrocontextPosition();
390 LASSERT(!parPos.empty(), /**/);
395 // FIXME: We should always use getFont(), see documentation of
396 // noFontChange() in Inset.h.
397 Font const bufferfont = buffer.params().getFont();
398 InsetList::const_iterator ii = par.insetList().begin();
399 InsetList::const_iterator iend = par.insetList().end();
400 for (; ii != iend; ++ii) {
401 // position already initialized?
402 if (!parPos.empty()) {
403 parPos.pos() = ii->pos;
405 // A macro template would normally not be visible
406 // by itself. But the tex macro semantics allow
407 // recursion, so we artifically take the context
408 // after the macro template to simulate this.
409 if (ii->inset->lyxCode() == MATHMACRO_CODE)
413 // do the metric calculation
415 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
417 Font const & font = ii->inset->noFontChange() ?
418 bufferfont : displayFont(pit, ii->pos);
419 MacroContext mc(buffer, parPos);
420 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
421 ii->inset->metrics(mi, dim);
422 Dimension const old_dim = pm.insetDimension(ii->inset);
423 if (old_dim != dim) {
424 pm.setInsetDimension(ii->inset, dim);
429 par.setBeginOfBody();
431 size_t row_index = 0;
432 // maximum pixel width of a row
433 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
436 pos_type end = rowBreakPoint(width, pit, first);
437 if (row_index || end < par.size())
438 // If there is more than one row, expand the text to
439 // the full allowable width. This setting here is needed
440 // for the computeRowMetrics() below.
441 dim_.wid = max_width_;
443 dim = rowHeight(pit, first, end);
444 dim.wid = rowWidth(right_margin, pit, first, end);
445 if (row_index == pm.rows().size())
446 pm.rows().push_back(Row());
447 Row & row = pm.rows()[row_index];
448 row.setChanged(false);
451 row.setDimension(dim);
452 int const max_row_width = max(dim_.wid, dim.wid);
453 computeRowMetrics(pit, row, max_row_width);
457 pm.dim().wid = max(pm.dim().wid, dim.wid);
458 pm.dim().des += dim.height();
459 } while (first < par.size());
461 if (row_index < pm.rows().size())
462 pm.rows().resize(row_index);
464 // Make sure that if a par ends in newline, there is one more row
466 if (first > 0 && par.isNewline(first - 1)) {
467 Dimension dim = rowHeight(pit, first, first);
468 dim.wid = rowWidth(right_margin, pit, first, first);
469 if (row_index == pm.rows().size())
470 pm.rows().push_back(Row());
471 Row & row = pm.rows()[row_index];
472 row.setChanged(false);
475 row.setDimension(dim);
476 int const max_row_width = max(dim_.wid, dim.wid);
477 computeRowMetrics(pit, row, max_row_width);
478 pm.dim().des += dim.height();
481 pm.dim().asc += pm.rows()[0].ascent();
482 pm.dim().des -= pm.rows()[0].ascent();
484 changed |= old_dim.height() != pm.dim().height();
490 void TextMetrics::computeRowMetrics(pit_type const pit,
491 Row & row, int width) const
496 Buffer & buffer = bv_->buffer();
497 Paragraph const & par = text_->getPar(pit);
499 double w = width - row.width();
500 // FIXME: put back this assertion when the crash on new doc is solved.
501 //LASSERT(w >= 0, /**/);
503 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
504 //lyxerr << "row.width() " << row.width() << endl;
505 //lyxerr << "w " << w << endl;
507 bool const is_rtl = text_->isRTL(buffer, par);
509 row.x = rightMargin(pit);
511 row.x = leftMargin(max_width_, pit, row.pos());
513 // is there a manual margin with a manual label
514 Layout const & layout = par.layout();
516 if (layout.margintype == MARGIN_MANUAL
517 && layout.labeltype == LABEL_MANUAL) {
518 /// We might have real hfills in the label part
519 int nlh = numberOfLabelHfills(par, row);
521 // A manual label par (e.g. List) has an auto-hfill
522 // between the label text and the body of the
524 // But we don't want to do this auto hfill if the par
529 if (nlh && !par.getLabelWidthString().empty())
530 row.label_hfill = labelFill(pit, row) / double(nlh);
534 // are there any hfills in the row?
535 if (int const nh = numberOfHfills(par, row)) {
537 hfill = w / double(nh);
538 // we don't have to look at the alignment if it is ALIGN_LEFT and
539 // if the row is already larger then the permitted width as then
540 // we force the LEFT_ALIGN'edness!
541 } else if (int(row.width()) < max_width_) {
542 // is it block, flushleft or flushright?
543 // set x how you need it
545 if (par.params().align() == LYX_ALIGN_LAYOUT)
546 align = layout.align;
548 align = par.params().align();
550 // handle alignment inside tabular cells
551 Inset const & owner = par.inInset();
552 switch (owner.contentAlignment()) {
553 case LYX_ALIGN_CENTER:
555 case LYX_ALIGN_RIGHT:
556 if (align == LYX_ALIGN_NONE
557 || align == LYX_ALIGN_BLOCK)
558 align = owner.contentAlignment();
561 // unchanged (use align)
565 // Display-style insets should always be on a centered row
566 if (Inset const * inset = par.getInset(row.pos())) {
567 switch (inset->display()) {
568 case Inset::AlignLeft:
569 align = LYX_ALIGN_BLOCK;
571 case Inset::AlignCenter:
572 align = LYX_ALIGN_CENTER;
575 // unchanged (use align)
577 case Inset::AlignRight:
578 align = LYX_ALIGN_RIGHT;
584 case LYX_ALIGN_BLOCK: {
585 int const ns = numberOfSeparators(par, row);
586 bool disp_inset = false;
587 if (row.endpos() < par.size()) {
588 Inset const * in = par.getInset(row.endpos());
590 disp_inset = in->display();
592 // If we have separators, this is not the last row of a
593 // par, does not end in newline, and is not row above a
594 // display inset... then stretch it
596 && row.endpos() < par.size()
597 && !par.isNewline(row.endpos() - 1)
600 row.separator = w / ns;
601 //lyxerr << "row.separator " << row.separator << endl;
602 //lyxerr << "ns " << ns << endl;
608 case LYX_ALIGN_RIGHT:
611 case LYX_ALIGN_CENTER:
618 pos_type body_pos = par.beginOfBody();
619 pos_type end = row.endpos();
622 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
624 row.x += theFontMetrics(text_->labelFont(buffer, par)).
625 width(layout.labelsep);
627 row.x += row.label_hfill;
631 pos_type const endpos = row.endpos();
632 pos_type body_pos = par.beginOfBody();
634 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
637 ParagraphMetrics & pm = par_metrics_[pit];
638 InsetList::const_iterator ii = par.insetList().begin();
639 InsetList::const_iterator iend = par.insetList().end();
640 for ( ; ii != iend; ++ii) {
641 if (ii->pos >= endpos || ii->pos < row.pos()
642 || (ii->inset->lyxCode() != SPACE_CODE ||
643 !ii->inset->isStretchableSpace()))
645 Dimension dim = row.dimension();
646 if (pm.hfillExpansion(row, ii->pos))
647 dim.wid = int(ii->pos >= body_pos ?
648 max(hfill, 5.0) : row.label_hfill);
651 // Cache the inset dimension.
652 bv_->coordCache().insets().add(ii->inset, dim);
653 pm.setInsetDimension(ii->inset, dim);
658 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
660 Buffer & buffer = bv_->buffer();
661 Paragraph const & par = text_->getPar(pit);
663 pos_type last = par.beginOfBody();
664 LASSERT(last > 0, /**/);
666 // -1 because a label ends with a space that is in the label
669 // a separator at this end does not count
670 if (par.isLineSeparator(last))
674 for (pos_type i = row.pos(); i <= last; ++i)
675 w += singleWidth(pit, i);
677 docstring const & label = par.params().labelWidthString();
681 FontMetrics const & fm
682 = theFontMetrics(text_->labelFont(buffer, par));
684 return max(0, fm.width(label) - w);
688 // this needs special handling - only newlines count as a break point
689 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
691 pos_type const end = par.size();
694 if (par.isNewline(i))
701 int TextMetrics::labelEnd(pit_type const pit) const
703 // labelEnd is only needed if the layout fills a flushleft label.
704 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
706 // return the beginning of the body
707 return leftMargin(max_width_, pit);
713 * Calling Text::getFont is slow. While rebreaking we scan a
714 * paragraph from left to right calling getFont for every char. This
715 * simple class address this problem by hidding an optimization trick
716 * (not mine btw -AB): the font is reused in the whole font span. The
717 * class handles transparently the "hidden" (not part of the fontlist)
718 * label font (as getFont does).
724 FontIterator(TextMetrics const & tm,
725 Paragraph const & par, pit_type pit, pos_type pos)
726 : tm_(tm), par_(par), pit_(pit), pos_(pos),
727 font_(tm.displayFont(pit, pos)),
728 endspan_(par.fontSpan(pos).last),
729 bodypos_(par.beginOfBody())
733 Font const & operator*() const { return font_; }
736 FontIterator & operator++()
739 if (pos_ > endspan_ || pos_ == bodypos_) {
740 font_ = tm_.displayFont(pit_, pos_);
741 endspan_ = par_.fontSpan(pos_).last;
747 Font * operator->() { return &font_; }
751 TextMetrics const & tm_;
753 Paragraph const & par_;
768 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
771 Buffer & buffer = bv_->buffer();
772 ParagraphMetrics const & pm = par_metrics_[pit];
773 Paragraph const & par = text_->getPar(pit);
774 pos_type const end = par.size();
775 if (pos == end || width < 0)
778 Layout const & layout = par.layout();
780 if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX)
781 return addressBreakPoint(pos, par);
783 pos_type const body_pos = par.beginOfBody();
785 // check for possible inline completion
786 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
787 pos_type inlineCompletionLPos = -1;
788 if (inlineCompletionPos.inTexted()
789 && inlineCompletionPos.text() == text_
790 && inlineCompletionPos.pit() == pit) {
791 // draw logically behind the previous character
792 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
795 // Now we iterate through until we reach the right margin
796 // or the end of the par, then choose the possible break
799 int label_end = labelEnd(pit);
800 int const left = leftMargin(max_width_, pit, pos);
803 // pixel width since last breakpoint
806 FontIterator fi = FontIterator(*this, par, pit, pos);
807 pos_type point = end;
809 for ( ; i < end; ++i, ++fi) {
810 int thiswidth = pm.singleWidth(i, *fi);
812 // add inline completion width
813 if (inlineCompletionLPos == i) {
814 docstring const & completion = bv_->inlineCompletion();
815 if (completion.length() > 0)
816 thiswidth += theFontMetrics(*fi).width(completion);
819 // add the auto-hfill from label end to the body
820 if (body_pos && i == body_pos) {
821 FontMetrics const & fm = theFontMetrics(
822 text_->labelFont(buffer, par));
823 int add = fm.width(layout.labelsep);
824 if (par.isLineSeparator(i - 1))
825 add -= singleWidth(pit, i - 1);
827 add = max(add, label_end - x);
832 chunkwidth += thiswidth;
834 // break before a character that will fall off
835 // the right of the row
837 // if no break before, break here
838 if (point == end || chunkwidth >= width - left) {
844 // exit on last registered breakpoint:
848 if (par.isNewline(i)) {
852 Inset const * inset = 0;
855 if ((inset = par.getInset(i + 1)) && inset->display()) {
860 if ((inset = par.getInset(i)) && inset->display()) {
866 inset = par.getInset(i);
867 if (!inset || inset->isChar()) {
868 // some insets are line separators too
869 if (par.isLineSeparator(i)) {
870 // register breakpoint:
877 // maybe found one, but the par is short enough.
878 if (i == end && x < width)
881 // manual labels cannot be broken in LaTeX. But we
882 // want to make our on-screen rendering of footnotes
884 if (body_pos && point < body_pos)
891 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
892 pos_type const first, pos_type const end) const
894 Buffer & buffer = bv_->buffer();
895 // get the pure distance
896 ParagraphMetrics const & pm = par_metrics_[pit];
897 Paragraph const & par = text_->getPar(pit);
898 int w = leftMargin(max_width_, pit, first);
899 int label_end = labelEnd(pit);
901 // check for possible inline completion
902 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
903 pos_type inlineCompletionLPos = -1;
904 if (inlineCompletionPos.inTexted()
905 && inlineCompletionPos.text() == text_
906 && inlineCompletionPos.pit() == pit) {
907 // draw logically behind the previous character
908 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
911 pos_type const body_pos = par.beginOfBody();
915 FontIterator fi = FontIterator(*this, par, pit, i);
916 for ( ; i < end; ++i, ++fi) {
917 if (body_pos > 0 && i == body_pos) {
918 FontMetrics const & fm = theFontMetrics(
919 text_->labelFont(buffer, par));
920 w += fm.width(par.layout().labelsep);
921 if (par.isLineSeparator(i - 1))
922 w -= singleWidth(pit, i - 1);
923 w = max(w, label_end);
925 w += pm.singleWidth(i, *fi);
927 // add inline completion width
928 if (inlineCompletionLPos == i) {
929 docstring const & completion = bv_->inlineCompletion();
930 if (completion.length() > 0)
931 w += theFontMetrics(*fi).width(completion);
936 if (body_pos > 0 && body_pos >= end) {
937 FontMetrics const & fm = theFontMetrics(
938 text_->labelFont(buffer, par));
939 w += fm.width(par.layout().labelsep);
940 if (end > 0 && par.isLineSeparator(end - 1))
941 w -= singleWidth(pit, end - 1);
942 w = max(w, label_end);
945 return w + right_margin;
949 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
950 pos_type const end, bool topBottomSpace) const
952 Paragraph const & par = text_->getPar(pit);
953 // get the maximum ascent and the maximum descent
954 double layoutasc = 0;
955 double layoutdesc = 0;
956 double const dh = defaultRowHeight();
958 // ok, let us initialize the maxasc and maxdesc value.
959 // Only the fontsize count. The other properties
960 // are taken from the layoutfont. Nicer on the screen :)
961 Layout const & layout = par.layout();
963 // as max get the first character of this row then it can
964 // increase but not decrease the height. Just some point to
965 // start with so we don't have to do the assignment below too
967 Buffer const & buffer = bv_->buffer();
968 Font font = displayFont(pit, first);
969 FontSize const tmpsize = font.fontInfo().size();
970 font.fontInfo() = text_->layoutFont(buffer, pit);
971 FontSize const size = font.fontInfo().size();
972 font.fontInfo().setSize(tmpsize);
974 FontInfo labelfont = text_->labelFont(buffer, par);
976 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
977 FontMetrics const & fontmetrics = theFontMetrics(font);
979 // these are minimum values
980 double const spacing_val = layout.spacing.getValue()
981 * text_->spacing(buffer, par);
982 //lyxerr << "spacing_val = " << spacing_val << endl;
983 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
984 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
986 // insets may be taller
987 ParagraphMetrics const & pm = par_metrics_[pit];
988 InsetList::const_iterator ii = par.insetList().begin();
989 InsetList::const_iterator iend = par.insetList().end();
990 for ( ; ii != iend; ++ii) {
991 if (ii->pos >= first && ii->pos < end) {
992 Dimension const & dim = pm.insetDimension(ii->inset);
993 maxasc = max(maxasc, dim.ascent());
994 maxdesc = max(maxdesc, dim.descent());
998 // Check if any custom fonts are larger (Asger)
999 // This is not completely correct, but we can live with the small,
1000 // cosmetic error for now.
1004 par.highestFontInRange(first, end, size);
1005 if (maxsize > font.fontInfo().size()) {
1006 // use standard paragraph font with the maximal size
1007 FontInfo maxfont = font.fontInfo();
1008 maxfont.setSize(maxsize);
1009 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
1010 maxasc = max(maxasc, maxfontmetrics.maxAscent());
1011 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
1014 // This is nicer with box insets:
1018 ParagraphList const & pars = text_->paragraphs();
1020 // is it a top line?
1021 if (first == 0 && topBottomSpace) {
1022 BufferParams const & bufparams = buffer.params();
1023 // some parskips VERY EASY IMPLEMENTATION
1024 if (bufparams.paragraph_separation
1025 == BufferParams::ParagraphSkipSeparation
1026 && par.ownerCode() != ERT_CODE
1027 && par.ownerCode() != LISTINGS_CODE
1029 && ((layout.isParagraph() && par.getDepth() == 0)
1030 || (pars[pit - 1].layout().isParagraph()
1031 && pars[pit - 1].getDepth() == 0)))
1033 maxasc += bufparams.getDefSkip().inPixels(*bv_);
1036 if (par.params().startOfAppendix())
1037 maxasc += int(3 * dh);
1039 // This is special code for the chapter, since the label of this
1040 // layout is printed in an extra row
1041 if (layout.counter == "chapter"
1042 && !par.params().labelString().empty()) {
1043 labeladdon = int(labelfont_metrics.maxHeight()
1044 * layout.spacing.getValue()
1045 * text_->spacing(buffer, par));
1048 // special code for the top label
1049 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1050 || layout.labeltype == LABEL_BIBLIO
1051 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1052 && isFirstInSequence(pit, pars)
1053 && !par.labelString().empty())
1056 labelfont_metrics.maxHeight()
1057 * layout.spacing.getValue()
1058 * text_->spacing(buffer, par)
1059 + (layout.topsep + layout.labelbottomsep) * dh);
1062 // Add the layout spaces, for example before and after
1063 // a section, or between the items of a itemize or enumerate
1066 pit_type prev = depthHook(pit, pars, par.getDepth());
1067 Paragraph const & prevpar = pars[prev];
1069 && prevpar.layout() == layout
1070 && prevpar.getDepth() == par.getDepth()
1071 && prevpar.getLabelWidthString()
1072 == par.getLabelWidthString()) {
1073 layoutasc = layout.itemsep * dh;
1074 } else if (pit != 0 || first != 0) {
1075 if (layout.topsep > 0)
1076 layoutasc = layout.topsep * dh;
1079 prev = outerHook(pit, pars);
1080 if (prev != pit_type(pars.size())) {
1081 maxasc += int(pars[prev].layout().parsep * dh);
1082 } else if (pit != 0) {
1083 Paragraph const & prevpar = pars[pit - 1];
1084 if (prevpar.getDepth() != 0 ||
1085 prevpar.layout() == layout) {
1086 maxasc += int(layout.parsep * dh);
1091 // is it a bottom line?
1092 if (end >= par.size() && topBottomSpace) {
1093 // add the layout spaces, for example before and after
1094 // a section, or between the items of a itemize or enumerate
1096 pit_type nextpit = pit + 1;
1097 if (nextpit != pit_type(pars.size())) {
1098 pit_type cpit = pit;
1102 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1103 usual = pars[cpit].layout().bottomsep * dh;
1104 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1105 if (pars[cpit].layout() != pars[nextpit].layout()
1106 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1108 unusual = pars[cpit].layout().bottomsep * dh;
1110 layoutdesc = max(unusual, usual);
1111 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1112 if (pars[cpit].layout() != pars[nextpit].layout()
1113 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1114 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1119 // incalculate the layout spaces
1120 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1121 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1123 // FIXME: the correct way is to do the following is to move the
1124 // following code in another method specially tailored for the
1125 // main Text. The following test is thus bogus.
1126 // Top and bottom margin of the document (only at top-level)
1127 if (main_text_ && topBottomSpace) {
1128 if (pit == 0 && first == 0)
1130 if (pit + 1 == pit_type(pars.size()) &&
1131 end == par.size() &&
1132 !(end > 0 && par.isNewline(end - 1)))
1136 return Dimension(0, maxasc + labeladdon, maxdesc);
1140 // x is an absolute screen coord
1141 // returns the column near the specified x-coordinate of the row
1142 // x is set to the real beginning of this column
1143 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1144 Row const & row, int & x, bool & boundary) const
1146 Buffer const & buffer = bv_->buffer();
1148 /// For the main Text, it is possible that this pit is not
1149 /// yet in the CoordCache when moving cursor up.
1150 /// x Paragraph coordinate is always 0 for main text anyway.
1151 int const xo = origin_.x_;
1153 Paragraph const & par = text_->getPar(pit);
1155 bidi.computeTables(par, buffer, row);
1157 pos_type vc = row.pos();
1158 pos_type end = row.endpos();
1160 Layout const & layout = par.layout();
1162 bool left_side = false;
1164 pos_type body_pos = par.beginOfBody();
1166 double tmpx = row.x;
1167 double last_tmpx = tmpx;
1170 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1173 // check for empty row
1179 while (vc < end && tmpx <= x) {
1180 c = bidi.vis2log(vc);
1182 if (body_pos > 0 && c == body_pos - 1) {
1183 FontMetrics const & fm = theFontMetrics(
1184 text_->labelFont(buffer, par));
1185 tmpx += row.label_hfill + fm.width(layout.labelsep);
1186 if (par.isLineSeparator(body_pos - 1))
1187 tmpx -= singleWidth(pit, body_pos - 1);
1190 tmpx += singleWidth(pit, c);
1191 if (par.isSeparator(c) && c >= body_pos)
1192 tmpx += row.separator;
1196 if ((tmpx + last_tmpx) / 2 > x) {
1201 LASSERT(vc <= end, /**/); // This shouldn't happen.
1204 // This (rtl_support test) is not needed, but gives
1205 // some speedup if rtl_support == false
1206 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1208 // If lastrow is false, we don't need to compute
1209 // the value of rtl.
1210 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1212 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1213 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1214 if (!par.isNewline(end - 1))
1216 } else if (vc == row.pos()) {
1217 c = bidi.vis2log(vc);
1218 if (bidi.level(c) % 2 == 1)
1221 c = bidi.vis2log(vc - 1);
1222 bool const rtl = (bidi.level(c) % 2 == 1);
1223 if (left_side == rtl) {
1225 boundary = isRTLBoundary(pit, c);
1229 // I believe this code is not needed anymore (Jug 20050717)
1231 // The following code is necessary because the cursor position past
1232 // the last char in a row is logically equivalent to that before
1233 // the first char in the next row. That's why insets causing row
1234 // divisions -- Newline and display-style insets -- must be treated
1235 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1236 // Newline inset, air gap below:
1237 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1238 if (bidi.level(end -1) % 2 == 0)
1239 tmpx -= singleWidth(pit, end - 1);
1241 tmpx += singleWidth(pit, end - 1);
1245 // Air gap above display inset:
1246 if (row.pos() < end && c >= end && end < par.size()
1247 && par.isInset(end) && par.getInset(end)->display()) {
1250 // Air gap below display inset:
1251 if (row.pos() < end && c >= end && par.isInset(end - 1)
1252 && par.getInset(end - 1)->display()) {
1258 pos_type const col = c - row.pos();
1260 if (!c || end == par.size())
1263 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1268 return min(col, end - 1 - row.pos());
1272 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1274 // We play safe and use parMetrics(pit) to make sure the
1275 // ParagraphMetrics will be redone and OK to use if needed.
1276 // Otherwise we would use an empty ParagraphMetrics in
1277 // upDownInText() while in selection mode.
1278 ParagraphMetrics const & pm = parMetrics(pit);
1280 LASSERT(row < int(pm.rows().size()), /**/);
1282 Row const & r = pm.rows()[row];
1283 return r.pos() + getColumnNearX(pit, r, x, bound);
1287 void TextMetrics::newParMetricsDown()
1289 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1290 pit_type const pit = last.first + 1;
1291 if (pit == int(text_->paragraphs().size()))
1294 // do it and update its position.
1296 par_metrics_[pit].setPosition(last.second.position()
1297 + last.second.descent() + par_metrics_[pit].ascent());
1301 void TextMetrics::newParMetricsUp()
1303 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1304 if (first.first == 0)
1307 pit_type const pit = first.first - 1;
1308 // do it and update its position.
1310 par_metrics_[pit].setPosition(first.second.position()
1311 - first.second.ascent() - par_metrics_[pit].descent());
1314 // y is screen coordinate
1315 pit_type TextMetrics::getPitNearY(int y)
1317 LASSERT(!text_->paragraphs().empty(), return -1);
1318 LASSERT(!par_metrics_.empty(), return -1);
1319 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1321 // look for highest numbered paragraph with y coordinate less than given y
1324 ParMetricsCache::const_iterator it = par_metrics_.begin();
1325 ParMetricsCache::const_iterator et = par_metrics_.end();
1326 ParMetricsCache::const_iterator last = et; last--;
1328 ParagraphMetrics const & pm = it->second;
1330 if (y < it->second.position() - int(pm.ascent())) {
1331 // We are looking for a position that is before the first paragraph in
1332 // the cache (which is in priciple off-screen, that is before the
1335 // We are already at the first paragraph in the inset.
1337 // OK, this is the paragraph we are looking for.
1338 pit = it->first - 1;
1343 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1345 if (y >= last->second.position() + int(pm_last.descent())) {
1346 // We are looking for a position that is after the last paragraph in
1347 // the cache (which is in priciple off-screen), that is before the
1349 pit = last->first + 1;
1350 if (pit == int(text_->paragraphs().size()))
1351 // We are already at the last paragraph in the inset.
1353 // OK, this is the paragraph we are looking for.
1354 newParMetricsDown();
1358 for (; it != et; ++it) {
1359 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1360 << " y: " << it->second.position());
1362 ParagraphMetrics const & pm = par_metrics_[it->first];
1364 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1366 yy = it->second.position();
1370 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1376 Row const & TextMetrics::getPitAndRowNearY(int y, pit_type & pit,
1377 bool assert_in_view, bool up)
1379 ParagraphMetrics const & pm = par_metrics_[pit];
1381 int yy = pm.position() - pm.ascent();
1382 LASSERT(!pm.rows().empty(), /**/);
1383 RowList::const_iterator rit = pm.rows().begin();
1384 RowList::const_iterator rlast = pm.rows().end();
1386 for (; rit != rlast; yy += rit->height(), ++rit)
1387 if (yy + rit->height() > y)
1390 if (assert_in_view && yy + rit->height() != y) {
1392 if (rit != pm.rows().begin())
1394 else if (pit != 0) {
1397 ParagraphMetrics const & pm2 = par_metrics_[pit];
1398 rit = pm2.rows().end();
1404 else if (pit != int(par_metrics_.size())) {
1406 newParMetricsDown();
1407 ParagraphMetrics const & pm2 = par_metrics_[pit];
1408 rit = pm2.rows().begin();
1416 // x,y are absolute screen coordinates
1417 // sets cursor recursively descending into nested editable insets
1418 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1419 bool assert_in_view, bool up)
1421 if (lyxerr.debugging(Debug::WORKAREA)) {
1422 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1423 cur.bv().coordCache().dump();
1425 pit_type pit = getPitNearY(y);
1426 LASSERT(pit != -1, return 0);
1428 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1431 int xx = x; // is modified by getColumnNearX
1432 pos_type const pos = row.pos()
1433 + getColumnNearX(pit, row, xx, bound);
1436 cur.boundary(bound);
1439 // try to descend into nested insets
1440 Inset * inset = checkInsetHit(x, y);
1441 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1443 // Either we deconst editXY or better we move current_font
1444 // and real_current_font to Cursor
1445 // FIXME: what is needed now that current_font and real_current_font
1447 cur.setCurrentFont();
1451 ParagraphList const & pars = text_->paragraphs();
1452 Inset const * insetBefore = pos ? pars[pit].getInset(pos - 1) : 0;
1453 //Inset * insetBehind = pars[pit].getInset(pos);
1455 // This should be just before or just behind the
1456 // cursor position set above.
1457 LASSERT((pos != 0 && inset == insetBefore)
1458 || inset == pars[pit].getInset(pos), /**/);
1460 // Make sure the cursor points to the position before
1462 if (inset == insetBefore) {
1464 cur.boundary(false);
1467 // Try to descend recursively inside the inset.
1468 inset = inset->editXY(cur, x, y);
1470 if (cur.top().text() == text_)
1471 cur.setCurrentFont();
1476 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1478 LASSERT(text_ == cur.text(), /**/);
1479 pit_type pit = getPitNearY(y);
1480 LASSERT(pit != -1, return);
1482 ParagraphMetrics const & pm = par_metrics_[pit];
1484 int yy = pm.position() - pm.ascent();
1485 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1486 " pit: " << pit << " yy: " << yy);
1489 LASSERT(pm.rows().size(), /**/);
1490 for (; r < int(pm.rows().size()) - 1; ++r) {
1491 Row const & row = pm.rows()[r];
1492 if (int(yy + row.height()) > y)
1497 Row const & row = pm.rows()[r];
1499 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1503 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1505 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1507 text_->setCursor(cur, pit, pos, true, bound);
1508 // remember new position.
1513 //takes screen x,y coordinates
1514 Inset * TextMetrics::checkInsetHit(int x, int y)
1516 pit_type pit = getPitNearY(y);
1517 LASSERT(pit != -1, return 0);
1519 Paragraph const & par = text_->paragraphs()[pit];
1520 ParagraphMetrics const & pm = par_metrics_[pit];
1522 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1524 InsetList::const_iterator iit = par.insetList().begin();
1525 InsetList::const_iterator iend = par.insetList().end();
1526 for (; iit != iend; ++iit) {
1527 Inset * inset = iit->inset;
1529 LYXERR(Debug::DEBUG, "examining inset " << inset);
1531 if (!bv_->coordCache().getInsets().has(inset)) {
1532 LYXERR(Debug::DEBUG, "inset has no cached position");
1536 Dimension const & dim = pm.insetDimension(inset);
1537 Point p = bv_->coordCache().getInsets().xy(inset);
1539 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1540 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1543 && x <= p.x_ + dim.wid
1544 && y >= p.y_ - dim.asc
1545 && y <= p.y_ + dim.des) {
1546 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1551 LYXERR(Debug::DEBUG, "No inset hit. ");
1556 int TextMetrics::cursorX(CursorSlice const & sl,
1557 bool boundary) const
1559 LASSERT(sl.text() == text_, /**/);
1560 pit_type const pit = sl.pit();
1561 Paragraph const & par = text_->paragraphs()[pit];
1562 ParagraphMetrics const & pm = par_metrics_[pit];
1563 if (pm.rows().empty())
1566 pos_type ppos = sl.pos();
1567 // Correct position in front of big insets
1568 bool const boundary_correction = ppos != 0 && boundary;
1569 if (boundary_correction)
1572 Row const & row = pm.getRow(sl.pos(), boundary);
1574 pos_type cursor_vpos = 0;
1576 Buffer const & buffer = bv_->buffer();
1579 bidi.computeTables(par, buffer, row);
1581 pos_type const row_pos = row.pos();
1582 pos_type const end = row.endpos();
1583 // Spaces at logical line breaks in bidi text must be skipped during
1584 // cursor positioning. However, they may appear visually in the middle
1585 // of a row; they must be skipped, wherever they are...
1586 // * logically "abc_[HEBREW_\nHEBREW]"
1587 // * visually "abc_[_WERBEH\nWERBEH]"
1588 pos_type skipped_sep_vpos = -1;
1591 cursor_vpos = row_pos;
1592 else if (ppos >= end)
1593 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1594 else if (ppos > row_pos && ppos >= end)
1595 // Place cursor after char at (logical) position pos - 1
1596 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1597 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1599 // Place cursor before char at (logical) position ppos
1600 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1601 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1603 pos_type body_pos = par.beginOfBody();
1605 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1608 // check for possible inline completion in this row
1609 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1610 pos_type inlineCompletionVPos = -1;
1611 if (inlineCompletionPos.inTexted()
1612 && inlineCompletionPos.text() == text_
1613 && inlineCompletionPos.pit() == pit
1614 && inlineCompletionPos.pos() - 1 >= row_pos
1615 && inlineCompletionPos.pos() - 1 < end) {
1616 // draw logically behind the previous character
1617 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1620 // Use font span to speed things up, see below
1624 // If the last logical character is a separator, skip it, unless
1625 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1626 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1627 skipped_sep_vpos = bidi.log2vis(end - 1);
1629 // Inline completion RTL special case row_pos == cursor_pos:
1630 // "__|b" => cursor_pos is right of __
1631 if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1632 font = displayFont(pit, row_pos + 1);
1633 docstring const & completion = bv_->inlineCompletion();
1634 if (font.isRightToLeft() && completion.length() > 0)
1635 x += theFontMetrics(font.fontInfo()).width(completion);
1638 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1639 // Skip the separator which is at the logical end of the row
1640 if (vpos == skipped_sep_vpos)
1642 pos_type pos = bidi.vis2log(vpos);
1643 if (body_pos > 0 && pos == body_pos - 1) {
1644 FontMetrics const & labelfm = theFontMetrics(
1645 text_->labelFont(buffer, par));
1646 x += row.label_hfill + labelfm.width(par.layout().labelsep);
1647 if (par.isLineSeparator(body_pos - 1))
1648 x -= singleWidth(pit, body_pos - 1);
1651 // Use font span to speed things up, see above
1652 if (pos < font_span.first || pos > font_span.last) {
1653 font_span = par.fontSpan(pos);
1654 font = displayFont(pit, pos);
1657 x += pm.singleWidth(pos, font);
1659 // Inline completion RTL case:
1660 // "a__|b", __ of b => non-boundary a-pos is right of __
1661 if (vpos + 1 == inlineCompletionVPos
1662 && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1663 font = displayFont(pit, vpos + 1);
1664 docstring const & completion = bv_->inlineCompletion();
1665 if (font.isRightToLeft() && completion.length() > 0)
1666 x += theFontMetrics(font.fontInfo()).width(completion);
1669 // Inline completion LTR case:
1670 // "b|__a", __ of b => non-boundary a-pos is in front of __
1671 if (vpos == inlineCompletionVPos
1672 && (vpos + 1 < cursor_vpos || boundary_correction)) {
1673 font = displayFont(pit, vpos);
1674 docstring const & completion = bv_->inlineCompletion();
1675 if (!font.isRightToLeft() && completion.length() > 0)
1676 x += theFontMetrics(font.fontInfo()).width(completion);
1679 if (par.isSeparator(pos) && pos >= body_pos)
1683 // see correction above
1684 if (boundary_correction) {
1685 if (isRTL(sl, boundary))
1686 x -= singleWidth(pit, ppos);
1688 x += singleWidth(pit, ppos);
1695 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1697 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1698 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1699 if (pm.rows().empty())
1703 h -= par_metrics_[0].rows()[0].ascent();
1704 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1705 h += par_metrics_[pit].height();
1708 if (pos && boundary)
1710 size_t const rend = pm.pos2row(pos);
1711 for (size_t rit = 0; rit != rend; ++rit)
1712 h += pm.rows()[rit].height();
1713 h += pm.rows()[rend].ascent();
1718 // the cursor set functions have a special mechanism. When they
1719 // realize you left an empty paragraph, they will delete it.
1721 bool TextMetrics::cursorHome(Cursor & cur)
1723 LASSERT(text_ == cur.text(), /**/);
1724 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1725 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1726 return text_->setCursor(cur, cur.pit(), row.pos());
1730 bool TextMetrics::cursorEnd(Cursor & cur)
1732 LASSERT(text_ == cur.text(), /**/);
1733 // if not on the last row of the par, put the cursor before
1734 // the final space exept if I have a spanning inset or one string
1735 // is so long that we force a break.
1736 pos_type end = cur.textRow().endpos();
1738 // empty text, end-1 is no valid position
1740 bool boundary = false;
1741 if (end != cur.lastpos()) {
1742 if (!cur.paragraph().isLineSeparator(end-1)
1743 && !cur.paragraph().isNewline(end-1))
1748 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1752 void TextMetrics::deleteLineForward(Cursor & cur)
1754 LASSERT(text_ == cur.text(), /**/);
1755 if (cur.lastpos() == 0) {
1756 // Paragraph is empty, so we just go forward
1757 text_->cursorForward(cur);
1760 cur.setSelection(true); // to avoid deletion
1763 // What is this test for ??? (JMarc)
1764 if (!cur.selection())
1765 text_->deleteWordForward(cur);
1767 cap::cutSelection(cur, true, false);
1768 cur.checkBufferStructure();
1773 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1775 ParagraphList const & pars = text_->paragraphs();
1776 return row.endpos() >= pars[pit].size()
1777 && pit + 1 == pit_type(pars.size());
1781 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1783 return row.pos() == 0 && pit == 0;
1787 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1789 LASSERT(pit >= 0, /**/);
1790 LASSERT(pit < int(text_->paragraphs().size()), /**/);
1791 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1795 int TextMetrics::leftMargin(int max_width,
1796 pit_type const pit, pos_type const pos) const
1798 ParagraphList const & pars = text_->paragraphs();
1800 LASSERT(pit >= 0, /**/);
1801 LASSERT(pit < int(pars.size()), /**/);
1802 Paragraph const & par = pars[pit];
1803 LASSERT(pos >= 0, /**/);
1804 LASSERT(pos <= par.size(), /**/);
1805 Buffer const & buffer = bv_->buffer();
1806 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1807 DocumentClass const & tclass = buffer.params().documentClass();
1808 Layout const & layout = par.layout();
1810 docstring parindent = layout.parindent;
1814 if (text_->isMainText(buffer))
1815 l_margin += bv_->leftMargin();
1817 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1818 tclass.leftmargin());
1820 if (par.getDepth() != 0) {
1821 // find the next level paragraph
1822 pit_type newpar = outerHook(pit, pars);
1823 if (newpar != pit_type(pars.size())) {
1824 if (pars[newpar].layout().isEnvironment()) {
1825 l_margin = leftMargin(max_width, newpar);
1827 if (tclass.isDefaultLayout(par.layout())
1828 || tclass.isPlainLayout(par.layout())) {
1829 if (pars[newpar].params().noindent())
1832 parindent = pars[newpar].layout().parindent;
1837 // This happens after sections in standard classes. The 1.3.x
1838 // code compared depths too, but it does not seem necessary
1840 if (tclass.isDefaultLayout(par.layout())
1841 && pit > 0 && pars[pit - 1].layout().nextnoindent)
1844 FontInfo const labelfont = text_->labelFont(buffer, par);
1845 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1847 switch (layout.margintype) {
1848 case MARGIN_DYNAMIC:
1849 if (!layout.leftmargin.empty()) {
1850 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1853 if (!par.labelString().empty()) {
1854 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1855 l_margin += labelfont_metrics.width(par.labelString());
1856 l_margin += labelfont_metrics.width(layout.labelsep);
1860 case MARGIN_MANUAL: {
1861 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1862 // The width of an empty par, even with manual label, should be 0
1863 if (!par.empty() && pos >= par.beginOfBody()) {
1864 if (!par.getLabelWidthString().empty()) {
1865 docstring labstr = par.getLabelWidthString();
1866 l_margin += labelfont_metrics.width(labstr);
1867 l_margin += labelfont_metrics.width(layout.labelsep);
1873 case MARGIN_STATIC: {
1874 l_margin += theFontMetrics(buffer.params().getFont()).
1875 signedWidth(layout.leftmargin) * 4 / (par.getDepth() + 4);
1879 case MARGIN_FIRST_DYNAMIC:
1880 if (layout.labeltype == LABEL_MANUAL) {
1881 // if we are at position 0, we are never in the body
1882 if (pos > 0 && pos >= par.beginOfBody())
1883 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1885 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1887 // Special case to fix problems with
1889 || (layout.labeltype == LABEL_STATIC
1890 && layout.latextype == LATEX_ENVIRONMENT
1891 && !isFirstInSequence(pit, pars))) {
1892 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1893 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
1894 && layout.labeltype != LABEL_BIBLIO
1895 && layout.labeltype !=
1896 LABEL_CENTERED_TOP_ENVIRONMENT) {
1897 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1898 l_margin += labelfont_metrics.width(layout.labelsep);
1899 l_margin += labelfont_metrics.width(par.labelString());
1903 case MARGIN_RIGHT_ADDRESS_BOX: {
1905 // ok, a terrible hack. The left margin depends on the widest
1906 // row in this paragraph.
1907 RowList::iterator rit = par.rows().begin();
1908 RowList::iterator end = par.rows().end();
1909 // FIXME: This is wrong.
1910 int minfill = max_width;
1911 for ( ; rit != end; ++rit)
1912 if (rit->fill() < minfill)
1913 minfill = rit->fill();
1914 l_margin += theFontMetrics(params.getFont()).signedWidth(layout.leftmargin);
1915 l_margin += minfill;
1917 // also wrong, but much shorter.
1918 l_margin += max_width / 2;
1923 if (!par.params().leftIndent().zero())
1924 l_margin += par.params().leftIndent().inPixels(max_width);
1928 if (par.params().align() == LYX_ALIGN_LAYOUT)
1929 align = layout.align;
1931 align = par.params().align();
1933 // set the correct parindent
1935 && (layout.labeltype == LABEL_NO_LABEL
1936 || layout.labeltype == LABEL_TOP_ENVIRONMENT
1937 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1938 || (layout.labeltype == LABEL_STATIC
1939 && layout.latextype == LATEX_ENVIRONMENT
1940 && !isFirstInSequence(pit, pars)))
1941 && align == LYX_ALIGN_BLOCK
1942 && !par.params().noindent()
1943 // in some insets, paragraphs are never indented
1944 && !par.inInset().neverIndent()
1945 // display style insets are always centered, omit indentation
1948 && par.getInset(pos)->display())
1949 && (!(tclass.isDefaultLayout(par.layout())
1950 || tclass.isPlainLayout(par.layout()))
1951 || buffer.params().paragraph_separation == BufferParams::ParagraphIndentSeparation)
1954 // use the parindent of the layout when the default indentation is used
1955 // otherwise use the indentation set in the document settings
1956 if (buffer.params().getIndentation().asLyXCommand() == "default")
1957 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1960 l_margin += buffer.params().getIndentation().inPixels(*bv_);
1967 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1969 ParagraphMetrics const & pm = par_metrics_[pit];
1971 return pm.singleWidth(pos, displayFont(pit, pos));
1975 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1977 if (par_metrics_.empty())
1983 ParMetricsCache::iterator it = par_metrics_.begin();
1984 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1985 y -= it->second.ascent();
1986 for (; it != pm_end; ++it) {
1987 ParagraphMetrics const & pmi = it->second;
1989 pit_type const pit = it->first;
1990 // Save the paragraph position in the cache.
1991 it->second.setPosition(y);
1992 drawParagraph(pi, pit, x, y);
1998 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
2000 BufferParams const & bparams = bv_->buffer().params();
2001 ParagraphMetrics const & pm = par_metrics_[pit];
2002 if (pm.rows().empty())
2006 bool const original_drawing_state = pi.pain.isDrawingEnabled();
2007 int const ww = bv_->workHeight();
2008 size_t const nrows = pm.rows().size();
2010 Cursor const & cur = bv_->cursor();
2011 DocIterator sel_beg = cur.selectionBegin();
2012 DocIterator sel_end = cur.selectionEnd();
2013 bool selection = cur.selection()
2014 // This is our text.
2015 && cur.text() == text_
2016 // if the anchor is outside, this is not our selection
2017 && cur.anchor().text() == text_
2018 && pit >= sel_beg.pit() && pit <= sel_end.pit();
2020 // We store the begin and end pos of the selection relative to this par
2021 DocIterator sel_beg_par = cur.selectionBegin();
2022 DocIterator sel_end_par = cur.selectionEnd();
2024 // We care only about visible selection.
2026 if (pit != sel_beg.pit()) {
2027 sel_beg_par.pit() = pit;
2028 sel_beg_par.pos() = 0;
2030 if (pit != sel_end.pit()) {
2031 sel_end_par.pit() = pit;
2032 sel_end_par.pos() = sel_end_par.lastpos();
2036 for (size_t i = 0; i != nrows; ++i) {
2038 Row const & row = pm.rows()[i];
2042 bool const inside = (y + row.descent() >= 0
2043 && y - row.ascent() < ww);
2044 // It is not needed to draw on screen if we are not inside.
2045 pi.pain.setDrawingEnabled(inside && original_drawing_state);
2046 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
2049 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2051 row.setSelection(-1, -1);
2053 // The row knows nothing about the paragraph, so we have to check
2054 // whether this row is the first or last and update the margins.
2055 if (row.selection()) {
2056 if (row.sel_beg == 0)
2057 row.begin_margin_sel = sel_beg.pit() < pit;
2058 if (row.sel_end == sel_end_par.lastpos())
2059 row.end_margin_sel = sel_end.pit() > pit;
2062 // Row signature; has row changed since last paint?
2063 row.setCrc(pm.computeRowSignature(row, bparams));
2064 bool row_has_changed = row.changed();
2066 // Don't paint the row if a full repaint has not been requested
2067 // and if it has not changed.
2068 if (!pi.full_repaint && !row_has_changed) {
2069 // Paint only the insets if the text itself is
2071 rp.paintOnlyInsets();
2076 // Clear background of this row if paragraph background was not
2077 // already cleared because of a full repaint.
2078 if (!pi.full_repaint && row_has_changed) {
2079 pi.pain.fillRectangle(x, y - row.ascent(),
2080 width(), row.height(), pi.background_color);
2083 if (row.selection())
2084 drawRowSelection(pi, x, row, cur, pit);
2086 // Instrumentation for testing row cache (see also
2088 if (lyxerr.debugging(Debug::PAINTING) && inside
2089 && (row.selection() || pi.full_repaint || row_has_changed)) {
2090 string const foreword = text_->isMainText(bv_->buffer()) ?
2091 "main text redraw " : "inset text redraw: ";
2092 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
2093 << " row_selection=" << row.selection()
2094 << " full_repaint=" << pi.full_repaint
2095 << " row_has_changed=" << row_has_changed);
2098 // Backup full_repaint status and force full repaint
2099 // for inner insets as the Row has been cleared out.
2100 bool tmp = pi.full_repaint;
2101 pi.full_repaint = true;
2104 rp.paintChangeBar();
2111 // Restore full_repaint status.
2112 pi.full_repaint = tmp;
2114 // Re-enable screen drawing for future use of the painter.
2115 pi.pain.setDrawingEnabled(original_drawing_state);
2117 //LYXERR(Debug::PAINTING, ".");
2121 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2122 Cursor const & curs, pit_type pit) const
2124 DocIterator beg = curs.selectionBegin();
2126 beg.pos() = row.sel_beg;
2128 DocIterator end = curs.selectionEnd();
2130 end.pos() = row.sel_end;
2132 bool const begin_boundary = beg.pos() >= row.endpos();
2133 bool const end_boundary = row.sel_end == row.endpos();
2135 Buffer & buffer = bv_->buffer();
2136 DocIterator cur = beg;
2137 cur.boundary(begin_boundary);
2138 int x1 = cursorX(beg.top(), begin_boundary);
2139 int x2 = cursorX(end.top(), end_boundary);
2140 int const y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2141 int const y2 = y1 + row.height();
2143 int const rm = text_->isMainText(buffer) ? bv_->rightMargin() : 0;
2144 int const lm = text_->isMainText(buffer) ? bv_->leftMargin() : 0;
2147 if (row.begin_margin_sel) {
2148 if (text_->isRTL(buffer, beg.paragraph())) {
2149 pi.pain.fillRectangle(x + x1, y1, width() - rm - x1, y2 - y1,
2152 pi.pain.fillRectangle(x + lm, y1, x1 - lm, y2 - y1,
2157 if (row.end_margin_sel) {
2158 if (text_->isRTL(buffer, beg.paragraph())) {
2159 pi.pain.fillRectangle(x + lm, y1, x2 - lm, y2 - y1,
2162 pi.pain.fillRectangle(x + x2, y1, width() - rm - x2, y2 - y1,
2167 // if we are on a boundary from the beginning, it's probably
2168 // a RTL boundary and we jump to the other side directly as this
2169 // segement is 0-size and confuses the logic below
2171 cur.boundary(false);
2173 // go through row and draw from RTL boundary to RTL boundary
2175 bool drawNow = false;
2177 // simplified cursorForward code below which does not
2178 // descend into insets and which does not go into the
2179 // next line. Compare the logic with the original cursorForward
2181 // if left of boundary -> just jump to right side, but
2182 // for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2183 if (cur.boundary()) {
2184 cur.boundary(false);
2185 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2186 // in front of RTL boundary -> Stay on this side of the boundary
2187 // because: ab|cDDEEFFghi -> abc|DDEEFFghi
2196 if (cur.pos() == row.endpos())
2201 // the previous segment was just drawn, now the next starts
2202 x1 = cursorX(cur.top(), cur.boundary());
2205 if (!(cur < end) || drawNow) {
2206 x2 = cursorX(cur.top(), cur.boundary());
2207 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2210 // reset x1, so it is set again next round (which will be on the
2211 // right side of a boundary or at the selection end)
2218 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2219 Dimension & dim) const
2221 Cursor const & bvcur = cur.bv().cursor();
2223 // get word in front of cursor
2224 docstring word = text_->previousWord(bvcur.top());
2225 DocIterator wordStart = bvcur;
2226 wordStart.pos() -= word.length();
2228 // get position on screen of the word start and end
2229 Point lxy = cur.bv().getPos(wordStart, false);
2230 Point rxy = cur.bv().getPos(bvcur, bvcur.boundary());
2232 // calculate dimensions of the word
2233 dim = rowHeight(bvcur.pit(), wordStart.pos(), bvcur.pos(), false);
2234 dim.wid = abs(rxy.x_ - lxy.x_);
2236 // calculate position of word
2238 x = min(rxy.x_, lxy.x_);
2240 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2241 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2244 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2246 // ParagraphMetrics const & pm = par_metrics_[pit];
2247 // Row const & r = pm.rows()[row];
2253 int defaultRowHeight()
2255 return int(theFontMetrics(sane_font).maxHeight() * 1.2);