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 "insets/InsetText.h"
47 #include "mathed/MacroTable.h"
48 #include "mathed/MathMacroTemplate.h"
50 #include "frontends/FontMetrics.h"
51 #include "frontends/Painter.h"
53 #include "support/debug.h"
55 #include "support/lassert.h"
62 using frontend::FontMetrics;
64 static int numberOfSeparators(Paragraph const & par, Row const & row)
66 pos_type const first = max(row.pos(), par.beginOfBody());
67 pos_type const last = row.endpos() - 1;
69 for (pos_type p = first; p < last; ++p) {
70 if (par.isSeparator(p))
77 static int numberOfLabelHfills(Paragraph const & par, Row const & row)
79 pos_type last = row.endpos() - 1;
80 pos_type first = row.pos();
82 // hfill *DO* count at the beginning of paragraphs!
84 while (first < last && par.isHfill(first))
88 last = min(last, par.beginOfBody());
90 for (pos_type p = first; p < last; ++p) {
98 static int numberOfHfills(Paragraph const & par, Row const & row)
100 pos_type const last = row.endpos();
101 pos_type first = row.pos();
103 // hfill *DO* count at the beginning of paragraphs!
105 while (first < last && par.isHfill(first))
109 first = max(first, par.beginOfBody());
112 for (pos_type p = first; p < last; ++p) {
120 /////////////////////////////////////////////////////////////////////
124 /////////////////////////////////////////////////////////////////////
127 TextMetrics::TextMetrics(BufferView * bv, Text * text)
128 : bv_(bv), text_(text)
131 max_width_ = bv_->workWidth();
132 dim_.wid = max_width_;
136 //text_->updateLabels(bv->buffer());
140 bool TextMetrics::contains(pit_type pit) const
142 return par_metrics_.find(pit) != par_metrics_.end();
146 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
148 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
153 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
155 ParMetricsCache::const_iterator it = par_metrics_.begin();
156 return make_pair(it->first, &it->second);
160 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
162 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
163 return make_pair(it->first, &it->second);
167 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
169 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
170 if (pmc_it == par_metrics_.end()) {
171 pmc_it = par_metrics_.insert(
172 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
174 if (pmc_it->second.rows().empty() && redo)
176 return pmc_it->second;
180 int TextMetrics::parPosition(pit_type pit) const
182 if (pit < par_metrics_.begin()->first)
184 if (pit > par_metrics_.rbegin()->first)
187 return par_metrics_[pit].position();
191 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
193 LASSERT(mi.base.textwidth > 0, /**/);
194 max_width_ = mi.base.textwidth;
195 // backup old dimension.
196 Dimension const old_dim = dim_;
199 dim_.wid = min_width;
200 pit_type const npar = text_->paragraphs().size();
202 // If there is more than one row, expand the text to
203 // the full allowable width.
204 dim_.wid = max_width_;
206 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
207 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
209 bool changed = false;
211 for (pit_type pit = 0; pit != npar; ++pit) {
212 changed |= redoParagraph(pit);
213 ParagraphMetrics const & pm = par_metrics_[pit];
215 if (dim_.wid < pm.width())
216 dim_.wid = pm.width();
219 dim_.asc = par_metrics_[0].ascent();
220 dim_.des = h - dim_.asc;
221 //lyxerr << "dim_.wid " << dim_.wid << endl;
222 //lyxerr << "dim_.asc " << dim_.asc << endl;
223 //lyxerr << "dim_.des " << dim_.des << endl;
225 changed |= dim_ != old_dim;
231 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
233 return main_text_? pm.rightMargin(*bv_) : 0;
237 int TextMetrics::rightMargin(pit_type const pit) const
239 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
243 void TextMetrics::applyOuterFont(Font & font) const
246 lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
247 lf.fontInfo().realize(font.fontInfo());
248 lf.setLanguage(font.language());
253 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
255 LASSERT(pos >= 0, /**/);
257 ParagraphList const & pars = text_->paragraphs();
258 Paragraph const & par = pars[pit];
259 Layout const & layout = par.layout();
260 Buffer const & buffer = bv_->buffer();
262 BufferParams const & params = buffer.params();
263 pos_type const body_pos = par.beginOfBody();
265 // We specialize the 95% common case:
266 if (!par.getDepth()) {
267 Font f = par.getFontSettings(params, pos);
268 if (!text_->isMainText())
270 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
272 FontInfo const & lf = lab ? layout.labelfont : layout.font;
273 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
275 // In case the default family has been customized
276 if (lf.family() == INHERIT_FAMILY)
277 rlf.setFamily(params.getFont().fontInfo().family());
278 f.fontInfo().realize(rlf);
282 // The uncommon case need not be optimized as much
283 FontInfo const & layoutfont = pos < body_pos ?
284 layout.labelfont : layout.font;
286 Font font = par.getFontSettings(params, pos);
287 font.fontInfo().realize(layoutfont);
289 if (!text_->isMainText())
290 applyOuterFont(font);
292 // Realize against environment font information
293 // NOTE: the cast to pit_type should be removed when pit_type
294 // changes to a unsigned integer.
295 if (pit < pit_type(pars.size()))
296 font.fontInfo().realize(outerFont(pit, pars).fontInfo());
298 // Realize with the fonts of lesser depth.
299 font.fontInfo().realize(params.getFont().fontInfo());
305 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
307 if (!lyxrc.rtl_support || !sl.text())
311 if (boundary && sl.pos() > 0)
314 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
318 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
320 if (!lyxrc.rtl_support)
323 // no RTL boundary at paragraph start
327 Font const & left_font = displayFont(pit, pos - 1);
329 return isRTLBoundary(pit, pos, left_font);
333 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
334 Font const & font) const
336 if (!lyxrc.rtl_support)
339 // no RTL boundary at paragraph start
343 ParagraphMetrics & pm = par_metrics_[pit];
344 // no RTL boundary in empty paragraph
345 if (pm.rows().empty())
348 pos_type endpos = pm.getRow(pos - 1, false).endpos();
349 pos_type startpos = pm.getRow(pos, false).pos();
350 // no RTL boundary at line start:
351 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
353 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
356 Paragraph const & par = text_->getPar(pit);
357 bool left = font.isVisibleRightToLeft();
359 if (pos == par.size())
360 right = par.isRTL(bv_->buffer().params());
362 right = displayFont(pit, pos).isVisibleRightToLeft();
364 // no RTL boundary at line break:
365 // abc|\n -> move right -> abc\n (and not: abc\n|
367 if (startpos == pos && endpos == pos && endpos != par.size()
368 && (par.isNewline(pos - 1)
369 || par.isLineSeparator(pos - 1)
370 || par.isSeparator(pos - 1)))
373 return left != right;
377 bool TextMetrics::redoParagraph(pit_type const pit)
379 Paragraph & par = text_->getPar(pit);
380 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
381 // redoParagraph() recursively inside parMetrics.
382 Dimension old_dim = parMetrics(pit, false).dim();
383 ParagraphMetrics & pm = par_metrics_[pit];
386 Buffer & buffer = bv_->buffer();
387 main_text_ = (text_ == &buffer.text());
388 bool changed = false;
390 // FIXME: This check ought to be done somewhere else. It is the reason
391 // why text_ is not const. But then, where else to do it?
392 // Well, how can you end up with either (a) a biblio environment that
393 // has no InsetBibitem or (b) a biblio environment with more than one
394 // InsetBibitem? I think the answer is: when paragraphs are merged;
395 // when layout is set; when material is pasted.
396 int const moveCursor = par.checkBiblio(buffer);
398 const_cast<Cursor &>(bv_->cursor()).posForward();
399 else if (moveCursor < 0) {
400 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
401 if (cursor.pos() >= -moveCursor)
402 cursor.posBackward();
405 // Optimisation: this is used in the next two loops
406 // so better to calculate that once here.
407 int const right_margin = rightMargin(pm);
409 // iterator pointing to paragraph to resolve macros
410 DocIterator parPos = text_->macrocontextPosition();
414 LYXERR(Debug::INFO, "MacroContext not initialised!"
415 << " Going through the buffer again and hope"
416 << " the context is better then.");
417 bv_->buffer().updateLabels();
418 parPos = text_->macrocontextPosition();
419 LASSERT(!parPos.empty(), /**/);
424 // FIXME: We should always use getFont(), see documentation of
425 // noFontChange() in Inset.h.
426 Font const bufferfont = buffer.params().getFont();
427 InsetList::const_iterator ii = par.insetList().begin();
428 InsetList::const_iterator iend = par.insetList().end();
429 for (; ii != iend; ++ii) {
430 // position already initialized?
431 if (!parPos.empty()) {
432 parPos.pos() = ii->pos;
434 // A macro template would normally not be visible
435 // by itself. But the tex macro semantics allow
436 // recursion, so we artifically take the context
437 // after the macro template to simulate this.
438 if (ii->inset->lyxCode() == MATHMACRO_CODE)
442 // do the metric calculation
444 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
446 Font const & font = ii->inset->noFontChange() ?
447 bufferfont : displayFont(pit, ii->pos);
448 MacroContext mc(buffer, parPos);
449 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
450 ii->inset->metrics(mi, dim);
451 Dimension const old_dim = pm.insetDimension(ii->inset);
452 if (old_dim != dim) {
453 pm.setInsetDimension(ii->inset, dim);
458 par.setBeginOfBody();
460 size_t row_index = 0;
461 // maximum pixel width of a row
462 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
465 pos_type end = rowBreakPoint(width, pit, first);
466 if (row_index || end < par.size())
467 // If there is more than one row, expand the text to
468 // the full allowable width. This setting here is needed
469 // for the computeRowMetrics() below.
470 dim_.wid = max_width_;
472 dim = rowHeight(pit, first, end);
473 dim.wid = rowWidth(right_margin, pit, first, end);
474 if (row_index == pm.rows().size())
475 pm.rows().push_back(Row());
476 Row & row = pm.rows()[row_index];
477 row.setChanged(false);
480 row.setDimension(dim);
481 int const max_row_width = max(dim_.wid, dim.wid);
482 computeRowMetrics(pit, row, max_row_width);
486 pm.dim().wid = max(pm.dim().wid, dim.wid);
487 pm.dim().des += dim.height();
488 } while (first < par.size());
490 if (row_index < pm.rows().size())
491 pm.rows().resize(row_index);
493 // Make sure that if a par ends in newline, there is one more row
495 if (first > 0 && par.isNewline(first - 1)) {
496 Dimension dim = rowHeight(pit, first, first);
497 dim.wid = rowWidth(right_margin, pit, first, first);
498 if (row_index == pm.rows().size())
499 pm.rows().push_back(Row());
500 Row & row = pm.rows()[row_index];
501 row.setChanged(false);
504 row.setDimension(dim);
505 int const max_row_width = max(dim_.wid, dim.wid);
506 computeRowMetrics(pit, row, max_row_width);
507 pm.dim().des += dim.height();
510 pm.dim().asc += pm.rows()[0].ascent();
511 pm.dim().des -= pm.rows()[0].ascent();
513 changed |= old_dim.height() != pm.dim().height();
519 void TextMetrics::computeRowMetrics(pit_type const pit,
520 Row & row, int width) const
525 Paragraph const & par = text_->getPar(pit);
527 double w = width - row.width();
528 // FIXME: put back this assertion when the crash on new doc is solved.
529 //LASSERT(w >= 0, /**/);
531 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
532 //lyxerr << "row.width() " << row.width() << endl;
533 //lyxerr << "w " << w << endl;
535 bool const is_rtl = text_->isRTL(par);
537 row.x = rightMargin(pit);
539 row.x = leftMargin(max_width_, pit, row.pos());
541 // is there a manual margin with a manual label
542 Layout const & layout = par.layout();
544 if (layout.margintype == MARGIN_MANUAL
545 && layout.labeltype == LABEL_MANUAL) {
546 /// We might have real hfills in the label part
547 int nlh = numberOfLabelHfills(par, row);
549 // A manual label par (e.g. List) has an auto-hfill
550 // between the label text and the body of the
552 // But we don't want to do this auto hfill if the par
557 if (nlh && !par.getLabelWidthString().empty())
558 row.label_hfill = labelFill(pit, row) / double(nlh);
562 // are there any hfills in the row?
563 if (int const nh = numberOfHfills(par, row)) {
565 hfill = w / double(nh);
566 // we don't have to look at the alignment if it is ALIGN_LEFT and
567 // if the row is already larger then the permitted width as then
568 // we force the LEFT_ALIGN'edness!
569 } else if (int(row.width()) < max_width_) {
570 // is it block, flushleft or flushright?
571 // set x how you need it
573 if (par.params().align() == LYX_ALIGN_LAYOUT)
574 align = layout.align;
576 align = par.params().align();
578 // handle alignment inside tabular cells
579 Inset const & owner = par.inInset();
580 switch (owner.contentAlignment()) {
581 case LYX_ALIGN_CENTER:
583 case LYX_ALIGN_RIGHT:
584 if (align == LYX_ALIGN_NONE
585 || align == LYX_ALIGN_BLOCK)
586 align = owner.contentAlignment();
589 // unchanged (use align)
593 // Display-style insets should always be on a centered row
594 if (Inset const * inset = par.getInset(row.pos())) {
595 switch (inset->display()) {
596 case Inset::AlignLeft:
597 align = LYX_ALIGN_BLOCK;
599 case Inset::AlignCenter:
600 align = LYX_ALIGN_CENTER;
603 // unchanged (use align)
605 case Inset::AlignRight:
606 align = LYX_ALIGN_RIGHT;
612 case LYX_ALIGN_BLOCK: {
613 int const ns = numberOfSeparators(par, row);
614 bool disp_inset = false;
615 if (row.endpos() < par.size()) {
616 Inset const * in = par.getInset(row.endpos());
618 disp_inset = in->display();
620 // If we have separators, this is not the last row of a
621 // par, does not end in newline, and is not row above a
622 // display inset... then stretch it
624 && row.endpos() < par.size()
625 && !par.isNewline(row.endpos() - 1)
628 row.separator = w / ns;
629 //lyxerr << "row.separator " << row.separator << endl;
630 //lyxerr << "ns " << ns << endl;
636 case LYX_ALIGN_RIGHT:
639 case LYX_ALIGN_CENTER:
646 pos_type body_pos = par.beginOfBody();
647 pos_type end = row.endpos();
650 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
652 row.x += theFontMetrics(text_->labelFont(par)).
653 width(layout.labelsep);
655 row.x += row.label_hfill;
659 pos_type const endpos = row.endpos();
660 pos_type body_pos = par.beginOfBody();
662 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
665 ParagraphMetrics & pm = par_metrics_[pit];
666 InsetList::const_iterator ii = par.insetList().begin();
667 InsetList::const_iterator iend = par.insetList().end();
668 for ( ; ii != iend; ++ii) {
669 if (ii->pos >= endpos || ii->pos < row.pos()
670 || (ii->inset->lyxCode() != SPACE_CODE ||
671 !ii->inset->isStretchableSpace()))
673 Dimension dim = row.dimension();
674 if (pm.hfillExpansion(row, ii->pos))
675 dim.wid = int(ii->pos >= body_pos ?
676 max(hfill, 5.0) : row.label_hfill);
679 // Cache the inset dimension.
680 bv_->coordCache().insets().add(ii->inset, dim);
681 pm.setInsetDimension(ii->inset, dim);
686 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
688 Paragraph const & par = text_->getPar(pit);
690 pos_type last = par.beginOfBody();
691 LASSERT(last > 0, /**/);
693 // -1 because a label ends with a space that is in the label
696 // a separator at this end does not count
697 if (par.isLineSeparator(last))
701 for (pos_type i = row.pos(); i <= last; ++i)
702 w += singleWidth(pit, i);
704 docstring const & label = par.params().labelWidthString();
708 FontMetrics const & fm
709 = theFontMetrics(text_->labelFont(par));
711 return max(0, fm.width(label) - w);
715 // this needs special handling - only newlines count as a break point
716 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
718 pos_type const end = par.size();
721 if (par.isNewline(i))
728 int TextMetrics::labelEnd(pit_type const pit) const
730 // labelEnd is only needed if the layout fills a flushleft label.
731 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
733 // return the beginning of the body
734 return leftMargin(max_width_, pit);
740 * Calling Text::getFont is slow. While rebreaking we scan a
741 * paragraph from left to right calling getFont for every char. This
742 * simple class address this problem by hidding an optimization trick
743 * (not mine btw -AB): the font is reused in the whole font span. The
744 * class handles transparently the "hidden" (not part of the fontlist)
745 * label font (as getFont does).
751 FontIterator(TextMetrics const & tm,
752 Paragraph const & par, pit_type pit, pos_type pos)
753 : tm_(tm), par_(par), pit_(pit), pos_(pos),
754 font_(tm.displayFont(pit, pos)),
755 endspan_(par.fontSpan(pos).last),
756 bodypos_(par.beginOfBody())
760 Font const & operator*() const { return font_; }
763 FontIterator & operator++()
766 if (pos_ > endspan_ || pos_ == bodypos_) {
767 font_ = tm_.displayFont(pit_, pos_);
768 endspan_ = par_.fontSpan(pos_).last;
774 Font * operator->() { return &font_; }
778 TextMetrics const & tm_;
780 Paragraph const & par_;
795 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
798 ParagraphMetrics const & pm = par_metrics_[pit];
799 Paragraph const & par = text_->getPar(pit);
800 pos_type const end = par.size();
801 if (pos == end || width < 0)
804 Layout const & layout = par.layout();
806 if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX)
807 return addressBreakPoint(pos, par);
809 pos_type const body_pos = par.beginOfBody();
811 // check for possible inline completion
812 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
813 pos_type inlineCompletionLPos = -1;
814 if (inlineCompletionPos.inTexted()
815 && inlineCompletionPos.text() == text_
816 && inlineCompletionPos.pit() == pit) {
817 // draw logically behind the previous character
818 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
821 // Now we iterate through until we reach the right margin
822 // or the end of the par, then choose the possible break
825 int label_end = labelEnd(pit);
826 int const left = leftMargin(max_width_, pit, pos);
829 // pixel width since last breakpoint
832 FontIterator fi = FontIterator(*this, par, pit, pos);
833 pos_type point = end;
835 for ( ; i < end; ++i, ++fi) {
836 int thiswidth = pm.singleWidth(i, *fi);
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);
950 w += pm.singleWidth(i, *fi);
952 // add inline completion width
953 if (inlineCompletionLPos == i) {
954 docstring const & completion = bv_->inlineCompletion();
955 if (completion.length() > 0)
956 w += theFontMetrics(*fi).width(completion);
961 if (body_pos > 0 && body_pos >= end) {
962 FontMetrics const & fm = theFontMetrics(
963 text_->labelFont(par));
964 w += fm.width(par.layout().labelsep);
965 if (end > 0 && par.isLineSeparator(end - 1))
966 w -= singleWidth(pit, end - 1);
967 w = max(w, label_end);
970 return w + right_margin;
974 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
975 pos_type const end, bool topBottomSpace) const
977 Paragraph const & par = text_->getPar(pit);
978 // get the maximum ascent and the maximum descent
979 double layoutasc = 0;
980 double layoutdesc = 0;
981 double const dh = defaultRowHeight();
983 // ok, let us initialize the maxasc and maxdesc value.
984 // Only the fontsize count. The other properties
985 // are taken from the layoutfont. Nicer on the screen :)
986 Layout const & layout = par.layout();
988 // as max get the first character of this row then it can
989 // increase but not decrease the height. Just some point to
990 // start with so we don't have to do the assignment below too
992 Buffer const & buffer = bv_->buffer();
993 Font font = displayFont(pit, first);
994 FontSize const tmpsize = font.fontInfo().size();
995 font.fontInfo() = text_->layoutFont(pit);
996 FontSize const size = font.fontInfo().size();
997 font.fontInfo().setSize(tmpsize);
999 FontInfo labelfont = text_->labelFont(par);
1001 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1002 FontMetrics const & fontmetrics = theFontMetrics(font);
1004 // these are minimum values
1005 double const spacing_val = layout.spacing.getValue()
1006 * text_->spacing(par);
1007 //lyxerr << "spacing_val = " << spacing_val << endl;
1008 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
1009 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
1011 // insets may be taller
1012 ParagraphMetrics const & pm = par_metrics_[pit];
1013 InsetList::const_iterator ii = par.insetList().begin();
1014 InsetList::const_iterator iend = par.insetList().end();
1015 for ( ; ii != iend; ++ii) {
1016 if (ii->pos >= first && ii->pos < end) {
1017 Dimension const & dim = pm.insetDimension(ii->inset);
1018 maxasc = max(maxasc, dim.ascent());
1019 maxdesc = max(maxdesc, dim.descent());
1023 // Check if any custom fonts are larger (Asger)
1024 // This is not completely correct, but we can live with the small,
1025 // cosmetic error for now.
1029 par.highestFontInRange(first, end, size);
1030 if (maxsize > font.fontInfo().size()) {
1031 // use standard paragraph font with the maximal size
1032 FontInfo maxfont = font.fontInfo();
1033 maxfont.setSize(maxsize);
1034 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
1035 maxasc = max(maxasc, maxfontmetrics.maxAscent());
1036 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
1039 // This is nicer with box insets:
1043 ParagraphList const & pars = text_->paragraphs();
1044 Inset const & inset = par.inInset();
1046 // is it a top line?
1047 if (first == 0 && topBottomSpace) {
1048 BufferParams const & bufparams = buffer.params();
1049 // some parskips VERY EASY IMPLEMENTATION
1050 if (bufparams.paragraph_separation
1051 == BufferParams::ParagraphSkipSeparation
1052 && inset.lyxCode() != ERT_CODE
1053 && inset.lyxCode() != LISTINGS_CODE
1055 && ((layout.isParagraph() && par.getDepth() == 0)
1056 || (pars[pit - 1].layout().isParagraph()
1057 && pars[pit - 1].getDepth() == 0)))
1059 maxasc += bufparams.getDefSkip().inPixels(*bv_);
1062 if (par.params().startOfAppendix())
1063 maxasc += int(3 * dh);
1065 // This is special code for the chapter, since the label of this
1066 // layout is printed in an extra row
1067 if (layout.counter == "chapter"
1068 && !par.params().labelString().empty()) {
1069 labeladdon = int(labelfont_metrics.maxHeight()
1070 * layout.spacing.getValue()
1071 * text_->spacing(par));
1074 // special code for the top label
1075 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1076 || layout.labeltype == LABEL_BIBLIO
1077 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1078 && isFirstInSequence(pit, pars)
1079 && !par.labelString().empty())
1082 labelfont_metrics.maxHeight()
1083 * layout.spacing.getValue()
1084 * text_->spacing(par)
1085 + (layout.topsep + layout.labelbottomsep) * dh);
1088 // Add the layout spaces, for example before and after
1089 // a section, or between the items of a itemize or enumerate
1092 pit_type prev = depthHook(pit, pars, par.getDepth());
1093 Paragraph const & prevpar = pars[prev];
1095 && prevpar.layout() == layout
1096 && prevpar.getDepth() == par.getDepth()
1097 && prevpar.getLabelWidthString()
1098 == par.getLabelWidthString()) {
1099 layoutasc = layout.itemsep * dh;
1100 } else if (pit != 0 || first != 0) {
1101 if (layout.topsep > 0)
1102 layoutasc = layout.topsep * dh;
1105 prev = outerHook(pit, pars);
1106 if (prev != pit_type(pars.size())) {
1107 maxasc += int(pars[prev].layout().parsep * dh);
1108 } else if (pit != 0) {
1109 Paragraph const & prevpar = pars[pit - 1];
1110 if (prevpar.getDepth() != 0 ||
1111 prevpar.layout() == layout) {
1112 maxasc += int(layout.parsep * dh);
1117 // is it a bottom line?
1118 if (end >= par.size() && topBottomSpace) {
1119 // add the layout spaces, for example before and after
1120 // a section, or between the items of a itemize or enumerate
1122 pit_type nextpit = pit + 1;
1123 if (nextpit != pit_type(pars.size())) {
1124 pit_type cpit = pit;
1128 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1129 usual = pars[cpit].layout().bottomsep * dh;
1130 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1131 if (pars[cpit].layout() != pars[nextpit].layout()
1132 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1134 unusual = pars[cpit].layout().bottomsep * dh;
1136 layoutdesc = max(unusual, usual);
1137 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1138 if (pars[cpit].layout() != pars[nextpit].layout()
1139 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1140 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1145 // incalculate the layout spaces
1146 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1147 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1149 // FIXME: the correct way is to do the following is to move the
1150 // following code in another method specially tailored for the
1151 // main Text. The following test is thus bogus.
1152 // Top and bottom margin of the document (only at top-level)
1153 if (main_text_ && topBottomSpace) {
1154 if (pit == 0 && first == 0)
1156 if (pit + 1 == pit_type(pars.size()) &&
1157 end == par.size() &&
1158 !(end > 0 && par.isNewline(end - 1)))
1162 return Dimension(0, maxasc + labeladdon, maxdesc);
1166 // x is an absolute screen coord
1167 // returns the column near the specified x-coordinate of the row
1168 // x is set to the real beginning of this column
1169 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1170 Row const & row, int & x, bool & boundary) const
1172 Buffer const & buffer = bv_->buffer();
1174 /// For the main Text, it is possible that this pit is not
1175 /// yet in the CoordCache when moving cursor up.
1176 /// x Paragraph coordinate is always 0 for main text anyway.
1177 int const xo = origin_.x_;
1179 Paragraph const & par = text_->getPar(pit);
1181 bidi.computeTables(par, buffer, row);
1183 pos_type vc = row.pos();
1184 pos_type end = row.endpos();
1186 Layout const & layout = par.layout();
1188 bool left_side = false;
1190 pos_type body_pos = par.beginOfBody();
1192 double tmpx = row.x;
1193 double last_tmpx = tmpx;
1196 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1199 // check for empty row
1205 while (vc < end && tmpx <= x) {
1206 c = bidi.vis2log(vc);
1208 if (body_pos > 0 && c == body_pos - 1) {
1209 FontMetrics const & fm = theFontMetrics(
1210 text_->labelFont(par));
1211 tmpx += row.label_hfill + fm.width(layout.labelsep);
1212 if (par.isLineSeparator(body_pos - 1))
1213 tmpx -= singleWidth(pit, body_pos - 1);
1216 tmpx += singleWidth(pit, c);
1217 if (par.isSeparator(c) && c >= body_pos)
1218 tmpx += row.separator;
1222 if ((tmpx + last_tmpx) / 2 > x) {
1227 LASSERT(vc <= end, /**/); // This shouldn't happen.
1230 // This (rtl_support test) is not needed, but gives
1231 // some speedup if rtl_support == false
1232 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1234 // If lastrow is false, we don't need to compute
1235 // the value of rtl.
1236 bool const rtl = lastrow ? text_->isRTL(par) : false;
1238 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1239 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1240 if (!par.isNewline(end - 1))
1242 } else if (vc == row.pos()) {
1243 c = bidi.vis2log(vc);
1244 if (bidi.level(c) % 2 == 1)
1247 c = bidi.vis2log(vc - 1);
1248 bool const rtl = (bidi.level(c) % 2 == 1);
1249 if (left_side == rtl) {
1251 boundary = isRTLBoundary(pit, c);
1255 // I believe this code is not needed anymore (Jug 20050717)
1257 // The following code is necessary because the cursor position past
1258 // the last char in a row is logically equivalent to that before
1259 // the first char in the next row. That's why insets causing row
1260 // divisions -- Newline and display-style insets -- must be treated
1261 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1262 // Newline inset, air gap below:
1263 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1264 if (bidi.level(end -1) % 2 == 0)
1265 tmpx -= singleWidth(pit, end - 1);
1267 tmpx += singleWidth(pit, end - 1);
1271 // Air gap above display inset:
1272 if (row.pos() < end && c >= end && end < par.size()
1273 && par.isInset(end) && par.getInset(end)->display()) {
1276 // Air gap below display inset:
1277 if (row.pos() < end && c >= end && par.isInset(end - 1)
1278 && par.getInset(end - 1)->display()) {
1284 pos_type const col = c - row.pos();
1286 if (!c || end == par.size())
1289 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1294 return min(col, end - 1 - row.pos());
1298 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1300 // We play safe and use parMetrics(pit) to make sure the
1301 // ParagraphMetrics will be redone and OK to use if needed.
1302 // Otherwise we would use an empty ParagraphMetrics in
1303 // upDownInText() while in selection mode.
1304 ParagraphMetrics const & pm = parMetrics(pit);
1306 LASSERT(row < int(pm.rows().size()), /**/);
1308 Row const & r = pm.rows()[row];
1309 return r.pos() + getColumnNearX(pit, r, x, bound);
1313 void TextMetrics::newParMetricsDown()
1315 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1316 pit_type const pit = last.first + 1;
1317 if (pit == int(text_->paragraphs().size()))
1320 // do it and update its position.
1322 par_metrics_[pit].setPosition(last.second.position()
1323 + last.second.descent() + par_metrics_[pit].ascent());
1327 void TextMetrics::newParMetricsUp()
1329 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1330 if (first.first == 0)
1333 pit_type const pit = first.first - 1;
1334 // do it and update its position.
1336 par_metrics_[pit].setPosition(first.second.position()
1337 - first.second.ascent() - par_metrics_[pit].descent());
1340 // y is screen coordinate
1341 pit_type TextMetrics::getPitNearY(int y)
1343 LASSERT(!text_->paragraphs().empty(), return -1);
1344 LASSERT(!par_metrics_.empty(), return -1);
1345 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1347 // look for highest numbered paragraph with y coordinate less than given y
1350 ParMetricsCache::const_iterator it = par_metrics_.begin();
1351 ParMetricsCache::const_iterator et = par_metrics_.end();
1352 ParMetricsCache::const_iterator last = et; last--;
1354 ParagraphMetrics const & pm = it->second;
1356 if (y < it->second.position() - int(pm.ascent())) {
1357 // We are looking for a position that is before the first paragraph in
1358 // the cache (which is in priciple off-screen, that is before the
1361 // We are already at the first paragraph in the inset.
1363 // OK, this is the paragraph we are looking for.
1364 pit = it->first - 1;
1369 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1371 if (y >= last->second.position() + int(pm_last.descent())) {
1372 // We are looking for a position that is after the last paragraph in
1373 // the cache (which is in priciple off-screen), that is before the
1375 pit = last->first + 1;
1376 if (pit == int(text_->paragraphs().size()))
1377 // We are already at the last paragraph in the inset.
1379 // OK, this is the paragraph we are looking for.
1380 newParMetricsDown();
1384 for (; it != et; ++it) {
1385 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1386 << " y: " << it->second.position());
1388 ParagraphMetrics const & pm = par_metrics_[it->first];
1390 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1392 yy = it->second.position();
1396 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1402 Row const & TextMetrics::getPitAndRowNearY(int y, pit_type & pit,
1403 bool assert_in_view, bool up)
1405 ParagraphMetrics const & pm = par_metrics_[pit];
1407 int yy = pm.position() - pm.ascent();
1408 LASSERT(!pm.rows().empty(), /**/);
1409 RowList::const_iterator rit = pm.rows().begin();
1410 RowList::const_iterator rlast = pm.rows().end();
1412 for (; rit != rlast; yy += rit->height(), ++rit)
1413 if (yy + rit->height() > y)
1416 if (assert_in_view && yy + rit->height() != y) {
1418 if (rit != pm.rows().begin())
1420 else if (pit != 0) {
1423 ParagraphMetrics const & pm2 = par_metrics_[pit];
1424 rit = pm2.rows().end();
1430 else if (pit != int(par_metrics_.size())) {
1432 newParMetricsDown();
1433 ParagraphMetrics const & pm2 = par_metrics_[pit];
1434 rit = pm2.rows().begin();
1442 // x,y are absolute screen coordinates
1443 // sets cursor recursively descending into nested editable insets
1444 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1445 bool assert_in_view, bool up)
1447 if (lyxerr.debugging(Debug::WORKAREA)) {
1448 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1449 cur.bv().coordCache().dump();
1451 pit_type pit = getPitNearY(y);
1452 LASSERT(pit != -1, return 0);
1454 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1457 int xx = x; // is modified by getColumnNearX
1458 pos_type const pos = row.pos()
1459 + getColumnNearX(pit, row, xx, bound);
1462 cur.boundary(bound);
1465 // try to descend into nested insets
1466 Inset * inset = checkInsetHit(x, y);
1467 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1469 // Either we deconst editXY or better we move current_font
1470 // and real_current_font to Cursor
1471 // FIXME: what is needed now that current_font and real_current_font
1473 cur.setCurrentFont();
1477 ParagraphList const & pars = text_->paragraphs();
1478 Inset const * insetBefore = pos ? pars[pit].getInset(pos - 1) : 0;
1479 //Inset * insetBehind = pars[pit].getInset(pos);
1481 // This should be just before or just behind the
1482 // cursor position set above.
1483 LASSERT((pos != 0 && inset == insetBefore)
1484 || inset == pars[pit].getInset(pos), /**/);
1486 // Make sure the cursor points to the position before
1488 if (inset == insetBefore) {
1490 cur.boundary(false);
1493 // Try to descend recursively inside the inset.
1494 inset = inset->editXY(cur, x, y);
1496 if (cur.top().text() == text_)
1497 cur.setCurrentFont();
1502 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1504 LASSERT(text_ == cur.text(), /**/);
1505 pit_type pit = getPitNearY(y);
1506 LASSERT(pit != -1, return);
1508 ParagraphMetrics const & pm = par_metrics_[pit];
1510 int yy = pm.position() - pm.ascent();
1511 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1512 " pit: " << pit << " yy: " << yy);
1515 LASSERT(pm.rows().size(), /**/);
1516 for (; r < int(pm.rows().size()) - 1; ++r) {
1517 Row const & row = pm.rows()[r];
1518 if (int(yy + row.height()) > y)
1523 Row const & row = pm.rows()[r];
1525 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1529 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1531 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1533 text_->setCursor(cur, pit, pos, true, bound);
1534 // remember new position.
1539 //takes screen x,y coordinates
1540 Inset * TextMetrics::checkInsetHit(int x, int y)
1542 pit_type pit = getPitNearY(y);
1543 LASSERT(pit != -1, return 0);
1545 Paragraph const & par = text_->paragraphs()[pit];
1546 ParagraphMetrics const & pm = par_metrics_[pit];
1548 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1550 InsetList::const_iterator iit = par.insetList().begin();
1551 InsetList::const_iterator iend = par.insetList().end();
1552 for (; iit != iend; ++iit) {
1553 Inset * inset = iit->inset;
1555 LYXERR(Debug::DEBUG, "examining inset " << inset);
1557 if (!bv_->coordCache().getInsets().has(inset)) {
1558 LYXERR(Debug::DEBUG, "inset has no cached position");
1562 Dimension const & dim = pm.insetDimension(inset);
1563 Point p = bv_->coordCache().getInsets().xy(inset);
1565 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1566 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1569 && x <= p.x_ + dim.wid
1570 && y >= p.y_ - dim.asc
1571 && y <= p.y_ + dim.des) {
1572 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1577 LYXERR(Debug::DEBUG, "No inset hit. ");
1582 int TextMetrics::cursorX(CursorSlice const & sl,
1583 bool boundary) const
1585 LASSERT(sl.text() == text_, /**/);
1586 pit_type const pit = sl.pit();
1587 Paragraph const & par = text_->paragraphs()[pit];
1588 ParagraphMetrics const & pm = par_metrics_[pit];
1589 if (pm.rows().empty())
1592 pos_type ppos = sl.pos();
1593 // Correct position in front of big insets
1594 bool const boundary_correction = ppos != 0 && boundary;
1595 if (boundary_correction)
1598 Row const & row = pm.getRow(sl.pos(), boundary);
1600 pos_type cursor_vpos = 0;
1602 Buffer const & buffer = bv_->buffer();
1605 bidi.computeTables(par, buffer, row);
1607 pos_type const row_pos = row.pos();
1608 pos_type const end = row.endpos();
1609 // Spaces at logical line breaks in bidi text must be skipped during
1610 // cursor positioning. However, they may appear visually in the middle
1611 // of a row; they must be skipped, wherever they are...
1612 // * logically "abc_[HEBREW_\nHEBREW]"
1613 // * visually "abc_[_WERBEH\nWERBEH]"
1614 pos_type skipped_sep_vpos = -1;
1617 cursor_vpos = row_pos;
1618 else if (ppos >= end)
1619 cursor_vpos = text_->isRTL(par) ? row_pos : end;
1620 else if (ppos > row_pos && ppos >= end)
1621 // Place cursor after char at (logical) position pos - 1
1622 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1623 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1625 // Place cursor before char at (logical) position ppos
1626 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1627 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1629 pos_type body_pos = par.beginOfBody();
1631 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1634 // check for possible inline completion in this row
1635 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1636 pos_type inlineCompletionVPos = -1;
1637 if (inlineCompletionPos.inTexted()
1638 && inlineCompletionPos.text() == text_
1639 && inlineCompletionPos.pit() == pit
1640 && inlineCompletionPos.pos() - 1 >= row_pos
1641 && inlineCompletionPos.pos() - 1 < end) {
1642 // draw logically behind the previous character
1643 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1646 // Use font span to speed things up, see below
1650 // If the last logical character is a separator, skip it, unless
1651 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1652 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1653 skipped_sep_vpos = bidi.log2vis(end - 1);
1655 // Inline completion RTL special case row_pos == cursor_pos:
1656 // "__|b" => cursor_pos is right of __
1657 if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1658 font = displayFont(pit, row_pos + 1);
1659 docstring const & completion = bv_->inlineCompletion();
1660 if (font.isRightToLeft() && completion.length() > 0)
1661 x += theFontMetrics(font.fontInfo()).width(completion);
1664 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1665 // Skip the separator which is at the logical end of the row
1666 if (vpos == skipped_sep_vpos)
1668 pos_type pos = bidi.vis2log(vpos);
1669 if (body_pos > 0 && pos == body_pos - 1) {
1670 FontMetrics const & labelfm = theFontMetrics(
1671 text_->labelFont(par));
1672 x += row.label_hfill + labelfm.width(par.layout().labelsep);
1673 if (par.isLineSeparator(body_pos - 1))
1674 x -= singleWidth(pit, body_pos - 1);
1677 // Use font span to speed things up, see above
1678 if (pos < font_span.first || pos > font_span.last) {
1679 font_span = par.fontSpan(pos);
1680 font = displayFont(pit, pos);
1683 x += pm.singleWidth(pos, font);
1685 // Inline completion RTL case:
1686 // "a__|b", __ of b => non-boundary a-pos is right of __
1687 if (vpos + 1 == inlineCompletionVPos
1688 && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1689 font = displayFont(pit, vpos + 1);
1690 docstring const & completion = bv_->inlineCompletion();
1691 if (font.isRightToLeft() && completion.length() > 0)
1692 x += theFontMetrics(font.fontInfo()).width(completion);
1695 // Inline completion LTR case:
1696 // "b|__a", __ of b => non-boundary a-pos is in front of __
1697 if (vpos == inlineCompletionVPos
1698 && (vpos + 1 < cursor_vpos || boundary_correction)) {
1699 font = displayFont(pit, vpos);
1700 docstring const & completion = bv_->inlineCompletion();
1701 if (!font.isRightToLeft() && completion.length() > 0)
1702 x += theFontMetrics(font.fontInfo()).width(completion);
1705 if (par.isSeparator(pos) && pos >= body_pos)
1709 // see correction above
1710 if (boundary_correction) {
1711 if (isRTL(sl, boundary))
1712 x -= singleWidth(pit, ppos);
1714 x += singleWidth(pit, ppos);
1721 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1723 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1724 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1725 if (pm.rows().empty())
1729 h -= par_metrics_[0].rows()[0].ascent();
1730 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1731 h += par_metrics_[pit].height();
1734 if (pos && boundary)
1736 size_t const rend = pm.pos2row(pos);
1737 for (size_t rit = 0; rit != rend; ++rit)
1738 h += pm.rows()[rit].height();
1739 h += pm.rows()[rend].ascent();
1744 // the cursor set functions have a special mechanism. When they
1745 // realize you left an empty paragraph, they will delete it.
1747 bool TextMetrics::cursorHome(Cursor & cur)
1749 LASSERT(text_ == cur.text(), /**/);
1750 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1751 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1752 return text_->setCursor(cur, cur.pit(), row.pos());
1756 bool TextMetrics::cursorEnd(Cursor & cur)
1758 LASSERT(text_ == cur.text(), /**/);
1759 // if not on the last row of the par, put the cursor before
1760 // the final space exept if I have a spanning inset or one string
1761 // is so long that we force a break.
1762 pos_type end = cur.textRow().endpos();
1764 // empty text, end-1 is no valid position
1766 bool boundary = false;
1767 if (end != cur.lastpos()) {
1768 if (!cur.paragraph().isLineSeparator(end-1)
1769 && !cur.paragraph().isNewline(end-1))
1774 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1778 void TextMetrics::deleteLineForward(Cursor & cur)
1780 LASSERT(text_ == cur.text(), /**/);
1781 if (cur.lastpos() == 0) {
1782 // Paragraph is empty, so we just go forward
1783 text_->cursorForward(cur);
1786 cur.setSelection(true); // to avoid deletion
1789 // What is this test for ??? (JMarc)
1790 if (!cur.selection())
1791 text_->deleteWordForward(cur);
1793 cap::cutSelection(cur, true, false);
1794 cur.checkBufferStructure();
1799 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1801 ParagraphList const & pars = text_->paragraphs();
1802 return row.endpos() >= pars[pit].size()
1803 && pit + 1 == pit_type(pars.size());
1807 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1809 return row.pos() == 0 && pit == 0;
1813 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1815 LASSERT(pit >= 0, /**/);
1816 LASSERT(pit < int(text_->paragraphs().size()), /**/);
1817 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1821 int TextMetrics::leftMargin(int max_width,
1822 pit_type const pit, pos_type const pos) const
1824 ParagraphList const & pars = text_->paragraphs();
1826 LASSERT(pit >= 0, /**/);
1827 LASSERT(pit < int(pars.size()), /**/);
1828 Paragraph const & par = pars[pit];
1829 LASSERT(pos >= 0, /**/);
1830 LASSERT(pos <= par.size(), /**/);
1831 Buffer const & buffer = bv_->buffer();
1832 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1833 DocumentClass const & tclass = buffer.params().documentClass();
1834 Layout const & layout = par.layout();
1836 docstring parindent = layout.parindent;
1840 if (text_->isMainText())
1841 l_margin += bv_->leftMargin();
1843 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1844 tclass.leftmargin());
1846 if (par.getDepth() != 0) {
1847 // find the next level paragraph
1848 pit_type newpar = outerHook(pit, pars);
1849 if (newpar != pit_type(pars.size())) {
1850 if (pars[newpar].layout().isEnvironment()) {
1851 l_margin = leftMargin(max_width, newpar);
1853 if (tclass.isDefaultLayout(par.layout())
1854 || tclass.isPlainLayout(par.layout())) {
1855 if (pars[newpar].params().noindent())
1858 parindent = pars[newpar].layout().parindent;
1863 // This happens after sections in standard classes. The 1.3.x
1864 // code compared depths too, but it does not seem necessary
1866 if (tclass.isDefaultLayout(par.layout())
1867 && pit > 0 && pars[pit - 1].layout().nextnoindent)
1870 FontInfo const labelfont = text_->labelFont(par);
1871 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1873 switch (layout.margintype) {
1874 case MARGIN_DYNAMIC:
1875 if (!layout.leftmargin.empty()) {
1876 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1879 if (!par.labelString().empty()) {
1880 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1881 l_margin += labelfont_metrics.width(par.labelString());
1882 l_margin += labelfont_metrics.width(layout.labelsep);
1886 case MARGIN_MANUAL: {
1887 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1888 // The width of an empty par, even with manual label, should be 0
1889 if (!par.empty() && pos >= par.beginOfBody()) {
1890 if (!par.getLabelWidthString().empty()) {
1891 docstring labstr = par.getLabelWidthString();
1892 l_margin += labelfont_metrics.width(labstr);
1893 l_margin += labelfont_metrics.width(layout.labelsep);
1899 case MARGIN_STATIC: {
1900 l_margin += theFontMetrics(buffer.params().getFont()).
1901 signedWidth(layout.leftmargin) * 4 / (par.getDepth() + 4);
1905 case MARGIN_FIRST_DYNAMIC:
1906 if (layout.labeltype == LABEL_MANUAL) {
1907 // if we are at position 0, we are never in the body
1908 if (pos > 0 && pos >= par.beginOfBody())
1909 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1911 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1913 // Special case to fix problems with
1915 || (layout.labeltype == LABEL_STATIC
1916 && layout.latextype == LATEX_ENVIRONMENT
1917 && !isFirstInSequence(pit, pars))) {
1918 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1919 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
1920 && layout.labeltype != LABEL_BIBLIO
1921 && layout.labeltype !=
1922 LABEL_CENTERED_TOP_ENVIRONMENT) {
1923 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1924 l_margin += labelfont_metrics.width(layout.labelsep);
1925 l_margin += labelfont_metrics.width(par.labelString());
1929 case MARGIN_RIGHT_ADDRESS_BOX: {
1931 // ok, a terrible hack. The left margin depends on the widest
1932 // row in this paragraph.
1933 RowList::iterator rit = par.rows().begin();
1934 RowList::iterator end = par.rows().end();
1935 // FIXME: This is wrong.
1936 int minfill = max_width;
1937 for ( ; rit != end; ++rit)
1938 if (rit->fill() < minfill)
1939 minfill = rit->fill();
1940 l_margin += theFontMetrics(params.getFont()).signedWidth(layout.leftmargin);
1941 l_margin += minfill;
1943 // also wrong, but much shorter.
1944 l_margin += max_width / 2;
1949 if (!par.params().leftIndent().zero())
1950 l_margin += par.params().leftIndent().inPixels(max_width);
1954 if (par.params().align() == LYX_ALIGN_LAYOUT)
1955 align = layout.align;
1957 align = par.params().align();
1959 // set the correct parindent
1961 && (layout.labeltype == LABEL_NO_LABEL
1962 || layout.labeltype == LABEL_TOP_ENVIRONMENT
1963 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1964 || (layout.labeltype == LABEL_STATIC
1965 && layout.latextype == LATEX_ENVIRONMENT
1966 && !isFirstInSequence(pit, pars)))
1967 && align == LYX_ALIGN_BLOCK
1968 && !par.params().noindent()
1969 // in some insets, paragraphs are never indented
1970 && !text_->inset().neverIndent()
1971 // display style insets are always centered, omit indentation
1974 && par.getInset(pos)->display())
1975 && (!(tclass.isDefaultLayout(par.layout())
1976 || tclass.isPlainLayout(par.layout()))
1977 || buffer.params().paragraph_separation == BufferParams::ParagraphIndentSeparation)
1980 // use the parindent of the layout when the default indentation is used
1981 // otherwise use the indentation set in the document settings
1982 if (buffer.params().getIndentation().asLyXCommand() == "default")
1983 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1986 l_margin += buffer.params().getIndentation().inPixels(*bv_);
1993 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1995 ParagraphMetrics const & pm = par_metrics_[pit];
1997 return pm.singleWidth(pos, displayFont(pit, pos));
2001 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
2003 if (par_metrics_.empty())
2009 ParMetricsCache::iterator it = par_metrics_.begin();
2010 ParMetricsCache::iterator const pm_end = par_metrics_.end();
2011 y -= it->second.ascent();
2012 for (; it != pm_end; ++it) {
2013 ParagraphMetrics const & pmi = it->second;
2015 pit_type const pit = it->first;
2016 // Save the paragraph position in the cache.
2017 it->second.setPosition(y);
2018 drawParagraph(pi, pit, x, y);
2024 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
2026 BufferParams const & bparams = bv_->buffer().params();
2027 ParagraphMetrics const & pm = par_metrics_[pit];
2028 if (pm.rows().empty())
2032 bool const original_drawing_state = pi.pain.isDrawingEnabled();
2033 int const ww = bv_->workHeight();
2034 size_t const nrows = pm.rows().size();
2036 Cursor const & cur = bv_->cursor();
2037 DocIterator sel_beg = cur.selectionBegin();
2038 DocIterator sel_end = cur.selectionEnd();
2039 bool selection = cur.selection()
2040 // This is our text.
2041 && cur.text() == text_
2042 // if the anchor is outside, this is not our selection
2043 && cur.anchor().text() == text_
2044 && pit >= sel_beg.pit() && pit <= sel_end.pit();
2046 // We store the begin and end pos of the selection relative to this par
2047 DocIterator sel_beg_par = cur.selectionBegin();
2048 DocIterator sel_end_par = cur.selectionEnd();
2050 // We care only about visible selection.
2052 if (pit != sel_beg.pit()) {
2053 sel_beg_par.pit() = pit;
2054 sel_beg_par.pos() = 0;
2056 if (pit != sel_end.pit()) {
2057 sel_end_par.pit() = pit;
2058 sel_end_par.pos() = sel_end_par.lastpos();
2062 for (size_t i = 0; i != nrows; ++i) {
2064 Row const & row = pm.rows()[i];
2068 bool const inside = (y + row.descent() >= 0
2069 && y - row.ascent() < ww);
2070 // It is not needed to draw on screen if we are not inside.
2071 pi.pain.setDrawingEnabled(inside && original_drawing_state);
2072 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
2075 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2077 row.setSelection(-1, -1);
2079 // The row knows nothing about the paragraph, so we have to check
2080 // whether this row is the first or last and update the margins.
2081 if (row.selection()) {
2082 if (row.sel_beg == 0)
2083 row.begin_margin_sel = sel_beg.pit() < pit;
2084 if (row.sel_end == sel_end_par.lastpos())
2085 row.end_margin_sel = sel_end.pit() > pit;
2088 // Row signature; has row changed since last paint?
2089 row.setCrc(pm.computeRowSignature(row, bparams));
2090 bool row_has_changed = row.changed();
2092 // Don't paint the row if a full repaint has not been requested
2093 // and if it has not changed.
2094 if (!pi.full_repaint && !row_has_changed) {
2095 // Paint only the insets if the text itself is
2097 rp.paintOnlyInsets();
2102 // Clear background of this row if paragraph background was not
2103 // already cleared because of a full repaint.
2104 if (!pi.full_repaint && row_has_changed) {
2105 pi.pain.fillRectangle(x, y - row.ascent(),
2106 width(), row.height(), pi.background_color);
2109 if (row.selection())
2110 drawRowSelection(pi, x, row, cur, pit);
2112 // Instrumentation for testing row cache (see also
2114 if (lyxerr.debugging(Debug::PAINTING) && inside
2115 && (row.selection() || pi.full_repaint || row_has_changed)) {
2116 string const foreword = text_->isMainText() ?
2117 "main text redraw " : "inset text redraw: ";
2118 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
2119 << " row_selection=" << row.selection()
2120 << " full_repaint=" << pi.full_repaint
2121 << " row_has_changed=" << row_has_changed);
2124 // Backup full_repaint status and force full repaint
2125 // for inner insets as the Row has been cleared out.
2126 bool tmp = pi.full_repaint;
2127 pi.full_repaint = true;
2130 rp.paintChangeBar();
2137 // Restore full_repaint status.
2138 pi.full_repaint = tmp;
2140 // Re-enable screen drawing for future use of the painter.
2141 pi.pain.setDrawingEnabled(original_drawing_state);
2143 //LYXERR(Debug::PAINTING, ".");
2147 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2148 Cursor const & curs, pit_type pit) const
2150 DocIterator beg = curs.selectionBegin();
2152 beg.pos() = row.sel_beg;
2154 DocIterator end = curs.selectionEnd();
2156 end.pos() = row.sel_end;
2158 bool const begin_boundary = beg.pos() >= row.endpos();
2159 bool const end_boundary = row.sel_end == row.endpos();
2161 DocIterator cur = beg;
2162 cur.boundary(begin_boundary);
2163 int x1 = cursorX(beg.top(), begin_boundary);
2164 int x2 = cursorX(end.top(), end_boundary);
2165 int const y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2166 int const y2 = y1 + row.height();
2168 int const rm = text_->isMainText() ? bv_->rightMargin() : 0;
2169 int const lm = text_->isMainText() ? bv_->leftMargin() : 0;
2172 if (row.begin_margin_sel) {
2173 if (text_->isRTL(beg.paragraph())) {
2174 pi.pain.fillRectangle(x + x1, y1, width() - rm - x1, y2 - y1,
2177 pi.pain.fillRectangle(x + lm, y1, x1 - lm, y2 - y1,
2182 if (row.end_margin_sel) {
2183 if (text_->isRTL(beg.paragraph())) {
2184 pi.pain.fillRectangle(x + lm, y1, x2 - lm, y2 - y1,
2187 pi.pain.fillRectangle(x + x2, y1, width() - rm - x2, y2 - y1,
2192 // if we are on a boundary from the beginning, it's probably
2193 // a RTL boundary and we jump to the other side directly as this
2194 // segement is 0-size and confuses the logic below
2196 cur.boundary(false);
2198 // go through row and draw from RTL boundary to RTL boundary
2200 bool drawNow = false;
2202 // simplified cursorForward code below which does not
2203 // descend into insets and which does not go into the
2204 // next line. Compare the logic with the original cursorForward
2206 // if left of boundary -> just jump to right side, but
2207 // for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2208 if (cur.boundary()) {
2209 cur.boundary(false);
2210 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2211 // in front of RTL boundary -> Stay on this side of the boundary
2212 // because: ab|cDDEEFFghi -> abc|DDEEFFghi
2221 if (cur.pos() == row.endpos())
2226 // the previous segment was just drawn, now the next starts
2227 x1 = cursorX(cur.top(), cur.boundary());
2230 if (!(cur < end) || drawNow) {
2231 x2 = cursorX(cur.top(), cur.boundary());
2232 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2235 // reset x1, so it is set again next round (which will be on the
2236 // right side of a boundary or at the selection end)
2243 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2244 Dimension & dim) const
2246 Cursor const & bvcur = cur.bv().cursor();
2248 // get word in front of cursor
2249 docstring word = text_->previousWord(bvcur.top());
2250 DocIterator wordStart = bvcur;
2251 wordStart.pos() -= word.length();
2253 // get position on screen of the word start and end
2254 Point lxy = cur.bv().getPos(wordStart, false);
2255 Point rxy = cur.bv().getPos(bvcur, bvcur.boundary());
2257 // calculate dimensions of the word
2258 dim = rowHeight(bvcur.pit(), wordStart.pos(), bvcur.pos(), false);
2259 dim.wid = abs(rxy.x_ - lxy.x_);
2261 // calculate position of word
2263 x = min(rxy.x_, lxy.x_);
2265 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2266 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2269 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2271 // ParagraphMetrics const & pm = par_metrics_[pit];
2272 // Row const & r = pm.rows()[row];
2278 int defaultRowHeight()
2280 return int(theFontMetrics(sane_font).maxHeight() * 1.2);