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 "support/debug.h"
31 #include "FontIterator.h"
32 #include "FuncRequest.h"
33 #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"
56 using frontend::FontMetrics;
60 int numberOfSeparators(Paragraph const & par, Row const & row)
62 pos_type const first = max(row.pos(), par.beginOfBody());
63 pos_type const last = row.endpos() - 1;
65 for (pos_type p = first; p < last; ++p) {
66 if (par.isSeparator(p))
73 int numberOfLabelHfills(Paragraph const & par, Row const & row)
75 pos_type last = row.endpos() - 1;
76 pos_type first = row.pos();
78 // hfill *DO* count at the beginning of paragraphs!
80 while (first < last && par.isHfill(first))
84 last = min(last, par.beginOfBody());
86 for (pos_type p = first; p < last; ++p) {
94 int numberOfHfills(Paragraph const & par, Row const & row)
96 pos_type const last = row.endpos();
97 pos_type first = row.pos();
99 // hfill *DO* count at the beginning of paragraphs!
101 while (first < last && par.isHfill(first))
105 first = max(first, par.beginOfBody());
108 for (pos_type p = first; p < last; ++p) {
117 TextMetrics::TextMetrics(BufferView * bv, Text * text)
118 : bv_(bv), text_(text)
121 max_width_ = bv_->workWidth();
122 dim_.wid = max_width_;
126 //text_->updateLabels(bv->buffer());
130 bool TextMetrics::has(pit_type pit) const
132 return par_metrics_.find(pit) != par_metrics_.end();
136 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
138 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
143 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
145 ParMetricsCache::const_iterator it = par_metrics_.begin();
146 return make_pair(it->first, &it->second);
150 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
152 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
153 return make_pair(it->first, &it->second);
157 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
159 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
160 if (pmc_it == par_metrics_.end()) {
161 pmc_it = par_metrics_.insert(
162 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
164 if (pmc_it->second.rows().empty() && redo)
166 return pmc_it->second;
170 int TextMetrics::parPosition(pit_type pit) const
172 if (pit < par_metrics_.begin()->first)
174 if (pit > par_metrics_.rbegin()->first)
177 return par_metrics_[pit].position();
181 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
183 BOOST_ASSERT(mi.base.textwidth);
184 max_width_ = mi.base.textwidth;
185 // backup old dimension.
186 Dimension const old_dim = dim_;
189 dim_.wid = min_width;
190 pit_type const npar = text_->paragraphs().size();
192 // If there is more than one row, expand the text to
193 // the full allowable width.
194 dim_.wid = max_width_;
196 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
197 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
199 bool changed = false;
201 for (pit_type pit = 0; pit != npar; ++pit) {
202 changed |= redoParagraph(pit);
203 ParagraphMetrics const & pm = par_metrics_[pit];
205 if (dim_.wid < pm.width())
206 dim_.wid = pm.width();
209 dim_.asc = par_metrics_[0].ascent();
210 dim_.des = h - dim_.asc;
211 //lyxerr << "dim_.wid " << dim_.wid << endl;
212 //lyxerr << "dim_.asc " << dim_.asc << endl;
213 //lyxerr << "dim_.des " << dim_.des << endl;
215 changed |= dim_ != old_dim;
221 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
223 return main_text_? pm.rightMargin(*bv_) : 0;
227 int TextMetrics::rightMargin(pit_type const pit) const
229 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
233 void TextMetrics::applyOuterFont(Font & font) const
236 lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
237 lf.fontInfo().realize(font.fontInfo());
238 lf.setLanguage(font.language());
243 Font TextMetrics::getDisplayFont(pit_type pit, pos_type pos) const
245 BOOST_ASSERT(pos >= 0);
247 ParagraphList const & pars = text_->paragraphs();
248 Paragraph const & par = pars[pit];
249 LayoutPtr const & layout = par.layout();
250 Buffer const & buffer = bv_->buffer();
252 BufferParams const & params = buffer.params();
253 pos_type const body_pos = par.beginOfBody();
255 // We specialize the 95% common case:
256 if (!par.getDepth()) {
257 Font f = par.getFontSettings(params, pos);
258 if (!text_->isMainText(buffer))
260 bool lab = layout->labeltype == LABEL_MANUAL && pos < body_pos;
262 FontInfo const & lf = lab ? layout->labelfont : layout->font;
263 FontInfo rlf = lab ? layout->reslabelfont : layout->resfont;
265 // In case the default family has been customized
266 if (lf.family() == INHERIT_FAMILY)
267 rlf.setFamily(params.getFont().fontInfo().family());
268 f.fontInfo().realize(rlf);
272 // The uncommon case need not be optimized as much
273 FontInfo const & layoutfont = pos < body_pos ?
274 layout->labelfont : layout->font;
276 Font font = par.getFontSettings(params, pos);
277 font.fontInfo().realize(layoutfont);
279 if (!text_->isMainText(buffer))
280 applyOuterFont(font);
282 // Realize against environment font information
283 // NOTE: the cast to pit_type should be removed when pit_type
284 // changes to a unsigned integer.
285 if (pit < pit_type(pars.size()))
286 font.fontInfo().realize(outerFont(pit, pars).fontInfo());
288 // Realize with the fonts of lesser depth.
289 font.fontInfo().realize(params.getFont().fontInfo());
295 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
297 if (!lyxrc.rtl_support || !sl.text())
301 if (boundary && sl.pos() > 0)
304 return getDisplayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
308 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
310 if (!lyxrc.rtl_support)
313 // no RTL boundary at line start
317 Paragraph const & par = text_->getPar(pit);
319 bool left = getDisplayFont(pit, pos - 1).isVisibleRightToLeft();
321 if (pos == par.size())
322 right = par.isRTL(bv_->buffer().params());
324 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
325 return left != right;
329 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
330 Font const & font) const
332 if (!lyxrc.rtl_support)
335 Paragraph const & par = text_->getPar(pit);
336 bool left = font.isVisibleRightToLeft();
338 if (pos == par.size())
339 right = par.isRTL(bv_->buffer().params());
341 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
342 return left != right;
346 bool TextMetrics::redoParagraph(pit_type const pit)
348 Paragraph & par = text_->getPar(pit);
349 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
350 // redoParagraph() recursively inside parMetrics.
351 Dimension old_dim = parMetrics(pit, false).dim();
352 ParagraphMetrics & pm = par_metrics_[pit];
355 Buffer & buffer = bv_->buffer();
356 main_text_ = (text_ == &buffer.text());
357 bool changed = false;
359 // FIXME This check ought to be done somewhere else. It is the reason
360 // why text_ is not const. But then, where else to do it?
361 // Well, how can you end up with either (a) a biblio environment that
362 // has no InsetBibitem or (b) a biblio environment with more than one
363 // InsetBibitem? I think the answer is: when paragraphs are merged;
364 // when layout is set; when material is pasted.
365 int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
367 const_cast<Cursor &>(bv_->cursor()).posForward();
368 else if (moveCursor < 0) {
369 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
370 if (cursor.pos() >= -moveCursor)
371 cursor.posBackward();
374 // Optimisation: this is used in the next two loops
375 // so better to calculate that once here.
376 int const right_margin = rightMargin(pm);
378 // iterator pointing to paragraph to resolve macros
379 DocIterator parPos = text_->macrocontextPosition();
383 LYXERR(Debug::INFO, "MacroContext not initialised!"
384 << " Going through the buffer again and hope"
385 << " the context is better then.");
386 updateLabels(bv_->buffer());
387 parPos = text_->macrocontextPosition();
388 BOOST_ASSERT(!parPos.empty());
393 // FIXME: We should always use getFont(), see documentation of
394 // noFontChange() in Inset.h.
395 Font const bufferfont = buffer.params().getFont();
396 InsetList::const_iterator ii = par.insetList().begin();
397 InsetList::const_iterator iend = par.insetList().end();
398 for (; ii != iend; ++ii) {
399 // position already initialized?
400 if (!parPos.empty()) {
401 parPos.pos() = ii->pos;
403 // A macro template would normally not be visible
404 // by itself. But the tex macro semantics allow
405 // recursion, so we artifically take the context
406 // after the macro template to simulate this.
407 if (ii->inset->lyxCode() == MATHMACRO_CODE)
411 // do the metric calculation
413 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
415 Font const & font = ii->inset->noFontChange() ?
416 bufferfont : getDisplayFont(pit, ii->pos);
417 MacroContext mc(buffer, parPos);
418 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
419 ii->inset->metrics(mi, dim);
420 Dimension const old_dim = pm.insetDimension(ii->inset);
421 pm.setInsetDimension(ii->inset, dim);
422 changed |= (old_dim != dim);
425 Cursor const & cur = bv_->cursor();
426 DocIterator sel_beg = cur.selectionBegin();
427 DocIterator sel_end = cur.selectionEnd();
428 bool selection = cur.selection()
430 && cur.text() == text_
431 // if the anchor is outside, this is not our selection
432 && cur.anchor().text() == text_
433 && pit >= sel_beg.pit() && pit <= sel_end.pit();
435 // We care only about visible selection.
437 if (pit != sel_beg.pit()) {
441 if (pit != sel_end.pit()) {
443 sel_end.pos() = sel_end.lastpos();
447 par.setBeginOfBody();
449 size_t row_index = 0;
450 // maximum pixel width of a row
451 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
454 pos_type end = rowBreakPoint(width, pit, first);
455 if (row_index || end < par.size())
456 // If there is more than one row, expand the text to
457 // the full allowable width. This setting here is needed
458 // for the computeRowMetrics() below.
459 dim_.wid = max_width_;
461 dim = rowHeight(pit, first, end);
462 dim.wid = rowWidth(right_margin, pit, first, end);
463 if (row_index == pm.rows().size())
464 pm.rows().push_back(Row());
465 Row & row = pm.rows()[row_index];
466 row.setChanged(false);
470 row.setSelection(sel_beg.pos(), sel_end.pos());
472 row.setSelection(-1, -1);
473 row.setDimension(dim);
474 int const max_row_width = max(dim_.wid, dim.wid);
475 computeRowMetrics(pit, row, max_row_width);
479 pm.dim().wid = max(pm.dim().wid, dim.wid);
480 pm.dim().des += dim.height();
481 } while (first < par.size());
483 if (row_index < pm.rows().size())
484 pm.rows().resize(row_index);
486 // Make sure that if a par ends in newline, there is one more row
488 if (first > 0 && par.isNewline(first - 1)) {
489 Dimension dim = rowHeight(pit, first, first);
490 dim.wid = rowWidth(right_margin, pit, first, first);
491 if (row_index == pm.rows().size())
492 pm.rows().push_back(Row());
493 Row & row = pm.rows()[row_index];
494 row.setChanged(false);
497 row.setDimension(dim);
498 int const max_row_width = max(dim_.wid, dim.wid);
499 computeRowMetrics(pit, row, max_row_width);
500 pm.dim().des += dim.height();
503 pm.dim().asc += pm.rows()[0].ascent();
504 pm.dim().des -= pm.rows()[0].ascent();
506 changed |= old_dim.height() != pm.dim().height();
512 void TextMetrics::computeRowMetrics(pit_type const pit,
513 Row & row, int width) const
518 Buffer & buffer = bv_->buffer();
519 Paragraph const & par = text_->getPar(pit);
521 double w = width - row.width();
522 // FIXME: put back this assertion when the crash on new doc is solved.
523 //BOOST_ASSERT(w >= 0);
525 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
526 //lyxerr << "row.width() " << row.width() << endl;
527 //lyxerr << "w " << w << endl;
529 bool const is_rtl = text_->isRTL(buffer, par);
531 row.x = rightMargin(pit);
533 row.x = leftMargin(max_width_, pit, row.pos());
535 // is there a manual margin with a manual label
536 LayoutPtr const & layout = par.layout();
538 if (layout->margintype == MARGIN_MANUAL
539 && layout->labeltype == LABEL_MANUAL) {
540 /// We might have real hfills in the label part
541 int nlh = numberOfLabelHfills(par, row);
543 // A manual label par (e.g. List) has an auto-hfill
544 // between the label text and the body of the
546 // But we don't want to do this auto hfill if the par
551 if (nlh && !par.getLabelWidthString().empty())
552 row.label_hfill = labelFill(pit, row) / double(nlh);
556 // are there any hfills in the row?
557 if (int const nh = numberOfHfills(par, row)) {
559 hfill = w / double(nh);
560 // we don't have to look at the alignment if it is ALIGN_LEFT and
561 // if the row is already larger then the permitted width as then
562 // we force the LEFT_ALIGN'edness!
563 } else if (int(row.width()) < max_width_) {
564 // is it block, flushleft or flushright?
565 // set x how you need it
567 if (par.params().align() == LYX_ALIGN_LAYOUT)
568 align = layout->align;
570 align = par.params().align();
572 // Display-style insets should always be on a centred row
573 if (Inset const * inset = par.getInset(row.pos())) {
574 switch (inset->display()) {
575 case Inset::AlignLeft:
576 align = LYX_ALIGN_BLOCK;
578 case Inset::AlignCenter:
579 align = LYX_ALIGN_CENTER;
582 case Inset::AlignRight:
583 // unchanged (use align)
589 case LYX_ALIGN_BLOCK: {
590 int const ns = numberOfSeparators(par, row);
591 bool disp_inset = false;
592 if (row.endpos() < par.size()) {
593 Inset const * in = par.getInset(row.endpos());
595 disp_inset = in->display();
597 // If we have separators, this is not the last row of a
598 // par, does not end in newline, and is not row above a
599 // display inset... then stretch it
601 && row.endpos() < par.size()
602 && !par.isNewline(row.endpos() - 1)
605 row.separator = w / ns;
606 //lyxerr << "row.separator " << row.separator << endl;
607 //lyxerr << "ns " << ns << endl;
613 case LYX_ALIGN_RIGHT:
616 case LYX_ALIGN_CENTER:
623 pos_type body_pos = par.beginOfBody();
624 pos_type end = row.endpos();
627 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
629 row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
630 width(layout->labelsep);
632 row.x += row.label_hfill;
636 pos_type const endpos = row.endpos();
637 pos_type body_pos = par.beginOfBody();
639 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
642 ParagraphMetrics & pm = par_metrics_[pit];
643 InsetList::const_iterator ii = par.insetList().begin();
644 InsetList::const_iterator iend = par.insetList().end();
645 for ( ; ii != iend; ++ii) {
646 if (ii->pos >= endpos || ii->pos < row.pos()
647 || ii->inset->lyxCode() != HFILL_CODE)
649 Dimension dim = row.dimension();
650 if (pm.hfillExpansion(row, ii->pos))
651 dim.wid = int(ii->pos >= body_pos ?
652 max(hfill, 5.0) : row.label_hfill);
655 // Cache the inset dimension.
656 bv_->coordCache().insets().add(ii->inset, dim);
657 pm.setInsetDimension(ii->inset, dim);
662 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
664 Buffer & buffer = bv_->buffer();
665 Paragraph const & par = text_->getPar(pit);
667 pos_type last = par.beginOfBody();
668 BOOST_ASSERT(last > 0);
670 // -1 because a label ends with a space that is in the label
673 // a separator at this end does not count
674 if (par.isLineSeparator(last))
678 for (pos_type i = row.pos(); i <= last; ++i)
679 w += singleWidth(pit, i);
681 docstring const & label = par.params().labelWidthString();
685 FontMetrics const & fm
686 = theFontMetrics(text_->getLabelFont(buffer, par));
688 return max(0, fm.width(label) - w);
692 // this needs special handling - only newlines count as a break point
693 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
695 pos_type const end = par.size();
698 if (par.isNewline(i))
705 int TextMetrics::labelEnd(pit_type const pit) const
707 // labelEnd is only needed if the layout fills a flushleft label.
708 if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
710 // return the beginning of the body
711 return leftMargin(max_width_, pit);
715 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
718 Buffer & buffer = bv_->buffer();
719 ParagraphMetrics const & pm = par_metrics_[pit];
720 Paragraph const & par = text_->getPar(pit);
721 pos_type const end = par.size();
722 if (pos == end || width < 0)
725 LayoutPtr const & layout = par.layout();
727 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
728 return addressBreakPoint(pos, par);
730 pos_type const body_pos = par.beginOfBody();
733 // Now we iterate through until we reach the right margin
734 // or the end of the par, then choose the possible break
737 int label_end = labelEnd(pit);
738 int const left = leftMargin(max_width_, pit, pos);
741 // pixel width since last breakpoint
744 FontIterator fi = FontIterator(*this, par, pit, pos);
745 pos_type point = end;
747 for ( ; i < end; ++i, ++fi) {
748 int thiswidth = pm.singleWidth(i, *fi);
750 // add the auto-hfill from label end to the body
751 if (body_pos && i == body_pos) {
752 FontMetrics const & fm = theFontMetrics(
753 text_->getLabelFont(buffer, par));
754 int add = fm.width(layout->labelsep);
755 if (par.isLineSeparator(i - 1))
756 add -= singleWidth(pit, i - 1);
758 add = max(add, label_end - x);
763 chunkwidth += thiswidth;
765 // break before a character that will fall off
766 // the right of the row
768 // if no break before, break here
769 if (point == end || chunkwidth >= width - left) {
775 // exit on last registered breakpoint:
779 if (par.isNewline(i)) {
783 Inset const * inset = 0;
786 if ((inset = par.getInset(i + 1)) && inset->display()) {
791 if ((inset = par.getInset(i)) && inset->display()) {
797 inset = par.getInset(i);
798 if (!inset || inset->isChar()) {
799 // some insets are line separators too
800 if (par.isLineSeparator(i)) {
801 // register breakpoint:
808 // maybe found one, but the par is short enough.
809 if (i == end && x < width)
812 // manual labels cannot be broken in LaTeX. But we
813 // want to make our on-screen rendering of footnotes
815 if (body_pos && point < body_pos)
822 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
823 pos_type const first, pos_type const end) const
825 Buffer & buffer = bv_->buffer();
826 // get the pure distance
827 ParagraphMetrics const & pm = par_metrics_[pit];
828 Paragraph const & par = text_->getPar(pit);
829 int w = leftMargin(max_width_, pit, first);
830 int label_end = labelEnd(pit);
832 pos_type const body_pos = par.beginOfBody();
836 FontIterator fi = FontIterator(*this, par, pit, i);
837 for ( ; i < end; ++i, ++fi) {
838 if (body_pos > 0 && i == body_pos) {
839 FontMetrics const & fm = theFontMetrics(
840 text_->getLabelFont(buffer, par));
841 w += fm.width(par.layout()->labelsep);
842 if (par.isLineSeparator(i - 1))
843 w -= singleWidth(pit, i - 1);
844 w = max(w, label_end);
846 w += pm.singleWidth(i, *fi);
850 if (body_pos > 0 && body_pos >= end) {
851 FontMetrics const & fm = theFontMetrics(
852 text_->getLabelFont(buffer, par));
853 w += fm.width(par.layout()->labelsep);
854 if (end > 0 && par.isLineSeparator(end - 1))
855 w -= singleWidth(pit, end - 1);
856 w = max(w, label_end);
859 return w + right_margin;
863 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
864 pos_type const end) const
866 Paragraph const & par = text_->getPar(pit);
867 // get the maximum ascent and the maximum descent
868 double layoutasc = 0;
869 double layoutdesc = 0;
870 double const dh = defaultRowHeight();
872 // ok, let us initialize the maxasc and maxdesc value.
873 // Only the fontsize count. The other properties
874 // are taken from the layoutfont. Nicer on the screen :)
875 LayoutPtr const & layout = par.layout();
877 // as max get the first character of this row then it can
878 // increase but not decrease the height. Just some point to
879 // start with so we don't have to do the assignment below too
881 Buffer const & buffer = bv_->buffer();
882 Font font = getDisplayFont(pit, first);
883 FontSize const tmpsize = font.fontInfo().size();
884 font.fontInfo() = text_->getLayoutFont(buffer, pit);
885 FontSize const size = font.fontInfo().size();
886 font.fontInfo().setSize(tmpsize);
888 FontInfo labelfont = text_->getLabelFont(buffer, par);
890 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
891 FontMetrics const & fontmetrics = theFontMetrics(font);
893 // these are minimum values
894 double const spacing_val = layout->spacing.getValue()
895 * text_->spacing(buffer, par);
896 //lyxerr << "spacing_val = " << spacing_val << endl;
897 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
898 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
900 // insets may be taller
901 ParagraphMetrics const & pm = par_metrics_[pit];
902 InsetList::const_iterator ii = par.insetList().begin();
903 InsetList::const_iterator iend = par.insetList().end();
904 for ( ; ii != iend; ++ii) {
905 Dimension const & dim = pm.insetDimension(ii->inset);
906 if (ii->pos >= first && ii->pos < end) {
907 maxasc = max(maxasc, dim.ascent());
908 maxdesc = max(maxdesc, dim.descent());
912 // Check if any custom fonts are larger (Asger)
913 // This is not completely correct, but we can live with the small,
914 // cosmetic error for now.
918 par.highestFontInRange(first, end, size);
919 if (maxsize > font.fontInfo().size()) {
920 // use standard paragraph font with the maximal size
921 FontInfo maxfont = font.fontInfo();
922 maxfont.setSize(maxsize);
923 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
924 maxasc = max(maxasc, maxfontmetrics.maxAscent());
925 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
928 // This is nicer with box insets:
932 ParagraphList const & pars = text_->paragraphs();
936 BufferParams const & bufparams = buffer.params();
937 // some parskips VERY EASY IMPLEMENTATION
938 if (bufparams.paragraph_separation
939 == BufferParams::PARSEP_SKIP
940 && par.ownerCode() != ERT_CODE
941 && par.ownerCode() != LISTINGS_CODE
943 && ((layout->isParagraph() && par.getDepth() == 0)
944 || (pars[pit - 1].layout()->isParagraph()
945 && pars[pit - 1].getDepth() == 0)))
947 maxasc += bufparams.getDefSkip().inPixels(*bv_);
950 if (par.params().startOfAppendix())
951 maxasc += int(3 * dh);
953 // This is special code for the chapter, since the label of this
954 // layout is printed in an extra row
955 if (layout->counter == "chapter"
956 && !par.params().labelString().empty()) {
957 labeladdon = int(labelfont_metrics.maxHeight()
958 * layout->spacing.getValue()
959 * text_->spacing(buffer, par));
962 // special code for the top label
963 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
964 || layout->labeltype == LABEL_BIBLIO
965 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
966 && isFirstInSequence(pit, pars)
967 && !par.getLabelstring().empty())
970 labelfont_metrics.maxHeight()
971 * layout->spacing.getValue()
972 * text_->spacing(buffer, par)
973 + (layout->topsep + layout->labelbottomsep) * dh);
976 // Add the layout spaces, for example before and after
977 // a section, or between the items of a itemize or enumerate
980 pit_type prev = depthHook(pit, pars, par.getDepth());
981 Paragraph const & prevpar = pars[prev];
983 && prevpar.layout() == layout
984 && prevpar.getDepth() == par.getDepth()
985 && prevpar.getLabelWidthString()
986 == par.getLabelWidthString()) {
987 layoutasc = layout->itemsep * dh;
988 } else if (pit != 0 || first != 0) {
989 if (layout->topsep > 0)
990 layoutasc = layout->topsep * dh;
993 prev = outerHook(pit, pars);
994 if (prev != pit_type(pars.size())) {
995 maxasc += int(pars[prev].layout()->parsep * dh);
996 } else if (pit != 0) {
997 Paragraph const & prevpar = pars[pit - 1];
998 if (prevpar.getDepth() != 0 ||
999 prevpar.layout() == layout) {
1000 maxasc += int(layout->parsep * dh);
1005 // is it a bottom line?
1006 if (end >= par.size()) {
1007 // add the layout spaces, for example before and after
1008 // a section, or between the items of a itemize or enumerate
1010 pit_type nextpit = pit + 1;
1011 if (nextpit != pit_type(pars.size())) {
1012 pit_type cpit = pit;
1016 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1017 usual = pars[cpit].layout()->bottomsep * dh;
1018 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1019 if (pars[cpit].layout() != pars[nextpit].layout()
1020 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1022 unusual = pars[cpit].layout()->bottomsep * dh;
1024 layoutdesc = max(unusual, usual);
1025 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1026 if (pars[cpit].layout() != pars[nextpit].layout()
1027 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1028 layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
1033 // incalculate the layout spaces
1034 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1035 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1037 // FIXME: the correct way is to do the following is to move the
1038 // following code in another method specially tailored for the
1039 // main Text. The following test is thus bogus.
1040 // Top and bottom margin of the document (only at top-level)
1042 if (pit == 0 && first == 0)
1044 if (pit + 1 == pit_type(pars.size()) &&
1045 end == par.size() &&
1046 !(end > 0 && par.isNewline(end - 1)))
1050 return Dimension(0, maxasc + labeladdon, maxdesc);
1054 // x is an absolute screen coord
1055 // returns the column near the specified x-coordinate of the row
1056 // x is set to the real beginning of this column
1057 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1058 Row const & row, int & x, bool & boundary) const
1060 Buffer const & buffer = bv_->buffer();
1062 /// For the main Text, it is possible that this pit is not
1063 /// yet in the CoordCache when moving cursor up.
1064 /// x Paragraph coordinate is always 0 for main text anyway.
1065 int const xo = origin_.x_;
1067 Paragraph const & par = text_->getPar(pit);
1069 bidi.computeTables(par, buffer, row);
1071 pos_type vc = row.pos();
1072 pos_type end = row.endpos();
1074 LayoutPtr const & layout = par.layout();
1076 bool left_side = false;
1078 pos_type body_pos = par.beginOfBody();
1080 double tmpx = row.x;
1081 double last_tmpx = tmpx;
1084 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1087 // check for empty row
1093 while (vc < end && tmpx <= x) {
1094 c = bidi.vis2log(vc);
1096 if (body_pos > 0 && c == body_pos - 1) {
1097 FontMetrics const & fm = theFontMetrics(
1098 text_->getLabelFont(buffer, par));
1099 tmpx += row.label_hfill + fm.width(layout->labelsep);
1100 if (par.isLineSeparator(body_pos - 1))
1101 tmpx -= singleWidth(pit, body_pos - 1);
1104 tmpx += singleWidth(pit, c);
1105 if (par.isSeparator(c) && c >= body_pos)
1106 tmpx += row.separator;
1110 if ((tmpx + last_tmpx) / 2 > x) {
1115 BOOST_ASSERT(vc <= end); // This shouldn't happen.
1118 // This (rtl_support test) is not needed, but gives
1119 // some speedup if rtl_support == false
1120 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1122 // If lastrow is false, we don't need to compute
1123 // the value of rtl.
1124 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1126 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1127 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1128 if (!par.isNewline(end - 1))
1130 } else if (vc == row.pos()) {
1131 c = bidi.vis2log(vc);
1132 if (bidi.level(c) % 2 == 1)
1135 c = bidi.vis2log(vc - 1);
1136 bool const rtl = (bidi.level(c) % 2 == 1);
1137 if (left_side == rtl) {
1139 boundary = isRTLBoundary(pit, c);
1143 // I believe this code is not needed anymore (Jug 20050717)
1145 // The following code is necessary because the cursor position past
1146 // the last char in a row is logically equivalent to that before
1147 // the first char in the next row. That's why insets causing row
1148 // divisions -- Newline and display-style insets -- must be treated
1149 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1150 // Newline inset, air gap below:
1151 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1152 if (bidi.level(end -1) % 2 == 0)
1153 tmpx -= singleWidth(pit, end - 1);
1155 tmpx += singleWidth(pit, end - 1);
1159 // Air gap above display inset:
1160 if (row.pos() < end && c >= end && end < par.size()
1161 && par.isInset(end) && par.getInset(end)->display()) {
1164 // Air gap below display inset:
1165 if (row.pos() < end && c >= end && par.isInset(end - 1)
1166 && par.getInset(end - 1)->display()) {
1172 pos_type const col = c - row.pos();
1174 if (!c || end == par.size())
1177 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1182 return min(col, end - 1 - row.pos());
1186 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1188 // We play safe and use parMetrics(pit) to make sure the
1189 // ParagraphMetrics will be redone and OK to use if needed.
1190 // Otherwise we would use an empty ParagraphMetrics in
1191 // upDownInText() while in selection mode.
1192 ParagraphMetrics const & pm = parMetrics(pit);
1194 BOOST_ASSERT(row < int(pm.rows().size()));
1196 Row const & r = pm.rows()[row];
1197 return r.pos() + getColumnNearX(pit, r, x, bound);
1201 void TextMetrics::newParMetricsDown()
1203 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1204 pit_type const pit = last.first + 1;
1205 if (pit == int(text_->paragraphs().size()))
1208 // do it and update its position.
1210 par_metrics_[pit].setPosition(last.second.position()
1211 + last.second.descent() + par_metrics_[pit].ascent());
1215 void TextMetrics::newParMetricsUp()
1217 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1218 if (first.first == 0)
1221 pit_type const pit = first.first - 1;
1222 // do it and update its position.
1224 par_metrics_[pit].setPosition(first.second.position()
1225 - first.second.ascent() - par_metrics_[pit].descent());
1228 // y is screen coordinate
1229 pit_type TextMetrics::getPitNearY(int y)
1231 BOOST_ASSERT(!text_->paragraphs().empty());
1232 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1234 // look for highest numbered paragraph with y coordinate less than given y
1237 ParMetricsCache::const_iterator it = par_metrics_.begin();
1238 ParMetricsCache::const_iterator et = par_metrics_.end();
1239 ParMetricsCache::const_iterator last = et; last--;
1241 ParagraphMetrics const & pm = it->second;
1243 if (y < it->second.position() - int(pm.ascent())) {
1244 // We are looking for a position that is before the first paragraph in
1245 // the cache (which is in priciple off-screen, that is before the
1248 // We are already at the first paragraph in the inset.
1250 // OK, this is the paragraph we are looking for.
1251 pit = it->first - 1;
1256 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1258 if (y >= last->second.position() + int(pm_last.descent())) {
1259 // We are looking for a position that is after the last paragraph in
1260 // the cache (which is in priciple off-screen, that is before the
1262 pit = last->first + 1;
1263 if (pit == int(text_->paragraphs().size()))
1264 // We are already at the last paragraph in the inset.
1266 // OK, this is the paragraph we are looking for.
1267 newParMetricsDown();
1271 for (; it != et; ++it) {
1272 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1273 << " y: " << it->second.position());
1275 ParagraphMetrics const & pm = par_metrics_[it->first];
1277 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1279 yy = it->second.position();
1283 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1289 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1291 ParagraphMetrics const & pm = par_metrics_[pit];
1293 int yy = pm.position() - pm.ascent();
1294 BOOST_ASSERT(!pm.rows().empty());
1295 RowList::const_iterator rit = pm.rows().begin();
1296 RowList::const_iterator rlast = pm.rows().end();
1298 for (; rit != rlast; yy += rit->height(), ++rit)
1299 if (yy + rit->height() > y)
1305 // x,y are absolute screen coordinates
1306 // sets cursor recursively descending into nested editable insets
1307 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1309 if (lyxerr.debugging(Debug::WORKAREA)) {
1310 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1311 cur.bv().coordCache().dump();
1313 pit_type pit = getPitNearY(y);
1314 BOOST_ASSERT(pit != -1);
1316 Row const & row = getRowNearY(y, pit);
1319 int xx = x; // is modified by getColumnNearX
1320 pos_type const pos = row.pos()
1321 + getColumnNearX(pit, row, xx, bound);
1324 cur.boundary(bound);
1327 // try to descend into nested insets
1328 Inset * inset = checkInsetHit(x, y);
1329 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1331 // Either we deconst editXY or better we move current_font
1332 // and real_current_font to Cursor
1333 // FIXME: what is needed now that current_font and real_current_font
1335 cur.setCurrentFont();
1339 ParagraphList const & pars = text_->paragraphs();
1340 Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1341 //Inset * insetBehind = pars[pit].getInset(pos);
1343 // This should be just before or just behind the
1344 // cursor position set above.
1345 BOOST_ASSERT((pos != 0 && inset == insetBefore)
1346 || inset == pars[pit].getInset(pos));
1348 // Make sure the cursor points to the position before
1350 if (inset == insetBefore) {
1352 cur.boundary(false);
1355 // Try to descend recursively inside the inset.
1356 inset = inset->editXY(cur, x, y);
1358 if (cur.top().text() == text_)
1359 cur.setCurrentFont();
1364 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1366 BOOST_ASSERT(text_ == cur.text());
1367 pit_type pit = getPitNearY(y);
1369 ParagraphMetrics const & pm = par_metrics_[pit];
1371 int yy = pm.position() - pm.ascent();
1372 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1373 " pit: " << pit << " yy: " << yy);
1376 BOOST_ASSERT(pm.rows().size());
1377 for (; r < int(pm.rows().size()) - 1; ++r) {
1378 Row const & row = pm.rows()[r];
1379 if (int(yy + row.height()) > y)
1384 Row const & row = pm.rows()[r];
1386 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1390 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1392 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1394 text_->setCursor(cur, pit, pos, true, bound);
1395 // remember new position.
1400 //takes screen x,y coordinates
1401 Inset * TextMetrics::checkInsetHit(int x, int y)
1403 pit_type pit = getPitNearY(y);
1404 BOOST_ASSERT(pit != -1);
1406 Paragraph const & par = text_->paragraphs()[pit];
1407 ParagraphMetrics const & pm = par_metrics_[pit];
1409 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1411 InsetList::const_iterator iit = par.insetList().begin();
1412 InsetList::const_iterator iend = par.insetList().end();
1413 for (; iit != iend; ++iit) {
1414 Inset * inset = iit->inset;
1416 LYXERR(Debug::DEBUG, "examining inset " << inset);
1418 if (!bv_->coordCache().getInsets().has(inset)) {
1419 LYXERR(Debug::DEBUG, "inset has no cached position");
1423 Dimension const & dim = pm.insetDimension(inset);
1424 Point p = bv_->coordCache().getInsets().xy(inset);
1426 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1427 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1430 && x <= p.x_ + dim.wid
1431 && y >= p.y_ - dim.asc
1432 && y <= p.y_ + dim.des) {
1433 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1438 LYXERR(Debug::DEBUG, "No inset hit. ");
1443 int TextMetrics::cursorX(CursorSlice const & sl,
1444 bool boundary) const
1446 BOOST_ASSERT(sl.text() == text_);
1447 pit_type const pit = sl.pit();
1448 Paragraph const & par = text_->paragraphs()[pit];
1449 ParagraphMetrics const & pm = par_metrics_[pit];
1450 if (pm.rows().empty())
1453 pos_type ppos = sl.pos();
1454 // Correct position in front of big insets
1455 bool const boundary_correction = ppos != 0 && boundary;
1456 if (boundary_correction)
1459 Row const & row = pm.getRow(sl.pos(), boundary);
1461 pos_type cursor_vpos = 0;
1463 Buffer const & buffer = bv_->buffer();
1466 bidi.computeTables(par, buffer, row);
1468 pos_type const row_pos = row.pos();
1469 pos_type const end = row.endpos();
1470 // Spaces at logical line breaks in bidi text must be skipped during
1471 // cursor positioning. However, they may appear visually in the middle
1472 // of a row; they must be skipped, wherever they are...
1473 // * logically "abc_[HEBREW_\nHEBREW]"
1474 // * visually "abc_[_WERBEH\nWERBEH]"
1475 pos_type skipped_sep_vpos = -1;
1478 cursor_vpos = row_pos;
1479 else if (ppos >= end)
1480 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1481 else if (ppos > row_pos && ppos >= end)
1482 // Place cursor after char at (logical) position pos - 1
1483 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1484 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1486 // Place cursor before char at (logical) position ppos
1487 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1488 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1490 pos_type body_pos = par.beginOfBody();
1492 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1495 // Use font span to speed things up, see below
1499 // If the last logical character is a separator, skip it, unless
1500 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1501 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1502 skipped_sep_vpos = bidi.log2vis(end - 1);
1504 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1505 // Skip the separator which is at the logical end of the row
1506 if (vpos == skipped_sep_vpos)
1508 pos_type pos = bidi.vis2log(vpos);
1509 if (body_pos > 0 && pos == body_pos - 1) {
1510 FontMetrics const & labelfm = theFontMetrics(
1511 text_->getLabelFont(buffer, par));
1512 x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1513 if (par.isLineSeparator(body_pos - 1))
1514 x -= singleWidth(pit, body_pos - 1);
1517 // Use font span to speed things up, see above
1518 if (pos < font_span.first || pos > font_span.last) {
1519 font_span = par.fontSpan(pos);
1520 font = getDisplayFont(pit, pos);
1523 x += pm.singleWidth(pos, font);
1525 if (par.isSeparator(pos) && pos >= body_pos)
1529 // see correction above
1530 if (boundary_correction) {
1531 if (isRTL(sl, boundary))
1532 x -= singleWidth(pit, ppos);
1534 x += singleWidth(pit, ppos);
1541 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1543 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1544 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1545 if (pm.rows().empty())
1549 h -= par_metrics_[0].rows()[0].ascent();
1550 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1551 h += par_metrics_[pit].height();
1554 if (pos && boundary)
1556 size_t const rend = pm.pos2row(pos);
1557 for (size_t rit = 0; rit != rend; ++rit)
1558 h += pm.rows()[rit].height();
1559 h += pm.rows()[rend].ascent();
1564 void TextMetrics::cursorPrevious(Cursor & cur)
1566 pos_type cpos = cur.pos();
1567 pit_type cpar = cur.pit();
1569 int x = cur.x_target();
1570 setCursorFromCoordinates(cur, x, 0);
1571 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1573 if (cpar == cur.pit() && cpos == cur.pos())
1574 // we have a row which is taller than the workarea. The
1575 // simplest solution is to move to the previous row instead.
1576 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1579 cur.updateFlags(Update::Force | Update::FitCursor);
1583 void TextMetrics::cursorNext(Cursor & cur)
1585 pos_type cpos = cur.pos();
1586 pit_type cpar = cur.pit();
1588 int x = cur.x_target();
1589 setCursorFromCoordinates(cur, x, cur.bv().workHeight() - 1);
1590 cur.dispatch(FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1592 if (cpar == cur.pit() && cpos == cur.pos())
1593 // we have a row which is taller than the workarea. The
1594 // simplest solution is to move to the next row instead.
1596 FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1599 cur.updateFlags(Update::Force | Update::FitCursor);
1603 // the cursor set functions have a special mechanism. When they
1604 // realize you left an empty paragraph, they will delete it.
1606 bool TextMetrics::cursorHome(Cursor & cur)
1608 BOOST_ASSERT(text_ == cur.text());
1609 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1610 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1611 return text_->setCursor(cur, cur.pit(), row.pos());
1615 bool TextMetrics::cursorEnd(Cursor & cur)
1617 BOOST_ASSERT(text_ == cur.text());
1618 // if not on the last row of the par, put the cursor before
1619 // the final space exept if I have a spanning inset or one string
1620 // is so long that we force a break.
1621 pos_type end = cur.textRow().endpos();
1623 // empty text, end-1 is no valid position
1625 bool boundary = false;
1626 if (end != cur.lastpos()) {
1627 if (!cur.paragraph().isLineSeparator(end-1)
1628 && !cur.paragraph().isNewline(end-1))
1633 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1637 void TextMetrics::deleteLineForward(Cursor & cur)
1639 BOOST_ASSERT(text_ == cur.text());
1640 if (cur.lastpos() == 0) {
1641 // Paragraph is empty, so we just go forward
1642 text_->cursorForward(cur);
1645 cur.selection() = true; // to avoid deletion
1648 // What is this test for ??? (JMarc)
1649 if (!cur.selection())
1650 text_->deleteWordForward(cur);
1652 cap::cutSelection(cur, true, false);
1653 cur.checkBufferStructure();
1658 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1660 ParagraphList const & pars = text_->paragraphs();
1661 return row.endpos() >= pars[pit].size()
1662 && pit + 1 == pit_type(pars.size());
1666 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1668 return row.pos() == 0 && pit == 0;
1672 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1674 BOOST_ASSERT(pit >= 0);
1675 BOOST_ASSERT(pit < int(text_->paragraphs().size()));
1676 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1680 int TextMetrics::leftMargin(int max_width,
1681 pit_type const pit, pos_type const pos) const
1683 ParagraphList const & pars = text_->paragraphs();
1685 BOOST_ASSERT(pit >= 0);
1686 BOOST_ASSERT(pit < int(pars.size()));
1687 Paragraph const & par = pars[pit];
1688 BOOST_ASSERT(pos >= 0);
1689 BOOST_ASSERT(pos <= par.size());
1690 Buffer const & buffer = bv_->buffer();
1691 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1692 TextClass const & tclass = buffer.params().getTextClass();
1693 LayoutPtr const & layout = par.layout();
1695 docstring parindent = layout->parindent;
1699 if (text_->isMainText(buffer))
1700 l_margin += bv_->leftMargin();
1702 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1703 tclass.leftmargin());
1705 if (par.getDepth() != 0) {
1706 // find the next level paragraph
1707 pit_type newpar = outerHook(pit, pars);
1708 if (newpar != pit_type(pars.size())) {
1709 if (pars[newpar].layout()->isEnvironment()) {
1710 l_margin = leftMargin(max_width, newpar);
1712 //FIXME Should this check for emptyLayout() as well?
1713 if (par.layout() == tclass.defaultLayout()) {
1714 if (pars[newpar].params().noindent())
1717 parindent = pars[newpar].layout()->parindent;
1722 // This happens after sections in standard classes. The 1.3.x
1723 // code compared depths too, but it does not seem necessary
1725 if (par.layout() == tclass.defaultLayout()
1726 && pit > 0 && pars[pit - 1].layout()->nextnoindent)
1729 FontInfo const labelfont = text_->getLabelFont(buffer, par);
1730 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1732 switch (layout->margintype) {
1733 case MARGIN_DYNAMIC:
1734 if (!layout->leftmargin.empty()) {
1735 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1736 layout->leftmargin);
1738 if (!par.getLabelstring().empty()) {
1739 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1740 l_margin += labelfont_metrics.width(par.getLabelstring());
1741 l_margin += labelfont_metrics.width(layout->labelsep);
1745 case MARGIN_MANUAL: {
1746 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1747 // The width of an empty par, even with manual label, should be 0
1748 if (!par.empty() && pos >= par.beginOfBody()) {
1749 if (!par.getLabelWidthString().empty()) {
1750 docstring labstr = par.getLabelWidthString();
1751 l_margin += labelfont_metrics.width(labstr);
1752 l_margin += labelfont_metrics.width(layout->labelsep);
1758 case MARGIN_STATIC: {
1759 l_margin += theFontMetrics(buffer.params().getFont()).
1760 signedWidth(layout->leftmargin) * 4 / (par.getDepth() + 4);
1764 case MARGIN_FIRST_DYNAMIC:
1765 if (layout->labeltype == LABEL_MANUAL) {
1766 if (pos >= par.beginOfBody()) {
1767 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1769 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1772 // Special case to fix problems with
1774 || (layout->labeltype == LABEL_STATIC
1775 && layout->latextype == LATEX_ENVIRONMENT
1776 && !isFirstInSequence(pit, pars))) {
1777 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1778 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
1779 && layout->labeltype != LABEL_BIBLIO
1780 && layout->labeltype !=
1781 LABEL_CENTERED_TOP_ENVIRONMENT) {
1782 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1783 l_margin += labelfont_metrics.width(layout->labelsep);
1784 l_margin += labelfont_metrics.width(par.getLabelstring());
1788 case MARGIN_RIGHT_ADDRESS_BOX: {
1790 // ok, a terrible hack. The left margin depends on the widest
1791 // row in this paragraph.
1792 RowList::iterator rit = par.rows().begin();
1793 RowList::iterator end = par.rows().end();
1794 // FIXME: This is wrong.
1795 int minfill = max_width;
1796 for ( ; rit != end; ++rit)
1797 if (rit->fill() < minfill)
1798 minfill = rit->fill();
1799 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
1800 l_margin += minfill;
1802 // also wrong, but much shorter.
1803 l_margin += max_width / 2;
1808 if (!par.params().leftIndent().zero())
1809 l_margin += par.params().leftIndent().inPixels(max_width);
1813 if (par.params().align() == LYX_ALIGN_LAYOUT)
1814 align = layout->align;
1816 align = par.params().align();
1818 // set the correct parindent
1820 && (layout->labeltype == LABEL_NO_LABEL
1821 || layout->labeltype == LABEL_TOP_ENVIRONMENT
1822 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1823 || (layout->labeltype == LABEL_STATIC
1824 && layout->latextype == LATEX_ENVIRONMENT
1825 && !isFirstInSequence(pit, pars)))
1826 && align == LYX_ALIGN_BLOCK
1827 && !par.params().noindent()
1828 // in some insets, paragraphs are never indented
1829 && !(par.inInset() && par.inInset()->neverIndent(buffer))
1830 // display style insets are always centered, omit indentation
1833 && par.getInset(pos)->display())
1834 && (par.layout() != tclass.defaultLayout() //should this check emptyLayout()?
1835 || buffer.params().paragraph_separation ==
1836 BufferParams::PARSEP_INDENT))
1838 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1846 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1848 ParagraphMetrics const & pm = par_metrics_[pit];
1850 return pm.singleWidth(pos, getDisplayFont(pit, pos));
1854 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1856 if (par_metrics_.empty())
1862 ParMetricsCache::iterator it = par_metrics_.begin();
1863 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1864 y -= it->second.ascent();
1865 for (; it != pm_end; ++it) {
1866 ParagraphMetrics const & pmi = it->second;
1868 pit_type const pit = it->first;
1869 // Save the paragraph position in the cache.
1870 it->second.setPosition(y);
1871 drawParagraph(pi, pit, x, y);
1877 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1879 BufferParams const & bparams = bv_->buffer().params();
1880 ParagraphMetrics const & pm = par_metrics_[pit];
1881 if (pm.rows().empty())
1885 bool const original_drawing_state = pi.pain.isDrawingEnabled();
1886 int const ww = bv_->workHeight();
1887 size_t const nrows = pm.rows().size();
1889 for (size_t i = 0; i != nrows; ++i) {
1891 Row const & row = pm.rows()[i];
1895 bool const inside = (y + row.descent() >= 0
1896 && y - row.ascent() < ww);
1897 // It is not needed to draw on screen if we are not inside.
1898 pi.pain.setDrawingEnabled(inside && original_drawing_state);
1899 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
1901 // Row signature; has row changed since last paint?
1902 row.setCrc(pm.computeRowSignature(row, bparams));
1903 bool row_has_changed = row.changed();
1905 // Don't paint the row if a full repaint has not been requested
1906 // and if it has not changed.
1907 if (!pi.full_repaint && !row_has_changed) {
1908 // Paint only the insets if the text itself is
1910 rp.paintOnlyInsets();
1915 // Clear background of this row if paragraph background was not
1916 // already cleared because of a full repaint.
1917 if (!pi.full_repaint && row_has_changed) {
1918 pi.pain.fillRectangle(x, y - row.ascent(),
1919 width(), row.height(), pi.background_color);
1922 bool row_selection = row.sel_beg != -1 && row.sel_end != -1;
1923 if (row_selection) {
1924 DocIterator beg = bv_->cursor().selectionBegin();
1925 DocIterator end = bv_->cursor().selectionEnd();
1926 bool const beg_margin = beg.pit() < pit && i == 0;
1927 bool const end_margin = end.pit() > pit && i == nrows - 1;
1929 beg.pos() = row.sel_beg;
1931 end.pos() = row.sel_end;
1932 drawRowSelection(pi, x, row, beg, end, beg_margin, end_margin);
1935 // Instrumentation for testing row cache (see also
1937 if (lyxerr.debugging(Debug::PAINTING) && inside
1938 && (row_selection || pi.full_repaint || row_has_changed)) {
1939 string const foreword = text_->isMainText(bv_->buffer()) ?
1940 "main text redraw " : "inset text redraw: ";
1941 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
1942 << " row_selection=" << row_selection
1943 << " full_repaint=" << pi.full_repaint
1944 << " row_has_changed=" << row_has_changed);
1947 // Backup full_repaint status and force full repaint
1948 // for inner insets as the Row has been cleared out.
1949 bool tmp = pi.full_repaint;
1950 pi.full_repaint = true;
1953 rp.paintChangeBar();
1960 // Restore full_repaint status.
1961 pi.full_repaint = tmp;
1963 // Re-enable screen drawing for future use of the painter.
1964 pi.pain.setDrawingEnabled(original_drawing_state);
1966 //LYXERR(Debug::PAINTING, ".");
1970 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
1971 DocIterator const & beg, DocIterator const & end,
1972 bool drawOnBegMargin, bool drawOnEndMargin) const
1974 Buffer & buffer = bv_->buffer();
1975 DocIterator cur = beg;
1976 int x1 = cursorX(beg.top(), beg.boundary());
1977 int x2 = cursorX(end.top(), end.boundary());
1978 int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
1979 int y2 = y1 + row.height();
1982 if (drawOnBegMargin) {
1983 if (text_->isRTL(buffer, beg.paragraph()))
1984 pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color_selection);
1986 pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color_selection);
1989 if (drawOnEndMargin) {
1990 if (text_->isRTL(buffer, beg.paragraph()))
1991 pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color_selection);
1993 pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color_selection);
1996 // if we are on a boundary from the beginning, it's probably
1997 // a RTL boundary and we jump to the other side directly as this
1998 // segement is 0-size and confuses the logic below
2000 cur.boundary(false);
2002 // go through row and draw from RTL boundary to RTL boundary
2004 bool drawNow = false;
2006 // simplified cursorForward code below which does not
2007 // descend into insets and which does not go into the
2008 // next line. Compare the logic with the original cursorForward
2010 // if left of boundary -> just jump to right side
2011 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2012 if (cur.boundary()) {
2013 cur.boundary(false);
2014 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2015 // in front of RTL boundary -> Stay on this side of the boundary because:
2016 // ab|cDDEEFFghi -> abc|DDEEFFghi
2025 if (cur.pos() == row.endpos())
2030 // the previous segment was just drawn, now the next starts
2031 x1 = cursorX(cur.top(), cur.boundary());
2034 if (!(cur < end) || drawNow) {
2035 x2 = cursorX(cur.top(), cur.boundary());
2036 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2039 // reset x1, so it is set again next round (which will be on the
2040 // right side of a boundary or at the selection end)
2046 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2048 // ParagraphMetrics const & pm = par_metrics_[pit];
2049 // Row const & r = pm.rows()[row];
2055 int defaultRowHeight()
2057 return int(theFontMetrics(sane_font).maxHeight() * 1.2);