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::contains(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::displayFont(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 Layout 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 displayFont(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 = displayFont(pit, pos - 1).isVisibleRightToLeft();
322 if (pos == par.size())
323 right = par.isRTL(bv_->buffer().params());
325 right = displayFont(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 = displayFont(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);
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 : displayFont(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 par.setBeginOfBody();
428 size_t row_index = 0;
429 // maximum pixel width of a row
430 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
433 pos_type end = rowBreakPoint(width, pit, first);
434 if (row_index || end < par.size())
435 // If there is more than one row, expand the text to
436 // the full allowable width. This setting here is needed
437 // for the computeRowMetrics() below.
438 dim_.wid = max_width_;
440 dim = rowHeight(pit, first, end);
441 dim.wid = rowWidth(right_margin, pit, first, end);
442 if (row_index == pm.rows().size())
443 pm.rows().push_back(Row());
444 Row & row = pm.rows()[row_index];
445 row.setChanged(false);
448 row.setDimension(dim);
449 int const max_row_width = max(dim_.wid, dim.wid);
450 computeRowMetrics(pit, row, max_row_width);
454 pm.dim().wid = max(pm.dim().wid, dim.wid);
455 pm.dim().des += dim.height();
456 } while (first < par.size());
458 if (row_index < pm.rows().size())
459 pm.rows().resize(row_index);
461 // Make sure that if a par ends in newline, there is one more row
463 if (first > 0 && par.isNewline(first - 1)) {
464 Dimension dim = rowHeight(pit, first, first);
465 dim.wid = rowWidth(right_margin, pit, first, first);
466 if (row_index == pm.rows().size())
467 pm.rows().push_back(Row());
468 Row & row = pm.rows()[row_index];
469 row.setChanged(false);
472 row.setDimension(dim);
473 int const max_row_width = max(dim_.wid, dim.wid);
474 computeRowMetrics(pit, row, max_row_width);
475 pm.dim().des += dim.height();
478 pm.dim().asc += pm.rows()[0].ascent();
479 pm.dim().des -= pm.rows()[0].ascent();
481 changed |= old_dim.height() != pm.dim().height();
487 void TextMetrics::computeRowMetrics(pit_type const pit,
488 Row & row, int width) const
493 Buffer & buffer = bv_->buffer();
494 Paragraph const & par = text_->getPar(pit);
496 double w = width - row.width();
497 // FIXME: put back this assertion when the crash on new doc is solved.
498 //BOOST_ASSERT(w >= 0);
500 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
501 //lyxerr << "row.width() " << row.width() << endl;
502 //lyxerr << "w " << w << endl;
504 bool const is_rtl = text_->isRTL(buffer, par);
506 row.x = rightMargin(pit);
508 row.x = leftMargin(max_width_, pit, row.pos());
510 // is there a manual margin with a manual label
511 Layout const & layout = par.layout();
513 if (layout.margintype == MARGIN_MANUAL
514 && layout.labeltype == LABEL_MANUAL) {
515 /// We might have real hfills in the label part
516 int nlh = numberOfLabelHfills(par, row);
518 // A manual label par (e.g. List) has an auto-hfill
519 // between the label text and the body of the
521 // But we don't want to do this auto hfill if the par
526 if (nlh && !par.getLabelWidthString().empty())
527 row.label_hfill = labelFill(pit, row) / double(nlh);
531 // are there any hfills in the row?
532 if (int const nh = numberOfHfills(par, row)) {
534 hfill = w / double(nh);
535 // we don't have to look at the alignment if it is ALIGN_LEFT and
536 // if the row is already larger then the permitted width as then
537 // we force the LEFT_ALIGN'edness!
538 } else if (int(row.width()) < max_width_) {
539 // is it block, flushleft or flushright?
540 // set x how you need it
542 if (par.params().align() == LYX_ALIGN_LAYOUT)
543 align = layout.align;
545 align = par.params().align();
547 // Display-style insets should always be on a centred row
548 if (Inset const * inset = par.getInset(row.pos())) {
549 switch (inset->display()) {
550 case Inset::AlignLeft:
551 align = LYX_ALIGN_BLOCK;
553 case Inset::AlignCenter:
554 align = LYX_ALIGN_CENTER;
557 case Inset::AlignRight:
558 // unchanged (use align)
564 case LYX_ALIGN_BLOCK: {
565 int const ns = numberOfSeparators(par, row);
566 bool disp_inset = false;
567 if (row.endpos() < par.size()) {
568 Inset const * in = par.getInset(row.endpos());
570 disp_inset = in->display();
572 // If we have separators, this is not the last row of a
573 // par, does not end in newline, and is not row above a
574 // display inset... then stretch it
576 && row.endpos() < par.size()
577 && !par.isNewline(row.endpos() - 1)
580 row.separator = w / ns;
581 //lyxerr << "row.separator " << row.separator << endl;
582 //lyxerr << "ns " << ns << endl;
588 case LYX_ALIGN_RIGHT:
591 case LYX_ALIGN_CENTER:
598 pos_type body_pos = par.beginOfBody();
599 pos_type end = row.endpos();
602 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
604 row.x += theFontMetrics(text_->labelFont(buffer, par)).
605 width(layout.labelsep);
607 row.x += row.label_hfill;
611 pos_type const endpos = row.endpos();
612 pos_type body_pos = par.beginOfBody();
614 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
617 ParagraphMetrics & pm = par_metrics_[pit];
618 InsetList::const_iterator ii = par.insetList().begin();
619 InsetList::const_iterator iend = par.insetList().end();
620 for ( ; ii != iend; ++ii) {
621 if (ii->pos >= endpos || ii->pos < row.pos()
622 || ii->inset->lyxCode() != HFILL_CODE)
624 Dimension dim = row.dimension();
625 if (pm.hfillExpansion(row, ii->pos))
626 dim.wid = int(ii->pos >= body_pos ?
627 max(hfill, 5.0) : row.label_hfill);
630 // Cache the inset dimension.
631 bv_->coordCache().insets().add(ii->inset, dim);
632 pm.setInsetDimension(ii->inset, dim);
637 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
639 Buffer & buffer = bv_->buffer();
640 Paragraph const & par = text_->getPar(pit);
642 pos_type last = par.beginOfBody();
643 BOOST_ASSERT(last > 0);
645 // -1 because a label ends with a space that is in the label
648 // a separator at this end does not count
649 if (par.isLineSeparator(last))
653 for (pos_type i = row.pos(); i <= last; ++i)
654 w += singleWidth(pit, i);
656 docstring const & label = par.params().labelWidthString();
660 FontMetrics const & fm
661 = theFontMetrics(text_->labelFont(buffer, par));
663 return max(0, fm.width(label) - w);
667 // this needs special handling - only newlines count as a break point
668 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
670 pos_type const end = par.size();
673 if (par.isNewline(i))
680 int TextMetrics::labelEnd(pit_type const pit) const
682 // labelEnd is only needed if the layout fills a flushleft label.
683 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
685 // return the beginning of the body
686 return leftMargin(max_width_, pit);
690 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
693 Buffer & buffer = bv_->buffer();
694 ParagraphMetrics const & pm = par_metrics_[pit];
695 Paragraph const & par = text_->getPar(pit);
696 pos_type const end = par.size();
697 if (pos == end || width < 0)
700 Layout const & layout = par.layout();
702 if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX)
703 return addressBreakPoint(pos, par);
705 pos_type const body_pos = par.beginOfBody();
707 // check for possible inline completion
708 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
709 pos_type inlineCompletionLPos = -1;
710 if (inlineCompletionPos.inTexted()
711 && inlineCompletionPos.text() == text_
712 && inlineCompletionPos.pit() == pit) {
713 // draw logically behind the previous character
714 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
717 // Now we iterate through until we reach the right margin
718 // or the end of the par, then choose the possible break
721 int label_end = labelEnd(pit);
722 int const left = leftMargin(max_width_, pit, pos);
725 // pixel width since last breakpoint
728 FontIterator fi = FontIterator(*this, par, pit, pos);
729 pos_type point = end;
731 for ( ; i < end; ++i, ++fi) {
732 int thiswidth = pm.singleWidth(i, *fi);
734 // add inline completion width
735 if (inlineCompletionLPos == i) {
736 docstring const & completion = bv_->inlineCompletion();
737 if (completion.length() > 0)
738 thiswidth += theFontMetrics(*fi).width(completion);
741 // add the auto-hfill from label end to the body
742 if (body_pos && i == body_pos) {
743 FontMetrics const & fm = theFontMetrics(
744 text_->labelFont(buffer, par));
745 int add = fm.width(layout.labelsep);
746 if (par.isLineSeparator(i - 1))
747 add -= singleWidth(pit, i - 1);
749 add = max(add, label_end - x);
754 chunkwidth += thiswidth;
756 // break before a character that will fall off
757 // the right of the row
759 // if no break before, break here
760 if (point == end || chunkwidth >= width - left) {
766 // exit on last registered breakpoint:
770 if (par.isNewline(i)) {
774 Inset const * inset = 0;
777 if ((inset = par.getInset(i + 1)) && inset->display()) {
782 if ((inset = par.getInset(i)) && inset->display()) {
788 inset = par.getInset(i);
789 if (!inset || inset->isChar()) {
790 // some insets are line separators too
791 if (par.isLineSeparator(i)) {
792 // register breakpoint:
799 // maybe found one, but the par is short enough.
800 if (i == end && x < width)
803 // manual labels cannot be broken in LaTeX. But we
804 // want to make our on-screen rendering of footnotes
806 if (body_pos && point < body_pos)
813 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
814 pos_type const first, pos_type const end) const
816 Buffer & buffer = bv_->buffer();
817 // get the pure distance
818 ParagraphMetrics const & pm = par_metrics_[pit];
819 Paragraph const & par = text_->getPar(pit);
820 int w = leftMargin(max_width_, pit, first);
821 int label_end = labelEnd(pit);
823 // check for possible inline completion
824 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
825 pos_type inlineCompletionLPos = -1;
826 if (inlineCompletionPos.inTexted()
827 && inlineCompletionPos.text() == text_
828 && inlineCompletionPos.pit() == pit) {
829 // draw logically behind the previous character
830 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
833 pos_type const body_pos = par.beginOfBody();
837 FontIterator fi = FontIterator(*this, par, pit, i);
838 for ( ; i < end; ++i, ++fi) {
839 if (body_pos > 0 && i == body_pos) {
840 FontMetrics const & fm = theFontMetrics(
841 text_->labelFont(buffer, par));
842 w += fm.width(par.layout().labelsep);
843 if (par.isLineSeparator(i - 1))
844 w -= singleWidth(pit, i - 1);
845 w = max(w, label_end);
847 w += pm.singleWidth(i, *fi);
849 // add inline completion width
850 if (inlineCompletionLPos == i) {
851 docstring const & completion = bv_->inlineCompletion();
852 if (completion.length() > 0)
853 w += theFontMetrics(*fi).width(completion);
858 if (body_pos > 0 && body_pos >= end) {
859 FontMetrics const & fm = theFontMetrics(
860 text_->labelFont(buffer, par));
861 w += fm.width(par.layout().labelsep);
862 if (end > 0 && par.isLineSeparator(end - 1))
863 w -= singleWidth(pit, end - 1);
864 w = max(w, label_end);
867 return w + right_margin;
871 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
872 pos_type const end, bool topBottomSpace) const
874 Paragraph const & par = text_->getPar(pit);
875 // get the maximum ascent and the maximum descent
876 double layoutasc = 0;
877 double layoutdesc = 0;
878 double const dh = defaultRowHeight();
880 // ok, let us initialize the maxasc and maxdesc value.
881 // Only the fontsize count. The other properties
882 // are taken from the layoutfont. Nicer on the screen :)
883 Layout const & layout = par.layout();
885 // as max get the first character of this row then it can
886 // increase but not decrease the height. Just some point to
887 // start with so we don't have to do the assignment below too
889 Buffer const & buffer = bv_->buffer();
890 Font font = displayFont(pit, first);
891 FontSize const tmpsize = font.fontInfo().size();
892 font.fontInfo() = text_->layoutFont(buffer, pit);
893 FontSize const size = font.fontInfo().size();
894 font.fontInfo().setSize(tmpsize);
896 FontInfo labelfont = text_->labelFont(buffer, par);
898 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
899 FontMetrics const & fontmetrics = theFontMetrics(font);
901 // these are minimum values
902 double const spacing_val = layout.spacing.getValue()
903 * text_->spacing(buffer, par);
904 //lyxerr << "spacing_val = " << spacing_val << endl;
905 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
906 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
908 // insets may be taller
909 ParagraphMetrics const & pm = par_metrics_[pit];
910 InsetList::const_iterator ii = par.insetList().begin();
911 InsetList::const_iterator iend = par.insetList().end();
912 for ( ; ii != iend; ++ii) {
913 Dimension const & dim = pm.insetDimension(ii->inset);
914 if (ii->pos >= first && ii->pos < end) {
915 maxasc = max(maxasc, dim.ascent());
916 maxdesc = max(maxdesc, dim.descent());
920 // Check if any custom fonts are larger (Asger)
921 // This is not completely correct, but we can live with the small,
922 // cosmetic error for now.
926 par.highestFontInRange(first, end, size);
927 if (maxsize > font.fontInfo().size()) {
928 // use standard paragraph font with the maximal size
929 FontInfo maxfont = font.fontInfo();
930 maxfont.setSize(maxsize);
931 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
932 maxasc = max(maxasc, maxfontmetrics.maxAscent());
933 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
936 // This is nicer with box insets:
940 ParagraphList const & pars = text_->paragraphs();
943 if (first == 0 && topBottomSpace) {
944 BufferParams const & bufparams = buffer.params();
945 // some parskips VERY EASY IMPLEMENTATION
946 if (bufparams.paragraph_separation
947 == BufferParams::PARSEP_SKIP
948 && par.ownerCode() != ERT_CODE
949 && par.ownerCode() != LISTINGS_CODE
951 && ((layout.isParagraph() && par.getDepth() == 0)
952 || (pars[pit - 1].layout().isParagraph()
953 && pars[pit - 1].getDepth() == 0)))
955 maxasc += bufparams.getDefSkip().inPixels(*bv_);
958 if (par.params().startOfAppendix())
959 maxasc += int(3 * dh);
961 // This is special code for the chapter, since the label of this
962 // layout is printed in an extra row
963 if (layout.counter == "chapter"
964 && !par.params().labelString().empty()) {
965 labeladdon = int(labelfont_metrics.maxHeight()
966 * layout.spacing.getValue()
967 * text_->spacing(buffer, par));
970 // special code for the top label
971 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
972 || layout.labeltype == LABEL_BIBLIO
973 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
974 && isFirstInSequence(pit, pars)
975 && !par.labelString().empty())
978 labelfont_metrics.maxHeight()
979 * layout.spacing.getValue()
980 * text_->spacing(buffer, par)
981 + (layout.topsep + layout.labelbottomsep) * dh);
984 // Add the layout spaces, for example before and after
985 // a section, or between the items of a itemize or enumerate
988 pit_type prev = depthHook(pit, pars, par.getDepth());
989 Paragraph const & prevpar = pars[prev];
991 && prevpar.layout() == layout
992 && prevpar.getDepth() == par.getDepth()
993 && prevpar.getLabelWidthString()
994 == par.getLabelWidthString()) {
995 layoutasc = layout.itemsep * dh;
996 } else if (pit != 0 || first != 0) {
997 if (layout.topsep > 0)
998 layoutasc = layout.topsep * dh;
1001 prev = outerHook(pit, pars);
1002 if (prev != pit_type(pars.size())) {
1003 maxasc += int(pars[prev].layout().parsep * dh);
1004 } else if (pit != 0) {
1005 Paragraph const & prevpar = pars[pit - 1];
1006 if (prevpar.getDepth() != 0 ||
1007 prevpar.layout() == layout) {
1008 maxasc += int(layout.parsep * dh);
1013 // is it a bottom line?
1014 if (end >= par.size() && topBottomSpace) {
1015 // add the layout spaces, for example before and after
1016 // a section, or between the items of a itemize or enumerate
1018 pit_type nextpit = pit + 1;
1019 if (nextpit != pit_type(pars.size())) {
1020 pit_type cpit = pit;
1024 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1025 usual = pars[cpit].layout().bottomsep * dh;
1026 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1027 if (pars[cpit].layout() != pars[nextpit].layout()
1028 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1030 unusual = pars[cpit].layout().bottomsep * dh;
1032 layoutdesc = max(unusual, usual);
1033 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1034 if (pars[cpit].layout() != pars[nextpit].layout()
1035 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1036 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1041 // incalculate the layout spaces
1042 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1043 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1045 // FIXME: the correct way is to do the following is to move the
1046 // following code in another method specially tailored for the
1047 // main Text. The following test is thus bogus.
1048 // Top and bottom margin of the document (only at top-level)
1049 if (main_text_ && topBottomSpace) {
1050 if (pit == 0 && first == 0)
1052 if (pit + 1 == pit_type(pars.size()) &&
1053 end == par.size() &&
1054 !(end > 0 && par.isNewline(end - 1)))
1058 return Dimension(0, maxasc + labeladdon, maxdesc);
1062 // x is an absolute screen coord
1063 // returns the column near the specified x-coordinate of the row
1064 // x is set to the real beginning of this column
1065 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1066 Row const & row, int & x, bool & boundary) const
1068 Buffer const & buffer = bv_->buffer();
1070 /// For the main Text, it is possible that this pit is not
1071 /// yet in the CoordCache when moving cursor up.
1072 /// x Paragraph coordinate is always 0 for main text anyway.
1073 int const xo = origin_.x_;
1075 Paragraph const & par = text_->getPar(pit);
1077 bidi.computeTables(par, buffer, row);
1079 pos_type vc = row.pos();
1080 pos_type end = row.endpos();
1082 Layout const & layout = par.layout();
1084 bool left_side = false;
1086 pos_type body_pos = par.beginOfBody();
1088 double tmpx = row.x;
1089 double last_tmpx = tmpx;
1092 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1095 // check for empty row
1101 while (vc < end && tmpx <= x) {
1102 c = bidi.vis2log(vc);
1104 if (body_pos > 0 && c == body_pos - 1) {
1105 FontMetrics const & fm = theFontMetrics(
1106 text_->labelFont(buffer, par));
1107 tmpx += row.label_hfill + fm.width(layout.labelsep);
1108 if (par.isLineSeparator(body_pos - 1))
1109 tmpx -= singleWidth(pit, body_pos - 1);
1112 tmpx += singleWidth(pit, c);
1113 if (par.isSeparator(c) && c >= body_pos)
1114 tmpx += row.separator;
1118 if ((tmpx + last_tmpx) / 2 > x) {
1123 BOOST_ASSERT(vc <= end); // This shouldn't happen.
1126 // This (rtl_support test) is not needed, but gives
1127 // some speedup if rtl_support == false
1128 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1130 // If lastrow is false, we don't need to compute
1131 // the value of rtl.
1132 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1134 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1135 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1136 if (!par.isNewline(end - 1))
1138 } else if (vc == row.pos()) {
1139 c = bidi.vis2log(vc);
1140 if (bidi.level(c) % 2 == 1)
1143 c = bidi.vis2log(vc - 1);
1144 bool const rtl = (bidi.level(c) % 2 == 1);
1145 if (left_side == rtl) {
1147 boundary = isRTLBoundary(pit, c);
1151 // I believe this code is not needed anymore (Jug 20050717)
1153 // The following code is necessary because the cursor position past
1154 // the last char in a row is logically equivalent to that before
1155 // the first char in the next row. That's why insets causing row
1156 // divisions -- Newline and display-style insets -- must be treated
1157 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1158 // Newline inset, air gap below:
1159 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1160 if (bidi.level(end -1) % 2 == 0)
1161 tmpx -= singleWidth(pit, end - 1);
1163 tmpx += singleWidth(pit, end - 1);
1167 // Air gap above display inset:
1168 if (row.pos() < end && c >= end && end < par.size()
1169 && par.isInset(end) && par.getInset(end)->display()) {
1172 // Air gap below display inset:
1173 if (row.pos() < end && c >= end && par.isInset(end - 1)
1174 && par.getInset(end - 1)->display()) {
1180 pos_type const col = c - row.pos();
1182 if (!c || end == par.size())
1185 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1190 return min(col, end - 1 - row.pos());
1194 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1196 // We play safe and use parMetrics(pit) to make sure the
1197 // ParagraphMetrics will be redone and OK to use if needed.
1198 // Otherwise we would use an empty ParagraphMetrics in
1199 // upDownInText() while in selection mode.
1200 ParagraphMetrics const & pm = parMetrics(pit);
1202 BOOST_ASSERT(row < int(pm.rows().size()));
1204 Row const & r = pm.rows()[row];
1205 return r.pos() + getColumnNearX(pit, r, x, bound);
1209 void TextMetrics::newParMetricsDown()
1211 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1212 pit_type const pit = last.first + 1;
1213 if (pit == int(text_->paragraphs().size()))
1216 // do it and update its position.
1218 par_metrics_[pit].setPosition(last.second.position()
1219 + last.second.descent() + par_metrics_[pit].ascent());
1223 void TextMetrics::newParMetricsUp()
1225 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1226 if (first.first == 0)
1229 pit_type const pit = first.first - 1;
1230 // do it and update its position.
1232 par_metrics_[pit].setPosition(first.second.position()
1233 - first.second.ascent() - par_metrics_[pit].descent());
1236 // y is screen coordinate
1237 pit_type TextMetrics::getPitNearY(int y)
1239 BOOST_ASSERT(!text_->paragraphs().empty());
1240 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1242 // look for highest numbered paragraph with y coordinate less than given y
1245 ParMetricsCache::const_iterator it = par_metrics_.begin();
1246 ParMetricsCache::const_iterator et = par_metrics_.end();
1247 ParMetricsCache::const_iterator last = et; last--;
1249 ParagraphMetrics const & pm = it->second;
1251 if (y < it->second.position() - int(pm.ascent())) {
1252 // We are looking for a position that is before the first paragraph in
1253 // the cache (which is in priciple off-screen, that is before the
1256 // We are already at the first paragraph in the inset.
1258 // OK, this is the paragraph we are looking for.
1259 pit = it->first - 1;
1264 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1266 if (y >= last->second.position() + int(pm_last.descent())) {
1267 // We are looking for a position that is after the last paragraph in
1268 // the cache (which is in priciple off-screen, that is before the
1270 pit = last->first + 1;
1271 if (pit == int(text_->paragraphs().size()))
1272 // We are already at the last paragraph in the inset.
1274 // OK, this is the paragraph we are looking for.
1275 newParMetricsDown();
1279 for (; it != et; ++it) {
1280 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1281 << " y: " << it->second.position());
1283 ParagraphMetrics const & pm = par_metrics_[it->first];
1285 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1287 yy = it->second.position();
1291 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1297 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1299 ParagraphMetrics const & pm = par_metrics_[pit];
1301 int yy = pm.position() - pm.ascent();
1302 BOOST_ASSERT(!pm.rows().empty());
1303 RowList::const_iterator rit = pm.rows().begin();
1304 RowList::const_iterator rlast = pm.rows().end();
1306 for (; rit != rlast; yy += rit->height(), ++rit)
1307 if (yy + rit->height() > y)
1313 // x,y are absolute screen coordinates
1314 // sets cursor recursively descending into nested editable insets
1315 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1317 if (lyxerr.debugging(Debug::WORKAREA)) {
1318 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1319 cur.bv().coordCache().dump();
1321 pit_type pit = getPitNearY(y);
1322 BOOST_ASSERT(pit != -1);
1324 Row const & row = getRowNearY(y, pit);
1327 int xx = x; // is modified by getColumnNearX
1328 pos_type const pos = row.pos()
1329 + getColumnNearX(pit, row, xx, bound);
1332 cur.boundary(bound);
1335 // try to descend into nested insets
1336 Inset * inset = checkInsetHit(x, y);
1337 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1339 // Either we deconst editXY or better we move current_font
1340 // and real_current_font to Cursor
1341 // FIXME: what is needed now that current_font and real_current_font
1343 cur.setCurrentFont();
1347 ParagraphList const & pars = text_->paragraphs();
1348 Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1349 //Inset * insetBehind = pars[pit].getInset(pos);
1351 // This should be just before or just behind the
1352 // cursor position set above.
1353 BOOST_ASSERT((pos != 0 && inset == insetBefore)
1354 || inset == pars[pit].getInset(pos));
1356 // Make sure the cursor points to the position before
1358 if (inset == insetBefore) {
1360 cur.boundary(false);
1363 // Try to descend recursively inside the inset.
1364 inset = inset->editXY(cur, x, y);
1366 if (cur.top().text() == text_)
1367 cur.setCurrentFont();
1372 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1374 BOOST_ASSERT(text_ == cur.text());
1375 pit_type pit = getPitNearY(y);
1377 ParagraphMetrics const & pm = par_metrics_[pit];
1379 int yy = pm.position() - pm.ascent();
1380 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1381 " pit: " << pit << " yy: " << yy);
1384 BOOST_ASSERT(pm.rows().size());
1385 for (; r < int(pm.rows().size()) - 1; ++r) {
1386 Row const & row = pm.rows()[r];
1387 if (int(yy + row.height()) > y)
1392 Row const & row = pm.rows()[r];
1394 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1398 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1400 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1402 text_->setCursor(cur, pit, pos, true, bound);
1403 // remember new position.
1408 //takes screen x,y coordinates
1409 Inset * TextMetrics::checkInsetHit(int x, int y)
1411 pit_type pit = getPitNearY(y);
1412 BOOST_ASSERT(pit != -1);
1414 Paragraph const & par = text_->paragraphs()[pit];
1415 ParagraphMetrics const & pm = par_metrics_[pit];
1417 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1419 InsetList::const_iterator iit = par.insetList().begin();
1420 InsetList::const_iterator iend = par.insetList().end();
1421 for (; iit != iend; ++iit) {
1422 Inset * inset = iit->inset;
1424 LYXERR(Debug::DEBUG, "examining inset " << inset);
1426 if (!bv_->coordCache().getInsets().has(inset)) {
1427 LYXERR(Debug::DEBUG, "inset has no cached position");
1431 Dimension const & dim = pm.insetDimension(inset);
1432 Point p = bv_->coordCache().getInsets().xy(inset);
1434 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1435 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1438 && x <= p.x_ + dim.wid
1439 && y >= p.y_ - dim.asc
1440 && y <= p.y_ + dim.des) {
1441 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1446 LYXERR(Debug::DEBUG, "No inset hit. ");
1451 int TextMetrics::cursorX(CursorSlice const & sl,
1452 bool boundary) const
1454 BOOST_ASSERT(sl.text() == text_);
1455 pit_type const pit = sl.pit();
1456 Paragraph const & par = text_->paragraphs()[pit];
1457 ParagraphMetrics const & pm = par_metrics_[pit];
1458 if (pm.rows().empty())
1461 pos_type ppos = sl.pos();
1462 // Correct position in front of big insets
1463 bool const boundary_correction = ppos != 0 && boundary;
1464 if (boundary_correction)
1467 Row const & row = pm.getRow(sl.pos(), boundary);
1469 pos_type cursor_vpos = 0;
1471 Buffer const & buffer = bv_->buffer();
1474 bidi.computeTables(par, buffer, row);
1476 pos_type const row_pos = row.pos();
1477 pos_type const end = row.endpos();
1478 // Spaces at logical line breaks in bidi text must be skipped during
1479 // cursor positioning. However, they may appear visually in the middle
1480 // of a row; they must be skipped, wherever they are...
1481 // * logically "abc_[HEBREW_\nHEBREW]"
1482 // * visually "abc_[_WERBEH\nWERBEH]"
1483 pos_type skipped_sep_vpos = -1;
1486 cursor_vpos = row_pos;
1487 else if (ppos >= end)
1488 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1489 else if (ppos > row_pos && ppos >= end)
1490 // Place cursor after char at (logical) position pos - 1
1491 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1492 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1494 // Place cursor before char at (logical) position ppos
1495 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1496 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1498 pos_type body_pos = par.beginOfBody();
1500 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1503 // check for possible inline completion in this row
1504 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1505 pos_type inlineCompletionVPos = -1;
1506 if (inlineCompletionPos.inTexted()
1507 && inlineCompletionPos.text() == text_
1508 && inlineCompletionPos.pit() == pit
1509 && inlineCompletionPos.pos() - 1 >= row_pos
1510 && inlineCompletionPos.pos() - 1 < end) {
1511 // draw logically behind the previous character
1512 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1515 // Use font span to speed things up, see below
1519 // If the last logical character is a separator, skip it, unless
1520 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1521 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1522 skipped_sep_vpos = bidi.log2vis(end - 1);
1524 // Inline completion RTL special case row_pos == cursor_pos:
1525 // "__|b" => cursor_pos is right of __
1526 if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1527 font = displayFont(pit, row_pos + 1);
1528 docstring const & completion = bv_->inlineCompletion();
1529 if (font.isRightToLeft() && completion.length() > 0)
1530 x += theFontMetrics(font.fontInfo()).width(completion);
1533 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1534 // Skip the separator which is at the logical end of the row
1535 if (vpos == skipped_sep_vpos)
1537 pos_type pos = bidi.vis2log(vpos);
1538 if (body_pos > 0 && pos == body_pos - 1) {
1539 FontMetrics const & labelfm = theFontMetrics(
1540 text_->labelFont(buffer, par));
1541 x += row.label_hfill + labelfm.width(par.layout().labelsep);
1542 if (par.isLineSeparator(body_pos - 1))
1543 x -= singleWidth(pit, body_pos - 1);
1546 // Use font span to speed things up, see above
1547 if (pos < font_span.first || pos > font_span.last) {
1548 font_span = par.fontSpan(pos);
1549 font = displayFont(pit, pos);
1552 x += pm.singleWidth(pos, font);
1554 // Inline completion RTL case:
1555 // "a__|b", __ of b => non-boundary a-pos is right of __
1556 if (vpos + 1 == inlineCompletionVPos
1557 && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1558 font = displayFont(pit, vpos + 1);
1559 docstring const & completion = bv_->inlineCompletion();
1560 if (font.isRightToLeft() && completion.length() > 0)
1561 x += theFontMetrics(font.fontInfo()).width(completion);
1564 // Inline completion LTR case:
1565 // "b|__a", __ of b => non-boundary a-pos is in front of __
1566 if (vpos == inlineCompletionVPos
1567 && (vpos + 1 < cursor_vpos || boundary_correction)) {
1568 font = displayFont(pit, vpos);
1569 docstring const & completion = bv_->inlineCompletion();
1570 if (!font.isRightToLeft() && completion.length() > 0)
1571 x += theFontMetrics(font.fontInfo()).width(completion);
1574 if (par.isSeparator(pos) && pos >= body_pos)
1578 // see correction above
1579 if (boundary_correction) {
1580 if (isRTL(sl, boundary))
1581 x -= singleWidth(pit, ppos);
1583 x += singleWidth(pit, ppos);
1590 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1592 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1593 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1594 if (pm.rows().empty())
1598 h -= par_metrics_[0].rows()[0].ascent();
1599 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1600 h += par_metrics_[pit].height();
1603 if (pos && boundary)
1605 size_t const rend = pm.pos2row(pos);
1606 for (size_t rit = 0; rit != rend; ++rit)
1607 h += pm.rows()[rit].height();
1608 h += pm.rows()[rend].ascent();
1613 // the cursor set functions have a special mechanism. When they
1614 // realize you left an empty paragraph, they will delete it.
1616 bool TextMetrics::cursorHome(Cursor & cur)
1618 BOOST_ASSERT(text_ == cur.text());
1619 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1620 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1621 return text_->setCursor(cur, cur.pit(), row.pos());
1625 bool TextMetrics::cursorEnd(Cursor & cur)
1627 BOOST_ASSERT(text_ == cur.text());
1628 // if not on the last row of the par, put the cursor before
1629 // the final space exept if I have a spanning inset or one string
1630 // is so long that we force a break.
1631 pos_type end = cur.textRow().endpos();
1633 // empty text, end-1 is no valid position
1635 bool boundary = false;
1636 if (end != cur.lastpos()) {
1637 if (!cur.paragraph().isLineSeparator(end-1)
1638 && !cur.paragraph().isNewline(end-1))
1643 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1647 void TextMetrics::deleteLineForward(Cursor & cur)
1649 BOOST_ASSERT(text_ == cur.text());
1650 if (cur.lastpos() == 0) {
1651 // Paragraph is empty, so we just go forward
1652 text_->cursorForward(cur);
1655 cur.selection() = true; // to avoid deletion
1658 // What is this test for ??? (JMarc)
1659 if (!cur.selection())
1660 text_->deleteWordForward(cur);
1662 cap::cutSelection(cur, true, false);
1663 cur.checkBufferStructure();
1668 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1670 ParagraphList const & pars = text_->paragraphs();
1671 return row.endpos() >= pars[pit].size()
1672 && pit + 1 == pit_type(pars.size());
1676 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1678 return row.pos() == 0 && pit == 0;
1682 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1684 BOOST_ASSERT(pit >= 0);
1685 BOOST_ASSERT(pit < int(text_->paragraphs().size()));
1686 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1690 int TextMetrics::leftMargin(int max_width,
1691 pit_type const pit, pos_type const pos) const
1693 ParagraphList const & pars = text_->paragraphs();
1695 BOOST_ASSERT(pit >= 0);
1696 BOOST_ASSERT(pit < int(pars.size()));
1697 Paragraph const & par = pars[pit];
1698 BOOST_ASSERT(pos >= 0);
1699 BOOST_ASSERT(pos <= par.size());
1700 Buffer const & buffer = bv_->buffer();
1701 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1702 DocumentClass const & tclass = buffer.params().documentClass();
1703 Layout const & layout = par.layout();
1705 docstring parindent = layout.parindent;
1709 if (text_->isMainText(buffer))
1710 l_margin += bv_->leftMargin();
1712 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1713 tclass.leftmargin());
1715 if (par.getDepth() != 0) {
1716 // find the next level paragraph
1717 pit_type newpar = outerHook(pit, pars);
1718 if (newpar != pit_type(pars.size())) {
1719 if (pars[newpar].layout().isEnvironment()) {
1720 l_margin = leftMargin(max_width, newpar);
1722 if (tclass.isDefaultLayout(par.layout())
1723 || tclass.isEmptyLayout(par.layout())) {
1724 if (pars[newpar].params().noindent())
1727 parindent = pars[newpar].layout().parindent;
1732 // This happens after sections in standard classes. The 1.3.x
1733 // code compared depths too, but it does not seem necessary
1735 if (tclass.isDefaultLayout(par.layout())
1736 && pit > 0 && pars[pit - 1].layout().nextnoindent)
1739 FontInfo const labelfont = text_->labelFont(buffer, par);
1740 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1742 switch (layout.margintype) {
1743 case MARGIN_DYNAMIC:
1744 if (!layout.leftmargin.empty()) {
1745 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1748 if (!par.labelString().empty()) {
1749 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1750 l_margin += labelfont_metrics.width(par.labelString());
1751 l_margin += labelfont_metrics.width(layout.labelsep);
1755 case MARGIN_MANUAL: {
1756 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1757 // The width of an empty par, even with manual label, should be 0
1758 if (!par.empty() && pos >= par.beginOfBody()) {
1759 if (!par.getLabelWidthString().empty()) {
1760 docstring labstr = par.getLabelWidthString();
1761 l_margin += labelfont_metrics.width(labstr);
1762 l_margin += labelfont_metrics.width(layout.labelsep);
1768 case MARGIN_STATIC: {
1769 l_margin += theFontMetrics(buffer.params().getFont()).
1770 signedWidth(layout.leftmargin) * 4 / (par.getDepth() + 4);
1774 case MARGIN_FIRST_DYNAMIC:
1775 if (layout.labeltype == LABEL_MANUAL) {
1776 if (pos >= par.beginOfBody()) {
1777 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1779 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1782 // Special case to fix problems with
1784 || (layout.labeltype == LABEL_STATIC
1785 && layout.latextype == LATEX_ENVIRONMENT
1786 && !isFirstInSequence(pit, pars))) {
1787 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1788 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
1789 && layout.labeltype != LABEL_BIBLIO
1790 && layout.labeltype !=
1791 LABEL_CENTERED_TOP_ENVIRONMENT) {
1792 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1793 l_margin += labelfont_metrics.width(layout.labelsep);
1794 l_margin += labelfont_metrics.width(par.labelString());
1798 case MARGIN_RIGHT_ADDRESS_BOX: {
1800 // ok, a terrible hack. The left margin depends on the widest
1801 // row in this paragraph.
1802 RowList::iterator rit = par.rows().begin();
1803 RowList::iterator end = par.rows().end();
1804 // FIXME: This is wrong.
1805 int minfill = max_width;
1806 for ( ; rit != end; ++rit)
1807 if (rit->fill() < minfill)
1808 minfill = rit->fill();
1809 l_margin += theFontMetrics(params.getFont()).signedWidth(layout.leftmargin);
1810 l_margin += minfill;
1812 // also wrong, but much shorter.
1813 l_margin += max_width / 2;
1818 if (!par.params().leftIndent().zero())
1819 l_margin += par.params().leftIndent().inPixels(max_width);
1823 if (par.params().align() == LYX_ALIGN_LAYOUT)
1824 align = layout.align;
1826 align = par.params().align();
1828 // set the correct parindent
1830 && (layout.labeltype == LABEL_NO_LABEL
1831 || layout.labeltype == LABEL_TOP_ENVIRONMENT
1832 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1833 || (layout.labeltype == LABEL_STATIC
1834 && layout.latextype == LATEX_ENVIRONMENT
1835 && !isFirstInSequence(pit, pars)))
1836 && align == LYX_ALIGN_BLOCK
1837 && !par.params().noindent()
1838 // in some insets, paragraphs are never indented
1839 && !(par.inInset() && par.inInset()->neverIndent())
1840 // display style insets are always centered, omit indentation
1843 && par.getInset(pos)->display())
1844 && ((tclass.isDefaultLayout(par.layout())
1845 || tclass.isEmptyLayout(par.layout()))
1846 || buffer.params().paragraph_separation == BufferParams::PARSEP_INDENT)
1849 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1857 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1859 ParagraphMetrics const & pm = par_metrics_[pit];
1861 return pm.singleWidth(pos, displayFont(pit, pos));
1865 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1867 if (par_metrics_.empty())
1873 ParMetricsCache::iterator it = par_metrics_.begin();
1874 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1875 y -= it->second.ascent();
1876 for (; it != pm_end; ++it) {
1877 ParagraphMetrics const & pmi = it->second;
1879 pit_type const pit = it->first;
1880 // Save the paragraph position in the cache.
1881 it->second.setPosition(y);
1882 drawParagraph(pi, pit, x, y);
1888 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1890 BufferParams const & bparams = bv_->buffer().params();
1891 ParagraphMetrics const & pm = par_metrics_[pit];
1892 if (pm.rows().empty())
1896 bool const original_drawing_state = pi.pain.isDrawingEnabled();
1897 int const ww = bv_->workHeight();
1898 size_t const nrows = pm.rows().size();
1900 Cursor const & cur = bv_->cursor();
1901 DocIterator sel_beg = cur.selectionBegin();
1902 DocIterator sel_end = cur.selectionEnd();
1903 bool selection = cur.selection()
1904 // This is our text.
1905 && cur.text() == text_
1906 // if the anchor is outside, this is not our selection
1907 && cur.anchor().text() == text_
1908 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1910 // We care only about visible selection.
1912 if (pit != sel_beg.pit()) {
1913 sel_beg.pit() = pit;
1916 if (pit != sel_end.pit()) {
1917 sel_end.pit() = pit;
1918 sel_end.pos() = sel_end.lastpos();
1922 for (size_t i = 0; i != nrows; ++i) {
1924 Row const & row = pm.rows()[i];
1928 bool const inside = (y + row.descent() >= 0
1929 && y - row.ascent() < ww);
1930 // It is not needed to draw on screen if we are not inside.
1931 pi.pain.setDrawingEnabled(inside && original_drawing_state);
1932 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
1935 row.setSelection(sel_beg.pos(), sel_end.pos());
1937 row.setSelection(-1, -1);
1939 // Row signature; has row changed since last paint?
1940 row.setCrc(pm.computeRowSignature(row, bparams));
1941 bool row_has_changed = row.changed();
1943 // Don't paint the row if a full repaint has not been requested
1944 // and if it has not changed.
1945 if (!pi.full_repaint && !row_has_changed) {
1946 // Paint only the insets if the text itself is
1948 rp.paintOnlyInsets();
1953 // Clear background of this row if paragraph background was not
1954 // already cleared because of a full repaint.
1955 if (!pi.full_repaint && row_has_changed) {
1956 pi.pain.fillRectangle(x, y - row.ascent(),
1957 width(), row.height(), pi.background_color);
1960 bool row_selection = row.sel_beg != -1 && row.sel_end != -1;
1961 if (row_selection) {
1962 DocIterator beg = bv_->cursor().selectionBegin();
1963 DocIterator end = bv_->cursor().selectionEnd();
1964 bool const beg_margin = beg.pit() < pit && i == 0;
1965 bool const end_margin = end.pit() > pit && i == nrows - 1;
1967 beg.pos() = row.sel_beg;
1969 end.pos() = row.sel_end;
1970 drawRowSelection(pi, x, row, beg, end, beg_margin, end_margin);
1973 // Instrumentation for testing row cache (see also
1975 if (lyxerr.debugging(Debug::PAINTING) && inside
1976 && (row_selection || pi.full_repaint || row_has_changed)) {
1977 string const foreword = text_->isMainText(bv_->buffer()) ?
1978 "main text redraw " : "inset text redraw: ";
1979 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
1980 << " row_selection=" << row_selection
1981 << " full_repaint=" << pi.full_repaint
1982 << " row_has_changed=" << row_has_changed);
1985 // Backup full_repaint status and force full repaint
1986 // for inner insets as the Row has been cleared out.
1987 bool tmp = pi.full_repaint;
1988 pi.full_repaint = true;
1991 rp.paintChangeBar();
1998 // Restore full_repaint status.
1999 pi.full_repaint = tmp;
2001 // Re-enable screen drawing for future use of the painter.
2002 pi.pain.setDrawingEnabled(original_drawing_state);
2004 //LYXERR(Debug::PAINTING, ".");
2008 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2009 DocIterator const & beg, DocIterator const & end,
2010 bool drawOnBegMargin, bool drawOnEndMargin) const
2012 Buffer & buffer = bv_->buffer();
2013 DocIterator cur = beg;
2014 int x1 = cursorX(beg.top(), beg.boundary());
2015 int x2 = cursorX(end.top(), end.boundary());
2016 int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2017 int y2 = y1 + row.height();
2020 if (drawOnBegMargin) {
2021 if (text_->isRTL(buffer, beg.paragraph()))
2022 pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color_selection);
2024 pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color_selection);
2027 if (drawOnEndMargin) {
2028 if (text_->isRTL(buffer, beg.paragraph()))
2029 pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color_selection);
2031 pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color_selection);
2034 // if we are on a boundary from the beginning, it's probably
2035 // a RTL boundary and we jump to the other side directly as this
2036 // segement is 0-size and confuses the logic below
2038 cur.boundary(false);
2040 // go through row and draw from RTL boundary to RTL boundary
2042 bool drawNow = false;
2044 // simplified cursorForward code below which does not
2045 // descend into insets and which does not go into the
2046 // next line. Compare the logic with the original cursorForward
2048 // if left of boundary -> just jump to right side
2049 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2050 if (cur.boundary()) {
2051 cur.boundary(false);
2052 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2053 // in front of RTL boundary -> Stay on this side of the boundary because:
2054 // ab|cDDEEFFghi -> abc|DDEEFFghi
2063 if (cur.pos() == row.endpos())
2068 // the previous segment was just drawn, now the next starts
2069 x1 = cursorX(cur.top(), cur.boundary());
2072 if (!(cur < end) || drawNow) {
2073 x2 = cursorX(cur.top(), cur.boundary());
2074 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2077 // reset x1, so it is set again next round (which will be on the
2078 // right side of a boundary or at the selection end)
2084 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2086 // ParagraphMetrics const & pm = par_metrics_[pit];
2087 // Row const & r = pm.rows()[row];
2093 int defaultRowHeight()
2095 return int(theFontMetrics(sane_font).maxHeight() * 1.2);