2 * \file src/TextMetrics.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * \author Jürgen Vigna
13 * \author Abdelrazak Younes
15 * Full author contact details are available in file CREDITS.
20 #include "TextMetrics.h"
24 #include "buffer_funcs.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "CoordCache.h"
29 #include "CutAndPaste.h"
30 #include "FuncRequest.h"
31 #include "InsetList.h"
35 #include "MetricsInfo.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.h"
39 #include "rowpainter.h"
41 #include "TextClass.h"
44 #include "mathed/MacroTable.h"
45 #include "mathed/MathMacroTemplate.h"
47 #include "frontends/FontMetrics.h"
48 #include "frontends/Painter.h"
50 #include "support/debug.h"
52 #include "support/lassert.h"
59 using frontend::FontMetrics;
61 static 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 static 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 static 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) {
117 /////////////////////////////////////////////////////////////////////
121 /////////////////////////////////////////////////////////////////////
124 TextMetrics::TextMetrics(BufferView * bv, Text * text)
125 : bv_(bv), text_(text)
128 max_width_ = bv_->workWidth();
129 dim_.wid = max_width_;
133 //text_->updateLabels(bv->buffer());
137 bool TextMetrics::contains(pit_type pit) const
139 return par_metrics_.find(pit) != par_metrics_.end();
143 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
145 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
150 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
152 ParMetricsCache::const_iterator it = par_metrics_.begin();
153 return make_pair(it->first, &it->second);
157 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
159 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
160 return make_pair(it->first, &it->second);
164 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
166 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
167 if (pmc_it == par_metrics_.end()) {
168 pmc_it = par_metrics_.insert(
169 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
171 if (pmc_it->second.rows().empty() && redo)
173 return pmc_it->second;
177 int TextMetrics::parPosition(pit_type pit) const
179 if (pit < par_metrics_.begin()->first)
181 if (pit > par_metrics_.rbegin()->first)
184 return par_metrics_[pit].position();
188 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
190 LASSERT(mi.base.textwidth, /**/);
191 max_width_ = mi.base.textwidth;
192 // backup old dimension.
193 Dimension const old_dim = dim_;
196 dim_.wid = min_width;
197 pit_type const npar = text_->paragraphs().size();
199 // If there is more than one row, expand the text to
200 // the full allowable width.
201 dim_.wid = max_width_;
203 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
204 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
206 bool changed = false;
208 for (pit_type pit = 0; pit != npar; ++pit) {
209 changed |= redoParagraph(pit);
210 ParagraphMetrics const & pm = par_metrics_[pit];
212 if (dim_.wid < pm.width())
213 dim_.wid = pm.width();
216 dim_.asc = par_metrics_[0].ascent();
217 dim_.des = h - dim_.asc;
218 //lyxerr << "dim_.wid " << dim_.wid << endl;
219 //lyxerr << "dim_.asc " << dim_.asc << endl;
220 //lyxerr << "dim_.des " << dim_.des << endl;
222 changed |= dim_ != old_dim;
228 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
230 return main_text_? pm.rightMargin(*bv_) : 0;
234 int TextMetrics::rightMargin(pit_type const pit) const
236 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
240 void TextMetrics::applyOuterFont(Font & font) const
243 lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
244 lf.fontInfo().realize(font.fontInfo());
245 lf.setLanguage(font.language());
250 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
252 LASSERT(pos >= 0, /**/);
254 ParagraphList const & pars = text_->paragraphs();
255 Paragraph const & par = pars[pit];
256 Layout const & layout = par.layout();
257 Buffer const & buffer = bv_->buffer();
259 BufferParams const & params = buffer.params();
260 pos_type const body_pos = par.beginOfBody();
262 // We specialize the 95% common case:
263 if (!par.getDepth()) {
264 Font f = par.getFontSettings(params, pos);
265 if (!text_->isMainText(buffer))
267 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
269 FontInfo const & lf = lab ? layout.labelfont : layout.font;
270 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
272 // In case the default family has been customized
273 if (lf.family() == INHERIT_FAMILY)
274 rlf.setFamily(params.getFont().fontInfo().family());
275 f.fontInfo().realize(rlf);
279 // The uncommon case need not be optimized as much
280 FontInfo const & layoutfont = pos < body_pos ?
281 layout.labelfont : layout.font;
283 Font font = par.getFontSettings(params, pos);
284 font.fontInfo().realize(layoutfont);
286 if (!text_->isMainText(buffer))
287 applyOuterFont(font);
289 // Realize against environment font information
290 // NOTE: the cast to pit_type should be removed when pit_type
291 // changes to a unsigned integer.
292 if (pit < pit_type(pars.size()))
293 font.fontInfo().realize(outerFont(pit, pars).fontInfo());
295 // Realize with the fonts of lesser depth.
296 font.fontInfo().realize(params.getFont().fontInfo());
302 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
304 if (!lyxrc.rtl_support || !sl.text())
308 if (boundary && sl.pos() > 0)
311 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
315 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
317 if (!lyxrc.rtl_support)
320 // no RTL boundary at line start
324 Paragraph const & par = text_->getPar(pit);
326 bool left = displayFont(pit, pos - 1).isVisibleRightToLeft();
328 if (pos == par.size())
329 right = par.isRTL(bv_->buffer().params());
331 right = displayFont(pit, pos).isVisibleRightToLeft();
332 return left != right;
336 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
337 Font const & font) const
339 if (!lyxrc.rtl_support)
342 Paragraph const & par = text_->getPar(pit);
343 bool left = font.isVisibleRightToLeft();
345 if (pos == par.size())
346 right = par.isRTL(bv_->buffer().params());
348 right = displayFont(pit, pos).isVisibleRightToLeft();
349 return left != right;
353 bool TextMetrics::redoParagraph(pit_type const pit)
355 Paragraph & par = text_->getPar(pit);
356 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
357 // redoParagraph() recursively inside parMetrics.
358 Dimension old_dim = parMetrics(pit, false).dim();
359 ParagraphMetrics & pm = par_metrics_[pit];
362 Buffer & buffer = bv_->buffer();
363 main_text_ = (text_ == &buffer.text());
364 bool changed = false;
366 // FIXME: This check ought to be done somewhere else. It is the reason
367 // why text_ is not const. But then, where else to do it?
368 // Well, how can you end up with either (a) a biblio environment that
369 // has no InsetBibitem or (b) a biblio environment with more than one
370 // InsetBibitem? I think the answer is: when paragraphs are merged;
371 // when layout is set; when material is pasted.
372 int const moveCursor = par.checkBiblio(buffer);
374 const_cast<Cursor &>(bv_->cursor()).posForward();
375 else if (moveCursor < 0) {
376 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
377 if (cursor.pos() >= -moveCursor)
378 cursor.posBackward();
381 // Optimisation: this is used in the next two loops
382 // so better to calculate that once here.
383 int const right_margin = rightMargin(pm);
385 // iterator pointing to paragraph to resolve macros
386 DocIterator parPos = text_->macrocontextPosition();
390 LYXERR(Debug::INFO, "MacroContext not initialised!"
391 << " Going through the buffer again and hope"
392 << " the context is better then.");
393 updateLabels(bv_->buffer());
394 parPos = text_->macrocontextPosition();
395 LASSERT(!parPos.empty(), /**/);
400 // FIXME: We should always use getFont(), see documentation of
401 // noFontChange() in Inset.h.
402 Font const bufferfont = buffer.params().getFont();
403 InsetList::const_iterator ii = par.insetList().begin();
404 InsetList::const_iterator iend = par.insetList().end();
405 for (; ii != iend; ++ii) {
406 // position already initialized?
407 if (!parPos.empty()) {
408 parPos.pos() = ii->pos;
410 // A macro template would normally not be visible
411 // by itself. But the tex macro semantics allow
412 // recursion, so we artifically take the context
413 // after the macro template to simulate this.
414 if (ii->inset->lyxCode() == MATHMACRO_CODE)
418 // do the metric calculation
420 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
422 Font const & font = ii->inset->noFontChange() ?
423 bufferfont : displayFont(pit, ii->pos);
424 MacroContext mc(buffer, parPos);
425 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
426 ii->inset->metrics(mi, dim);
427 Dimension const old_dim = pm.insetDimension(ii->inset);
428 pm.setInsetDimension(ii->inset, dim);
429 changed |= (old_dim != dim);
432 par.setBeginOfBody();
434 size_t row_index = 0;
435 // maximum pixel width of a row
436 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
439 pos_type end = rowBreakPoint(width, pit, first);
440 if (row_index || end < par.size())
441 // If there is more than one row, expand the text to
442 // the full allowable width. This setting here is needed
443 // for the computeRowMetrics() below.
444 dim_.wid = max_width_;
446 dim = rowHeight(pit, first, end);
447 dim.wid = rowWidth(right_margin, pit, first, end);
448 if (row_index == pm.rows().size())
449 pm.rows().push_back(Row());
450 Row & row = pm.rows()[row_index];
451 row.setChanged(false);
454 row.setDimension(dim);
455 int const max_row_width = max(dim_.wid, dim.wid);
456 computeRowMetrics(pit, row, max_row_width);
460 pm.dim().wid = max(pm.dim().wid, dim.wid);
461 pm.dim().des += dim.height();
462 } while (first < par.size());
464 if (row_index < pm.rows().size())
465 pm.rows().resize(row_index);
467 // Make sure that if a par ends in newline, there is one more row
469 if (first > 0 && par.isNewline(first - 1)) {
470 Dimension dim = rowHeight(pit, first, first);
471 dim.wid = rowWidth(right_margin, pit, first, first);
472 if (row_index == pm.rows().size())
473 pm.rows().push_back(Row());
474 Row & row = pm.rows()[row_index];
475 row.setChanged(false);
478 row.setDimension(dim);
479 int const max_row_width = max(dim_.wid, dim.wid);
480 computeRowMetrics(pit, row, max_row_width);
481 pm.dim().des += dim.height();
484 pm.dim().asc += pm.rows()[0].ascent();
485 pm.dim().des -= pm.rows()[0].ascent();
487 changed |= old_dim.height() != pm.dim().height();
493 void TextMetrics::computeRowMetrics(pit_type const pit,
494 Row & row, int width) const
499 Buffer & buffer = bv_->buffer();
500 Paragraph const & par = text_->getPar(pit);
502 double w = width - row.width();
503 // FIXME: put back this assertion when the crash on new doc is solved.
504 //LASSERT(w >= 0, /**/);
506 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
507 //lyxerr << "row.width() " << row.width() << endl;
508 //lyxerr << "w " << w << endl;
510 bool const is_rtl = text_->isRTL(buffer, par);
512 row.x = rightMargin(pit);
514 row.x = leftMargin(max_width_, pit, row.pos());
516 // is there a manual margin with a manual label
517 Layout const & layout = par.layout();
519 if (layout.margintype == MARGIN_MANUAL
520 && layout.labeltype == LABEL_MANUAL) {
521 /// We might have real hfills in the label part
522 int nlh = numberOfLabelHfills(par, row);
524 // A manual label par (e.g. List) has an auto-hfill
525 // between the label text and the body of the
527 // But we don't want to do this auto hfill if the par
532 if (nlh && !par.getLabelWidthString().empty())
533 row.label_hfill = labelFill(pit, row) / double(nlh);
537 // are there any hfills in the row?
538 if (int const nh = numberOfHfills(par, row)) {
540 hfill = w / double(nh);
541 // we don't have to look at the alignment if it is ALIGN_LEFT and
542 // if the row is already larger then the permitted width as then
543 // we force the LEFT_ALIGN'edness!
544 } else if (int(row.width()) < max_width_) {
545 // is it block, flushleft or flushright?
546 // set x how you need it
548 if (par.params().align() == LYX_ALIGN_LAYOUT)
549 align = layout.align;
551 align = par.params().align();
553 // handle alignment inside tabular cells
554 if (Inset const * owner = par.inInset()) {
555 switch (owner->contentAlignment()) {
556 case LYX_ALIGN_CENTER:
558 case LYX_ALIGN_RIGHT:
559 if (align == LYX_ALIGN_NONE
560 || align == LYX_ALIGN_BLOCK)
561 align = owner->contentAlignment();
564 // unchanged (use align)
569 // Display-style insets should always be on a centred row
570 if (Inset const * inset = par.getInset(row.pos())) {
571 switch (inset->display()) {
572 case Inset::AlignLeft:
573 align = LYX_ALIGN_BLOCK;
575 case Inset::AlignCenter:
576 align = LYX_ALIGN_CENTER;
579 case Inset::AlignRight:
580 // unchanged (use align)
586 case LYX_ALIGN_BLOCK: {
587 int const ns = numberOfSeparators(par, row);
588 bool disp_inset = false;
589 if (row.endpos() < par.size()) {
590 Inset const * in = par.getInset(row.endpos());
592 disp_inset = in->display();
594 // If we have separators, this is not the last row of a
595 // par, does not end in newline, and is not row above a
596 // display inset... then stretch it
598 && row.endpos() < par.size()
599 && !par.isNewline(row.endpos() - 1)
602 row.separator = w / ns;
603 //lyxerr << "row.separator " << row.separator << endl;
604 //lyxerr << "ns " << ns << endl;
610 case LYX_ALIGN_RIGHT:
613 case LYX_ALIGN_CENTER:
620 pos_type body_pos = par.beginOfBody();
621 pos_type end = row.endpos();
624 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
626 row.x += theFontMetrics(text_->labelFont(buffer, par)).
627 width(layout.labelsep);
629 row.x += row.label_hfill;
633 pos_type const endpos = row.endpos();
634 pos_type body_pos = par.beginOfBody();
636 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
639 ParagraphMetrics & pm = par_metrics_[pit];
640 InsetList::const_iterator ii = par.insetList().begin();
641 InsetList::const_iterator iend = par.insetList().end();
642 for ( ; ii != iend; ++ii) {
643 if (ii->pos >= endpos || ii->pos < row.pos()
644 || (ii->inset->lyxCode() != SPACE_CODE ||
645 !ii->inset->isStretchableSpace()))
647 Dimension dim = row.dimension();
648 if (pm.hfillExpansion(row, ii->pos))
649 dim.wid = int(ii->pos >= body_pos ?
650 max(hfill, 5.0) : row.label_hfill);
653 // Cache the inset dimension.
654 bv_->coordCache().insets().add(ii->inset, dim);
655 pm.setInsetDimension(ii->inset, dim);
660 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
662 Buffer & buffer = bv_->buffer();
663 Paragraph const & par = text_->getPar(pit);
665 pos_type last = par.beginOfBody();
666 LASSERT(last > 0, /**/);
668 // -1 because a label ends with a space that is in the label
671 // a separator at this end does not count
672 if (par.isLineSeparator(last))
676 for (pos_type i = row.pos(); i <= last; ++i)
677 w += singleWidth(pit, i);
679 docstring const & label = par.params().labelWidthString();
683 FontMetrics const & fm
684 = theFontMetrics(text_->labelFont(buffer, par));
686 return max(0, fm.width(label) - w);
690 // this needs special handling - only newlines count as a break point
691 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
693 pos_type const end = par.size();
696 if (par.isNewline(i))
703 int TextMetrics::labelEnd(pit_type const pit) const
705 // labelEnd is only needed if the layout fills a flushleft label.
706 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
708 // return the beginning of the body
709 return leftMargin(max_width_, pit);
715 * Calling Text::getFont is slow. While rebreaking we scan a
716 * paragraph from left to right calling getFont for every char. This
717 * simple class address this problem by hidding an optimization trick
718 * (not mine btw -AB): the font is reused in the whole font span. The
719 * class handles transparently the "hidden" (not part of the fontlist)
720 * label font (as getFont does).
726 FontIterator(TextMetrics const & tm,
727 Paragraph const & par, pit_type pit, pos_type pos)
728 : tm_(tm), par_(par), pit_(pit), pos_(pos),
729 font_(tm.displayFont(pit, pos)),
730 endspan_(par.fontSpan(pos).last),
731 bodypos_(par.beginOfBody())
735 Font const & operator*() const { return font_; }
738 FontIterator & operator++()
741 if (pos_ > endspan_ || pos_ == bodypos_) {
742 font_ = tm_.displayFont(pit_, pos_);
743 endspan_ = par_.fontSpan(pos_).last;
749 Font * operator->() { return &font_; }
753 TextMetrics const & tm_;
755 Paragraph const & par_;
770 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
773 Buffer & buffer = bv_->buffer();
774 ParagraphMetrics const & pm = par_metrics_[pit];
775 Paragraph const & par = text_->getPar(pit);
776 pos_type const end = par.size();
777 if (pos == end || width < 0)
780 Layout const & layout = par.layout();
782 if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX)
783 return addressBreakPoint(pos, par);
785 pos_type const body_pos = par.beginOfBody();
787 // check for possible inline completion
788 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
789 pos_type inlineCompletionLPos = -1;
790 if (inlineCompletionPos.inTexted()
791 && inlineCompletionPos.text() == text_
792 && inlineCompletionPos.pit() == pit) {
793 // draw logically behind the previous character
794 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
797 // Now we iterate through until we reach the right margin
798 // or the end of the par, then choose the possible break
801 int label_end = labelEnd(pit);
802 int const left = leftMargin(max_width_, pit, pos);
805 // pixel width since last breakpoint
808 FontIterator fi = FontIterator(*this, par, pit, pos);
809 pos_type point = end;
811 for ( ; i < end; ++i, ++fi) {
812 int thiswidth = pm.singleWidth(i, *fi);
814 // add inline completion width
815 if (inlineCompletionLPos == i) {
816 docstring const & completion = bv_->inlineCompletion();
817 if (completion.length() > 0)
818 thiswidth += theFontMetrics(*fi).width(completion);
821 // add the auto-hfill from label end to the body
822 if (body_pos && i == body_pos) {
823 FontMetrics const & fm = theFontMetrics(
824 text_->labelFont(buffer, par));
825 int add = fm.width(layout.labelsep);
826 if (par.isLineSeparator(i - 1))
827 add -= singleWidth(pit, i - 1);
829 add = max(add, label_end - x);
834 chunkwidth += thiswidth;
836 // break before a character that will fall off
837 // the right of the row
839 // if no break before, break here
840 if (point == end || chunkwidth >= width - left) {
846 // exit on last registered breakpoint:
850 if (par.isNewline(i)) {
854 Inset const * inset = 0;
857 if ((inset = par.getInset(i + 1)) && inset->display()) {
862 if ((inset = par.getInset(i)) && inset->display()) {
868 inset = par.getInset(i);
869 if (!inset || inset->isChar()) {
870 // some insets are line separators too
871 if (par.isLineSeparator(i)) {
872 // register breakpoint:
879 // maybe found one, but the par is short enough.
880 if (i == end && x < width)
883 // manual labels cannot be broken in LaTeX. But we
884 // want to make our on-screen rendering of footnotes
886 if (body_pos && point < body_pos)
893 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
894 pos_type const first, pos_type const end) const
896 Buffer & buffer = bv_->buffer();
897 // get the pure distance
898 ParagraphMetrics const & pm = par_metrics_[pit];
899 Paragraph const & par = text_->getPar(pit);
900 int w = leftMargin(max_width_, pit, first);
901 int label_end = labelEnd(pit);
903 // check for possible inline completion
904 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
905 pos_type inlineCompletionLPos = -1;
906 if (inlineCompletionPos.inTexted()
907 && inlineCompletionPos.text() == text_
908 && inlineCompletionPos.pit() == pit) {
909 // draw logically behind the previous character
910 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
913 pos_type const body_pos = par.beginOfBody();
917 FontIterator fi = FontIterator(*this, par, pit, i);
918 for ( ; i < end; ++i, ++fi) {
919 if (body_pos > 0 && i == body_pos) {
920 FontMetrics const & fm = theFontMetrics(
921 text_->labelFont(buffer, par));
922 w += fm.width(par.layout().labelsep);
923 if (par.isLineSeparator(i - 1))
924 w -= singleWidth(pit, i - 1);
925 w = max(w, label_end);
927 w += pm.singleWidth(i, *fi);
929 // add inline completion width
930 if (inlineCompletionLPos == i) {
931 docstring const & completion = bv_->inlineCompletion();
932 if (completion.length() > 0)
933 w += theFontMetrics(*fi).width(completion);
938 if (body_pos > 0 && body_pos >= end) {
939 FontMetrics const & fm = theFontMetrics(
940 text_->labelFont(buffer, par));
941 w += fm.width(par.layout().labelsep);
942 if (end > 0 && par.isLineSeparator(end - 1))
943 w -= singleWidth(pit, end - 1);
944 w = max(w, label_end);
947 return w + right_margin;
951 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
952 pos_type const end, bool topBottomSpace) const
954 Paragraph const & par = text_->getPar(pit);
955 // get the maximum ascent and the maximum descent
956 double layoutasc = 0;
957 double layoutdesc = 0;
958 double const dh = defaultRowHeight();
960 // ok, let us initialize the maxasc and maxdesc value.
961 // Only the fontsize count. The other properties
962 // are taken from the layoutfont. Nicer on the screen :)
963 Layout const & layout = par.layout();
965 // as max get the first character of this row then it can
966 // increase but not decrease the height. Just some point to
967 // start with so we don't have to do the assignment below too
969 Buffer const & buffer = bv_->buffer();
970 Font font = displayFont(pit, first);
971 FontSize const tmpsize = font.fontInfo().size();
972 font.fontInfo() = text_->layoutFont(buffer, pit);
973 FontSize const size = font.fontInfo().size();
974 font.fontInfo().setSize(tmpsize);
976 FontInfo labelfont = text_->labelFont(buffer, par);
978 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
979 FontMetrics const & fontmetrics = theFontMetrics(font);
981 // these are minimum values
982 double const spacing_val = layout.spacing.getValue()
983 * text_->spacing(buffer, par);
984 //lyxerr << "spacing_val = " << spacing_val << endl;
985 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
986 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
988 // insets may be taller
989 ParagraphMetrics const & pm = par_metrics_[pit];
990 InsetList::const_iterator ii = par.insetList().begin();
991 InsetList::const_iterator iend = par.insetList().end();
992 for ( ; ii != iend; ++ii) {
993 Dimension const & dim = pm.insetDimension(ii->inset);
994 if (ii->pos >= first && ii->pos < end) {
995 maxasc = max(maxasc, dim.ascent());
996 maxdesc = max(maxdesc, dim.descent());
1000 // Check if any custom fonts are larger (Asger)
1001 // This is not completely correct, but we can live with the small,
1002 // cosmetic error for now.
1006 par.highestFontInRange(first, end, size);
1007 if (maxsize > font.fontInfo().size()) {
1008 // use standard paragraph font with the maximal size
1009 FontInfo maxfont = font.fontInfo();
1010 maxfont.setSize(maxsize);
1011 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
1012 maxasc = max(maxasc, maxfontmetrics.maxAscent());
1013 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
1016 // This is nicer with box insets:
1020 ParagraphList const & pars = text_->paragraphs();
1022 // is it a top line?
1023 if (first == 0 && topBottomSpace) {
1024 BufferParams const & bufparams = buffer.params();
1025 // some parskips VERY EASY IMPLEMENTATION
1026 if (bufparams.paragraph_separation
1027 == BufferParams::ParagraphSkipSeparation
1028 && par.ownerCode() != ERT_CODE
1029 && par.ownerCode() != LISTINGS_CODE
1031 && ((layout.isParagraph() && par.getDepth() == 0)
1032 || (pars[pit - 1].layout().isParagraph()
1033 && pars[pit - 1].getDepth() == 0)))
1035 maxasc += bufparams.getDefSkip().inPixels(*bv_);
1038 if (par.params().startOfAppendix())
1039 maxasc += int(3 * dh);
1041 // This is special code for the chapter, since the label of this
1042 // layout is printed in an extra row
1043 if (layout.counter == "chapter"
1044 && !par.params().labelString().empty()) {
1045 labeladdon = int(labelfont_metrics.maxHeight()
1046 * layout.spacing.getValue()
1047 * text_->spacing(buffer, par));
1050 // special code for the top label
1051 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1052 || layout.labeltype == LABEL_BIBLIO
1053 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1054 && isFirstInSequence(pit, pars)
1055 && !par.labelString().empty())
1058 labelfont_metrics.maxHeight()
1059 * layout.spacing.getValue()
1060 * text_->spacing(buffer, par)
1061 + (layout.topsep + layout.labelbottomsep) * dh);
1064 // Add the layout spaces, for example before and after
1065 // a section, or between the items of a itemize or enumerate
1068 pit_type prev = depthHook(pit, pars, par.getDepth());
1069 Paragraph const & prevpar = pars[prev];
1071 && prevpar.layout() == layout
1072 && prevpar.getDepth() == par.getDepth()
1073 && prevpar.getLabelWidthString()
1074 == par.getLabelWidthString()) {
1075 layoutasc = layout.itemsep * dh;
1076 } else if (pit != 0 || first != 0) {
1077 if (layout.topsep > 0)
1078 layoutasc = layout.topsep * dh;
1081 prev = outerHook(pit, pars);
1082 if (prev != pit_type(pars.size())) {
1083 maxasc += int(pars[prev].layout().parsep * dh);
1084 } else if (pit != 0) {
1085 Paragraph const & prevpar = pars[pit - 1];
1086 if (prevpar.getDepth() != 0 ||
1087 prevpar.layout() == layout) {
1088 maxasc += int(layout.parsep * dh);
1093 // is it a bottom line?
1094 if (end >= par.size() && topBottomSpace) {
1095 // add the layout spaces, for example before and after
1096 // a section, or between the items of a itemize or enumerate
1098 pit_type nextpit = pit + 1;
1099 if (nextpit != pit_type(pars.size())) {
1100 pit_type cpit = pit;
1104 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1105 usual = pars[cpit].layout().bottomsep * dh;
1106 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1107 if (pars[cpit].layout() != pars[nextpit].layout()
1108 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1110 unusual = pars[cpit].layout().bottomsep * dh;
1112 layoutdesc = max(unusual, usual);
1113 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1114 if (pars[cpit].layout() != pars[nextpit].layout()
1115 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1116 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1121 // incalculate the layout spaces
1122 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1123 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1125 // FIXME: the correct way is to do the following is to move the
1126 // following code in another method specially tailored for the
1127 // main Text. The following test is thus bogus.
1128 // Top and bottom margin of the document (only at top-level)
1129 if (main_text_ && topBottomSpace) {
1130 if (pit == 0 && first == 0)
1132 if (pit + 1 == pit_type(pars.size()) &&
1133 end == par.size() &&
1134 !(end > 0 && par.isNewline(end - 1)))
1138 return Dimension(0, maxasc + labeladdon, maxdesc);
1142 // x is an absolute screen coord
1143 // returns the column near the specified x-coordinate of the row
1144 // x is set to the real beginning of this column
1145 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1146 Row const & row, int & x, bool & boundary) const
1148 Buffer const & buffer = bv_->buffer();
1150 /// For the main Text, it is possible that this pit is not
1151 /// yet in the CoordCache when moving cursor up.
1152 /// x Paragraph coordinate is always 0 for main text anyway.
1153 int const xo = origin_.x_;
1155 Paragraph const & par = text_->getPar(pit);
1157 bidi.computeTables(par, buffer, row);
1159 pos_type vc = row.pos();
1160 pos_type end = row.endpos();
1162 Layout const & layout = par.layout();
1164 bool left_side = false;
1166 pos_type body_pos = par.beginOfBody();
1168 double tmpx = row.x;
1169 double last_tmpx = tmpx;
1172 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1175 // check for empty row
1181 while (vc < end && tmpx <= x) {
1182 c = bidi.vis2log(vc);
1184 if (body_pos > 0 && c == body_pos - 1) {
1185 FontMetrics const & fm = theFontMetrics(
1186 text_->labelFont(buffer, par));
1187 tmpx += row.label_hfill + fm.width(layout.labelsep);
1188 if (par.isLineSeparator(body_pos - 1))
1189 tmpx -= singleWidth(pit, body_pos - 1);
1192 tmpx += singleWidth(pit, c);
1193 if (par.isSeparator(c) && c >= body_pos)
1194 tmpx += row.separator;
1198 if ((tmpx + last_tmpx) / 2 > x) {
1203 LASSERT(vc <= end, /**/); // This shouldn't happen.
1206 // This (rtl_support test) is not needed, but gives
1207 // some speedup if rtl_support == false
1208 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1210 // If lastrow is false, we don't need to compute
1211 // the value of rtl.
1212 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1214 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1215 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1216 if (!par.isNewline(end - 1))
1218 } else if (vc == row.pos()) {
1219 c = bidi.vis2log(vc);
1220 if (bidi.level(c) % 2 == 1)
1223 c = bidi.vis2log(vc - 1);
1224 bool const rtl = (bidi.level(c) % 2 == 1);
1225 if (left_side == rtl) {
1227 boundary = isRTLBoundary(pit, c);
1231 // I believe this code is not needed anymore (Jug 20050717)
1233 // The following code is necessary because the cursor position past
1234 // the last char in a row is logically equivalent to that before
1235 // the first char in the next row. That's why insets causing row
1236 // divisions -- Newline and display-style insets -- must be treated
1237 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1238 // Newline inset, air gap below:
1239 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1240 if (bidi.level(end -1) % 2 == 0)
1241 tmpx -= singleWidth(pit, end - 1);
1243 tmpx += singleWidth(pit, end - 1);
1247 // Air gap above display inset:
1248 if (row.pos() < end && c >= end && end < par.size()
1249 && par.isInset(end) && par.getInset(end)->display()) {
1252 // Air gap below display inset:
1253 if (row.pos() < end && c >= end && par.isInset(end - 1)
1254 && par.getInset(end - 1)->display()) {
1260 pos_type const col = c - row.pos();
1262 if (!c || end == par.size())
1265 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1270 return min(col, end - 1 - row.pos());
1274 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1276 // We play safe and use parMetrics(pit) to make sure the
1277 // ParagraphMetrics will be redone and OK to use if needed.
1278 // Otherwise we would use an empty ParagraphMetrics in
1279 // upDownInText() while in selection mode.
1280 ParagraphMetrics const & pm = parMetrics(pit);
1282 LASSERT(row < int(pm.rows().size()), /**/);
1284 Row const & r = pm.rows()[row];
1285 return r.pos() + getColumnNearX(pit, r, x, bound);
1289 void TextMetrics::newParMetricsDown()
1291 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1292 pit_type const pit = last.first + 1;
1293 if (pit == int(text_->paragraphs().size()))
1296 // do it and update its position.
1298 par_metrics_[pit].setPosition(last.second.position()
1299 + last.second.descent() + par_metrics_[pit].ascent());
1303 void TextMetrics::newParMetricsUp()
1305 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1306 if (first.first == 0)
1309 pit_type const pit = first.first - 1;
1310 // do it and update its position.
1312 par_metrics_[pit].setPosition(first.second.position()
1313 - first.second.ascent() - par_metrics_[pit].descent());
1316 // y is screen coordinate
1317 pit_type TextMetrics::getPitNearY(int y)
1319 LASSERT(!text_->paragraphs().empty(), /**/);
1320 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1322 // look for highest numbered paragraph with y coordinate less than given y
1325 ParMetricsCache::const_iterator it = par_metrics_.begin();
1326 ParMetricsCache::const_iterator et = par_metrics_.end();
1327 ParMetricsCache::const_iterator last = et; last--;
1329 ParagraphMetrics const & pm = it->second;
1331 if (y < it->second.position() - int(pm.ascent())) {
1332 // We are looking for a position that is before the first paragraph in
1333 // the cache (which is in priciple off-screen, that is before the
1336 // We are already at the first paragraph in the inset.
1338 // OK, this is the paragraph we are looking for.
1339 pit = it->first - 1;
1344 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1346 if (y >= last->second.position() + int(pm_last.descent())) {
1347 // We are looking for a position that is after the last paragraph in
1348 // the cache (which is in priciple off-screen, that is before the
1350 pit = last->first + 1;
1351 if (pit == int(text_->paragraphs().size()))
1352 // We are already at the last paragraph in the inset.
1354 // OK, this is the paragraph we are looking for.
1355 newParMetricsDown();
1359 for (; it != et; ++it) {
1360 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1361 << " y: " << it->second.position());
1363 ParagraphMetrics const & pm = par_metrics_[it->first];
1365 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1367 yy = it->second.position();
1371 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1377 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1379 ParagraphMetrics const & pm = par_metrics_[pit];
1381 int yy = pm.position() - pm.ascent();
1382 LASSERT(!pm.rows().empty(), /**/);
1383 RowList::const_iterator rit = pm.rows().begin();
1384 RowList::const_iterator rlast = pm.rows().end();
1386 for (; rit != rlast; yy += rit->height(), ++rit)
1387 if (yy + rit->height() > y)
1393 // x,y are absolute screen coordinates
1394 // sets cursor recursively descending into nested editable insets
1395 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1397 if (lyxerr.debugging(Debug::WORKAREA)) {
1398 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1399 cur.bv().coordCache().dump();
1401 pit_type pit = getPitNearY(y);
1402 LASSERT(pit != -1, /**/);
1404 Row const & row = getRowNearY(y, pit);
1407 int xx = x; // is modified by getColumnNearX
1408 pos_type const pos = row.pos()
1409 + getColumnNearX(pit, row, xx, bound);
1412 cur.boundary(bound);
1415 // try to descend into nested insets
1416 Inset * inset = checkInsetHit(x, y);
1417 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1419 // Either we deconst editXY or better we move current_font
1420 // and real_current_font to Cursor
1421 // FIXME: what is needed now that current_font and real_current_font
1423 cur.setCurrentFont();
1427 ParagraphList const & pars = text_->paragraphs();
1428 Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1429 //Inset * insetBehind = pars[pit].getInset(pos);
1431 // This should be just before or just behind the
1432 // cursor position set above.
1433 LASSERT((pos != 0 && inset == insetBefore)
1434 || inset == pars[pit].getInset(pos), /**/);
1436 // Make sure the cursor points to the position before
1438 if (inset == insetBefore) {
1440 cur.boundary(false);
1443 // Try to descend recursively inside the inset.
1444 inset = inset->editXY(cur, x, y);
1446 if (cur.top().text() == text_)
1447 cur.setCurrentFont();
1452 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1454 LASSERT(text_ == cur.text(), /**/);
1455 pit_type pit = getPitNearY(y);
1457 ParagraphMetrics const & pm = par_metrics_[pit];
1459 int yy = pm.position() - pm.ascent();
1460 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1461 " pit: " << pit << " yy: " << yy);
1464 LASSERT(pm.rows().size(), /**/);
1465 for (; r < int(pm.rows().size()) - 1; ++r) {
1466 Row const & row = pm.rows()[r];
1467 if (int(yy + row.height()) > y)
1472 Row const & row = pm.rows()[r];
1474 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1478 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1480 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1482 text_->setCursor(cur, pit, pos, true, bound);
1483 // remember new position.
1488 //takes screen x,y coordinates
1489 Inset * TextMetrics::checkInsetHit(int x, int y)
1491 pit_type pit = getPitNearY(y);
1492 LASSERT(pit != -1, /**/);
1494 Paragraph const & par = text_->paragraphs()[pit];
1495 ParagraphMetrics const & pm = par_metrics_[pit];
1497 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1499 InsetList::const_iterator iit = par.insetList().begin();
1500 InsetList::const_iterator iend = par.insetList().end();
1501 for (; iit != iend; ++iit) {
1502 Inset * inset = iit->inset;
1504 LYXERR(Debug::DEBUG, "examining inset " << inset);
1506 if (!bv_->coordCache().getInsets().has(inset)) {
1507 LYXERR(Debug::DEBUG, "inset has no cached position");
1511 Dimension const & dim = pm.insetDimension(inset);
1512 Point p = bv_->coordCache().getInsets().xy(inset);
1514 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1515 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1518 && x <= p.x_ + dim.wid
1519 && y >= p.y_ - dim.asc
1520 && y <= p.y_ + dim.des) {
1521 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1526 LYXERR(Debug::DEBUG, "No inset hit. ");
1531 int TextMetrics::cursorX(CursorSlice const & sl,
1532 bool boundary) const
1534 LASSERT(sl.text() == text_, /**/);
1535 pit_type const pit = sl.pit();
1536 Paragraph const & par = text_->paragraphs()[pit];
1537 ParagraphMetrics const & pm = par_metrics_[pit];
1538 if (pm.rows().empty())
1541 pos_type ppos = sl.pos();
1542 // Correct position in front of big insets
1543 bool const boundary_correction = ppos != 0 && boundary;
1544 if (boundary_correction)
1547 Row const & row = pm.getRow(sl.pos(), boundary);
1549 pos_type cursor_vpos = 0;
1551 Buffer const & buffer = bv_->buffer();
1554 bidi.computeTables(par, buffer, row);
1556 pos_type const row_pos = row.pos();
1557 pos_type const end = row.endpos();
1558 // Spaces at logical line breaks in bidi text must be skipped during
1559 // cursor positioning. However, they may appear visually in the middle
1560 // of a row; they must be skipped, wherever they are...
1561 // * logically "abc_[HEBREW_\nHEBREW]"
1562 // * visually "abc_[_WERBEH\nWERBEH]"
1563 pos_type skipped_sep_vpos = -1;
1566 cursor_vpos = row_pos;
1567 else if (ppos >= end)
1568 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1569 else if (ppos > row_pos && ppos >= end)
1570 // Place cursor after char at (logical) position pos - 1
1571 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1572 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1574 // Place cursor before char at (logical) position ppos
1575 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1576 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1578 pos_type body_pos = par.beginOfBody();
1580 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1583 // check for possible inline completion in this row
1584 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1585 pos_type inlineCompletionVPos = -1;
1586 if (inlineCompletionPos.inTexted()
1587 && inlineCompletionPos.text() == text_
1588 && inlineCompletionPos.pit() == pit
1589 && inlineCompletionPos.pos() - 1 >= row_pos
1590 && inlineCompletionPos.pos() - 1 < end) {
1591 // draw logically behind the previous character
1592 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1595 // Use font span to speed things up, see below
1599 // If the last logical character is a separator, skip it, unless
1600 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1601 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1602 skipped_sep_vpos = bidi.log2vis(end - 1);
1604 // Inline completion RTL special case row_pos == cursor_pos:
1605 // "__|b" => cursor_pos is right of __
1606 if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1607 font = displayFont(pit, row_pos + 1);
1608 docstring const & completion = bv_->inlineCompletion();
1609 if (font.isRightToLeft() && completion.length() > 0)
1610 x += theFontMetrics(font.fontInfo()).width(completion);
1613 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1614 // Skip the separator which is at the logical end of the row
1615 if (vpos == skipped_sep_vpos)
1617 pos_type pos = bidi.vis2log(vpos);
1618 if (body_pos > 0 && pos == body_pos - 1) {
1619 FontMetrics const & labelfm = theFontMetrics(
1620 text_->labelFont(buffer, par));
1621 x += row.label_hfill + labelfm.width(par.layout().labelsep);
1622 if (par.isLineSeparator(body_pos - 1))
1623 x -= singleWidth(pit, body_pos - 1);
1626 // Use font span to speed things up, see above
1627 if (pos < font_span.first || pos > font_span.last) {
1628 font_span = par.fontSpan(pos);
1629 font = displayFont(pit, pos);
1632 x += pm.singleWidth(pos, font);
1634 // Inline completion RTL case:
1635 // "a__|b", __ of b => non-boundary a-pos is right of __
1636 if (vpos + 1 == inlineCompletionVPos
1637 && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1638 font = displayFont(pit, vpos + 1);
1639 docstring const & completion = bv_->inlineCompletion();
1640 if (font.isRightToLeft() && completion.length() > 0)
1641 x += theFontMetrics(font.fontInfo()).width(completion);
1644 // Inline completion LTR case:
1645 // "b|__a", __ of b => non-boundary a-pos is in front of __
1646 if (vpos == inlineCompletionVPos
1647 && (vpos + 1 < cursor_vpos || boundary_correction)) {
1648 font = displayFont(pit, vpos);
1649 docstring const & completion = bv_->inlineCompletion();
1650 if (!font.isRightToLeft() && completion.length() > 0)
1651 x += theFontMetrics(font.fontInfo()).width(completion);
1654 if (par.isSeparator(pos) && pos >= body_pos)
1658 // see correction above
1659 if (boundary_correction) {
1660 if (isRTL(sl, boundary))
1661 x -= singleWidth(pit, ppos);
1663 x += singleWidth(pit, ppos);
1670 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1672 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1673 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1674 if (pm.rows().empty())
1678 h -= par_metrics_[0].rows()[0].ascent();
1679 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1680 h += par_metrics_[pit].height();
1683 if (pos && boundary)
1685 size_t const rend = pm.pos2row(pos);
1686 for (size_t rit = 0; rit != rend; ++rit)
1687 h += pm.rows()[rit].height();
1688 h += pm.rows()[rend].ascent();
1693 // the cursor set functions have a special mechanism. When they
1694 // realize you left an empty paragraph, they will delete it.
1696 bool TextMetrics::cursorHome(Cursor & cur)
1698 LASSERT(text_ == cur.text(), /**/);
1699 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1700 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1701 return text_->setCursor(cur, cur.pit(), row.pos());
1705 bool TextMetrics::cursorEnd(Cursor & cur)
1707 LASSERT(text_ == cur.text(), /**/);
1708 // if not on the last row of the par, put the cursor before
1709 // the final space exept if I have a spanning inset or one string
1710 // is so long that we force a break.
1711 pos_type end = cur.textRow().endpos();
1713 // empty text, end-1 is no valid position
1715 bool boundary = false;
1716 if (end != cur.lastpos()) {
1717 if (!cur.paragraph().isLineSeparator(end-1)
1718 && !cur.paragraph().isNewline(end-1))
1723 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1727 void TextMetrics::deleteLineForward(Cursor & cur)
1729 LASSERT(text_ == cur.text(), /**/);
1730 if (cur.lastpos() == 0) {
1731 // Paragraph is empty, so we just go forward
1732 text_->cursorForward(cur);
1735 cur.selection() = true; // to avoid deletion
1738 // What is this test for ??? (JMarc)
1739 if (!cur.selection())
1740 text_->deleteWordForward(cur);
1742 cap::cutSelection(cur, true, false);
1743 cur.checkBufferStructure();
1748 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1750 ParagraphList const & pars = text_->paragraphs();
1751 return row.endpos() >= pars[pit].size()
1752 && pit + 1 == pit_type(pars.size());
1756 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1758 return row.pos() == 0 && pit == 0;
1762 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1764 LASSERT(pit >= 0, /**/);
1765 LASSERT(pit < int(text_->paragraphs().size()), /**/);
1766 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1770 int TextMetrics::leftMargin(int max_width,
1771 pit_type const pit, pos_type const pos) const
1773 ParagraphList const & pars = text_->paragraphs();
1775 LASSERT(pit >= 0, /**/);
1776 LASSERT(pit < int(pars.size()), /**/);
1777 Paragraph const & par = pars[pit];
1778 LASSERT(pos >= 0, /**/);
1779 LASSERT(pos <= par.size(), /**/);
1780 Buffer const & buffer = bv_->buffer();
1781 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1782 DocumentClass const & tclass = buffer.params().documentClass();
1783 Layout const & layout = par.layout();
1785 docstring parindent = layout.parindent;
1789 if (text_->isMainText(buffer))
1790 l_margin += bv_->leftMargin();
1792 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1793 tclass.leftmargin());
1795 if (par.getDepth() != 0) {
1796 // find the next level paragraph
1797 pit_type newpar = outerHook(pit, pars);
1798 if (newpar != pit_type(pars.size())) {
1799 if (pars[newpar].layout().isEnvironment()) {
1800 l_margin = leftMargin(max_width, newpar);
1802 if (tclass.isDefaultLayout(par.layout())
1803 || tclass.isPlainLayout(par.layout())) {
1804 if (pars[newpar].params().noindent())
1807 parindent = pars[newpar].layout().parindent;
1812 // This happens after sections in standard classes. The 1.3.x
1813 // code compared depths too, but it does not seem necessary
1815 if (tclass.isDefaultLayout(par.layout())
1816 && pit > 0 && pars[pit - 1].layout().nextnoindent)
1819 FontInfo const labelfont = text_->labelFont(buffer, par);
1820 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1822 switch (layout.margintype) {
1823 case MARGIN_DYNAMIC:
1824 if (!layout.leftmargin.empty()) {
1825 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1828 if (!par.labelString().empty()) {
1829 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1830 l_margin += labelfont_metrics.width(par.labelString());
1831 l_margin += labelfont_metrics.width(layout.labelsep);
1835 case MARGIN_MANUAL: {
1836 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1837 // The width of an empty par, even with manual label, should be 0
1838 if (!par.empty() && pos >= par.beginOfBody()) {
1839 if (!par.getLabelWidthString().empty()) {
1840 docstring labstr = par.getLabelWidthString();
1841 l_margin += labelfont_metrics.width(labstr);
1842 l_margin += labelfont_metrics.width(layout.labelsep);
1848 case MARGIN_STATIC: {
1849 l_margin += theFontMetrics(buffer.params().getFont()).
1850 signedWidth(layout.leftmargin) * 4 / (par.getDepth() + 4);
1854 case MARGIN_FIRST_DYNAMIC:
1855 if (layout.labeltype == LABEL_MANUAL) {
1856 if (pos >= par.beginOfBody()) {
1857 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1859 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1862 // Special case to fix problems with
1864 || (layout.labeltype == LABEL_STATIC
1865 && layout.latextype == LATEX_ENVIRONMENT
1866 && !isFirstInSequence(pit, pars))) {
1867 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1868 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
1869 && layout.labeltype != LABEL_BIBLIO
1870 && layout.labeltype !=
1871 LABEL_CENTERED_TOP_ENVIRONMENT) {
1872 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1873 l_margin += labelfont_metrics.width(layout.labelsep);
1874 l_margin += labelfont_metrics.width(par.labelString());
1878 case MARGIN_RIGHT_ADDRESS_BOX: {
1880 // ok, a terrible hack. The left margin depends on the widest
1881 // row in this paragraph.
1882 RowList::iterator rit = par.rows().begin();
1883 RowList::iterator end = par.rows().end();
1884 // FIXME: This is wrong.
1885 int minfill = max_width;
1886 for ( ; rit != end; ++rit)
1887 if (rit->fill() < minfill)
1888 minfill = rit->fill();
1889 l_margin += theFontMetrics(params.getFont()).signedWidth(layout.leftmargin);
1890 l_margin += minfill;
1892 // also wrong, but much shorter.
1893 l_margin += max_width / 2;
1898 if (!par.params().leftIndent().zero())
1899 l_margin += par.params().leftIndent().inPixels(max_width);
1903 if (par.params().align() == LYX_ALIGN_LAYOUT)
1904 align = layout.align;
1906 align = par.params().align();
1908 // set the correct parindent
1910 && (layout.labeltype == LABEL_NO_LABEL
1911 || layout.labeltype == LABEL_TOP_ENVIRONMENT
1912 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1913 || (layout.labeltype == LABEL_STATIC
1914 && layout.latextype == LATEX_ENVIRONMENT
1915 && !isFirstInSequence(pit, pars)))
1916 && align == LYX_ALIGN_BLOCK
1917 && !par.params().noindent()
1918 // in some insets, paragraphs are never indented
1919 && !(par.inInset() && par.inInset()->neverIndent())
1920 // display style insets are always centered, omit indentation
1923 && par.getInset(pos)->display())
1924 && (!(tclass.isDefaultLayout(par.layout())
1925 || tclass.isPlainLayout(par.layout()))
1926 || buffer.params().paragraph_separation == BufferParams::ParagraphIndentSeparation)
1929 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1937 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1939 ParagraphMetrics const & pm = par_metrics_[pit];
1941 return pm.singleWidth(pos, displayFont(pit, pos));
1945 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1947 if (par_metrics_.empty())
1953 ParMetricsCache::iterator it = par_metrics_.begin();
1954 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1955 y -= it->second.ascent();
1956 for (; it != pm_end; ++it) {
1957 ParagraphMetrics const & pmi = it->second;
1959 pit_type const pit = it->first;
1960 // Save the paragraph position in the cache.
1961 it->second.setPosition(y);
1962 drawParagraph(pi, pit, x, y);
1968 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1970 BufferParams const & bparams = bv_->buffer().params();
1971 ParagraphMetrics const & pm = par_metrics_[pit];
1972 if (pm.rows().empty())
1976 bool const original_drawing_state = pi.pain.isDrawingEnabled();
1977 int const ww = bv_->workHeight();
1978 size_t const nrows = pm.rows().size();
1980 Cursor const & cur = bv_->cursor();
1981 DocIterator sel_beg = cur.selectionBegin();
1982 DocIterator sel_end = cur.selectionEnd();
1983 bool selection = cur.selection()
1984 // This is our text.
1985 && cur.text() == text_
1986 // if the anchor is outside, this is not our selection
1987 && cur.anchor().text() == text_
1988 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1990 // We care only about visible selection.
1992 if (pit != sel_beg.pit()) {
1993 sel_beg.pit() = pit;
1996 if (pit != sel_end.pit()) {
1997 sel_end.pit() = pit;
1998 sel_end.pos() = sel_end.lastpos();
2002 for (size_t i = 0; i != nrows; ++i) {
2004 Row const & row = pm.rows()[i];
2008 bool const inside = (y + row.descent() >= 0
2009 && y - row.ascent() < ww);
2010 // It is not needed to draw on screen if we are not inside.
2011 pi.pain.setDrawingEnabled(inside && original_drawing_state);
2012 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
2015 row.setSelection(sel_beg.pos(), sel_end.pos());
2017 row.setSelection(-1, -1);
2019 // Row signature; has row changed since last paint?
2020 row.setCrc(pm.computeRowSignature(row, bparams));
2021 bool row_has_changed = row.changed();
2023 // Don't paint the row if a full repaint has not been requested
2024 // and if it has not changed.
2025 if (!pi.full_repaint && !row_has_changed) {
2026 // Paint only the insets if the text itself is
2028 rp.paintOnlyInsets();
2033 // Clear background of this row if paragraph background was not
2034 // already cleared because of a full repaint.
2035 if (!pi.full_repaint && row_has_changed) {
2036 pi.pain.fillRectangle(x, y - row.ascent(),
2037 width(), row.height(), pi.background_color);
2040 bool row_selection = row.sel_beg != -1 && row.sel_end != -1;
2041 if (row_selection) {
2042 DocIterator beg = bv_->cursor().selectionBegin();
2043 DocIterator end = bv_->cursor().selectionEnd();
2044 // FIXME (not here): pit is not updated when extending
2045 // a selection to a new row with cursor right/left
2046 bool const beg_margin = beg.pit() < pit;
2047 bool const end_margin = end.pit() > pit;
2049 beg.pos() = row.sel_beg;
2051 end.pos() = row.sel_end;
2052 if (end.pos() == row.endpos()) {
2053 // selection goes till the end of the row.
2056 drawRowSelection(pi, x, row, beg, end, beg_margin, end_margin);
2059 // Instrumentation for testing row cache (see also
2061 if (lyxerr.debugging(Debug::PAINTING) && inside
2062 && (row_selection || pi.full_repaint || row_has_changed)) {
2063 string const foreword = text_->isMainText(bv_->buffer()) ?
2064 "main text redraw " : "inset text redraw: ";
2065 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
2066 << " row_selection=" << row_selection
2067 << " full_repaint=" << pi.full_repaint
2068 << " row_has_changed=" << row_has_changed);
2071 // Backup full_repaint status and force full repaint
2072 // for inner insets as the Row has been cleared out.
2073 bool tmp = pi.full_repaint;
2074 pi.full_repaint = true;
2077 rp.paintChangeBar();
2084 // Restore full_repaint status.
2085 pi.full_repaint = tmp;
2087 // Re-enable screen drawing for future use of the painter.
2088 pi.pain.setDrawingEnabled(original_drawing_state);
2090 //LYXERR(Debug::PAINTING, ".");
2094 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2095 DocIterator const & beg, DocIterator const & end,
2096 bool drawOnBegMargin, bool drawOnEndMargin) const
2098 Buffer & buffer = bv_->buffer();
2099 DocIterator cur = beg;
2100 int x1 = cursorX(beg.top(), beg.boundary());
2101 int x2 = cursorX(end.top(), end.boundary());
2102 int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2103 int y2 = y1 + row.height();
2106 if (drawOnBegMargin) {
2107 if (text_->isRTL(buffer, beg.paragraph())) {
2108 int lm = bv_->leftMargin();
2109 pi.pain.fillRectangle(x + x1, y1, width() - lm - x1, y2 - y1, Color_selection);
2111 int rm = bv_->rightMargin();
2112 pi.pain.fillRectangle(rm, y1, x1 - rm, y2 - y1, Color_selection);
2116 if (drawOnEndMargin) {
2117 if (text_->isRTL(buffer, beg.paragraph())) {
2118 int rm = bv_->rightMargin();
2119 pi.pain.fillRectangle(x + rm, y1, x2 - rm, y2 - y1, Color_selection);
2121 int lm = bv_->leftMargin();
2122 pi.pain.fillRectangle(x + x2, y1, width() - lm - x2, y2 - y1, Color_selection);
2126 // if we are on a boundary from the beginning, it's probably
2127 // a RTL boundary and we jump to the other side directly as this
2128 // segement is 0-size and confuses the logic below
2130 cur.boundary(false);
2132 // go through row and draw from RTL boundary to RTL boundary
2134 bool drawNow = false;
2136 // simplified cursorForward code below which does not
2137 // descend into insets and which does not go into the
2138 // next line. Compare the logic with the original cursorForward
2140 // if left of boundary -> just jump to right side
2141 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2142 if (cur.boundary()) {
2143 cur.boundary(false);
2144 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2145 // in front of RTL boundary -> Stay on this side of the boundary because:
2146 // ab|cDDEEFFghi -> abc|DDEEFFghi
2155 if (cur.pos() == row.endpos())
2160 // the previous segment was just drawn, now the next starts
2161 x1 = cursorX(cur.top(), cur.boundary());
2164 if (!(cur < end) || drawNow) {
2165 x2 = cursorX(cur.top(), cur.boundary());
2166 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2169 // reset x1, so it is set again next round (which will be on the
2170 // right side of a boundary or at the selection end)
2177 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2178 Dimension & dim) const
2180 Cursor const & bvcur = cur.bv().cursor();
2182 // get word in front of cursor
2183 docstring word = text_->previousWord(bvcur.top());
2184 DocIterator wordStart = bvcur;
2185 wordStart.pos() -= word.length();
2187 // get position on screen of the word start and end
2188 Point lxy = cur.bv().getPos(wordStart, false);
2189 Point rxy = cur.bv().getPos(bvcur, bvcur.boundary());
2191 // calculate dimensions of the word
2192 dim = rowHeight(bvcur.pit(), wordStart.pos(), bvcur.pos(), false);
2193 dim.wid = abs(rxy.x_ - lxy.x_);
2195 // calculate position of word
2197 x = min(rxy.x_, lxy.x_);
2199 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2200 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2203 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2205 // ParagraphMetrics const & pm = par_metrics_[pit];
2206 // Row const & r = pm.rows()[row];
2212 int defaultRowHeight()
2214 return int(theFontMetrics(sane_font).maxHeight() * 1.2);