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"
37 #include "MetricsInfo.h"
38 #include "paragraph_funcs.h"
39 #include "ParagraphParameters.h"
40 #include "ParIterator.h"
41 #include "rowpainter.h"
43 #include "TextClass.h"
46 #include "mathed/MacroTable.h"
47 #include "mathed/MathMacroTemplate.h"
49 #include "frontends/FontMetrics.h"
50 #include "frontends/Painter.h"
52 #include "support/debug.h"
58 using frontend::FontMetrics;
62 int numberOfSeparators(Paragraph const & par, Row const & row)
64 pos_type const first = max(row.pos(), par.beginOfBody());
65 pos_type const last = row.endpos() - 1;
67 for (pos_type p = first; p < last; ++p) {
68 if (par.isSeparator(p))
75 int numberOfLabelHfills(Paragraph const & par, Row const & row)
77 pos_type last = row.endpos() - 1;
78 pos_type first = row.pos();
80 // hfill *DO* count at the beginning of paragraphs!
82 while (first < last && par.isHfill(first))
86 last = min(last, par.beginOfBody());
88 for (pos_type p = first; p < last; ++p) {
96 int numberOfHfills(Paragraph const & par, Row const & row)
98 pos_type const last = row.endpos();
99 pos_type first = row.pos();
101 // hfill *DO* count at the beginning of paragraphs!
103 while (first < last && par.isHfill(first))
107 first = max(first, par.beginOfBody());
110 for (pos_type p = first; p < last; ++p) {
119 TextMetrics::TextMetrics(BufferView * bv, Text * text)
120 : bv_(bv), text_(text)
123 max_width_ = bv_->workWidth();
124 dim_.wid = max_width_;
128 //text_->updateLabels(bv->buffer());
132 bool TextMetrics::contains(pit_type pit) const
134 return par_metrics_.find(pit) != par_metrics_.end();
138 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
140 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
145 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
147 ParMetricsCache::const_iterator it = par_metrics_.begin();
148 return make_pair(it->first, &it->second);
152 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
154 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
155 return make_pair(it->first, &it->second);
159 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
161 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
162 if (pmc_it == par_metrics_.end()) {
163 pmc_it = par_metrics_.insert(
164 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
166 if (pmc_it->second.rows().empty() && redo)
168 return pmc_it->second;
172 int TextMetrics::parPosition(pit_type pit) const
174 if (pit < par_metrics_.begin()->first)
176 if (pit > par_metrics_.rbegin()->first)
179 return par_metrics_[pit].position();
183 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
185 BOOST_ASSERT(mi.base.textwidth);
186 max_width_ = mi.base.textwidth;
187 // backup old dimension.
188 Dimension const old_dim = dim_;
191 dim_.wid = min_width;
192 pit_type const npar = text_->paragraphs().size();
194 // If there is more than one row, expand the text to
195 // the full allowable width.
196 dim_.wid = max_width_;
198 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
199 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
201 bool changed = false;
203 for (pit_type pit = 0; pit != npar; ++pit) {
204 changed |= redoParagraph(pit);
205 ParagraphMetrics const & pm = par_metrics_[pit];
207 if (dim_.wid < pm.width())
208 dim_.wid = pm.width();
211 dim_.asc = par_metrics_[0].ascent();
212 dim_.des = h - dim_.asc;
213 //lyxerr << "dim_.wid " << dim_.wid << endl;
214 //lyxerr << "dim_.asc " << dim_.asc << endl;
215 //lyxerr << "dim_.des " << dim_.des << endl;
217 changed |= dim_ != old_dim;
223 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
225 return main_text_? pm.rightMargin(*bv_) : 0;
229 int TextMetrics::rightMargin(pit_type const pit) const
231 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
235 void TextMetrics::applyOuterFont(Font & font) const
238 lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
239 lf.fontInfo().realize(font.fontInfo());
240 lf.setLanguage(font.language());
245 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
247 BOOST_ASSERT(pos >= 0);
249 ParagraphList const & pars = text_->paragraphs();
250 Paragraph const & par = pars[pit];
251 LayoutPtr const & layout = par.layout();
252 Buffer const & buffer = bv_->buffer();
254 BufferParams const & params = buffer.params();
255 pos_type const body_pos = par.beginOfBody();
257 // We specialize the 95% common case:
258 if (!par.getDepth()) {
259 Font f = par.getFontSettings(params, pos);
260 if (!text_->isMainText(buffer))
262 bool lab = layout->labeltype == LABEL_MANUAL && pos < body_pos;
264 FontInfo const & lf = lab ? layout->labelfont : layout->font;
265 FontInfo rlf = lab ? layout->reslabelfont : layout->resfont;
267 // In case the default family has been customized
268 if (lf.family() == INHERIT_FAMILY)
269 rlf.setFamily(params.getFont().fontInfo().family());
270 f.fontInfo().realize(rlf);
274 // The uncommon case need not be optimized as much
275 FontInfo const & layoutfont = pos < body_pos ?
276 layout->labelfont : layout->font;
278 Font font = par.getFontSettings(params, pos);
279 font.fontInfo().realize(layoutfont);
281 if (!text_->isMainText(buffer))
282 applyOuterFont(font);
284 // Realize against environment font information
285 // NOTE: the cast to pit_type should be removed when pit_type
286 // changes to a unsigned integer.
287 if (pit < pit_type(pars.size()))
288 font.fontInfo().realize(outerFont(pit, pars).fontInfo());
290 // Realize with the fonts of lesser depth.
291 font.fontInfo().realize(params.getFont().fontInfo());
297 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
299 if (!lyxrc.rtl_support || !sl.text())
303 if (boundary && sl.pos() > 0)
306 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
310 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
312 if (!lyxrc.rtl_support)
315 // no RTL boundary at line start
319 Paragraph const & par = text_->getPar(pit);
321 bool left = displayFont(pit, pos - 1).isVisibleRightToLeft();
323 if (pos == par.size())
324 right = par.isRTL(bv_->buffer().params());
326 right = displayFont(pit, pos).isVisibleRightToLeft();
327 return left != right;
331 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
332 Font const & font) const
334 if (!lyxrc.rtl_support)
337 Paragraph const & par = text_->getPar(pit);
338 bool left = font.isVisibleRightToLeft();
340 if (pos == par.size())
341 right = par.isRTL(bv_->buffer().params());
343 right = displayFont(pit, pos).isVisibleRightToLeft();
344 return left != right;
348 bool TextMetrics::redoParagraph(pit_type const pit)
350 Paragraph & par = text_->getPar(pit);
351 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
352 // redoParagraph() recursively inside parMetrics.
353 Dimension old_dim = parMetrics(pit, false).dim();
354 ParagraphMetrics & pm = par_metrics_[pit];
357 Buffer & buffer = bv_->buffer();
358 main_text_ = (text_ == &buffer.text());
359 bool changed = false;
361 // FIXME: This check ought to be done somewhere else. It is the reason
362 // why text_ is not const. But then, where else to do it?
363 // Well, how can you end up with either (a) a biblio environment that
364 // has no InsetBibitem or (b) a biblio environment with more than one
365 // InsetBibitem? I think the answer is: when paragraphs are merged;
366 // when layout is set; when material is pasted.
367 int const moveCursor = par.checkBiblio(buffer);
369 const_cast<Cursor &>(bv_->cursor()).posForward();
370 else if (moveCursor < 0) {
371 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
372 if (cursor.pos() >= -moveCursor)
373 cursor.posBackward();
376 // Optimisation: this is used in the next two loops
377 // so better to calculate that once here.
378 int const right_margin = rightMargin(pm);
380 // iterator pointing to paragraph to resolve macros
381 DocIterator parPos = text_->macrocontextPosition();
385 LYXERR(Debug::INFO, "MacroContext not initialised!"
386 << " Going through the buffer again and hope"
387 << " the context is better then.");
388 updateLabels(bv_->buffer());
389 parPos = text_->macrocontextPosition();
390 BOOST_ASSERT(!parPos.empty());
395 // FIXME: We should always use getFont(), see documentation of
396 // noFontChange() in Inset.h.
397 Font const bufferfont = buffer.params().getFont();
398 InsetList::const_iterator ii = par.insetList().begin();
399 InsetList::const_iterator iend = par.insetList().end();
400 for (; ii != iend; ++ii) {
401 // position already initialized?
402 if (!parPos.empty()) {
403 parPos.pos() = ii->pos;
405 // A macro template would normally not be visible
406 // by itself. But the tex macro semantics allow
407 // recursion, so we artifically take the context
408 // after the macro template to simulate this.
409 if (ii->inset->lyxCode() == MATHMACRO_CODE)
413 // do the metric calculation
415 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
417 Font const & font = ii->inset->noFontChange() ?
418 bufferfont : displayFont(pit, ii->pos);
419 MacroContext mc(buffer, parPos);
420 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
421 ii->inset->metrics(mi, dim);
422 Dimension const old_dim = pm.insetDimension(ii->inset);
423 pm.setInsetDimension(ii->inset, dim);
424 changed |= (old_dim != dim);
427 par.setBeginOfBody();
429 size_t row_index = 0;
430 // maximum pixel width of a row
431 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
434 pos_type end = rowBreakPoint(width, pit, first);
435 if (row_index || end < par.size())
436 // If there is more than one row, expand the text to
437 // the full allowable width. This setting here is needed
438 // for the computeRowMetrics() below.
439 dim_.wid = max_width_;
441 dim = rowHeight(pit, first, end);
442 dim.wid = rowWidth(right_margin, pit, first, end);
443 if (row_index == pm.rows().size())
444 pm.rows().push_back(Row());
445 Row & row = pm.rows()[row_index];
446 row.setChanged(false);
449 row.setDimension(dim);
450 int const max_row_width = max(dim_.wid, dim.wid);
451 computeRowMetrics(pit, row, max_row_width);
455 pm.dim().wid = max(pm.dim().wid, dim.wid);
456 pm.dim().des += dim.height();
457 } while (first < par.size());
459 if (row_index < pm.rows().size())
460 pm.rows().resize(row_index);
462 // Make sure that if a par ends in newline, there is one more row
464 if (first > 0 && par.isNewline(first - 1)) {
465 Dimension dim = rowHeight(pit, first, first);
466 dim.wid = rowWidth(right_margin, pit, first, first);
467 if (row_index == pm.rows().size())
468 pm.rows().push_back(Row());
469 Row & row = pm.rows()[row_index];
470 row.setChanged(false);
473 row.setDimension(dim);
474 int const max_row_width = max(dim_.wid, dim.wid);
475 computeRowMetrics(pit, row, max_row_width);
476 pm.dim().des += dim.height();
479 pm.dim().asc += pm.rows()[0].ascent();
480 pm.dim().des -= pm.rows()[0].ascent();
482 changed |= old_dim.height() != pm.dim().height();
488 void TextMetrics::computeRowMetrics(pit_type const pit,
489 Row & row, int width) const
494 Buffer & buffer = bv_->buffer();
495 Paragraph const & par = text_->getPar(pit);
497 double w = width - row.width();
498 // FIXME: put back this assertion when the crash on new doc is solved.
499 //BOOST_ASSERT(w >= 0);
501 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
502 //lyxerr << "row.width() " << row.width() << endl;
503 //lyxerr << "w " << w << endl;
505 bool const is_rtl = text_->isRTL(buffer, par);
507 row.x = rightMargin(pit);
509 row.x = leftMargin(max_width_, pit, row.pos());
511 // is there a manual margin with a manual label
512 LayoutPtr const & layout = par.layout();
514 if (layout->margintype == MARGIN_MANUAL
515 && layout->labeltype == LABEL_MANUAL) {
516 /// We might have real hfills in the label part
517 int nlh = numberOfLabelHfills(par, row);
519 // A manual label par (e.g. List) has an auto-hfill
520 // between the label text and the body of the
522 // But we don't want to do this auto hfill if the par
527 if (nlh && !par.getLabelWidthString().empty())
528 row.label_hfill = labelFill(pit, row) / double(nlh);
532 // are there any hfills in the row?
533 if (int const nh = numberOfHfills(par, row)) {
535 hfill = w / double(nh);
536 // we don't have to look at the alignment if it is ALIGN_LEFT and
537 // if the row is already larger then the permitted width as then
538 // we force the LEFT_ALIGN'edness!
539 } else if (int(row.width()) < max_width_) {
540 // is it block, flushleft or flushright?
541 // set x how you need it
543 if (par.params().align() == LYX_ALIGN_LAYOUT)
544 align = layout->align;
546 align = par.params().align();
548 // Display-style insets should always be on a centred row
549 if (Inset const * inset = par.getInset(row.pos())) {
550 switch (inset->display()) {
551 case Inset::AlignLeft:
552 align = LYX_ALIGN_BLOCK;
554 case Inset::AlignCenter:
555 align = LYX_ALIGN_CENTER;
558 case Inset::AlignRight:
559 // unchanged (use align)
565 case LYX_ALIGN_BLOCK: {
566 int const ns = numberOfSeparators(par, row);
567 bool disp_inset = false;
568 if (row.endpos() < par.size()) {
569 Inset const * in = par.getInset(row.endpos());
571 disp_inset = in->display();
573 // If we have separators, this is not the last row of a
574 // par, does not end in newline, and is not row above a
575 // display inset... then stretch it
577 && row.endpos() < par.size()
578 && !par.isNewline(row.endpos() - 1)
581 row.separator = w / ns;
582 //lyxerr << "row.separator " << row.separator << endl;
583 //lyxerr << "ns " << ns << endl;
589 case LYX_ALIGN_RIGHT:
592 case LYX_ALIGN_CENTER:
599 pos_type body_pos = par.beginOfBody();
600 pos_type end = row.endpos();
603 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
605 row.x += theFontMetrics(text_->labelFont(buffer, par)).
606 width(layout->labelsep);
608 row.x += row.label_hfill;
612 pos_type const endpos = row.endpos();
613 pos_type body_pos = par.beginOfBody();
615 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
618 ParagraphMetrics & pm = par_metrics_[pit];
619 InsetList::const_iterator ii = par.insetList().begin();
620 InsetList::const_iterator iend = par.insetList().end();
621 for ( ; ii != iend; ++ii) {
622 if (ii->pos >= endpos || ii->pos < row.pos()
623 || ii->inset->lyxCode() != HFILL_CODE)
625 Dimension dim = row.dimension();
626 if (pm.hfillExpansion(row, ii->pos))
627 dim.wid = int(ii->pos >= body_pos ?
628 max(hfill, 5.0) : row.label_hfill);
631 // Cache the inset dimension.
632 bv_->coordCache().insets().add(ii->inset, dim);
633 pm.setInsetDimension(ii->inset, dim);
638 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
640 Buffer & buffer = bv_->buffer();
641 Paragraph const & par = text_->getPar(pit);
643 pos_type last = par.beginOfBody();
644 BOOST_ASSERT(last > 0);
646 // -1 because a label ends with a space that is in the label
649 // a separator at this end does not count
650 if (par.isLineSeparator(last))
654 for (pos_type i = row.pos(); i <= last; ++i)
655 w += singleWidth(pit, i);
657 docstring const & label = par.params().labelWidthString();
661 FontMetrics const & fm
662 = theFontMetrics(text_->labelFont(buffer, par));
664 return max(0, fm.width(label) - w);
668 // this needs special handling - only newlines count as a break point
669 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
671 pos_type const end = par.size();
674 if (par.isNewline(i))
681 int TextMetrics::labelEnd(pit_type const pit) const
683 // labelEnd is only needed if the layout fills a flushleft label.
684 if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
686 // return the beginning of the body
687 return leftMargin(max_width_, pit);
691 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
694 Buffer & buffer = bv_->buffer();
695 ParagraphMetrics const & pm = par_metrics_[pit];
696 Paragraph const & par = text_->getPar(pit);
697 pos_type const end = par.size();
698 if (pos == end || width < 0)
701 LayoutPtr const & layout = par.layout();
703 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
704 return addressBreakPoint(pos, par);
706 pos_type const body_pos = par.beginOfBody();
708 // check for possible inline completion
709 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
710 pos_type inlineCompletionLPos = -1;
711 if (inlineCompletionPos.inTexted()
712 && inlineCompletionPos.text() == text_
713 && inlineCompletionPos.pit() == pit) {
714 // draw logically behind the previous character
715 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
718 // Now we iterate through until we reach the right margin
719 // or the end of the par, then choose the possible break
722 int label_end = labelEnd(pit);
723 int const left = leftMargin(max_width_, pit, pos);
726 // pixel width since last breakpoint
729 FontIterator fi = FontIterator(*this, par, pit, pos);
730 pos_type point = end;
732 for ( ; i < end; ++i, ++fi) {
733 int thiswidth = pm.singleWidth(i, *fi);
735 // add inline completion width
736 if (inlineCompletionLPos == i) {
737 docstring const & completion = bv_->inlineCompletion();
738 if (completion.length() > 0)
739 thiswidth += theFontMetrics(*fi).width(completion);
742 // add the auto-hfill from label end to the body
743 if (body_pos && i == body_pos) {
744 FontMetrics const & fm = theFontMetrics(
745 text_->labelFont(buffer, par));
746 int add = fm.width(layout->labelsep);
747 if (par.isLineSeparator(i - 1))
748 add -= singleWidth(pit, i - 1);
750 add = max(add, label_end - x);
755 chunkwidth += thiswidth;
757 // break before a character that will fall off
758 // the right of the row
760 // if no break before, break here
761 if (point == end || chunkwidth >= width - left) {
767 // exit on last registered breakpoint:
771 if (par.isNewline(i)) {
775 Inset const * inset = 0;
778 if ((inset = par.getInset(i + 1)) && inset->display()) {
783 if ((inset = par.getInset(i)) && inset->display()) {
789 inset = par.getInset(i);
790 if (!inset || inset->isChar()) {
791 // some insets are line separators too
792 if (par.isLineSeparator(i)) {
793 // register breakpoint:
800 // maybe found one, but the par is short enough.
801 if (i == end && x < width)
804 // manual labels cannot be broken in LaTeX. But we
805 // want to make our on-screen rendering of footnotes
807 if (body_pos && point < body_pos)
814 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
815 pos_type const first, pos_type const end) const
817 Buffer & buffer = bv_->buffer();
818 // get the pure distance
819 ParagraphMetrics const & pm = par_metrics_[pit];
820 Paragraph const & par = text_->getPar(pit);
821 int w = leftMargin(max_width_, pit, first);
822 int label_end = labelEnd(pit);
824 // check for possible inline completion
825 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
826 pos_type inlineCompletionLPos = -1;
827 if (inlineCompletionPos.inTexted()
828 && inlineCompletionPos.text() == text_
829 && inlineCompletionPos.pit() == pit) {
830 // draw logically behind the previous character
831 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
834 pos_type const body_pos = par.beginOfBody();
838 FontIterator fi = FontIterator(*this, par, pit, i);
839 for ( ; i < end; ++i, ++fi) {
840 if (body_pos > 0 && i == body_pos) {
841 FontMetrics const & fm = theFontMetrics(
842 text_->labelFont(buffer, par));
843 w += fm.width(par.layout()->labelsep);
844 if (par.isLineSeparator(i - 1))
845 w -= singleWidth(pit, i - 1);
846 w = max(w, label_end);
848 w += pm.singleWidth(i, *fi);
850 // add inline completion width
851 if (inlineCompletionLPos == i) {
852 docstring const & completion = bv_->inlineCompletion();
853 if (completion.length() > 0)
854 w += theFontMetrics(*fi).width(completion);
859 if (body_pos > 0 && body_pos >= end) {
860 FontMetrics const & fm = theFontMetrics(
861 text_->labelFont(buffer, par));
862 w += fm.width(par.layout()->labelsep);
863 if (end > 0 && par.isLineSeparator(end - 1))
864 w -= singleWidth(pit, end - 1);
865 w = max(w, label_end);
868 return w + right_margin;
872 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
873 pos_type const end, bool topBottomSpace) const
875 Paragraph const & par = text_->getPar(pit);
876 // get the maximum ascent and the maximum descent
877 double layoutasc = 0;
878 double layoutdesc = 0;
879 double const dh = defaultRowHeight();
881 // ok, let us initialize the maxasc and maxdesc value.
882 // Only the fontsize count. The other properties
883 // are taken from the layoutfont. Nicer on the screen :)
884 LayoutPtr const & layout = par.layout();
886 // as max get the first character of this row then it can
887 // increase but not decrease the height. Just some point to
888 // start with so we don't have to do the assignment below too
890 Buffer const & buffer = bv_->buffer();
891 Font font = displayFont(pit, first);
892 FontSize const tmpsize = font.fontInfo().size();
893 font.fontInfo() = text_->layoutFont(buffer, pit);
894 FontSize const size = font.fontInfo().size();
895 font.fontInfo().setSize(tmpsize);
897 FontInfo labelfont = text_->labelFont(buffer, par);
899 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
900 FontMetrics const & fontmetrics = theFontMetrics(font);
902 // these are minimum values
903 double const spacing_val = layout->spacing.getValue()
904 * text_->spacing(buffer, par);
905 //lyxerr << "spacing_val = " << spacing_val << endl;
906 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
907 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
909 // insets may be taller
910 ParagraphMetrics const & pm = par_metrics_[pit];
911 InsetList::const_iterator ii = par.insetList().begin();
912 InsetList::const_iterator iend = par.insetList().end();
913 for ( ; ii != iend; ++ii) {
914 Dimension const & dim = pm.insetDimension(ii->inset);
915 if (ii->pos >= first && ii->pos < end) {
916 maxasc = max(maxasc, dim.ascent());
917 maxdesc = max(maxdesc, dim.descent());
921 // Check if any custom fonts are larger (Asger)
922 // This is not completely correct, but we can live with the small,
923 // cosmetic error for now.
927 par.highestFontInRange(first, end, size);
928 if (maxsize > font.fontInfo().size()) {
929 // use standard paragraph font with the maximal size
930 FontInfo maxfont = font.fontInfo();
931 maxfont.setSize(maxsize);
932 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
933 maxasc = max(maxasc, maxfontmetrics.maxAscent());
934 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
937 // This is nicer with box insets:
941 ParagraphList const & pars = text_->paragraphs();
944 if (first == 0 && topBottomSpace) {
945 BufferParams const & bufparams = buffer.params();
946 // some parskips VERY EASY IMPLEMENTATION
947 if (bufparams.paragraph_separation
948 == BufferParams::PARSEP_SKIP
949 && par.ownerCode() != ERT_CODE
950 && par.ownerCode() != LISTINGS_CODE
952 && ((layout->isParagraph() && par.getDepth() == 0)
953 || (pars[pit - 1].layout()->isParagraph()
954 && pars[pit - 1].getDepth() == 0)))
956 maxasc += bufparams.getDefSkip().inPixels(*bv_);
959 if (par.params().startOfAppendix())
960 maxasc += int(3 * dh);
962 // This is special code for the chapter, since the label of this
963 // layout is printed in an extra row
964 if (layout->counter == "chapter"
965 && !par.params().labelString().empty()) {
966 labeladdon = int(labelfont_metrics.maxHeight()
967 * layout->spacing.getValue()
968 * text_->spacing(buffer, par));
971 // special code for the top label
972 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
973 || layout->labeltype == LABEL_BIBLIO
974 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
975 && isFirstInSequence(pit, pars)
976 && !par.labelString().empty())
979 labelfont_metrics.maxHeight()
980 * layout->spacing.getValue()
981 * text_->spacing(buffer, par)
982 + (layout->topsep + layout->labelbottomsep) * dh);
985 // Add the layout spaces, for example before and after
986 // a section, or between the items of a itemize or enumerate
989 pit_type prev = depthHook(pit, pars, par.getDepth());
990 Paragraph const & prevpar = pars[prev];
992 && prevpar.layout() == layout
993 && prevpar.getDepth() == par.getDepth()
994 && prevpar.getLabelWidthString()
995 == par.getLabelWidthString()) {
996 layoutasc = layout->itemsep * dh;
997 } else if (pit != 0 || first != 0) {
998 if (layout->topsep > 0)
999 layoutasc = layout->topsep * dh;
1002 prev = outerHook(pit, pars);
1003 if (prev != pit_type(pars.size())) {
1004 maxasc += int(pars[prev].layout()->parsep * dh);
1005 } else if (pit != 0) {
1006 Paragraph const & prevpar = pars[pit - 1];
1007 if (prevpar.getDepth() != 0 ||
1008 prevpar.layout() == layout) {
1009 maxasc += int(layout->parsep * dh);
1014 // is it a bottom line?
1015 if (end >= par.size() && topBottomSpace) {
1016 // add the layout spaces, for example before and after
1017 // a section, or between the items of a itemize or enumerate
1019 pit_type nextpit = pit + 1;
1020 if (nextpit != pit_type(pars.size())) {
1021 pit_type cpit = pit;
1025 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1026 usual = pars[cpit].layout()->bottomsep * dh;
1027 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1028 if (pars[cpit].layout() != pars[nextpit].layout()
1029 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1031 unusual = pars[cpit].layout()->bottomsep * dh;
1033 layoutdesc = max(unusual, usual);
1034 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1035 if (pars[cpit].layout() != pars[nextpit].layout()
1036 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1037 layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
1042 // incalculate the layout spaces
1043 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1044 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1046 // FIXME: the correct way is to do the following is to move the
1047 // following code in another method specially tailored for the
1048 // main Text. The following test is thus bogus.
1049 // Top and bottom margin of the document (only at top-level)
1050 if (main_text_ && topBottomSpace) {
1051 if (pit == 0 && first == 0)
1053 if (pit + 1 == pit_type(pars.size()) &&
1054 end == par.size() &&
1055 !(end > 0 && par.isNewline(end - 1)))
1059 return Dimension(0, maxasc + labeladdon, maxdesc);
1063 // x is an absolute screen coord
1064 // returns the column near the specified x-coordinate of the row
1065 // x is set to the real beginning of this column
1066 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1067 Row const & row, int & x, bool & boundary) const
1069 Buffer const & buffer = bv_->buffer();
1071 /// For the main Text, it is possible that this pit is not
1072 /// yet in the CoordCache when moving cursor up.
1073 /// x Paragraph coordinate is always 0 for main text anyway.
1074 int const xo = origin_.x_;
1076 Paragraph const & par = text_->getPar(pit);
1078 bidi.computeTables(par, buffer, row);
1080 pos_type vc = row.pos();
1081 pos_type end = row.endpos();
1083 LayoutPtr const & layout = par.layout();
1085 bool left_side = false;
1087 pos_type body_pos = par.beginOfBody();
1089 double tmpx = row.x;
1090 double last_tmpx = tmpx;
1093 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1096 // check for empty row
1102 while (vc < end && tmpx <= x) {
1103 c = bidi.vis2log(vc);
1105 if (body_pos > 0 && c == body_pos - 1) {
1106 FontMetrics const & fm = theFontMetrics(
1107 text_->labelFont(buffer, par));
1108 tmpx += row.label_hfill + fm.width(layout->labelsep);
1109 if (par.isLineSeparator(body_pos - 1))
1110 tmpx -= singleWidth(pit, body_pos - 1);
1113 tmpx += singleWidth(pit, c);
1114 if (par.isSeparator(c) && c >= body_pos)
1115 tmpx += row.separator;
1119 if ((tmpx + last_tmpx) / 2 > x) {
1124 BOOST_ASSERT(vc <= end); // This shouldn't happen.
1127 // This (rtl_support test) is not needed, but gives
1128 // some speedup if rtl_support == false
1129 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1131 // If lastrow is false, we don't need to compute
1132 // the value of rtl.
1133 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1135 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1136 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1137 if (!par.isNewline(end - 1))
1139 } else if (vc == row.pos()) {
1140 c = bidi.vis2log(vc);
1141 if (bidi.level(c) % 2 == 1)
1144 c = bidi.vis2log(vc - 1);
1145 bool const rtl = (bidi.level(c) % 2 == 1);
1146 if (left_side == rtl) {
1148 boundary = isRTLBoundary(pit, c);
1152 // I believe this code is not needed anymore (Jug 20050717)
1154 // The following code is necessary because the cursor position past
1155 // the last char in a row is logically equivalent to that before
1156 // the first char in the next row. That's why insets causing row
1157 // divisions -- Newline and display-style insets -- must be treated
1158 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1159 // Newline inset, air gap below:
1160 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1161 if (bidi.level(end -1) % 2 == 0)
1162 tmpx -= singleWidth(pit, end - 1);
1164 tmpx += singleWidth(pit, end - 1);
1168 // Air gap above display inset:
1169 if (row.pos() < end && c >= end && end < par.size()
1170 && par.isInset(end) && par.getInset(end)->display()) {
1173 // Air gap below display inset:
1174 if (row.pos() < end && c >= end && par.isInset(end - 1)
1175 && par.getInset(end - 1)->display()) {
1181 pos_type const col = c - row.pos();
1183 if (!c || end == par.size())
1186 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1191 return min(col, end - 1 - row.pos());
1195 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1197 // We play safe and use parMetrics(pit) to make sure the
1198 // ParagraphMetrics will be redone and OK to use if needed.
1199 // Otherwise we would use an empty ParagraphMetrics in
1200 // upDownInText() while in selection mode.
1201 ParagraphMetrics const & pm = parMetrics(pit);
1203 BOOST_ASSERT(row < int(pm.rows().size()));
1205 Row const & r = pm.rows()[row];
1206 return r.pos() + getColumnNearX(pit, r, x, bound);
1210 void TextMetrics::newParMetricsDown()
1212 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1213 pit_type const pit = last.first + 1;
1214 if (pit == int(text_->paragraphs().size()))
1217 // do it and update its position.
1219 par_metrics_[pit].setPosition(last.second.position()
1220 + last.second.descent() + par_metrics_[pit].ascent());
1224 void TextMetrics::newParMetricsUp()
1226 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1227 if (first.first == 0)
1230 pit_type const pit = first.first - 1;
1231 // do it and update its position.
1233 par_metrics_[pit].setPosition(first.second.position()
1234 - first.second.ascent() - par_metrics_[pit].descent());
1237 // y is screen coordinate
1238 pit_type TextMetrics::getPitNearY(int y)
1240 BOOST_ASSERT(!text_->paragraphs().empty());
1241 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1243 // look for highest numbered paragraph with y coordinate less than given y
1246 ParMetricsCache::const_iterator it = par_metrics_.begin();
1247 ParMetricsCache::const_iterator et = par_metrics_.end();
1248 ParMetricsCache::const_iterator last = et; last--;
1250 ParagraphMetrics const & pm = it->second;
1252 if (y < it->second.position() - int(pm.ascent())) {
1253 // We are looking for a position that is before the first paragraph in
1254 // the cache (which is in priciple off-screen, that is before the
1257 // We are already at the first paragraph in the inset.
1259 // OK, this is the paragraph we are looking for.
1260 pit = it->first - 1;
1265 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1267 if (y >= last->second.position() + int(pm_last.descent())) {
1268 // We are looking for a position that is after the last paragraph in
1269 // the cache (which is in priciple off-screen, that is before the
1271 pit = last->first + 1;
1272 if (pit == int(text_->paragraphs().size()))
1273 // We are already at the last paragraph in the inset.
1275 // OK, this is the paragraph we are looking for.
1276 newParMetricsDown();
1280 for (; it != et; ++it) {
1281 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1282 << " y: " << it->second.position());
1284 ParagraphMetrics const & pm = par_metrics_[it->first];
1286 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1288 yy = it->second.position();
1292 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1298 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1300 ParagraphMetrics const & pm = par_metrics_[pit];
1302 int yy = pm.position() - pm.ascent();
1303 BOOST_ASSERT(!pm.rows().empty());
1304 RowList::const_iterator rit = pm.rows().begin();
1305 RowList::const_iterator rlast = pm.rows().end();
1307 for (; rit != rlast; yy += rit->height(), ++rit)
1308 if (yy + rit->height() > y)
1314 // x,y are absolute screen coordinates
1315 // sets cursor recursively descending into nested editable insets
1316 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1318 if (lyxerr.debugging(Debug::WORKAREA)) {
1319 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1320 cur.bv().coordCache().dump();
1322 pit_type pit = getPitNearY(y);
1323 BOOST_ASSERT(pit != -1);
1325 Row const & row = getRowNearY(y, pit);
1328 int xx = x; // is modified by getColumnNearX
1329 pos_type const pos = row.pos()
1330 + getColumnNearX(pit, row, xx, bound);
1333 cur.boundary(bound);
1336 // try to descend into nested insets
1337 Inset * inset = checkInsetHit(x, y);
1338 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1340 // Either we deconst editXY or better we move current_font
1341 // and real_current_font to Cursor
1342 // FIXME: what is needed now that current_font and real_current_font
1344 cur.setCurrentFont();
1348 ParagraphList const & pars = text_->paragraphs();
1349 Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1350 //Inset * insetBehind = pars[pit].getInset(pos);
1352 // This should be just before or just behind the
1353 // cursor position set above.
1354 BOOST_ASSERT((pos != 0 && inset == insetBefore)
1355 || inset == pars[pit].getInset(pos));
1357 // Make sure the cursor points to the position before
1359 if (inset == insetBefore) {
1361 cur.boundary(false);
1364 // Try to descend recursively inside the inset.
1365 inset = inset->editXY(cur, x, y);
1367 if (cur.top().text() == text_)
1368 cur.setCurrentFont();
1373 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1375 BOOST_ASSERT(text_ == cur.text());
1376 pit_type pit = getPitNearY(y);
1378 ParagraphMetrics const & pm = par_metrics_[pit];
1380 int yy = pm.position() - pm.ascent();
1381 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1382 " pit: " << pit << " yy: " << yy);
1385 BOOST_ASSERT(pm.rows().size());
1386 for (; r < int(pm.rows().size()) - 1; ++r) {
1387 Row const & row = pm.rows()[r];
1388 if (int(yy + row.height()) > y)
1393 Row const & row = pm.rows()[r];
1395 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1399 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1401 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1403 text_->setCursor(cur, pit, pos, true, bound);
1404 // remember new position.
1409 //takes screen x,y coordinates
1410 Inset * TextMetrics::checkInsetHit(int x, int y)
1412 pit_type pit = getPitNearY(y);
1413 BOOST_ASSERT(pit != -1);
1415 Paragraph const & par = text_->paragraphs()[pit];
1416 ParagraphMetrics const & pm = par_metrics_[pit];
1418 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1420 InsetList::const_iterator iit = par.insetList().begin();
1421 InsetList::const_iterator iend = par.insetList().end();
1422 for (; iit != iend; ++iit) {
1423 Inset * inset = iit->inset;
1425 LYXERR(Debug::DEBUG, "examining inset " << inset);
1427 if (!bv_->coordCache().getInsets().has(inset)) {
1428 LYXERR(Debug::DEBUG, "inset has no cached position");
1432 Dimension const & dim = pm.insetDimension(inset);
1433 Point p = bv_->coordCache().getInsets().xy(inset);
1435 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1436 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1439 && x <= p.x_ + dim.wid
1440 && y >= p.y_ - dim.asc
1441 && y <= p.y_ + dim.des) {
1442 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1447 LYXERR(Debug::DEBUG, "No inset hit. ");
1452 int TextMetrics::cursorX(CursorSlice const & sl,
1453 bool boundary) const
1455 BOOST_ASSERT(sl.text() == text_);
1456 pit_type const pit = sl.pit();
1457 Paragraph const & par = text_->paragraphs()[pit];
1458 ParagraphMetrics const & pm = par_metrics_[pit];
1459 if (pm.rows().empty())
1462 pos_type ppos = sl.pos();
1463 // Correct position in front of big insets
1464 bool const boundary_correction = ppos != 0 && boundary;
1465 if (boundary_correction)
1468 Row const & row = pm.getRow(sl.pos(), boundary);
1470 pos_type cursor_vpos = 0;
1472 Buffer const & buffer = bv_->buffer();
1475 bidi.computeTables(par, buffer, row);
1477 pos_type const row_pos = row.pos();
1478 pos_type const end = row.endpos();
1479 // Spaces at logical line breaks in bidi text must be skipped during
1480 // cursor positioning. However, they may appear visually in the middle
1481 // of a row; they must be skipped, wherever they are...
1482 // * logically "abc_[HEBREW_\nHEBREW]"
1483 // * visually "abc_[_WERBEH\nWERBEH]"
1484 pos_type skipped_sep_vpos = -1;
1487 cursor_vpos = row_pos;
1488 else if (ppos >= end)
1489 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1490 else if (ppos > row_pos && ppos >= end)
1491 // Place cursor after char at (logical) position pos - 1
1492 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1493 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1495 // Place cursor before char at (logical) position ppos
1496 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1497 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1499 pos_type body_pos = par.beginOfBody();
1501 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1504 // check for possible inline completion in this row
1505 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1506 pos_type inlineCompletionVPos = -1;
1507 if (inlineCompletionPos.inTexted()
1508 && inlineCompletionPos.text() == text_
1509 && inlineCompletionPos.pit() == pit
1510 && inlineCompletionPos.pos() - 1 >= row_pos
1511 && inlineCompletionPos.pos() - 1 < end) {
1512 // draw logically behind the previous character
1513 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1516 // Use font span to speed things up, see below
1520 // If the last logical character is a separator, skip it, unless
1521 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1522 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1523 skipped_sep_vpos = bidi.log2vis(end - 1);
1525 // Inline completion RTL special case row_pos == cursor_pos:
1526 // "__|b" => cursor_pos is right of __
1527 if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1528 font = displayFont(pit, row_pos + 1);
1529 docstring const & completion = bv_->inlineCompletion();
1530 if (font.isRightToLeft() && completion.length() > 0)
1531 x += theFontMetrics(font.fontInfo()).width(completion);
1534 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1535 // Skip the separator which is at the logical end of the row
1536 if (vpos == skipped_sep_vpos)
1538 pos_type pos = bidi.vis2log(vpos);
1539 if (body_pos > 0 && pos == body_pos - 1) {
1540 FontMetrics const & labelfm = theFontMetrics(
1541 text_->labelFont(buffer, par));
1542 x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1543 if (par.isLineSeparator(body_pos - 1))
1544 x -= singleWidth(pit, body_pos - 1);
1547 // Use font span to speed things up, see above
1548 if (pos < font_span.first || pos > font_span.last) {
1549 font_span = par.fontSpan(pos);
1550 font = displayFont(pit, pos);
1553 x += pm.singleWidth(pos, font);
1555 // Inline completion RTL case:
1556 // "a__|b", __ of b => non-boundary a-pos is right of __
1557 if (vpos + 1 == inlineCompletionVPos
1558 && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1559 font = displayFont(pit, vpos + 1);
1560 docstring const & completion = bv_->inlineCompletion();
1561 if (font.isRightToLeft() && completion.length() > 0)
1562 x += theFontMetrics(font.fontInfo()).width(completion);
1565 // Inline completion LTR case:
1566 // "b|__a", __ of b => non-boundary a-pos is in front of __
1567 if (vpos == inlineCompletionVPos
1568 && (vpos + 1 < cursor_vpos || boundary_correction)) {
1569 font = displayFont(pit, vpos);
1570 docstring const & completion = bv_->inlineCompletion();
1571 if (!font.isRightToLeft() && completion.length() > 0)
1572 x += theFontMetrics(font.fontInfo()).width(completion);
1575 if (par.isSeparator(pos) && pos >= body_pos)
1579 // see correction above
1580 if (boundary_correction) {
1581 if (isRTL(sl, boundary))
1582 x -= singleWidth(pit, ppos);
1584 x += singleWidth(pit, ppos);
1591 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1593 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1594 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1595 if (pm.rows().empty())
1599 h -= par_metrics_[0].rows()[0].ascent();
1600 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1601 h += par_metrics_[pit].height();
1604 if (pos && boundary)
1606 size_t const rend = pm.pos2row(pos);
1607 for (size_t rit = 0; rit != rend; ++rit)
1608 h += pm.rows()[rit].height();
1609 h += pm.rows()[rend].ascent();
1614 void TextMetrics::cursorPrevious(Cursor & cur)
1616 pos_type cpos = cur.pos();
1617 pit_type cpar = cur.pit();
1619 // Memorize current position.
1620 Point p = bv_->getPos(cur, cur.boundary());
1621 // Scroll one full page.
1622 lyx::dispatch(FuncRequest(LFUN_SCROLL, "page up"));
1623 // Try to place the cursor to the same coordinates.
1624 setCursorFromCoordinates(cur, p.x_, p.y_);
1625 // And move one line up in order to acknowledge in inset movement and/or
1627 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1629 if (cpar == cur.pit() && cpos == cur.pos())
1630 // we have a row which is taller than the workarea. The
1631 // simplest solution is to move to the previous row instead.
1632 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1635 cur.updateFlags(Update::Force | Update::FitCursor);
1639 void TextMetrics::cursorNext(Cursor & cur)
1641 pos_type cpos = cur.pos();
1642 pit_type cpar = cur.pit();
1644 // Memorize current position.
1645 Point p = bv_->getPos(cur, cur.boundary());
1646 // Scroll one full page.
1647 lyx::dispatch(FuncRequest(LFUN_SCROLL, "page down"));
1648 // Try to place the cursor to the same coordinates.
1649 setCursorFromCoordinates(cur, p.x_, p.y_);
1650 // And move one line down in order to acknowledge in inset movement and/or
1652 cur.dispatch(FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1654 if (cpar == cur.pit() && cpos == cur.pos())
1655 // we have a row which is taller than the workarea. The
1656 // simplest solution is to move to the next row instead.
1658 FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1661 cur.updateFlags(Update::Force | Update::FitCursor);
1665 // the cursor set functions have a special mechanism. When they
1666 // realize you left an empty paragraph, they will delete it.
1668 bool TextMetrics::cursorHome(Cursor & cur)
1670 BOOST_ASSERT(text_ == cur.text());
1671 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1672 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1673 return text_->setCursor(cur, cur.pit(), row.pos());
1677 bool TextMetrics::cursorEnd(Cursor & cur)
1679 BOOST_ASSERT(text_ == cur.text());
1680 // if not on the last row of the par, put the cursor before
1681 // the final space exept if I have a spanning inset or one string
1682 // is so long that we force a break.
1683 pos_type end = cur.textRow().endpos();
1685 // empty text, end-1 is no valid position
1687 bool boundary = false;
1688 if (end != cur.lastpos()) {
1689 if (!cur.paragraph().isLineSeparator(end-1)
1690 && !cur.paragraph().isNewline(end-1))
1695 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1699 void TextMetrics::deleteLineForward(Cursor & cur)
1701 BOOST_ASSERT(text_ == cur.text());
1702 if (cur.lastpos() == 0) {
1703 // Paragraph is empty, so we just go forward
1704 text_->cursorForward(cur);
1707 cur.selection() = true; // to avoid deletion
1710 // What is this test for ??? (JMarc)
1711 if (!cur.selection())
1712 text_->deleteWordForward(cur);
1714 cap::cutSelection(cur, true, false);
1715 cur.checkBufferStructure();
1720 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1722 ParagraphList const & pars = text_->paragraphs();
1723 return row.endpos() >= pars[pit].size()
1724 && pit + 1 == pit_type(pars.size());
1728 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1730 return row.pos() == 0 && pit == 0;
1734 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1736 BOOST_ASSERT(pit >= 0);
1737 BOOST_ASSERT(pit < int(text_->paragraphs().size()));
1738 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1742 int TextMetrics::leftMargin(int max_width,
1743 pit_type const pit, pos_type const pos) const
1745 ParagraphList const & pars = text_->paragraphs();
1747 BOOST_ASSERT(pit >= 0);
1748 BOOST_ASSERT(pit < int(pars.size()));
1749 Paragraph const & par = pars[pit];
1750 BOOST_ASSERT(pos >= 0);
1751 BOOST_ASSERT(pos <= par.size());
1752 Buffer const & buffer = bv_->buffer();
1753 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1754 DocumentClass const & tclass = buffer.params().documentClass();
1755 LayoutPtr const & layout = par.layout();
1757 docstring parindent = layout->parindent;
1761 if (text_->isMainText(buffer))
1762 l_margin += bv_->leftMargin();
1764 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1765 tclass.leftmargin());
1767 if (par.getDepth() != 0) {
1768 // find the next level paragraph
1769 pit_type newpar = outerHook(pit, pars);
1770 if (newpar != pit_type(pars.size())) {
1771 if (pars[newpar].layout()->isEnvironment()) {
1772 l_margin = leftMargin(max_width, newpar);
1774 //FIXME Should this check for emptyLayout() as well?
1775 if (par.layout() == tclass.defaultLayout()) {
1776 if (pars[newpar].params().noindent())
1779 parindent = pars[newpar].layout()->parindent;
1784 // This happens after sections in standard classes. The 1.3.x
1785 // code compared depths too, but it does not seem necessary
1787 if (par.layout() == tclass.defaultLayout()
1788 && pit > 0 && pars[pit - 1].layout()->nextnoindent)
1791 FontInfo const labelfont = text_->labelFont(buffer, par);
1792 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1794 switch (layout->margintype) {
1795 case MARGIN_DYNAMIC:
1796 if (!layout->leftmargin.empty()) {
1797 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1798 layout->leftmargin);
1800 if (!par.labelString().empty()) {
1801 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1802 l_margin += labelfont_metrics.width(par.labelString());
1803 l_margin += labelfont_metrics.width(layout->labelsep);
1807 case MARGIN_MANUAL: {
1808 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1809 // The width of an empty par, even with manual label, should be 0
1810 if (!par.empty() && pos >= par.beginOfBody()) {
1811 if (!par.getLabelWidthString().empty()) {
1812 docstring labstr = par.getLabelWidthString();
1813 l_margin += labelfont_metrics.width(labstr);
1814 l_margin += labelfont_metrics.width(layout->labelsep);
1820 case MARGIN_STATIC: {
1821 l_margin += theFontMetrics(buffer.params().getFont()).
1822 signedWidth(layout->leftmargin) * 4 / (par.getDepth() + 4);
1826 case MARGIN_FIRST_DYNAMIC:
1827 if (layout->labeltype == LABEL_MANUAL) {
1828 if (pos >= par.beginOfBody()) {
1829 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1831 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1834 // Special case to fix problems with
1836 || (layout->labeltype == LABEL_STATIC
1837 && layout->latextype == LATEX_ENVIRONMENT
1838 && !isFirstInSequence(pit, pars))) {
1839 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1840 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
1841 && layout->labeltype != LABEL_BIBLIO
1842 && layout->labeltype !=
1843 LABEL_CENTERED_TOP_ENVIRONMENT) {
1844 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1845 l_margin += labelfont_metrics.width(layout->labelsep);
1846 l_margin += labelfont_metrics.width(par.labelString());
1850 case MARGIN_RIGHT_ADDRESS_BOX: {
1852 // ok, a terrible hack. The left margin depends on the widest
1853 // row in this paragraph.
1854 RowList::iterator rit = par.rows().begin();
1855 RowList::iterator end = par.rows().end();
1856 // FIXME: This is wrong.
1857 int minfill = max_width;
1858 for ( ; rit != end; ++rit)
1859 if (rit->fill() < minfill)
1860 minfill = rit->fill();
1861 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
1862 l_margin += minfill;
1864 // also wrong, but much shorter.
1865 l_margin += max_width / 2;
1870 if (!par.params().leftIndent().zero())
1871 l_margin += par.params().leftIndent().inPixels(max_width);
1875 if (par.params().align() == LYX_ALIGN_LAYOUT)
1876 align = layout->align;
1878 align = par.params().align();
1880 // set the correct parindent
1882 && (layout->labeltype == LABEL_NO_LABEL
1883 || layout->labeltype == LABEL_TOP_ENVIRONMENT
1884 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1885 || (layout->labeltype == LABEL_STATIC
1886 && layout->latextype == LATEX_ENVIRONMENT
1887 && !isFirstInSequence(pit, pars)))
1888 && align == LYX_ALIGN_BLOCK
1889 && !par.params().noindent()
1890 // in some insets, paragraphs are never indented
1891 && !(par.inInset() && par.inInset()->neverIndent())
1892 // display style insets are always centered, omit indentation
1895 && par.getInset(pos)->display())
1896 && (par.layout() != tclass.defaultLayout() //should this check emptyLayout()?
1897 || buffer.params().paragraph_separation ==
1898 BufferParams::PARSEP_INDENT))
1900 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1908 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1910 ParagraphMetrics const & pm = par_metrics_[pit];
1912 return pm.singleWidth(pos, displayFont(pit, pos));
1916 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1918 if (par_metrics_.empty())
1924 ParMetricsCache::iterator it = par_metrics_.begin();
1925 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1926 y -= it->second.ascent();
1927 for (; it != pm_end; ++it) {
1928 ParagraphMetrics const & pmi = it->second;
1930 pit_type const pit = it->first;
1931 // Save the paragraph position in the cache.
1932 it->second.setPosition(y);
1933 drawParagraph(pi, pit, x, y);
1939 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1941 BufferParams const & bparams = bv_->buffer().params();
1942 ParagraphMetrics const & pm = par_metrics_[pit];
1943 if (pm.rows().empty())
1947 bool const original_drawing_state = pi.pain.isDrawingEnabled();
1948 int const ww = bv_->workHeight();
1949 size_t const nrows = pm.rows().size();
1951 Cursor const & cur = bv_->cursor();
1952 DocIterator sel_beg = cur.selectionBegin();
1953 DocIterator sel_end = cur.selectionEnd();
1954 bool selection = cur.selection()
1955 // This is our text.
1956 && cur.text() == text_
1957 // if the anchor is outside, this is not our selection
1958 && cur.anchor().text() == text_
1959 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1961 // We care only about visible selection.
1963 if (pit != sel_beg.pit()) {
1964 sel_beg.pit() = pit;
1967 if (pit != sel_end.pit()) {
1968 sel_end.pit() = pit;
1969 sel_end.pos() = sel_end.lastpos();
1973 for (size_t i = 0; i != nrows; ++i) {
1975 Row const & row = pm.rows()[i];
1979 bool const inside = (y + row.descent() >= 0
1980 && y - row.ascent() < ww);
1981 // It is not needed to draw on screen if we are not inside.
1982 pi.pain.setDrawingEnabled(inside && original_drawing_state);
1983 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
1986 row.setSelection(sel_beg.pos(), sel_end.pos());
1988 row.setSelection(-1, -1);
1990 // Row signature; has row changed since last paint?
1991 row.setCrc(pm.computeRowSignature(row, bparams));
1992 bool row_has_changed = row.changed();
1994 // Don't paint the row if a full repaint has not been requested
1995 // and if it has not changed.
1996 if (!pi.full_repaint && !row_has_changed) {
1997 // Paint only the insets if the text itself is
1999 rp.paintOnlyInsets();
2004 // Clear background of this row if paragraph background was not
2005 // already cleared because of a full repaint.
2006 if (!pi.full_repaint && row_has_changed) {
2007 pi.pain.fillRectangle(x, y - row.ascent(),
2008 width(), row.height(), pi.background_color);
2011 bool row_selection = row.sel_beg != -1 && row.sel_end != -1;
2012 if (row_selection) {
2013 DocIterator beg = bv_->cursor().selectionBegin();
2014 DocIterator end = bv_->cursor().selectionEnd();
2015 bool const beg_margin = beg.pit() < pit && i == 0;
2016 bool const end_margin = end.pit() > pit && i == nrows - 1;
2018 beg.pos() = row.sel_beg;
2020 end.pos() = row.sel_end;
2021 drawRowSelection(pi, x, row, beg, end, beg_margin, end_margin);
2024 // Instrumentation for testing row cache (see also
2026 if (lyxerr.debugging(Debug::PAINTING) && inside
2027 && (row_selection || pi.full_repaint || row_has_changed)) {
2028 string const foreword = text_->isMainText(bv_->buffer()) ?
2029 "main text redraw " : "inset text redraw: ";
2030 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
2031 << " row_selection=" << row_selection
2032 << " full_repaint=" << pi.full_repaint
2033 << " row_has_changed=" << row_has_changed);
2036 // Backup full_repaint status and force full repaint
2037 // for inner insets as the Row has been cleared out.
2038 bool tmp = pi.full_repaint;
2039 pi.full_repaint = true;
2042 rp.paintChangeBar();
2049 // Restore full_repaint status.
2050 pi.full_repaint = tmp;
2052 // Re-enable screen drawing for future use of the painter.
2053 pi.pain.setDrawingEnabled(original_drawing_state);
2055 //LYXERR(Debug::PAINTING, ".");
2059 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2060 DocIterator const & beg, DocIterator const & end,
2061 bool drawOnBegMargin, bool drawOnEndMargin) const
2063 Buffer & buffer = bv_->buffer();
2064 DocIterator cur = beg;
2065 int x1 = cursorX(beg.top(), beg.boundary());
2066 int x2 = cursorX(end.top(), end.boundary());
2067 int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2068 int y2 = y1 + row.height();
2071 if (drawOnBegMargin) {
2072 if (text_->isRTL(buffer, beg.paragraph()))
2073 pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color_selection);
2075 pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color_selection);
2078 if (drawOnEndMargin) {
2079 if (text_->isRTL(buffer, beg.paragraph()))
2080 pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color_selection);
2082 pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color_selection);
2085 // if we are on a boundary from the beginning, it's probably
2086 // a RTL boundary and we jump to the other side directly as this
2087 // segement is 0-size and confuses the logic below
2089 cur.boundary(false);
2091 // go through row and draw from RTL boundary to RTL boundary
2093 bool drawNow = false;
2095 // simplified cursorForward code below which does not
2096 // descend into insets and which does not go into the
2097 // next line. Compare the logic with the original cursorForward
2099 // if left of boundary -> just jump to right side
2100 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2101 if (cur.boundary()) {
2102 cur.boundary(false);
2103 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2104 // in front of RTL boundary -> Stay on this side of the boundary because:
2105 // ab|cDDEEFFghi -> abc|DDEEFFghi
2114 if (cur.pos() == row.endpos())
2119 // the previous segment was just drawn, now the next starts
2120 x1 = cursorX(cur.top(), cur.boundary());
2123 if (!(cur < end) || drawNow) {
2124 x2 = cursorX(cur.top(), cur.boundary());
2125 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2128 // reset x1, so it is set again next round (which will be on the
2129 // right side of a boundary or at the selection end)
2135 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2137 // ParagraphMetrics const & pm = par_metrics_[pit];
2138 // Row const & r = pm.rows()[row];
2144 int defaultRowHeight()
2146 return int(theFontMetrics(sane_font).maxHeight() * 1.2);