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"
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"
45 #include "mathed/MacroTable.h"
46 #include "mathed/MathMacroTemplate.h"
48 #include "frontends/FontMetrics.h"
49 #include "frontends/Painter.h"
51 #include <boost/current_function.hpp>
61 using frontend::FontMetrics;
65 int numberOfSeparators(Paragraph const & par, Row const & row)
67 pos_type const first = max(row.pos(), par.beginOfBody());
68 pos_type const last = row.endpos() - 1;
70 for (pos_type p = first; p < last; ++p) {
71 if (par.isSeparator(p))
78 int numberOfLabelHfills(Paragraph const & par, Row const & row)
80 pos_type last = row.endpos() - 1;
81 pos_type first = row.pos();
83 // hfill *DO* count at the beginning of paragraphs!
85 while (first < last && par.isHfill(first))
89 last = min(last, par.beginOfBody());
91 for (pos_type p = first; p < last; ++p) {
99 int numberOfHfills(Paragraph const & par, Row const & row)
101 pos_type const last = row.endpos();
102 pos_type first = row.pos();
104 // hfill *DO* count at the beginning of paragraphs!
106 while (first < last && par.isHfill(first))
110 first = max(first, par.beginOfBody());
113 for (pos_type p = first; p < last; ++p) {
122 TextMetrics::TextMetrics(BufferView * bv, Text * text)
123 : bv_(bv), text_(text)
126 max_width_ = bv_->workWidth();
127 dim_.wid = max_width_;
131 //text_->updateLabels(bv->buffer());
135 bool TextMetrics::has(pit_type pit) const
137 return par_metrics_.find(pit) != par_metrics_.end();
141 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
143 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
148 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
150 ParMetricsCache::const_iterator it = par_metrics_.begin();
151 return make_pair(it->first, &it->second);
155 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
157 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
158 return make_pair(it->first, &it->second);
162 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
164 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
165 if (pmc_it == par_metrics_.end()) {
166 pmc_it = par_metrics_.insert(
167 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
169 if (pmc_it->second.rows().empty() && redo)
171 return pmc_it->second;
175 int TextMetrics::parPosition(pit_type pit) const
177 if (pit < par_metrics_.begin()->first)
179 if (pit > par_metrics_.rbegin()->first)
182 return par_metrics_[pit].position();
186 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
188 BOOST_ASSERT(mi.base.textwidth);
189 max_width_ = mi.base.textwidth;
190 // backup old dimension.
191 Dimension const old_dim = dim_;
194 dim_.wid = min_width;
195 pit_type const npar = text_->paragraphs().size();
197 // If there is more than one row, expand the text to
198 // the full allowable width.
199 dim_.wid = max_width_;
201 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
202 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
204 bool changed = false;
206 for (pit_type pit = 0; pit != npar; ++pit) {
207 changed |= redoParagraph(pit);
208 ParagraphMetrics const & pm = par_metrics_[pit];
210 if (dim_.wid < pm.width())
211 dim_.wid = pm.width();
214 dim_.asc = par_metrics_[0].ascent();
215 dim_.des = h - dim_.asc;
216 //lyxerr << "dim_.wid " << dim_.wid << endl;
217 //lyxerr << "dim_.asc " << dim_.asc << endl;
218 //lyxerr << "dim_.des " << dim_.des << endl;
220 changed |= dim_ != old_dim;
226 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
228 return main_text_? pm.rightMargin(bv_->buffer()) : 0;
232 int TextMetrics::rightMargin(pit_type const pit) const
234 return main_text_? par_metrics_[pit].rightMargin(bv_->buffer()) : 0;
238 void TextMetrics::applyOuterFont(Font & font) const
241 lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
242 lf.fontInfo().realize(font.fontInfo());
243 lf.setLanguage(font.language());
248 Font TextMetrics::getDisplayFont(pit_type pit, pos_type pos) const
250 BOOST_ASSERT(pos >= 0);
252 ParagraphList const & pars = text_->paragraphs();
253 Paragraph const & par = pars[pit];
254 LayoutPtr const & layout = par.layout();
255 Buffer const & buffer = bv_->buffer();
257 BufferParams const & params = buffer.params();
258 pos_type const body_pos = par.beginOfBody();
260 // We specialize the 95% common case:
261 if (!par.getDepth()) {
262 Font f = par.getFontSettings(params, pos);
263 if (!text_->isMainText(buffer))
265 bool lab = layout->labeltype == LABEL_MANUAL && pos < body_pos;
267 FontInfo const & lf = lab ? layout->labelfont : layout->font;
268 FontInfo rlf = lab ? layout->reslabelfont : layout->resfont;
270 // In case the default family has been customized
271 if (lf.family() == INHERIT_FAMILY)
272 rlf.setFamily(params.getFont().fontInfo().family());
273 f.fontInfo().realize(rlf);
277 // The uncommon case need not be optimized as much
278 FontInfo const & layoutfont = pos < body_pos ?
279 layout->labelfont : layout->font;
281 Font font = par.getFontSettings(params, pos);
282 font.fontInfo().realize(layoutfont);
284 if (!text_->isMainText(buffer))
285 applyOuterFont(font);
287 // Realize against environment font information
288 // NOTE: the cast to pit_type should be removed when pit_type
289 // changes to a unsigned integer.
290 if (pit < pit_type(pars.size()))
291 font.fontInfo().realize(outerFont(pit, pars).fontInfo());
293 // Realize with the fonts of lesser depth.
294 font.fontInfo().realize(params.getFont().fontInfo());
300 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
302 if (!lyxrc.rtl_support || !sl.text())
306 if (boundary && sl.pos() > 0)
309 return getDisplayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
313 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
315 if (!lyxrc.rtl_support)
318 // no RTL boundary at line start
322 Paragraph const & par = text_->getPar(pit);
324 bool left = getDisplayFont(pit, pos - 1).isVisibleRightToLeft();
326 if (pos == par.size())
327 right = par.isRTL(bv_->buffer().params());
329 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
330 return left != right;
334 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
335 Font const & font) const
337 if (!lyxrc.rtl_support)
340 Paragraph const & par = text_->getPar(pit);
341 bool left = font.isVisibleRightToLeft();
343 if (pos == par.size())
344 right = par.isRTL(bv_->buffer().params());
346 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
347 return left != right;
351 bool TextMetrics::redoParagraph(pit_type const pit)
353 Paragraph & par = text_->getPar(pit);
354 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
355 // redoParagraph() recursively inside parMetrics.
356 Dimension old_dim = parMetrics(pit, false).dim();
357 ParagraphMetrics & pm = par_metrics_[pit];
360 Buffer & buffer = bv_->buffer();
361 BufferParams const & bparams = buffer.params();
362 main_text_ = (text_ == &buffer.text());
363 bool changed = false;
365 // FIXME This check ought to be done somewhere else. It is the reason
366 // why text_ is not const. But then, where else to do it?
367 // Well, how can you end up with either (a) a biblio environment that
368 // has no InsetBibitem or (b) a biblio environment with more than one
369 // InsetBibitem? I think the answer is: when paragraphs are merged;
370 // when layout is set; when material is pasted.
371 int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
373 const_cast<Cursor &>(bv_->cursor()).posForward();
374 else if (moveCursor < 0) {
375 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
376 if (cursor.pos() >= -moveCursor)
377 cursor.posBackward();
380 // Optimisation: this is used in the next two loops
381 // so better to calculate that once here.
382 int const right_margin = rightMargin(pm);
385 // FIXME: We should always use getFont(), see documentation of
386 // noFontChange() in Inset.h.
387 Font const bufferfont = buffer.params().getFont();
388 MacroContext mc(buffer, par);
389 InsetList::const_iterator ii = par.insetList().begin();
390 InsetList::const_iterator iend = par.insetList().end();
391 for (; ii != iend; ++ii) {
392 // the macro must come here, _before_ the metric call, because
393 // the macro should see itself to detect recursions. To find out
394 // whether the macro definition is a redefinition it will look
395 // at the MacroData::redefinition_. So it doesn't get confused
396 // by the already existing macro definition of itself in the
398 if (ii->inset->lyxCode() == MATHMACRO_CODE) {
400 MathMacroTemplate const & macroTemplate
401 = static_cast<MathMacroTemplate const &>(*ii->inset);
404 if (macroTemplate.validMacro()) {
405 MacroData macro = macroTemplate.asMacroData();
408 macro.setRedefinition(mc.has(macroTemplate.name()));
410 // register macro (possibly overwrite the previous one of this paragraph)
411 mc.insert(macroTemplate.name(), macro);
415 // do the metric calculation
417 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
419 Font const & font = ii->inset->noFontChange() ?
420 bufferfont : getDisplayFont(pit, ii->pos);
421 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
422 ii->inset->metrics(mi, dim);
423 Dimension const old_dim = pm.insetDimension(ii->inset);
424 pm.setInsetDimension(ii->inset, dim);
425 changed |= (old_dim != dim);
428 Cursor const & cur = bv_->cursor();
429 DocIterator sel_beg = cur.selectionBegin();
430 DocIterator sel_end = cur.selectionEnd();
431 bool selection = cur.selection()
433 && cur.text() == text_
434 // if the anchor is outside, this is not our selection
435 && cur.anchor().text() == text_
436 && pit >= sel_beg.pit() && pit <= sel_end.pit();
438 // We care only about visible selection.
440 if (pit != sel_beg.pit()) {
444 if (pit != sel_end.pit()) {
446 sel_end.pos() = sel_end.lastpos();
450 par.setBeginOfBody();
452 size_t row_index = 0;
453 // maximum pixel width of a row
454 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
457 pos_type end = rowBreakPoint(width, pit, first);
458 if (row_index || end < par.size())
459 // If there is more than one row, expand the text to
460 // the full allowable width. This setting here is needed
461 // for the computeRowMetrics() below.
462 dim_.wid = max_width_;
464 dim = rowHeight(pit, first, end);
465 dim.wid = rowWidth(right_margin, pit, first, end);
466 if (row_index == pm.rows().size())
467 pm.rows().push_back(Row());
468 Row & row = pm.rows()[row_index];
469 row.setChanged(false);
473 row.setSelection(sel_beg.pos(), sel_end.pos());
475 row.setSelection(-1, -1);
476 row.setDimension(dim);
477 int const max_row_width = max(dim_.wid, dim.wid);
478 computeRowMetrics(pit, row, max_row_width);
479 pm.computeRowSignature(row, bparams);
483 pm.dim().wid = std::max(pm.dim().wid, dim.wid);
484 pm.dim().des += dim.height();
485 } while (first < par.size());
487 if (row_index < pm.rows().size())
488 pm.rows().resize(row_index);
490 // Make sure that if a par ends in newline, there is one more row
492 if (first > 0 && par.isNewline(first - 1)) {
493 Dimension dim = rowHeight(pit, first, first);
494 dim.wid = rowWidth(right_margin, pit, first, first);
495 if (row_index == pm.rows().size())
496 pm.rows().push_back(Row());
497 Row & row = pm.rows()[row_index];
498 row.setChanged(false);
501 row.setDimension(dim);
502 int const max_row_width = max(dim_.wid, dim.wid);
503 computeRowMetrics(pit, row, max_row_width);
504 pm.computeRowSignature(row, bparams);
505 pm.dim().des += dim.height();
508 pm.dim().asc += pm.rows()[0].ascent();
509 pm.dim().des -= pm.rows()[0].ascent();
511 changed |= old_dim.height() != pm.dim().height();
517 void TextMetrics::computeRowMetrics(pit_type const pit,
518 Row & row, int width) const
525 Buffer & buffer = bv_->buffer();
526 Paragraph const & par = text_->getPar(pit);
528 double w = width - row.width();
529 // FIXME: put back this assertion when the crash on new doc is solved.
530 //BOOST_ASSERT(w >= 0);
532 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
533 //lyxerr << "row.width() " << row.width() << endl;
534 //lyxerr << "w " << w << endl;
536 bool const is_rtl = text_->isRTL(buffer, par);
538 row.x = rightMargin(pit);
540 row.x = leftMargin(max_width_, pit, row.pos());
542 // is there a manual margin with a manual label
543 LayoutPtr const & layout = par.layout();
545 if (layout->margintype == MARGIN_MANUAL
546 && layout->labeltype == LABEL_MANUAL) {
547 /// We might have real hfills in the label part
548 int nlh = numberOfLabelHfills(par, row);
550 // A manual label par (e.g. List) has an auto-hfill
551 // between the label text and the body of the
553 // But we don't want to do this auto hfill if the par
558 if (nlh && !par.getLabelWidthString().empty())
559 row.label_hfill = labelFill(pit, row) / double(nlh);
562 // are there any hfills in the row?
563 int const nh = numberOfHfills(par, row);
568 // we don't have to look at the alignment if it is ALIGN_LEFT and
569 // if the row is already larger then the permitted width as then
570 // we force the LEFT_ALIGN'edness!
571 } else if (int(row.width()) < max_width_) {
572 // is it block, flushleft or flushright?
573 // set x how you need it
575 if (par.params().align() == LYX_ALIGN_LAYOUT)
576 align = layout->align;
578 align = par.params().align();
580 // Display-style insets should always be on a centred row
581 // The test on par.size() is to catch zero-size pars, which
582 // would trigger the assert in Paragraph::getInset().
583 //inset = par.size() ? par.getInset(row.pos()) : 0;
584 if (row.pos() < par.size() && par.isInset(row.pos())) {
585 switch(par.getInset(row.pos())->display()) {
586 case Inset::AlignLeft:
587 align = LYX_ALIGN_BLOCK;
589 case Inset::AlignCenter:
590 align = LYX_ALIGN_CENTER;
593 case Inset::AlignRight:
594 // unchanged (use align)
600 case LYX_ALIGN_BLOCK: {
601 int const ns = numberOfSeparators(par, row);
602 bool disp_inset = false;
603 if (row.endpos() < par.size()) {
604 Inset const * in = par.getInset(row.endpos());
606 disp_inset = in->display();
608 // If we have separators, this is not the last row of a
609 // par, does not end in newline, and is not row above a
610 // display inset... then stretch it
612 && row.endpos() < par.size()
613 && !par.isNewline(row.endpos() - 1)
616 row.separator = w / ns;
617 //lyxerr << "row.separator " << row.separator << endl;
618 //lyxerr << "ns " << ns << endl;
624 case LYX_ALIGN_RIGHT:
627 case LYX_ALIGN_CENTER:
634 pos_type body_pos = par.beginOfBody();
635 pos_type end = row.endpos();
638 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
640 row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
641 width(layout->labelsep);
643 row.x += row.label_hfill;
649 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
651 Buffer & buffer = bv_->buffer();
652 Paragraph const & par = text_->getPar(pit);
654 pos_type last = par.beginOfBody();
655 BOOST_ASSERT(last > 0);
657 // -1 because a label ends with a space that is in the label
660 // a separator at this end does not count
661 if (par.isLineSeparator(last))
665 for (pos_type i = row.pos(); i <= last; ++i)
666 w += singleWidth(pit, i);
668 docstring const & label = par.params().labelWidthString();
672 FontMetrics const & fm
673 = theFontMetrics(text_->getLabelFont(buffer, par));
675 return max(0, fm.width(label) - w);
679 // this needs special handling - only newlines count as a break point
680 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
682 pos_type const end = par.size();
685 if (par.isNewline(i))
692 int TextMetrics::labelEnd(pit_type const pit) const
694 // labelEnd is only needed if the layout fills a flushleft label.
695 if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
697 // return the beginning of the body
698 return leftMargin(max_width_, pit);
702 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
705 Buffer & buffer = bv_->buffer();
706 ParagraphMetrics const & pm = par_metrics_[pit];
707 Paragraph const & par = text_->getPar(pit);
708 pos_type const end = par.size();
709 if (pos == end || width < 0)
712 LayoutPtr const & layout = par.layout();
714 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
715 return addressBreakPoint(pos, par);
717 pos_type const body_pos = par.beginOfBody();
720 // Now we iterate through until we reach the right margin
721 // or the end of the par, then choose the possible break
724 int label_end = labelEnd(pit);
725 int const left = leftMargin(max_width_, pit, pos);
728 // pixel width since last breakpoint
731 FontIterator fi = FontIterator(*this, par, pit, pos);
732 pos_type point = end;
734 for ( ; i < end; ++i, ++fi) {
735 int thiswidth = pm.singleWidth(i, *fi);
737 // add the auto-hfill from label end to the body
738 if (body_pos && i == body_pos) {
739 FontMetrics const & fm = theFontMetrics(
740 text_->getLabelFont(buffer, par));
741 int add = fm.width(layout->labelsep);
742 if (par.isLineSeparator(i - 1))
743 add -= singleWidth(pit, i - 1);
745 add = std::max(add, label_end - x);
750 chunkwidth += thiswidth;
752 // break before a character that will fall off
753 // the right of the row
755 // if no break before, break here
756 if (point == end || chunkwidth >= width - left) {
762 // exit on last registered breakpoint:
766 if (par.isNewline(i)) {
772 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
777 if (par.isInset(i) && par.getInset(i)->display()) {
783 if (!par.isInset(i) || par.getInset(i)->isChar()) {
784 // some insets are line separators too
785 if (par.isLineSeparator(i)) {
786 // register breakpoint:
793 // maybe found one, but the par is short enough.
794 if (i == end && x < width)
797 // manual labels cannot be broken in LaTeX. But we
798 // want to make our on-screen rendering of footnotes
800 if (body_pos && point < body_pos)
807 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
808 pos_type const first, pos_type const end) const
810 Buffer & buffer = bv_->buffer();
811 // get the pure distance
812 ParagraphMetrics const & pm = par_metrics_[pit];
813 Paragraph const & par = text_->getPar(pit);
814 int w = leftMargin(max_width_, pit, first);
815 int label_end = labelEnd(pit);
817 pos_type const body_pos = par.beginOfBody();
821 FontIterator fi = FontIterator(*this, par, pit, i);
822 for ( ; i < end; ++i, ++fi) {
823 if (body_pos > 0 && i == body_pos) {
824 FontMetrics const & fm = theFontMetrics(
825 text_->getLabelFont(buffer, par));
826 w += fm.width(par.layout()->labelsep);
827 if (par.isLineSeparator(i - 1))
828 w -= singleWidth(pit, i - 1);
829 w = max(w, label_end);
831 w += pm.singleWidth(i, *fi);
835 if (body_pos > 0 && body_pos >= end) {
836 FontMetrics const & fm = theFontMetrics(
837 text_->getLabelFont(buffer, par));
838 w += fm.width(par.layout()->labelsep);
839 if (end > 0 && par.isLineSeparator(end - 1))
840 w -= singleWidth(pit, end - 1);
841 w = max(w, label_end);
844 return w + right_margin;
848 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
849 pos_type const end) const
851 Paragraph const & par = text_->getPar(pit);
852 // get the maximum ascent and the maximum descent
853 double layoutasc = 0;
854 double layoutdesc = 0;
855 double const dh = defaultRowHeight();
857 // ok, let us initialize the maxasc and maxdesc value.
858 // Only the fontsize count. The other properties
859 // are taken from the layoutfont. Nicer on the screen :)
860 LayoutPtr const & layout = par.layout();
862 // as max get the first character of this row then it can
863 // increase but not decrease the height. Just some point to
864 // start with so we don't have to do the assignment below too
866 Buffer const & buffer = bv_->buffer();
867 Font font = getDisplayFont(pit, first);
868 FontSize const tmpsize = font.fontInfo().size();
869 font.fontInfo() = text_->getLayoutFont(buffer, pit);
870 FontSize const size = font.fontInfo().size();
871 font.fontInfo().setSize(tmpsize);
873 FontInfo labelfont = text_->getLabelFont(buffer, par);
875 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
876 FontMetrics const & fontmetrics = theFontMetrics(font);
878 // these are minimum values
879 double const spacing_val = layout->spacing.getValue()
880 * text_->spacing(buffer, par);
881 //lyxerr << "spacing_val = " << spacing_val << endl;
882 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
883 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
885 // insets may be taller
886 ParagraphMetrics const & pm = par_metrics_[pit];
887 InsetList::const_iterator ii = par.insetList().begin();
888 InsetList::const_iterator iend = par.insetList().end();
889 for ( ; ii != iend; ++ii) {
890 Dimension const & dim = pm.insetDimension(ii->inset);
891 if (ii->pos >= first && ii->pos < end) {
892 maxasc = max(maxasc, dim.ascent());
893 maxdesc = max(maxdesc, dim.descent());
897 // Check if any custom fonts are larger (Asger)
898 // This is not completely correct, but we can live with the small,
899 // cosmetic error for now.
903 par.highestFontInRange(first, end, size);
904 if (maxsize > font.fontInfo().size()) {
905 // use standard paragraph font with the maximal size
906 FontInfo maxfont = font.fontInfo();
907 maxfont.setSize(maxsize);
908 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
909 maxasc = max(maxasc, maxfontmetrics.maxAscent());
910 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
913 // This is nicer with box insets:
917 ParagraphList const & pars = text_->paragraphs();
921 BufferParams const & bufparams = buffer.params();
922 // some parskips VERY EASY IMPLEMENTATION
923 if (bufparams.paragraph_separation
924 == BufferParams::PARSEP_SKIP
925 && par.ownerCode() != ERT_CODE
926 && par.ownerCode() != LISTINGS_CODE
928 && ((layout->isParagraph() && par.getDepth() == 0)
929 || (pars[pit - 1].layout()->isParagraph()
930 && pars[pit - 1].getDepth() == 0)))
932 maxasc += bufparams.getDefSkip().inPixels(*bv_);
935 if (par.params().startOfAppendix())
936 maxasc += int(3 * dh);
938 // This is special code for the chapter, since the label of this
939 // layout is printed in an extra row
940 if (layout->counter == "chapter"
941 && !par.params().labelString().empty()) {
942 labeladdon = int(labelfont_metrics.maxHeight()
943 * layout->spacing.getValue()
944 * text_->spacing(buffer, par));
947 // special code for the top label
948 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
949 || layout->labeltype == LABEL_BIBLIO
950 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
951 && isFirstInSequence(pit, pars)
952 && !par.getLabelstring().empty())
955 labelfont_metrics.maxHeight()
956 * layout->spacing.getValue()
957 * text_->spacing(buffer, par)
958 + (layout->topsep + layout->labelbottomsep) * dh);
961 // Add the layout spaces, for example before and after
962 // a section, or between the items of a itemize or enumerate
965 pit_type prev = depthHook(pit, pars, par.getDepth());
966 Paragraph const & prevpar = pars[prev];
968 && prevpar.layout() == layout
969 && prevpar.getDepth() == par.getDepth()
970 && prevpar.getLabelWidthString()
971 == par.getLabelWidthString()) {
972 layoutasc = layout->itemsep * dh;
973 } else if (pit != 0 || first != 0) {
974 if (layout->topsep > 0)
975 layoutasc = layout->topsep * dh;
978 prev = outerHook(pit, pars);
979 if (prev != pit_type(pars.size())) {
980 maxasc += int(pars[prev].layout()->parsep * dh);
981 } else if (pit != 0) {
982 Paragraph const & prevpar = pars[pit - 1];
983 if (prevpar.getDepth() != 0 ||
984 prevpar.layout() == layout) {
985 maxasc += int(layout->parsep * dh);
990 // is it a bottom line?
991 if (end >= par.size()) {
992 // add the layout spaces, for example before and after
993 // a section, or between the items of a itemize or enumerate
995 pit_type nextpit = pit + 1;
996 if (nextpit != pit_type(pars.size())) {
1001 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1002 usual = pars[cpit].layout()->bottomsep * dh;
1003 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1004 if (pars[cpit].layout() != pars[nextpit].layout()
1005 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1007 unusual = pars[cpit].layout()->bottomsep * dh;
1009 layoutdesc = max(unusual, usual);
1010 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1011 if (pars[cpit].layout() != pars[nextpit].layout()
1012 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1013 layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
1018 // incalculate the layout spaces
1019 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1020 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1022 // FIXME: the correct way is to do the following is to move the
1023 // following code in another method specially tailored for the
1024 // main Text. The following test is thus bogus.
1025 // Top and bottom margin of the document (only at top-level)
1027 if (pit == 0 && first == 0)
1029 if (pit + 1 == pit_type(pars.size()) &&
1030 end == par.size() &&
1031 !(end > 0 && par.isNewline(end - 1)))
1035 return Dimension(0, maxasc + labeladdon, maxdesc);
1039 // x is an absolute screen coord
1040 // returns the column near the specified x-coordinate of the row
1041 // x is set to the real beginning of this column
1042 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1043 Row const & row, int & x, bool & boundary) const
1045 Buffer const & buffer = bv_->buffer();
1047 /// For the main Text, it is possible that this pit is not
1048 /// yet in the CoordCache when moving cursor up.
1049 /// x Paragraph coordinate is always 0 for main text anyway.
1050 int const xo = origin_.x_;
1052 Paragraph const & par = text_->getPar(pit);
1053 ParagraphMetrics const & pm = par_metrics_[pit];
1055 bidi.computeTables(par, buffer, row);
1057 pos_type vc = row.pos();
1058 pos_type end = row.endpos();
1060 LayoutPtr const & layout = par.layout();
1062 bool left_side = false;
1064 pos_type body_pos = par.beginOfBody();
1066 double tmpx = row.x;
1067 double last_tmpx = tmpx;
1070 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1073 // check for empty row
1079 while (vc < end && tmpx <= x) {
1080 c = bidi.vis2log(vc);
1082 if (body_pos > 0 && c == body_pos - 1) {
1083 FontMetrics const & fm = theFontMetrics(
1084 text_->getLabelFont(buffer, par));
1085 tmpx += row.label_hfill + fm.width(layout->labelsep);
1086 if (par.isLineSeparator(body_pos - 1))
1087 tmpx -= singleWidth(pit, body_pos - 1);
1090 if (pm.hfillExpansion(row, c)) {
1091 tmpx += singleWidth(pit, c);
1095 tmpx += row.label_hfill;
1096 } else if (par.isSeparator(c)) {
1097 tmpx += singleWidth(pit, c);
1099 tmpx += row.separator;
1101 tmpx += singleWidth(pit, c);
1106 if ((tmpx + last_tmpx) / 2 > x) {
1111 BOOST_ASSERT(vc <= end); // This shouldn't happen.
1114 // This (rtl_support test) is not needed, but gives
1115 // some speedup if rtl_support == false
1116 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1118 // If lastrow is false, we don't need to compute
1119 // the value of rtl.
1120 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1122 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1123 (!rtl && !left_side && vc == end && x > tmpx + 5)))
1125 else if (vc == row.pos()) {
1126 c = bidi.vis2log(vc);
1127 if (bidi.level(c) % 2 == 1)
1130 c = bidi.vis2log(vc - 1);
1131 bool const rtl = (bidi.level(c) % 2 == 1);
1132 if (left_side == rtl) {
1134 boundary = isRTLBoundary(pit, c);
1138 // I believe this code is not needed anymore (Jug 20050717)
1140 // The following code is necessary because the cursor position past
1141 // the last char in a row is logically equivalent to that before
1142 // the first char in the next row. That's why insets causing row
1143 // divisions -- Newline and display-style insets -- must be treated
1144 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1145 // Newline inset, air gap below:
1146 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1147 if (bidi.level(end -1) % 2 == 0)
1148 tmpx -= singleWidth(pit, end - 1);
1150 tmpx += singleWidth(pit, end - 1);
1154 // Air gap above display inset:
1155 if (row.pos() < end && c >= end && end < par.size()
1156 && par.isInset(end) && par.getInset(end)->display()) {
1159 // Air gap below display inset:
1160 if (row.pos() < end && c >= end && par.isInset(end - 1)
1161 && par.getInset(end - 1)->display()) {
1167 pos_type const col = c - row.pos();
1169 if (!c || end == par.size())
1172 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1177 return min(col, end - 1 - row.pos());
1181 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1183 // We play safe and use parMetrics(pit) to make sure the
1184 // ParagraphMetrics will be redone and OK to use if needed.
1185 // Otherwise we would use an empty ParagraphMetrics in
1186 // upDownInText() while in selection mode.
1187 ParagraphMetrics const & pm = parMetrics(pit);
1189 BOOST_ASSERT(row < int(pm.rows().size()));
1191 Row const & r = pm.rows()[row];
1192 return r.pos() + getColumnNearX(pit, r, x, bound);
1196 void TextMetrics::newParMetricsDown()
1198 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1199 pit_type const pit = last.first + 1;
1200 if (pit == int(text_->paragraphs().size()))
1203 // do it and update its position.
1205 par_metrics_[pit].setPosition(last.second.position()
1206 + last.second.descent());
1210 void TextMetrics::newParMetricsUp()
1212 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1213 if (first.first == 0)
1216 pit_type const pit = first.first - 1;
1217 // do it and update its position.
1219 par_metrics_[pit].setPosition(first.second.position()
1220 - first.second.ascent());
1223 // y is screen coordinate
1224 pit_type TextMetrics::getPitNearY(int y)
1226 BOOST_ASSERT(!text_->paragraphs().empty());
1227 LYXERR(Debug::DEBUG)
1228 << BOOST_CURRENT_FUNCTION
1229 << ": y: " << y << " cache size: " << par_metrics_.size()
1232 // look for highest numbered paragraph with y coordinate less than given y
1235 ParMetricsCache::const_iterator it = par_metrics_.begin();
1236 ParMetricsCache::const_iterator et = par_metrics_.end();
1237 ParMetricsCache::const_iterator last = et; last--;
1239 ParagraphMetrics const & pm = it->second;
1241 // If we are off-screen (before the visible part)
1243 // and even before the first paragraph in the cache.
1244 && y < it->second.position() - int(pm.ascent())) {
1245 // and we are not at the first paragraph in the inset.
1248 // then this is the paragraph we are looking for.
1249 pit = it->first - 1;
1250 // rebreak it and update the CoordCache.
1252 par_metrics_[pit].setPosition(it->second.position() - pm.descent());
1256 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1258 // If we are off-screen (after the visible part)
1259 if (y > bv_->workHeight()
1260 // and even after the first paragraph in the cache.
1261 && y >= last->second.position() + int(pm_last.descent())) {
1262 pit = last->first + 1;
1263 // and we are not at the last paragraph in the inset.
1264 if (pit == int(text_->paragraphs().size()))
1266 // then this is the paragraph we are looking for.
1267 // rebreak it and update the CoordCache.
1269 par_metrics_[pit].setPosition(last->second.position() + pm_last.ascent());
1273 for (; it != et; ++it) {
1274 LYXERR(Debug::DEBUG)
1275 << BOOST_CURRENT_FUNCTION
1276 << " examining: pit: " << it->first
1277 << " y: " << it->second.position()
1280 ParagraphMetrics const & pm = par_metrics_[it->first];
1282 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1284 yy = it->second.position();
1288 LYXERR(Debug::DEBUG)
1289 << BOOST_CURRENT_FUNCTION
1290 << ": found best y: " << yy << " for pit: " << pit
1297 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1299 ParagraphMetrics const & pm = par_metrics_[pit];
1301 int yy = pm.position() - pm.ascent();
1302 BOOST_ASSERT(!pm.rows().empty());
1303 RowList::const_iterator rit = pm.rows().begin();
1304 RowList::const_iterator rlast = pm.rows().end();
1306 for (; rit != rlast; yy += rit->height(), ++rit)
1307 if (yy + rit->height() > y)
1313 // x,y are absolute screen coordinates
1314 // sets cursor recursively descending into nested editable insets
1315 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1317 if (lyxerr.debugging(Debug::WORKAREA)) {
1318 lyxerr << "TextMetrics::editXY(cur, " << x << ", " << y << ")" << std::endl;
1319 cur.bv().coordCache().dump();
1321 pit_type pit = getPitNearY(y);
1322 BOOST_ASSERT(pit != -1);
1324 Row const & row = getRowNearY(y, pit);
1327 int xx = x; // is modified by getColumnNearX
1328 pos_type const pos = row.pos()
1329 + getColumnNearX(pit, row, xx, bound);
1332 cur.boundary(bound);
1335 // try to descend into nested insets
1336 Inset * inset = checkInsetHit(x, y);
1337 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1339 // Either we deconst editXY or better we move current_font
1340 // and real_current_font to Cursor
1341 // FIXME: what is needed now that current_font and real_current_font
1343 cur.setCurrentFont();
1347 ParagraphList const & pars = text_->paragraphs();
1348 Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1349 //Inset * insetBehind = pars[pit].getInset(pos);
1351 // This should be just before or just behind the
1352 // cursor position set above.
1353 BOOST_ASSERT((pos != 0 && inset == insetBefore)
1354 || inset == pars[pit].getInset(pos));
1356 // Make sure the cursor points to the position before
1358 if (inset == insetBefore) {
1360 cur.boundary(false);
1363 // Try to descend recursively inside the inset.
1364 inset = inset->editXY(cur, x, y);
1366 if (cur.top().text() == text_)
1367 cur.setCurrentFont();
1372 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1374 BOOST_ASSERT(text_ == cur.text());
1375 pit_type pit = getPitNearY(y);
1377 ParagraphMetrics const & pm = par_metrics_[pit];
1379 int yy = pm.position() - pm.ascent();
1380 LYXERR(Debug::DEBUG)
1381 << BOOST_CURRENT_FUNCTION
1385 << " yy: " << yy << endl;
1388 BOOST_ASSERT(pm.rows().size());
1389 for (; r < int(pm.rows().size()) - 1; ++r) {
1390 Row const & row = pm.rows()[r];
1391 if (int(yy + row.height()) > y)
1396 Row const & row = pm.rows()[r];
1398 LYXERR(Debug::DEBUG)
1399 << BOOST_CURRENT_FUNCTION
1401 << " from pos: " << row.pos()
1406 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1408 LYXERR(Debug::DEBUG)
1409 << BOOST_CURRENT_FUNCTION
1410 << ": setting cursor pit: " << pit
1414 text_->setCursor(cur, pit, pos, true, bound);
1415 // remember new position.
1420 //takes screen x,y coordinates
1421 Inset * TextMetrics::checkInsetHit(int x, int y)
1423 pit_type pit = getPitNearY(y);
1424 BOOST_ASSERT(pit != -1);
1426 Paragraph const & par = text_->paragraphs()[pit];
1427 ParagraphMetrics const & pm = par_metrics_[pit];
1429 LYXERR(Debug::DEBUG)
1430 << BOOST_CURRENT_FUNCTION
1435 InsetList::const_iterator iit = par.insetList().begin();
1436 InsetList::const_iterator iend = par.insetList().end();
1437 for (; iit != iend; ++iit) {
1438 Inset * inset = iit->inset;
1440 LYXERR(Debug::DEBUG)
1441 << BOOST_CURRENT_FUNCTION
1442 << ": examining inset " << inset << endl;
1444 if (!bv_->coordCache().getInsets().has(inset)) {
1445 LYXERR(Debug::DEBUG)
1446 << BOOST_CURRENT_FUNCTION
1447 << ": inset has no cached position" << endl;
1451 Dimension const & dim = pm.insetDimension(inset);
1452 Point p = bv_->coordCache().getInsets().xy(inset);
1454 LYXERR(Debug::DEBUG)
1455 << BOOST_CURRENT_FUNCTION
1456 << ": xo: " << p.x_ << "..." << p.x_ + dim.wid
1457 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des
1461 && x <= p.x_ + dim.wid
1462 && y >= p.y_ - dim.asc
1463 && y <= p.y_ + dim.des) {
1464 LYXERR(Debug::DEBUG)
1465 << BOOST_CURRENT_FUNCTION
1466 << ": Hit inset: " << inset << endl;
1471 LYXERR(Debug::DEBUG)
1472 << BOOST_CURRENT_FUNCTION
1473 << ": No inset hit. " << endl;
1478 int TextMetrics::cursorX(CursorSlice const & sl,
1479 bool boundary) const
1481 BOOST_ASSERT(sl.text() == text_);
1482 pit_type const pit = sl.pit();
1483 Paragraph const & par = text_->paragraphs()[pit];
1484 ParagraphMetrics const & pm = par_metrics_[pit];
1485 if (pm.rows().empty())
1488 pos_type ppos = sl.pos();
1489 // Correct position in front of big insets
1490 bool const boundary_correction = ppos != 0 && boundary;
1491 if (boundary_correction)
1494 Row const & row = pm.getRow(sl.pos(), boundary);
1496 pos_type cursor_vpos = 0;
1498 Buffer const & buffer = bv_->buffer();
1501 bidi.computeTables(par, buffer, row);
1503 pos_type const row_pos = row.pos();
1504 pos_type const end = row.endpos();
1505 // Spaces at logical line breaks in bidi text must be skipped during
1506 // cursor positioning. However, they may appear visually in the middle
1507 // of a row; they must be skipped, wherever they are...
1508 // * logically "abc_[HEBREW_\nHEBREW]"
1509 // * visually "abc_[_WERBEH\nWERBEH]"
1510 pos_type skipped_sep_vpos = -1;
1513 cursor_vpos = row_pos;
1514 else if (ppos >= end)
1515 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1516 else if (ppos > row_pos && ppos >= end)
1517 // Place cursor after char at (logical) position pos - 1
1518 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1519 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1521 // Place cursor before char at (logical) position ppos
1522 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1523 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1525 pos_type body_pos = par.beginOfBody();
1527 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1530 // Use font span to speed things up, see below
1534 // If the last logical character is a separator, skip it, unless
1535 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1536 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1537 skipped_sep_vpos = bidi.log2vis(end - 1);
1539 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1540 // Skip the separator which is at the logical end of the row
1541 if (vpos == skipped_sep_vpos)
1543 pos_type pos = bidi.vis2log(vpos);
1544 if (body_pos > 0 && pos == body_pos - 1) {
1545 FontMetrics const & labelfm = theFontMetrics(
1546 text_->getLabelFont(buffer, par));
1547 x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1548 if (par.isLineSeparator(body_pos - 1))
1549 x -= singleWidth(pit, body_pos - 1);
1552 // Use font span to speed things up, see above
1553 if (pos < font_span.first || pos > font_span.last) {
1554 font_span = par.fontSpan(pos);
1555 font = getDisplayFont(pit, pos);
1558 x += pm.singleWidth(pos, font);
1560 if (pm.hfillExpansion(row, pos))
1561 x += (pos >= body_pos) ? row.hfill : row.label_hfill;
1562 else if (par.isSeparator(pos) && pos >= body_pos)
1566 // see correction above
1567 if (boundary_correction) {
1568 if (isRTL(sl, boundary))
1569 x -= singleWidth(pit, ppos);
1571 x += singleWidth(pit, ppos);
1578 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1580 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << std::endl;
1581 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1582 if (pm.rows().empty())
1586 h -= par_metrics_[0].rows()[0].ascent();
1587 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1588 h += par_metrics_[pit].height();
1591 if (pos && boundary)
1593 size_t const rend = pm.pos2row(pos);
1594 for (size_t rit = 0; rit != rend; ++rit)
1595 h += pm.rows()[rit].height();
1596 h += pm.rows()[rend].ascent();
1601 void TextMetrics::cursorPrevious(Cursor & cur)
1603 pos_type cpos = cur.pos();
1604 pit_type cpar = cur.pit();
1606 int x = cur.x_target();
1607 setCursorFromCoordinates(cur, x, 0);
1608 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1610 if (cpar == cur.pit() && cpos == cur.pos())
1611 // we have a row which is taller than the workarea. The
1612 // simplest solution is to move to the previous row instead.
1613 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1616 cur.updateFlags(Update::Force | Update::FitCursor);
1620 void TextMetrics::cursorNext(Cursor & cur)
1622 pos_type cpos = cur.pos();
1623 pit_type cpar = cur.pit();
1625 int x = cur.x_target();
1626 setCursorFromCoordinates(cur, x, cur.bv().workHeight() - 1);
1627 cur.dispatch(FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1629 if (cpar == cur.pit() && cpos == cur.pos())
1630 // we have a row which is taller than the workarea. The
1631 // simplest solution is to move to the next row instead.
1633 FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1636 cur.updateFlags(Update::Force | Update::FitCursor);
1640 // the cursor set functions have a special mechanism. When they
1641 // realize you left an empty paragraph, they will delete it.
1643 bool TextMetrics::cursorHome(Cursor & cur)
1645 BOOST_ASSERT(text_ == cur.text());
1646 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1647 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1648 return text_->setCursor(cur, cur.pit(), row.pos());
1652 bool TextMetrics::cursorEnd(Cursor & cur)
1654 BOOST_ASSERT(text_ == cur.text());
1655 // if not on the last row of the par, put the cursor before
1656 // the final space exept if I have a spanning inset or one string
1657 // is so long that we force a break.
1658 pos_type end = cur.textRow().endpos();
1660 // empty text, end-1 is no valid position
1662 bool boundary = false;
1663 if (end != cur.lastpos()) {
1664 if (!cur.paragraph().isLineSeparator(end-1)
1665 && !cur.paragraph().isNewline(end-1))
1670 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1674 void TextMetrics::deleteLineForward(Cursor & cur)
1676 BOOST_ASSERT(text_ == cur.text());
1677 if (cur.lastpos() == 0) {
1678 // Paragraph is empty, so we just go forward
1679 text_->cursorForward(cur);
1682 cur.selection() = true; // to avoid deletion
1685 // What is this test for ??? (JMarc)
1686 if (!cur.selection())
1687 text_->deleteWordForward(cur);
1689 cap::cutSelection(cur, true, false);
1690 checkBufferStructure(cur.buffer(), cur);
1695 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1697 ParagraphList const & pars = text_->paragraphs();
1698 return row.endpos() >= pars[pit].size()
1699 && pit + 1 == pit_type(pars.size());
1703 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1705 return row.pos() == 0 && pit == 0;
1709 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1711 BOOST_ASSERT(pit >= 0);
1712 BOOST_ASSERT(pit < int(text_->paragraphs().size()));
1713 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1717 int TextMetrics::leftMargin(int max_width,
1718 pit_type const pit, pos_type const pos) const
1720 ParagraphList const & pars = text_->paragraphs();
1722 BOOST_ASSERT(pit >= 0);
1723 BOOST_ASSERT(pit < int(pars.size()));
1724 Paragraph const & par = pars[pit];
1725 BOOST_ASSERT(pos >= 0);
1726 BOOST_ASSERT(pos <= par.size());
1727 Buffer const & buffer = bv_->buffer();
1728 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1729 TextClass const & tclass = buffer.params().getTextClass();
1730 LayoutPtr const & layout = par.layout();
1732 docstring parindent = layout->parindent;
1736 if (text_->isMainText(buffer))
1737 l_margin += changebarMargin();
1739 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1740 tclass.leftmargin());
1742 if (par.getDepth() != 0) {
1743 // find the next level paragraph
1744 pit_type newpar = outerHook(pit, pars);
1745 if (newpar != pit_type(pars.size())) {
1746 if (pars[newpar].layout()->isEnvironment()) {
1747 l_margin = leftMargin(max_width, newpar);
1749 if (par.layout() == tclass.defaultLayout()) {
1750 if (pars[newpar].params().noindent())
1753 parindent = pars[newpar].layout()->parindent;
1758 // This happens after sections in standard classes. The 1.3.x
1759 // code compared depths too, but it does not seem necessary
1761 if (par.layout() == tclass.defaultLayout()
1762 && pit > 0 && pars[pit - 1].layout()->nextnoindent)
1765 FontInfo const labelfont = text_->getLabelFont(buffer, par);
1766 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1768 switch (layout->margintype) {
1769 case MARGIN_DYNAMIC:
1770 if (!layout->leftmargin.empty()) {
1771 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1772 layout->leftmargin);
1774 if (!par.getLabelstring().empty()) {
1775 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1776 l_margin += labelfont_metrics.width(par.getLabelstring());
1777 l_margin += labelfont_metrics.width(layout->labelsep);
1781 case MARGIN_MANUAL: {
1782 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1783 // The width of an empty par, even with manual label, should be 0
1784 if (!par.empty() && pos >= par.beginOfBody()) {
1785 if (!par.getLabelWidthString().empty()) {
1786 docstring labstr = par.getLabelWidthString();
1787 l_margin += labelfont_metrics.width(labstr);
1788 l_margin += labelfont_metrics.width(layout->labelsep);
1794 case MARGIN_STATIC: {
1795 l_margin += theFontMetrics(buffer.params().getFont()).
1796 signedWidth(layout->leftmargin) * 4 / (par.getDepth() + 4);
1800 case MARGIN_FIRST_DYNAMIC:
1801 if (layout->labeltype == LABEL_MANUAL) {
1802 if (pos >= par.beginOfBody()) {
1803 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1805 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1808 // Special case to fix problems with
1810 || (layout->labeltype == LABEL_STATIC
1811 && layout->latextype == LATEX_ENVIRONMENT
1812 && !isFirstInSequence(pit, pars))) {
1813 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1814 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
1815 && layout->labeltype != LABEL_BIBLIO
1816 && layout->labeltype !=
1817 LABEL_CENTERED_TOP_ENVIRONMENT) {
1818 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1819 l_margin += labelfont_metrics.width(layout->labelsep);
1820 l_margin += labelfont_metrics.width(par.getLabelstring());
1824 case MARGIN_RIGHT_ADDRESS_BOX: {
1826 // ok, a terrible hack. The left margin depends on the widest
1827 // row in this paragraph.
1828 RowList::iterator rit = par.rows().begin();
1829 RowList::iterator end = par.rows().end();
1830 // FIXME: This is wrong.
1831 int minfill = max_width;
1832 for ( ; rit != end; ++rit)
1833 if (rit->fill() < minfill)
1834 minfill = rit->fill();
1835 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
1836 l_margin += minfill;
1838 // also wrong, but much shorter.
1839 l_margin += max_width / 2;
1844 if (!par.params().leftIndent().zero())
1845 l_margin += par.params().leftIndent().inPixels(max_width);
1849 if (par.params().align() == LYX_ALIGN_LAYOUT)
1850 align = layout->align;
1852 align = par.params().align();
1854 // set the correct parindent
1856 && (layout->labeltype == LABEL_NO_LABEL
1857 || layout->labeltype == LABEL_TOP_ENVIRONMENT
1858 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1859 || (layout->labeltype == LABEL_STATIC
1860 && layout->latextype == LATEX_ENVIRONMENT
1861 && !isFirstInSequence(pit, pars)))
1862 && align == LYX_ALIGN_BLOCK
1863 && !par.params().noindent()
1864 // in some insets, paragraphs are never indented
1865 && !(par.inInset() && par.inInset()->neverIndent(buffer))
1866 // display style insets are always centered, omit indentation
1869 && par.getInset(pos)->display())
1870 && (par.layout() != tclass.defaultLayout()
1871 || buffer.params().paragraph_separation ==
1872 BufferParams::PARSEP_INDENT))
1874 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1882 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1884 ParagraphMetrics const & pm = par_metrics_[pit];
1886 return pm.singleWidth(pos, getDisplayFont(pit, pos));
1890 // only used for inset right now. should also be used for main text
1891 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1893 if (par_metrics_.empty())
1899 ParMetricsCache::iterator it = par_metrics_.begin();
1900 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1901 y -= it->second.ascent();
1902 for (; it != pm_end; ++it) {
1903 ParagraphMetrics const & pmi = it->second;
1905 pit_type const pit = it->first;
1906 // Save the paragraph position in the cache.
1907 it->second.setPosition(y);
1908 drawParagraph(pi, pit, x, y);
1914 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1916 // lyxerr << " paintPar: pit: " << pit << " at y: " << y << endl;
1917 int const ww = bv_->workHeight();
1919 ParagraphMetrics const & pm = par_metrics_[pit];
1920 if (pm.rows().empty())
1923 RowList::const_iterator const rb = pm.rows().begin();
1924 RowList::const_iterator const re = pm.rows().end();
1928 bool const original_drawing_state = pi.pain.isDrawingEnabled();
1931 for (RowList::const_iterator rit = rb; rit != re; ++rit) {
1934 bool const inside = (y + rit->descent() >= 0
1935 && y - rit->ascent() < ww);
1936 // it is not needed to draw on screen if we are not inside.
1937 pi.pain.setDrawingEnabled(inside && original_drawing_state);
1938 RowPainter rp(pi, *text_, pit, *rit, bidi, x, y);
1940 // Row signature; has row changed since last paint?
1941 bool row_has_changed = rit->changed();
1943 bool row_selection = rit->sel_beg != -1 && rit->sel_end != -1;
1945 if (!row_selection && !pi.full_repaint && !row_has_changed) {
1946 // Paint the only the insets if the text itself is
1948 rp.paintOnlyInsets();
1949 y += rit->descent();
1953 // Paint the row if a full repaint has been requested or it has
1955 // Clear background of this row
1956 // (if paragraph background was not cleared)
1957 if (row_selection || (!pi.full_repaint && row_has_changed)) {
1958 pi.pain.fillRectangle(x, y - rit->ascent(),
1959 width(), rit->height(), pi.background_color);
1961 if (row_selection) {
1962 DocIterator beg = bv_->cursor().selectionBegin();
1963 DocIterator end = bv_->cursor().selectionEnd();
1965 beg.pos() = rit->sel_beg;
1966 if (pit == end.pit()) {
1967 end.pos() = rit->sel_end;
1969 end.pit() = pit + 1;
1972 drawSelection(pi, beg, end, x);
1975 // Instrumentation for testing row cache (see also
1977 if (lyxerr.debugging(Debug::PAINTING)) {
1978 if (text_->isMainText(bv_->buffer()))
1979 LYXERR(Debug::PAINTING) << "\n{" << inside <<
1980 pi.full_repaint << row_has_changed << "}";
1982 LYXERR(Debug::PAINTING) << "[" << inside <<
1983 pi.full_repaint << row_has_changed << "]";
1986 // Backup full_repaint status and force full repaint
1987 // for inner insets as the Row has been cleared out.
1988 bool tmp = pi.full_repaint;
1989 pi.full_repaint = true;
1992 rp.paintChangeBar();
1998 y += rit->descent();
1999 // Restore full_repaint status.
2000 pi.full_repaint = tmp;
2002 // Re-enable screen drawing for future use of the painter.
2003 pi.pain.setDrawingEnabled(original_drawing_state);
2005 //LYXERR(Debug::PAINTING) << "." << endl;
2009 // FIXME: only take care of one row!
2010 void TextMetrics::drawSelection(PainterInfo & pi,
2011 DocIterator const & beg, DocIterator const & end, int x) const
2013 ParagraphMetrics const & pm1 = parMetrics(beg.pit());
2014 ParagraphMetrics const & pm2 = parMetrics(end.pit());
2015 Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
2016 Row const & row2 = pm2.getRow(end.pos(), end.boundary());
2020 bool const clipAbove = (bv_->cursorStatus(beg) == CUR_ABOVE);
2024 middleTop = bv_->getPos(beg, beg.boundary()).y_ + row1.descent();
2028 bool const clipBelow = (bv_->cursorStatus(end) == CUR_BELOW);
2030 middleBottom = bv_->workHeight();
2032 middleBottom = bv_->getPos(end, end.boundary()).y_ - row2.ascent();
2034 // start and end in the same line?
2035 if (!clipAbove && !clipBelow && &row1 == &row2)
2036 // then only draw this row's selection
2037 drawRowSelection(pi, x, row1, beg, end, false, false);
2041 DocIterator begRowEnd = beg;
2042 begRowEnd.pos() = row1.endpos();
2043 begRowEnd.boundary(true);
2045 // draw upper rectangle
2046 drawRowSelection(pi, x, row1, beg, begRowEnd, false, true);
2049 if (middleTop < middleBottom) {
2050 // draw middle rectangle
2051 pi.pain.fillRectangle(x, middleTop, width(), middleBottom - middleTop,
2057 DocIterator endRowBeg = end;
2058 endRowBeg.pos() = row2.pos();
2059 endRowBeg.boundary(false);
2061 // draw low rectangle
2062 drawRowSelection(pi, x, row2, endRowBeg, end, true, false);
2068 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2069 DocIterator const & beg, DocIterator const & end,
2070 bool drawOnBegMargin, bool drawOnEndMargin) const
2072 Buffer & buffer = bv_->buffer();
2073 DocIterator cur = beg;
2074 int x1 = cursorX(beg.top(), beg.boundary());
2075 int x2 = cursorX(end.top(), end.boundary());
2076 int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2077 int y2 = y1 + row.height();
2080 if (drawOnBegMargin) {
2081 if (text_->isRTL(buffer, beg.paragraph()))
2082 pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color_selection);
2084 pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color_selection);
2087 if (drawOnEndMargin) {
2088 if (text_->isRTL(buffer, beg.paragraph()))
2089 pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color_selection);
2091 pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color_selection);
2094 // if we are on a boundary from the beginning, it's probably
2095 // a RTL boundary and we jump to the other side directly as this
2096 // segement is 0-size and confuses the logic below
2098 cur.boundary(false);
2100 // go through row and draw from RTL boundary to RTL boundary
2102 bool drawNow = false;
2104 // simplified cursorForward code below which does not
2105 // descend into insets and which does not go into the
2106 // next line. Compare the logic with the original cursorForward
2108 // if left of boundary -> just jump to right side
2109 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2110 if (cur.boundary()) {
2111 cur.boundary(false);
2112 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2113 // in front of RTL boundary -> Stay on this side of the boundary because:
2114 // ab|cDDEEFFghi -> abc|DDEEFFghi
2123 if (cur.pos() == row.endpos())
2128 // the previous segment was just drawn, now the next starts
2129 x1 = cursorX(cur.top(), cur.boundary());
2132 if (!(cur < end) || drawNow) {
2133 x2 = cursorX(cur.top(), cur.boundary());
2134 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2137 // reset x1, so it is set again next round (which will be on the
2138 // right side of a boundary or at the selection end)
2144 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2146 // ParagraphMetrics const & pm = par_metrics_[pit];
2147 // Row const & r = pm.rows()[row];
2153 int defaultRowHeight()
2155 return int(theFontMetrics(sane_font).maxHeight() * 1.2);