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 "FontIterator.h"
31 #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"
57 using frontend::FontMetrics;
61 int numberOfSeparators(Paragraph const & par, Row const & row)
63 pos_type const first = max(row.pos(), par.beginOfBody());
64 pos_type const last = row.endpos() - 1;
66 for (pos_type p = first; p < last; ++p) {
67 if (par.isSeparator(p))
74 int numberOfLabelHfills(Paragraph const & par, Row const & row)
76 pos_type last = row.endpos() - 1;
77 pos_type first = row.pos();
79 // hfill *DO* count at the beginning of paragraphs!
81 while (first < last && par.isHfill(first))
85 last = min(last, par.beginOfBody());
87 for (pos_type p = first; p < last; ++p) {
95 int numberOfHfills(Paragraph const & par, Row const & row)
97 pos_type const last = row.endpos();
98 pos_type first = row.pos();
100 // hfill *DO* count at the beginning of paragraphs!
102 while (first < last && par.isHfill(first))
106 first = max(first, par.beginOfBody());
109 for (pos_type p = first; p < last; ++p) {
118 TextMetrics::TextMetrics(BufferView * bv, Text * text)
119 : bv_(bv), text_(text)
122 max_width_ = bv_->workWidth();
123 dim_.wid = max_width_;
127 //text_->updateLabels(bv->buffer());
131 bool TextMetrics::has(pit_type pit) const
133 return par_metrics_.find(pit) != par_metrics_.end();
137 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
139 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
144 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
146 ParMetricsCache::const_iterator it = par_metrics_.begin();
147 return make_pair(it->first, &it->second);
151 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
153 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
154 return make_pair(it->first, &it->second);
158 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
160 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
161 if (pmc_it == par_metrics_.end()) {
162 pmc_it = par_metrics_.insert(
163 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
165 if (pmc_it->second.rows().empty() && redo)
167 return pmc_it->second;
171 int TextMetrics::parPosition(pit_type pit) const
173 if (pit < par_metrics_.begin()->first)
175 if (pit > par_metrics_.rbegin()->first)
178 return par_metrics_[pit].position();
182 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
184 BOOST_ASSERT(mi.base.textwidth);
185 max_width_ = mi.base.textwidth;
186 // backup old dimension.
187 Dimension const old_dim = dim_;
190 dim_.wid = min_width;
191 pit_type const npar = text_->paragraphs().size();
193 // If there is more than one row, expand the text to
194 // the full allowable width.
195 dim_.wid = max_width_;
197 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
198 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
200 bool changed = false;
202 for (pit_type pit = 0; pit != npar; ++pit) {
203 changed |= redoParagraph(pit);
204 ParagraphMetrics const & pm = par_metrics_[pit];
206 if (dim_.wid < pm.width())
207 dim_.wid = pm.width();
210 dim_.asc = par_metrics_[0].ascent();
211 dim_.des = h - dim_.asc;
212 //lyxerr << "dim_.wid " << dim_.wid << endl;
213 //lyxerr << "dim_.asc " << dim_.asc << endl;
214 //lyxerr << "dim_.des " << dim_.des << endl;
216 changed |= dim_ != old_dim;
222 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
224 return main_text_? pm.rightMargin(*bv_) : 0;
228 int TextMetrics::rightMargin(pit_type const pit) const
230 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
234 void TextMetrics::applyOuterFont(Font & font) const
237 lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
238 lf.fontInfo().realize(font.fontInfo());
239 lf.setLanguage(font.language());
244 Font TextMetrics::getDisplayFont(pit_type pit, pos_type pos) const
246 BOOST_ASSERT(pos >= 0);
248 ParagraphList const & pars = text_->paragraphs();
249 Paragraph const & par = pars[pit];
250 LayoutPtr const & layout = par.layout();
251 Buffer const & buffer = bv_->buffer();
253 BufferParams const & params = buffer.params();
254 pos_type const body_pos = par.beginOfBody();
256 // We specialize the 95% common case:
257 if (!par.getDepth()) {
258 Font f = par.getFontSettings(params, pos);
259 if (!text_->isMainText(buffer))
261 bool lab = layout->labeltype == LABEL_MANUAL && pos < body_pos;
263 FontInfo const & lf = lab ? layout->labelfont : layout->font;
264 FontInfo rlf = lab ? layout->reslabelfont : layout->resfont;
266 // In case the default family has been customized
267 if (lf.family() == INHERIT_FAMILY)
268 rlf.setFamily(params.getFont().fontInfo().family());
269 f.fontInfo().realize(rlf);
273 // The uncommon case need not be optimized as much
274 FontInfo const & layoutfont = pos < body_pos ?
275 layout->labelfont : layout->font;
277 Font font = par.getFontSettings(params, pos);
278 font.fontInfo().realize(layoutfont);
280 if (!text_->isMainText(buffer))
281 applyOuterFont(font);
283 // Realize against environment font information
284 // NOTE: the cast to pit_type should be removed when pit_type
285 // changes to a unsigned integer.
286 if (pit < pit_type(pars.size()))
287 font.fontInfo().realize(outerFont(pit, pars).fontInfo());
289 // Realize with the fonts of lesser depth.
290 font.fontInfo().realize(params.getFont().fontInfo());
296 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
298 if (!lyxrc.rtl_support || !sl.text())
302 if (boundary && sl.pos() > 0)
305 return getDisplayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
309 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
311 if (!lyxrc.rtl_support)
314 // no RTL boundary at line start
318 Paragraph const & par = text_->getPar(pit);
320 bool left = getDisplayFont(pit, pos - 1).isVisibleRightToLeft();
322 if (pos == par.size())
323 right = par.isRTL(bv_->buffer().params());
325 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
326 return left != right;
330 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
331 Font const & font) const
333 if (!lyxrc.rtl_support)
336 Paragraph const & par = text_->getPar(pit);
337 bool left = font.isVisibleRightToLeft();
339 if (pos == par.size())
340 right = par.isRTL(bv_->buffer().params());
342 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
343 return left != right;
347 bool TextMetrics::redoParagraph(pit_type const pit)
349 Paragraph & par = text_->getPar(pit);
350 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
351 // redoParagraph() recursively inside parMetrics.
352 Dimension old_dim = parMetrics(pit, false).dim();
353 ParagraphMetrics & pm = par_metrics_[pit];
356 Buffer & buffer = bv_->buffer();
357 main_text_ = (text_ == &buffer.text());
358 bool changed = false;
360 // FIXME This check ought to be done somewhere else. It is the reason
361 // why text_ is not const. But then, where else to do it?
362 // Well, how can you end up with either (a) a biblio environment that
363 // has no InsetBibitem or (b) a biblio environment with more than one
364 // InsetBibitem? I think the answer is: when paragraphs are merged;
365 // when layout is set; when material is pasted.
366 int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
368 const_cast<Cursor &>(bv_->cursor()).posForward();
369 else if (moveCursor < 0) {
370 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
371 if (cursor.pos() >= -moveCursor)
372 cursor.posBackward();
375 // Optimisation: this is used in the next two loops
376 // so better to calculate that once here.
377 int const right_margin = rightMargin(pm);
379 // iterator pointing to paragraph to resolve macros
380 DocIterator parPos = text_->macrocontextPosition();
384 LYXERR(Debug::INFO, "MacroContext not initialised!"
385 << " Going through the buffer again and hope"
386 << " the context is better then.");
387 updateLabels(bv_->buffer());
388 parPos = text_->macrocontextPosition();
389 BOOST_ASSERT(!parPos.empty());
394 // FIXME: We should always use getFont(), see documentation of
395 // noFontChange() in Inset.h.
396 Font const bufferfont = buffer.params().getFont();
397 InsetList::const_iterator ii = par.insetList().begin();
398 InsetList::const_iterator iend = par.insetList().end();
399 for (; ii != iend; ++ii) {
400 // position already initialized?
401 if (!parPos.empty()) {
402 parPos.pos() = ii->pos;
404 // A macro template would normally not be visible
405 // by itself. But the tex macro semantics allow
406 // recursion, so we artifically take the context
407 // after the macro template to simulate this.
408 if (ii->inset->lyxCode() == MATHMACRO_CODE)
412 // do the metric calculation
414 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
416 Font const & font = ii->inset->noFontChange() ?
417 bufferfont : getDisplayFont(pit, ii->pos);
418 MacroContext mc(buffer, parPos);
419 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
420 ii->inset->metrics(mi, dim);
421 Dimension const old_dim = pm.insetDimension(ii->inset);
422 pm.setInsetDimension(ii->inset, dim);
423 changed |= (old_dim != dim);
426 Cursor const & cur = bv_->cursor();
427 DocIterator sel_beg = cur.selectionBegin();
428 DocIterator sel_end = cur.selectionEnd();
429 bool selection = cur.selection()
431 && cur.text() == text_
432 // if the anchor is outside, this is not our selection
433 && cur.anchor().text() == text_
434 && pit >= sel_beg.pit() && pit <= sel_end.pit();
436 // We care only about visible selection.
438 if (pit != sel_beg.pit()) {
442 if (pit != sel_end.pit()) {
444 sel_end.pos() = sel_end.lastpos();
448 par.setBeginOfBody();
450 size_t row_index = 0;
451 // maximum pixel width of a row
452 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
455 pos_type end = rowBreakPoint(width, pit, first);
456 if (row_index || end < par.size())
457 // If there is more than one row, expand the text to
458 // the full allowable width. This setting here is needed
459 // for the computeRowMetrics() below.
460 dim_.wid = max_width_;
462 dim = rowHeight(pit, first, end);
463 dim.wid = rowWidth(right_margin, pit, first, end);
464 if (row_index == pm.rows().size())
465 pm.rows().push_back(Row());
466 Row & row = pm.rows()[row_index];
467 row.setChanged(false);
471 row.setSelection(sel_beg.pos(), sel_end.pos());
473 row.setSelection(-1, -1);
474 row.setDimension(dim);
475 int const max_row_width = max(dim_.wid, dim.wid);
476 computeRowMetrics(pit, row, max_row_width);
480 pm.dim().wid = max(pm.dim().wid, dim.wid);
481 pm.dim().des += dim.height();
482 } while (first < par.size());
484 if (row_index < pm.rows().size())
485 pm.rows().resize(row_index);
487 // Make sure that if a par ends in newline, there is one more row
489 if (first > 0 && par.isNewline(first - 1)) {
490 Dimension dim = rowHeight(pit, first, first);
491 dim.wid = rowWidth(right_margin, pit, first, first);
492 if (row_index == pm.rows().size())
493 pm.rows().push_back(Row());
494 Row & row = pm.rows()[row_index];
495 row.setChanged(false);
498 row.setDimension(dim);
499 int const max_row_width = max(dim_.wid, dim.wid);
500 computeRowMetrics(pit, row, max_row_width);
501 pm.dim().des += dim.height();
504 pm.dim().asc += pm.rows()[0].ascent();
505 pm.dim().des -= pm.rows()[0].ascent();
507 changed |= old_dim.height() != pm.dim().height();
513 void TextMetrics::computeRowMetrics(pit_type const pit,
514 Row & row, int width) const
519 Buffer & buffer = bv_->buffer();
520 Paragraph const & par = text_->getPar(pit);
522 double w = width - row.width();
523 // FIXME: put back this assertion when the crash on new doc is solved.
524 //BOOST_ASSERT(w >= 0);
526 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
527 //lyxerr << "row.width() " << row.width() << endl;
528 //lyxerr << "w " << w << endl;
530 bool const is_rtl = text_->isRTL(buffer, par);
532 row.x = rightMargin(pit);
534 row.x = leftMargin(max_width_, pit, row.pos());
536 // is there a manual margin with a manual label
537 LayoutPtr const & layout = par.layout();
539 if (layout->margintype == MARGIN_MANUAL
540 && layout->labeltype == LABEL_MANUAL) {
541 /// We might have real hfills in the label part
542 int nlh = numberOfLabelHfills(par, row);
544 // A manual label par (e.g. List) has an auto-hfill
545 // between the label text and the body of the
547 // But we don't want to do this auto hfill if the par
552 if (nlh && !par.getLabelWidthString().empty())
553 row.label_hfill = labelFill(pit, row) / double(nlh);
557 // are there any hfills in the row?
558 if (int const nh = numberOfHfills(par, row)) {
560 hfill = w / double(nh);
561 // we don't have to look at the alignment if it is ALIGN_LEFT and
562 // if the row is already larger then the permitted width as then
563 // we force the LEFT_ALIGN'edness!
564 } else if (int(row.width()) < max_width_) {
565 // is it block, flushleft or flushright?
566 // set x how you need it
568 if (par.params().align() == LYX_ALIGN_LAYOUT)
569 align = layout->align;
571 align = par.params().align();
573 // Display-style insets should always be on a centred row
574 if (Inset const * inset = par.getInset(row.pos())) {
575 switch (inset->display()) {
576 case Inset::AlignLeft:
577 align = LYX_ALIGN_BLOCK;
579 case Inset::AlignCenter:
580 align = LYX_ALIGN_CENTER;
583 case Inset::AlignRight:
584 // unchanged (use align)
590 case LYX_ALIGN_BLOCK: {
591 int const ns = numberOfSeparators(par, row);
592 bool disp_inset = false;
593 if (row.endpos() < par.size()) {
594 Inset const * in = par.getInset(row.endpos());
596 disp_inset = in->display();
598 // If we have separators, this is not the last row of a
599 // par, does not end in newline, and is not row above a
600 // display inset... then stretch it
602 && row.endpos() < par.size()
603 && !par.isNewline(row.endpos() - 1)
606 row.separator = w / ns;
607 //lyxerr << "row.separator " << row.separator << endl;
608 //lyxerr << "ns " << ns << endl;
614 case LYX_ALIGN_RIGHT:
617 case LYX_ALIGN_CENTER:
624 pos_type body_pos = par.beginOfBody();
625 pos_type end = row.endpos();
628 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
630 row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
631 width(layout->labelsep);
633 row.x += row.label_hfill;
637 pos_type const endpos = row.endpos();
638 pos_type body_pos = par.beginOfBody();
640 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
643 ParagraphMetrics & pm = par_metrics_[pit];
644 InsetList::const_iterator ii = par.insetList().begin();
645 InsetList::const_iterator iend = par.insetList().end();
646 for ( ; ii != iend; ++ii) {
647 if (ii->pos >= endpos || ii->pos < row.pos()
648 || ii->inset->lyxCode() != HFILL_CODE)
650 Dimension dim = row.dimension();
651 if (pm.hfillExpansion(row, ii->pos))
652 dim.wid = int(ii->pos >= body_pos ?
653 max(hfill, 5.0) : row.label_hfill);
656 // Cache the inset dimension.
657 bv_->coordCache().insets().add(ii->inset, dim);
658 pm.setInsetDimension(ii->inset, dim);
663 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
665 Buffer & buffer = bv_->buffer();
666 Paragraph const & par = text_->getPar(pit);
668 pos_type last = par.beginOfBody();
669 BOOST_ASSERT(last > 0);
671 // -1 because a label ends with a space that is in the label
674 // a separator at this end does not count
675 if (par.isLineSeparator(last))
679 for (pos_type i = row.pos(); i <= last; ++i)
680 w += singleWidth(pit, i);
682 docstring const & label = par.params().labelWidthString();
686 FontMetrics const & fm
687 = theFontMetrics(text_->getLabelFont(buffer, par));
689 return max(0, fm.width(label) - w);
693 // this needs special handling - only newlines count as a break point
694 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
696 pos_type const end = par.size();
699 if (par.isNewline(i))
706 int TextMetrics::labelEnd(pit_type const pit) const
708 // labelEnd is only needed if the layout fills a flushleft label.
709 if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
711 // return the beginning of the body
712 return leftMargin(max_width_, pit);
716 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
719 Buffer & buffer = bv_->buffer();
720 ParagraphMetrics const & pm = par_metrics_[pit];
721 Paragraph const & par = text_->getPar(pit);
722 pos_type const end = par.size();
723 if (pos == end || width < 0)
726 LayoutPtr const & layout = par.layout();
728 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
729 return addressBreakPoint(pos, par);
731 pos_type const body_pos = par.beginOfBody();
733 // check for possible inline completion
734 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
735 pos_type inlineCompletionVPos = -1;
736 if (inlineCompletionPos.inTexted()
737 && inlineCompletionPos.text() == text_
738 && inlineCompletionPos.pit() == pit) {
739 // draw visually behind the previous character
740 // FIXME: probably special RTL handling needed here
741 inlineCompletionVPos = inlineCompletionPos.pos() - 1;
744 // Now we iterate through until we reach the right margin
745 // or the end of the par, then choose the possible break
748 int label_end = labelEnd(pit);
749 int const left = leftMargin(max_width_, pit, pos);
752 // pixel width since last breakpoint
755 FontIterator fi = FontIterator(*this, par, pit, pos);
756 pos_type point = end;
758 for ( ; i < end; ++i, ++fi) {
759 int thiswidth = pm.singleWidth(i, *fi);
761 // add inline completion width
762 if (inlineCompletionVPos == i) {
763 docstring const & completion = bv_->inlineCompletion();
764 if (completion.length() > 0)
765 thiswidth += theFontMetrics(*fi).width(completion);
768 // add the auto-hfill from label end to the body
769 if (body_pos && i == body_pos) {
770 FontMetrics const & fm = theFontMetrics(
771 text_->getLabelFont(buffer, par));
772 int add = fm.width(layout->labelsep);
773 if (par.isLineSeparator(i - 1))
774 add -= singleWidth(pit, i - 1);
776 add = max(add, label_end - x);
781 chunkwidth += thiswidth;
783 // break before a character that will fall off
784 // the right of the row
786 // if no break before, break here
787 if (point == end || chunkwidth >= width - left) {
793 // exit on last registered breakpoint:
797 if (par.isNewline(i)) {
801 Inset const * inset = 0;
804 if ((inset = par.getInset(i + 1)) && inset->display()) {
809 if ((inset = par.getInset(i)) && inset->display()) {
815 inset = par.getInset(i);
816 if (!inset || inset->isChar()) {
817 // some insets are line separators too
818 if (par.isLineSeparator(i)) {
819 // register breakpoint:
826 // maybe found one, but the par is short enough.
827 if (i == end && x < width)
830 // manual labels cannot be broken in LaTeX. But we
831 // want to make our on-screen rendering of footnotes
833 if (body_pos && point < body_pos)
840 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
841 pos_type const first, pos_type const end) const
843 Buffer & buffer = bv_->buffer();
844 // get the pure distance
845 ParagraphMetrics const & pm = par_metrics_[pit];
846 Paragraph const & par = text_->getPar(pit);
847 int w = leftMargin(max_width_, pit, first);
848 int label_end = labelEnd(pit);
850 // check for possible inline completion
851 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
852 pos_type inlineCompletionVPos = -1;
853 if (inlineCompletionPos.inTexted()
854 && inlineCompletionPos.text() == text_
855 && inlineCompletionPos.pit() == pit) {
856 // draw visually behind the previous character
857 // FIXME: probably special RTL handling needed here
858 inlineCompletionVPos = inlineCompletionPos.pos() - 1;
861 pos_type const body_pos = par.beginOfBody();
865 FontIterator fi = FontIterator(*this, par, pit, i);
866 for ( ; i < end; ++i, ++fi) {
867 if (body_pos > 0 && i == body_pos) {
868 FontMetrics const & fm = theFontMetrics(
869 text_->getLabelFont(buffer, par));
870 w += fm.width(par.layout()->labelsep);
871 if (par.isLineSeparator(i - 1))
872 w -= singleWidth(pit, i - 1);
873 w = max(w, label_end);
875 w += pm.singleWidth(i, *fi);
877 // add inline completion width
878 if (inlineCompletionVPos == i) {
879 docstring const & completion = bv_->inlineCompletion();
880 if (completion.length() > 0)
881 w += theFontMetrics(*fi).width(completion);
886 if (body_pos > 0 && body_pos >= end) {
887 FontMetrics const & fm = theFontMetrics(
888 text_->getLabelFont(buffer, par));
889 w += fm.width(par.layout()->labelsep);
890 if (end > 0 && par.isLineSeparator(end - 1))
891 w -= singleWidth(pit, end - 1);
892 w = max(w, label_end);
895 return w + right_margin;
899 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
900 pos_type const end, bool topBottomSpace) const
902 Paragraph const & par = text_->getPar(pit);
903 // get the maximum ascent and the maximum descent
904 double layoutasc = 0;
905 double layoutdesc = 0;
906 double const dh = defaultRowHeight();
908 // ok, let us initialize the maxasc and maxdesc value.
909 // Only the fontsize count. The other properties
910 // are taken from the layoutfont. Nicer on the screen :)
911 LayoutPtr const & layout = par.layout();
913 // as max get the first character of this row then it can
914 // increase but not decrease the height. Just some point to
915 // start with so we don't have to do the assignment below too
917 Buffer const & buffer = bv_->buffer();
918 Font font = getDisplayFont(pit, first);
919 FontSize const tmpsize = font.fontInfo().size();
920 font.fontInfo() = text_->getLayoutFont(buffer, pit);
921 FontSize const size = font.fontInfo().size();
922 font.fontInfo().setSize(tmpsize);
924 FontInfo labelfont = text_->getLabelFont(buffer, par);
926 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
927 FontMetrics const & fontmetrics = theFontMetrics(font);
929 // these are minimum values
930 double const spacing_val = layout->spacing.getValue()
931 * text_->spacing(buffer, par);
932 //lyxerr << "spacing_val = " << spacing_val << endl;
933 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
934 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
936 // insets may be taller
937 ParagraphMetrics const & pm = par_metrics_[pit];
938 InsetList::const_iterator ii = par.insetList().begin();
939 InsetList::const_iterator iend = par.insetList().end();
940 for ( ; ii != iend; ++ii) {
941 Dimension const & dim = pm.insetDimension(ii->inset);
942 if (ii->pos >= first && ii->pos < end) {
943 maxasc = max(maxasc, dim.ascent());
944 maxdesc = max(maxdesc, dim.descent());
948 // Check if any custom fonts are larger (Asger)
949 // This is not completely correct, but we can live with the small,
950 // cosmetic error for now.
954 par.highestFontInRange(first, end, size);
955 if (maxsize > font.fontInfo().size()) {
956 // use standard paragraph font with the maximal size
957 FontInfo maxfont = font.fontInfo();
958 maxfont.setSize(maxsize);
959 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
960 maxasc = max(maxasc, maxfontmetrics.maxAscent());
961 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
964 // This is nicer with box insets:
968 ParagraphList const & pars = text_->paragraphs();
971 if (first == 0 && topBottomSpace) {
972 BufferParams const & bufparams = buffer.params();
973 // some parskips VERY EASY IMPLEMENTATION
974 if (bufparams.paragraph_separation
975 == BufferParams::PARSEP_SKIP
976 && par.ownerCode() != ERT_CODE
977 && par.ownerCode() != LISTINGS_CODE
979 && ((layout->isParagraph() && par.getDepth() == 0)
980 || (pars[pit - 1].layout()->isParagraph()
981 && pars[pit - 1].getDepth() == 0)))
983 maxasc += bufparams.getDefSkip().inPixels(*bv_);
986 if (par.params().startOfAppendix())
987 maxasc += int(3 * dh);
989 // This is special code for the chapter, since the label of this
990 // layout is printed in an extra row
991 if (layout->counter == "chapter"
992 && !par.params().labelString().empty()) {
993 labeladdon = int(labelfont_metrics.maxHeight()
994 * layout->spacing.getValue()
995 * text_->spacing(buffer, par));
998 // special code for the top label
999 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1000 || layout->labeltype == LABEL_BIBLIO
1001 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1002 && isFirstInSequence(pit, pars)
1003 && !par.getLabelstring().empty())
1006 labelfont_metrics.maxHeight()
1007 * layout->spacing.getValue()
1008 * text_->spacing(buffer, par)
1009 + (layout->topsep + layout->labelbottomsep) * dh);
1012 // Add the layout spaces, for example before and after
1013 // a section, or between the items of a itemize or enumerate
1016 pit_type prev = depthHook(pit, pars, par.getDepth());
1017 Paragraph const & prevpar = pars[prev];
1019 && prevpar.layout() == layout
1020 && prevpar.getDepth() == par.getDepth()
1021 && prevpar.getLabelWidthString()
1022 == par.getLabelWidthString()) {
1023 layoutasc = layout->itemsep * dh;
1024 } else if (pit != 0 || first != 0) {
1025 if (layout->topsep > 0)
1026 layoutasc = layout->topsep * dh;
1029 prev = outerHook(pit, pars);
1030 if (prev != pit_type(pars.size())) {
1031 maxasc += int(pars[prev].layout()->parsep * dh);
1032 } else if (pit != 0) {
1033 Paragraph const & prevpar = pars[pit - 1];
1034 if (prevpar.getDepth() != 0 ||
1035 prevpar.layout() == layout) {
1036 maxasc += int(layout->parsep * dh);
1041 // is it a bottom line?
1042 if (end >= par.size() && topBottomSpace) {
1043 // add the layout spaces, for example before and after
1044 // a section, or between the items of a itemize or enumerate
1046 pit_type nextpit = pit + 1;
1047 if (nextpit != pit_type(pars.size())) {
1048 pit_type cpit = pit;
1052 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1053 usual = pars[cpit].layout()->bottomsep * dh;
1054 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1055 if (pars[cpit].layout() != pars[nextpit].layout()
1056 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1058 unusual = pars[cpit].layout()->bottomsep * dh;
1060 layoutdesc = max(unusual, usual);
1061 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1062 if (pars[cpit].layout() != pars[nextpit].layout()
1063 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1064 layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
1069 // incalculate the layout spaces
1070 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1071 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1073 // FIXME: the correct way is to do the following is to move the
1074 // following code in another method specially tailored for the
1075 // main Text. The following test is thus bogus.
1076 // Top and bottom margin of the document (only at top-level)
1077 if (main_text_ && topBottomSpace) {
1078 if (pit == 0 && first == 0)
1080 if (pit + 1 == pit_type(pars.size()) &&
1081 end == par.size() &&
1082 !(end > 0 && par.isNewline(end - 1)))
1086 return Dimension(0, maxasc + labeladdon, maxdesc);
1090 // x is an absolute screen coord
1091 // returns the column near the specified x-coordinate of the row
1092 // x is set to the real beginning of this column
1093 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1094 Row const & row, int & x, bool & boundary) const
1096 Buffer const & buffer = bv_->buffer();
1098 /// For the main Text, it is possible that this pit is not
1099 /// yet in the CoordCache when moving cursor up.
1100 /// x Paragraph coordinate is always 0 for main text anyway.
1101 int const xo = origin_.x_;
1103 Paragraph const & par = text_->getPar(pit);
1105 bidi.computeTables(par, buffer, row);
1107 pos_type vc = row.pos();
1108 pos_type end = row.endpos();
1110 LayoutPtr const & layout = par.layout();
1112 bool left_side = false;
1114 pos_type body_pos = par.beginOfBody();
1116 double tmpx = row.x;
1117 double last_tmpx = tmpx;
1120 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1123 // check for empty row
1129 while (vc < end && tmpx <= x) {
1130 c = bidi.vis2log(vc);
1132 if (body_pos > 0 && c == body_pos - 1) {
1133 FontMetrics const & fm = theFontMetrics(
1134 text_->getLabelFont(buffer, par));
1135 tmpx += row.label_hfill + fm.width(layout->labelsep);
1136 if (par.isLineSeparator(body_pos - 1))
1137 tmpx -= singleWidth(pit, body_pos - 1);
1140 tmpx += singleWidth(pit, c);
1141 if (par.isSeparator(c) && c >= body_pos)
1142 tmpx += row.separator;
1146 if ((tmpx + last_tmpx) / 2 > x) {
1151 BOOST_ASSERT(vc <= end); // This shouldn't happen.
1154 // This (rtl_support test) is not needed, but gives
1155 // some speedup if rtl_support == false
1156 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1158 // If lastrow is false, we don't need to compute
1159 // the value of rtl.
1160 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1162 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1163 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1164 if (!par.isNewline(end - 1))
1166 } else if (vc == row.pos()) {
1167 c = bidi.vis2log(vc);
1168 if (bidi.level(c) % 2 == 1)
1171 c = bidi.vis2log(vc - 1);
1172 bool const rtl = (bidi.level(c) % 2 == 1);
1173 if (left_side == rtl) {
1175 boundary = isRTLBoundary(pit, c);
1179 // I believe this code is not needed anymore (Jug 20050717)
1181 // The following code is necessary because the cursor position past
1182 // the last char in a row is logically equivalent to that before
1183 // the first char in the next row. That's why insets causing row
1184 // divisions -- Newline and display-style insets -- must be treated
1185 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1186 // Newline inset, air gap below:
1187 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1188 if (bidi.level(end -1) % 2 == 0)
1189 tmpx -= singleWidth(pit, end - 1);
1191 tmpx += singleWidth(pit, end - 1);
1195 // Air gap above display inset:
1196 if (row.pos() < end && c >= end && end < par.size()
1197 && par.isInset(end) && par.getInset(end)->display()) {
1200 // Air gap below display inset:
1201 if (row.pos() < end && c >= end && par.isInset(end - 1)
1202 && par.getInset(end - 1)->display()) {
1208 pos_type const col = c - row.pos();
1210 if (!c || end == par.size())
1213 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1218 return min(col, end - 1 - row.pos());
1222 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1224 // We play safe and use parMetrics(pit) to make sure the
1225 // ParagraphMetrics will be redone and OK to use if needed.
1226 // Otherwise we would use an empty ParagraphMetrics in
1227 // upDownInText() while in selection mode.
1228 ParagraphMetrics const & pm = parMetrics(pit);
1230 BOOST_ASSERT(row < int(pm.rows().size()));
1232 Row const & r = pm.rows()[row];
1233 return r.pos() + getColumnNearX(pit, r, x, bound);
1237 void TextMetrics::newParMetricsDown()
1239 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1240 pit_type const pit = last.first + 1;
1241 if (pit == int(text_->paragraphs().size()))
1244 // do it and update its position.
1246 par_metrics_[pit].setPosition(last.second.position()
1247 + last.second.descent() + par_metrics_[pit].ascent());
1251 void TextMetrics::newParMetricsUp()
1253 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1254 if (first.first == 0)
1257 pit_type const pit = first.first - 1;
1258 // do it and update its position.
1260 par_metrics_[pit].setPosition(first.second.position()
1261 - first.second.ascent() - par_metrics_[pit].descent());
1264 // y is screen coordinate
1265 pit_type TextMetrics::getPitNearY(int y)
1267 BOOST_ASSERT(!text_->paragraphs().empty());
1268 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1270 // look for highest numbered paragraph with y coordinate less than given y
1273 ParMetricsCache::const_iterator it = par_metrics_.begin();
1274 ParMetricsCache::const_iterator et = par_metrics_.end();
1275 ParMetricsCache::const_iterator last = et; last--;
1277 ParagraphMetrics const & pm = it->second;
1279 if (y < it->second.position() - int(pm.ascent())) {
1280 // We are looking for a position that is before the first paragraph in
1281 // the cache (which is in priciple off-screen, that is before the
1284 // We are already at the first paragraph in the inset.
1286 // OK, this is the paragraph we are looking for.
1287 pit = it->first - 1;
1292 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1294 if (y >= last->second.position() + int(pm_last.descent())) {
1295 // We are looking for a position that is after the last paragraph in
1296 // the cache (which is in priciple off-screen, that is before the
1298 pit = last->first + 1;
1299 if (pit == int(text_->paragraphs().size()))
1300 // We are already at the last paragraph in the inset.
1302 // OK, this is the paragraph we are looking for.
1303 newParMetricsDown();
1307 for (; it != et; ++it) {
1308 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1309 << " y: " << it->second.position());
1311 ParagraphMetrics const & pm = par_metrics_[it->first];
1313 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1315 yy = it->second.position();
1319 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1325 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1327 ParagraphMetrics const & pm = par_metrics_[pit];
1329 int yy = pm.position() - pm.ascent();
1330 BOOST_ASSERT(!pm.rows().empty());
1331 RowList::const_iterator rit = pm.rows().begin();
1332 RowList::const_iterator rlast = pm.rows().end();
1334 for (; rit != rlast; yy += rit->height(), ++rit)
1335 if (yy + rit->height() > y)
1341 // x,y are absolute screen coordinates
1342 // sets cursor recursively descending into nested editable insets
1343 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1345 if (lyxerr.debugging(Debug::WORKAREA)) {
1346 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1347 cur.bv().coordCache().dump();
1349 pit_type pit = getPitNearY(y);
1350 BOOST_ASSERT(pit != -1);
1352 Row const & row = getRowNearY(y, pit);
1355 int xx = x; // is modified by getColumnNearX
1356 pos_type const pos = row.pos()
1357 + getColumnNearX(pit, row, xx, bound);
1360 cur.boundary(bound);
1363 // try to descend into nested insets
1364 Inset * inset = checkInsetHit(x, y);
1365 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1367 // Either we deconst editXY or better we move current_font
1368 // and real_current_font to Cursor
1369 // FIXME: what is needed now that current_font and real_current_font
1371 cur.setCurrentFont();
1375 ParagraphList const & pars = text_->paragraphs();
1376 Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1377 //Inset * insetBehind = pars[pit].getInset(pos);
1379 // This should be just before or just behind the
1380 // cursor position set above.
1381 BOOST_ASSERT((pos != 0 && inset == insetBefore)
1382 || inset == pars[pit].getInset(pos));
1384 // Make sure the cursor points to the position before
1386 if (inset == insetBefore) {
1388 cur.boundary(false);
1391 // Try to descend recursively inside the inset.
1392 inset = inset->editXY(cur, x, y);
1394 if (cur.top().text() == text_)
1395 cur.setCurrentFont();
1400 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1402 BOOST_ASSERT(text_ == cur.text());
1403 pit_type pit = getPitNearY(y);
1405 ParagraphMetrics const & pm = par_metrics_[pit];
1407 int yy = pm.position() - pm.ascent();
1408 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1409 " pit: " << pit << " yy: " << yy);
1412 BOOST_ASSERT(pm.rows().size());
1413 for (; r < int(pm.rows().size()) - 1; ++r) {
1414 Row const & row = pm.rows()[r];
1415 if (int(yy + row.height()) > y)
1420 Row const & row = pm.rows()[r];
1422 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1426 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1428 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1430 text_->setCursor(cur, pit, pos, true, bound);
1431 // remember new position.
1436 //takes screen x,y coordinates
1437 Inset * TextMetrics::checkInsetHit(int x, int y)
1439 pit_type pit = getPitNearY(y);
1440 BOOST_ASSERT(pit != -1);
1442 Paragraph const & par = text_->paragraphs()[pit];
1443 ParagraphMetrics const & pm = par_metrics_[pit];
1445 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1447 InsetList::const_iterator iit = par.insetList().begin();
1448 InsetList::const_iterator iend = par.insetList().end();
1449 for (; iit != iend; ++iit) {
1450 Inset * inset = iit->inset;
1452 LYXERR(Debug::DEBUG, "examining inset " << inset);
1454 if (!bv_->coordCache().getInsets().has(inset)) {
1455 LYXERR(Debug::DEBUG, "inset has no cached position");
1459 Dimension const & dim = pm.insetDimension(inset);
1460 Point p = bv_->coordCache().getInsets().xy(inset);
1462 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1463 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1466 && x <= p.x_ + dim.wid
1467 && y >= p.y_ - dim.asc
1468 && y <= p.y_ + dim.des) {
1469 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1474 LYXERR(Debug::DEBUG, "No inset hit. ");
1479 int TextMetrics::cursorX(CursorSlice const & sl,
1480 bool boundary) const
1482 BOOST_ASSERT(sl.text() == text_);
1483 pit_type const pit = sl.pit();
1484 Paragraph const & par = text_->paragraphs()[pit];
1485 ParagraphMetrics const & pm = par_metrics_[pit];
1486 if (pm.rows().empty())
1489 pos_type ppos = sl.pos();
1490 // Correct position in front of big insets
1491 bool const boundary_correction = ppos != 0 && boundary;
1492 if (boundary_correction)
1495 Row const & row = pm.getRow(sl.pos(), boundary);
1497 pos_type cursor_vpos = 0;
1499 Buffer const & buffer = bv_->buffer();
1502 bidi.computeTables(par, buffer, row);
1504 pos_type const row_pos = row.pos();
1505 pos_type const end = row.endpos();
1506 // Spaces at logical line breaks in bidi text must be skipped during
1507 // cursor positioning. However, they may appear visually in the middle
1508 // of a row; they must be skipped, wherever they are...
1509 // * logically "abc_[HEBREW_\nHEBREW]"
1510 // * visually "abc_[_WERBEH\nWERBEH]"
1511 pos_type skipped_sep_vpos = -1;
1514 cursor_vpos = row_pos;
1515 else if (ppos >= end)
1516 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1517 else if (ppos > row_pos && ppos >= end)
1518 // Place cursor after char at (logical) position pos - 1
1519 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1520 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1522 // Place cursor before char at (logical) position ppos
1523 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1524 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1526 pos_type body_pos = par.beginOfBody();
1528 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1531 // Use font span to speed things up, see below
1535 // If the last logical character is a separator, skip it, unless
1536 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1537 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1538 skipped_sep_vpos = bidi.log2vis(end - 1);
1540 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1541 // Skip the separator which is at the logical end of the row
1542 if (vpos == skipped_sep_vpos)
1544 pos_type pos = bidi.vis2log(vpos);
1545 if (body_pos > 0 && pos == body_pos - 1) {
1546 FontMetrics const & labelfm = theFontMetrics(
1547 text_->getLabelFont(buffer, par));
1548 x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1549 if (par.isLineSeparator(body_pos - 1))
1550 x -= singleWidth(pit, body_pos - 1);
1553 // Use font span to speed things up, see above
1554 if (pos < font_span.first || pos > font_span.last) {
1555 font_span = par.fontSpan(pos);
1556 font = getDisplayFont(pit, pos);
1559 x += pm.singleWidth(pos, font);
1561 if (par.isSeparator(pos) && pos >= body_pos)
1565 // see correction above
1566 if (boundary_correction) {
1567 if (isRTL(sl, boundary))
1568 x -= singleWidth(pit, ppos);
1570 x += singleWidth(pit, ppos);
1577 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1579 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1580 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1581 if (pm.rows().empty())
1585 h -= par_metrics_[0].rows()[0].ascent();
1586 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1587 h += par_metrics_[pit].height();
1590 if (pos && boundary)
1592 size_t const rend = pm.pos2row(pos);
1593 for (size_t rit = 0; rit != rend; ++rit)
1594 h += pm.rows()[rit].height();
1595 h += pm.rows()[rend].ascent();
1600 void TextMetrics::cursorPrevious(Cursor & cur)
1602 pos_type cpos = cur.pos();
1603 pit_type cpar = cur.pit();
1605 int x = cur.x_target();
1606 setCursorFromCoordinates(cur, x, 0);
1607 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1609 if (cpar == cur.pit() && cpos == cur.pos())
1610 // we have a row which is taller than the workarea. The
1611 // simplest solution is to move to the previous row instead.
1612 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1615 cur.updateFlags(Update::Force | Update::FitCursor);
1619 void TextMetrics::cursorNext(Cursor & cur)
1621 pos_type cpos = cur.pos();
1622 pit_type cpar = cur.pit();
1624 int x = cur.x_target();
1625 setCursorFromCoordinates(cur, x, cur.bv().workHeight() - 1);
1626 cur.dispatch(FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1628 if (cpar == cur.pit() && cpos == cur.pos())
1629 // we have a row which is taller than the workarea. The
1630 // simplest solution is to move to the next row instead.
1632 FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1635 cur.updateFlags(Update::Force | Update::FitCursor);
1639 // the cursor set functions have a special mechanism. When they
1640 // realize you left an empty paragraph, they will delete it.
1642 bool TextMetrics::cursorHome(Cursor & cur)
1644 BOOST_ASSERT(text_ == cur.text());
1645 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1646 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1647 return text_->setCursor(cur, cur.pit(), row.pos());
1651 bool TextMetrics::cursorEnd(Cursor & cur)
1653 BOOST_ASSERT(text_ == cur.text());
1654 // if not on the last row of the par, put the cursor before
1655 // the final space exept if I have a spanning inset or one string
1656 // is so long that we force a break.
1657 pos_type end = cur.textRow().endpos();
1659 // empty text, end-1 is no valid position
1661 bool boundary = false;
1662 if (end != cur.lastpos()) {
1663 if (!cur.paragraph().isLineSeparator(end-1)
1664 && !cur.paragraph().isNewline(end-1))
1669 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1673 void TextMetrics::deleteLineForward(Cursor & cur)
1675 BOOST_ASSERT(text_ == cur.text());
1676 if (cur.lastpos() == 0) {
1677 // Paragraph is empty, so we just go forward
1678 text_->cursorForward(cur);
1681 cur.selection() = true; // to avoid deletion
1684 // What is this test for ??? (JMarc)
1685 if (!cur.selection())
1686 text_->deleteWordForward(cur);
1688 cap::cutSelection(cur, true, false);
1689 cur.checkBufferStructure();
1694 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1696 ParagraphList const & pars = text_->paragraphs();
1697 return row.endpos() >= pars[pit].size()
1698 && pit + 1 == pit_type(pars.size());
1702 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1704 return row.pos() == 0 && pit == 0;
1708 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1710 BOOST_ASSERT(pit >= 0);
1711 BOOST_ASSERT(pit < int(text_->paragraphs().size()));
1712 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1716 int TextMetrics::leftMargin(int max_width,
1717 pit_type const pit, pos_type const pos) const
1719 ParagraphList const & pars = text_->paragraphs();
1721 BOOST_ASSERT(pit >= 0);
1722 BOOST_ASSERT(pit < int(pars.size()));
1723 Paragraph const & par = pars[pit];
1724 BOOST_ASSERT(pos >= 0);
1725 BOOST_ASSERT(pos <= par.size());
1726 Buffer const & buffer = bv_->buffer();
1727 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1728 TextClass const & tclass = buffer.params().getTextClass();
1729 LayoutPtr const & layout = par.layout();
1731 docstring parindent = layout->parindent;
1735 if (text_->isMainText(buffer))
1736 l_margin += bv_->leftMargin();
1738 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1739 tclass.leftmargin());
1741 if (par.getDepth() != 0) {
1742 // find the next level paragraph
1743 pit_type newpar = outerHook(pit, pars);
1744 if (newpar != pit_type(pars.size())) {
1745 if (pars[newpar].layout()->isEnvironment()) {
1746 l_margin = leftMargin(max_width, newpar);
1748 //FIXME Should this check for emptyLayout() as well?
1749 if (par.layout() == tclass.defaultLayout()) {
1750 if (pars[newpar].params().noindent())
1753 parindent = pars[newpar].layout()->parindent;
1758 // This happens after sections in standard classes. The 1.3.x
1759 // code compared depths too, but it does not seem necessary
1761 if (par.layout() == tclass.defaultLayout()
1762 && pit > 0 && pars[pit - 1].layout()->nextnoindent)
1765 FontInfo const labelfont = text_->getLabelFont(buffer, par);
1766 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1768 switch (layout->margintype) {
1769 case MARGIN_DYNAMIC:
1770 if (!layout->leftmargin.empty()) {
1771 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1772 layout->leftmargin);
1774 if (!par.getLabelstring().empty()) {
1775 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1776 l_margin += labelfont_metrics.width(par.getLabelstring());
1777 l_margin += labelfont_metrics.width(layout->labelsep);
1781 case MARGIN_MANUAL: {
1782 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1783 // The width of an empty par, even with manual label, should be 0
1784 if (!par.empty() && pos >= par.beginOfBody()) {
1785 if (!par.getLabelWidthString().empty()) {
1786 docstring labstr = par.getLabelWidthString();
1787 l_margin += labelfont_metrics.width(labstr);
1788 l_margin += labelfont_metrics.width(layout->labelsep);
1794 case MARGIN_STATIC: {
1795 l_margin += theFontMetrics(buffer.params().getFont()).
1796 signedWidth(layout->leftmargin) * 4 / (par.getDepth() + 4);
1800 case MARGIN_FIRST_DYNAMIC:
1801 if (layout->labeltype == LABEL_MANUAL) {
1802 if (pos >= par.beginOfBody()) {
1803 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1805 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1808 // Special case to fix problems with
1810 || (layout->labeltype == LABEL_STATIC
1811 && layout->latextype == LATEX_ENVIRONMENT
1812 && !isFirstInSequence(pit, pars))) {
1813 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1814 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
1815 && layout->labeltype != LABEL_BIBLIO
1816 && layout->labeltype !=
1817 LABEL_CENTERED_TOP_ENVIRONMENT) {
1818 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1819 l_margin += labelfont_metrics.width(layout->labelsep);
1820 l_margin += labelfont_metrics.width(par.getLabelstring());
1824 case MARGIN_RIGHT_ADDRESS_BOX: {
1826 // ok, a terrible hack. The left margin depends on the widest
1827 // row in this paragraph.
1828 RowList::iterator rit = par.rows().begin();
1829 RowList::iterator end = par.rows().end();
1830 // FIXME: This is wrong.
1831 int minfill = max_width;
1832 for ( ; rit != end; ++rit)
1833 if (rit->fill() < minfill)
1834 minfill = rit->fill();
1835 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
1836 l_margin += minfill;
1838 // also wrong, but much shorter.
1839 l_margin += max_width / 2;
1844 if (!par.params().leftIndent().zero())
1845 l_margin += par.params().leftIndent().inPixels(max_width);
1849 if (par.params().align() == LYX_ALIGN_LAYOUT)
1850 align = layout->align;
1852 align = par.params().align();
1854 // set the correct parindent
1856 && (layout->labeltype == LABEL_NO_LABEL
1857 || layout->labeltype == LABEL_TOP_ENVIRONMENT
1858 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1859 || (layout->labeltype == LABEL_STATIC
1860 && layout->latextype == LATEX_ENVIRONMENT
1861 && !isFirstInSequence(pit, pars)))
1862 && align == LYX_ALIGN_BLOCK
1863 && !par.params().noindent()
1864 // in some insets, paragraphs are never indented
1865 && !(par.inInset() && par.inInset()->neverIndent(buffer))
1866 // display style insets are always centered, omit indentation
1869 && par.getInset(pos)->display())
1870 && (par.layout() != tclass.defaultLayout() //should this check emptyLayout()?
1871 || buffer.params().paragraph_separation ==
1872 BufferParams::PARSEP_INDENT))
1874 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1882 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1884 ParagraphMetrics const & pm = par_metrics_[pit];
1886 return pm.singleWidth(pos, getDisplayFont(pit, pos));
1890 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1892 if (par_metrics_.empty())
1898 ParMetricsCache::iterator it = par_metrics_.begin();
1899 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1900 y -= it->second.ascent();
1901 for (; it != pm_end; ++it) {
1902 ParagraphMetrics const & pmi = it->second;
1904 pit_type const pit = it->first;
1905 // Save the paragraph position in the cache.
1906 it->second.setPosition(y);
1907 drawParagraph(pi, pit, x, y);
1913 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1915 BufferParams const & bparams = bv_->buffer().params();
1916 ParagraphMetrics const & pm = par_metrics_[pit];
1917 if (pm.rows().empty())
1921 bool const original_drawing_state = pi.pain.isDrawingEnabled();
1922 int const ww = bv_->workHeight();
1923 size_t const nrows = pm.rows().size();
1925 for (size_t i = 0; i != nrows; ++i) {
1927 Row const & row = pm.rows()[i];
1931 bool const inside = (y + row.descent() >= 0
1932 && y - row.ascent() < ww);
1933 // It is not needed to draw on screen if we are not inside.
1934 pi.pain.setDrawingEnabled(inside && original_drawing_state);
1935 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
1937 // Row signature; has row changed since last paint?
1938 row.setCrc(pm.computeRowSignature(row, bparams));
1939 bool row_has_changed = row.changed();
1941 // Don't paint the row if a full repaint has not been requested
1942 // and if it has not changed.
1943 if (!pi.full_repaint && !row_has_changed) {
1944 // Paint only the insets if the text itself is
1946 rp.paintOnlyInsets();
1951 // Clear background of this row if paragraph background was not
1952 // already cleared because of a full repaint.
1953 if (!pi.full_repaint && row_has_changed) {
1954 pi.pain.fillRectangle(x, y - row.ascent(),
1955 width(), row.height(), pi.background_color);
1958 bool row_selection = row.sel_beg != -1 && row.sel_end != -1;
1959 if (row_selection) {
1960 DocIterator beg = bv_->cursor().selectionBegin();
1961 DocIterator end = bv_->cursor().selectionEnd();
1962 bool const beg_margin = beg.pit() < pit && i == 0;
1963 bool const end_margin = end.pit() > pit && i == nrows - 1;
1965 beg.pos() = row.sel_beg;
1967 end.pos() = row.sel_end;
1968 drawRowSelection(pi, x, row, beg, end, beg_margin, end_margin);
1971 // Instrumentation for testing row cache (see also
1973 if (lyxerr.debugging(Debug::PAINTING) && inside
1974 && (row_selection || pi.full_repaint || row_has_changed)) {
1975 string const foreword = text_->isMainText(bv_->buffer()) ?
1976 "main text redraw " : "inset text redraw: ";
1977 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
1978 << " row_selection=" << row_selection
1979 << " full_repaint=" << pi.full_repaint
1980 << " row_has_changed=" << row_has_changed);
1983 // Backup full_repaint status and force full repaint
1984 // for inner insets as the Row has been cleared out.
1985 bool tmp = pi.full_repaint;
1986 pi.full_repaint = true;
1989 rp.paintChangeBar();
1996 // Restore full_repaint status.
1997 pi.full_repaint = tmp;
1999 // Re-enable screen drawing for future use of the painter.
2000 pi.pain.setDrawingEnabled(original_drawing_state);
2002 //LYXERR(Debug::PAINTING, ".");
2006 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2007 DocIterator const & beg, DocIterator const & end,
2008 bool drawOnBegMargin, bool drawOnEndMargin) const
2010 Buffer & buffer = bv_->buffer();
2011 DocIterator cur = beg;
2012 int x1 = cursorX(beg.top(), beg.boundary());
2013 int x2 = cursorX(end.top(), end.boundary());
2014 int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2015 int y2 = y1 + row.height();
2018 if (drawOnBegMargin) {
2019 if (text_->isRTL(buffer, beg.paragraph()))
2020 pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color_selection);
2022 pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color_selection);
2025 if (drawOnEndMargin) {
2026 if (text_->isRTL(buffer, beg.paragraph()))
2027 pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color_selection);
2029 pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color_selection);
2032 // if we are on a boundary from the beginning, it's probably
2033 // a RTL boundary and we jump to the other side directly as this
2034 // segement is 0-size and confuses the logic below
2036 cur.boundary(false);
2038 // go through row and draw from RTL boundary to RTL boundary
2040 bool drawNow = false;
2042 // simplified cursorForward code below which does not
2043 // descend into insets and which does not go into the
2044 // next line. Compare the logic with the original cursorForward
2046 // if left of boundary -> just jump to right side
2047 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2048 if (cur.boundary()) {
2049 cur.boundary(false);
2050 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2051 // in front of RTL boundary -> Stay on this side of the boundary because:
2052 // ab|cDDEEFFghi -> abc|DDEEFFghi
2061 if (cur.pos() == row.endpos())
2066 // the previous segment was just drawn, now the next starts
2067 x1 = cursorX(cur.top(), cur.boundary());
2070 if (!(cur < end) || drawNow) {
2071 x2 = cursorX(cur.top(), cur.boundary());
2072 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2075 // reset x1, so it is set again next round (which will be on the
2076 // right side of a boundary or at the selection end)
2082 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2084 // ParagraphMetrics const & pm = par_metrics_[pit];
2085 // Row const & r = pm.rows()[row];
2091 int defaultRowHeight()
2093 return int(theFontMetrics(sane_font).maxHeight() * 1.2);