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"
52 #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 main_text_ = (text_ == &buffer.text());
362 bool changed = false;
364 // FIXME This check ought to be done somewhere else. It is the reason
365 // why text_ is not const. But then, where else to do it?
366 // Well, how can you end up with either (a) a biblio environment that
367 // has no InsetBibitem or (b) a biblio environment with more than one
368 // InsetBibitem? I think the answer is: when paragraphs are merged;
369 // when layout is set; when material is pasted.
370 int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
372 const_cast<Cursor &>(bv_->cursor()).posForward();
373 else if (moveCursor < 0) {
374 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
375 if (cursor.pos() >= -moveCursor)
376 cursor.posBackward();
379 // Optimisation: this is used in the next two loops
380 // so better to calculate that once here.
381 int const right_margin = rightMargin(pm);
384 // FIXME: We should always use getFont(), see documentation of
385 // noFontChange() in Inset.h.
386 Font const bufferfont = buffer.params().getFont();
387 MacroContext mc(buffer, par);
388 InsetList::const_iterator ii = par.insetList().begin();
389 InsetList::const_iterator iend = par.insetList().end();
390 for (; ii != iend; ++ii) {
391 // the macro must come here, _before_ the metric call, because
392 // the macro should see itself to detect recursions. To find out
393 // whether the macro definition is a redefinition it will look
394 // at the MacroData::redefinition_. So it doesn't get confused
395 // by the already existing macro definition of itself in the
397 if (ii->inset->lyxCode() == MATHMACRO_CODE) {
399 MathMacroTemplate const & macroTemplate
400 = static_cast<MathMacroTemplate const &>(*ii->inset);
403 if (macroTemplate.validMacro()) {
404 MacroData macro = macroTemplate.asMacroData();
407 macro.setRedefinition(mc.has(macroTemplate.name()));
409 // register macro (possibly overwrite the previous one of this paragraph)
410 mc.insert(macroTemplate.name(), macro);
414 // do the metric calculation
416 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
418 Font const & font = ii->inset->noFontChange() ?
419 bufferfont : getDisplayFont(pit, ii->pos);
420 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
421 ii->inset->metrics(mi, dim);
422 Dimension const old_dim = pm.insetDimension(ii->inset);
423 pm.setInsetDimension(ii->inset, dim);
424 changed |= (old_dim != dim);
427 Cursor const & cur = bv_->cursor();
428 DocIterator sel_beg = cur.selectionBegin();
429 DocIterator sel_end = cur.selectionEnd();
430 bool selection = cur.selection()
432 && cur.text() == text_
433 // if the anchor is outside, this is not our selection
434 && cur.anchor().text() == text_
435 && pit >= sel_beg.pit() && pit <= sel_end.pit();
437 // We care only about visible selection.
439 if (pit != sel_beg.pit()) {
443 if (pit != sel_end.pit()) {
445 sel_end.pos() = sel_end.lastpos();
449 par.setBeginOfBody();
451 size_t row_index = 0;
452 // maximum pixel width of a row
453 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
456 pos_type end = rowBreakPoint(width, pit, first);
457 if (row_index || end < par.size())
458 // If there is more than one row, expand the text to
459 // the full allowable width. This setting here is needed
460 // for the computeRowMetrics() below.
461 dim_.wid = max_width_;
463 dim = rowHeight(pit, first, end);
464 dim.wid = rowWidth(right_margin, pit, first, end);
465 if (row_index == pm.rows().size())
466 pm.rows().push_back(Row());
467 Row & row = pm.rows()[row_index];
468 row.setChanged(false);
472 row.setSelection(sel_beg.pos(), sel_end.pos());
474 row.setSelection(-1, -1);
475 row.setDimension(dim);
476 int const max_row_width = max(dim_.wid, dim.wid);
477 computeRowMetrics(pit, row, max_row_width);
481 pm.dim().wid = std::max(pm.dim().wid, dim.wid);
482 pm.dim().des += dim.height();
483 } while (first < par.size());
485 if (row_index < pm.rows().size())
486 pm.rows().resize(row_index);
488 // Make sure that if a par ends in newline, there is one more row
490 if (first > 0 && par.isNewline(first - 1)) {
491 Dimension dim = rowHeight(pit, first, first);
492 dim.wid = rowWidth(right_margin, pit, first, first);
493 if (row_index == pm.rows().size())
494 pm.rows().push_back(Row());
495 Row & row = pm.rows()[row_index];
496 row.setChanged(false);
499 row.setDimension(dim);
500 int const max_row_width = max(dim_.wid, dim.wid);
501 computeRowMetrics(pit, row, max_row_width);
502 pm.dim().des += dim.height();
505 pm.dim().asc += pm.rows()[0].ascent();
506 pm.dim().des -= pm.rows()[0].ascent();
508 changed |= old_dim.height() != pm.dim().height();
514 void TextMetrics::computeRowMetrics(pit_type const pit,
515 Row & row, int width) const
522 Buffer & buffer = bv_->buffer();
523 Paragraph const & par = text_->getPar(pit);
525 double w = width - row.width();
526 // FIXME: put back this assertion when the crash on new doc is solved.
527 //BOOST_ASSERT(w >= 0);
529 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
530 //lyxerr << "row.width() " << row.width() << endl;
531 //lyxerr << "w " << w << endl;
533 bool const is_rtl = text_->isRTL(buffer, par);
535 row.x = rightMargin(pit);
537 row.x = leftMargin(max_width_, pit, row.pos());
539 // is there a manual margin with a manual label
540 LayoutPtr const & layout = par.layout();
542 if (layout->margintype == MARGIN_MANUAL
543 && layout->labeltype == LABEL_MANUAL) {
544 /// We might have real hfills in the label part
545 int nlh = numberOfLabelHfills(par, row);
547 // A manual label par (e.g. List) has an auto-hfill
548 // between the label text and the body of the
550 // But we don't want to do this auto hfill if the par
555 if (nlh && !par.getLabelWidthString().empty())
556 row.label_hfill = labelFill(pit, row) / double(nlh);
559 // are there any hfills in the row?
560 int const nh = numberOfHfills(par, row);
565 // we don't have to look at the alignment if it is ALIGN_LEFT and
566 // if the row is already larger then the permitted width as then
567 // we force the LEFT_ALIGN'edness!
568 } else if (int(row.width()) < max_width_) {
569 // is it block, flushleft or flushright?
570 // set x how you need it
572 if (par.params().align() == LYX_ALIGN_LAYOUT)
573 align = layout->align;
575 align = par.params().align();
577 // Display-style insets should always be on a centred row
578 // The test on par.size() is to catch zero-size pars, which
579 // would trigger the assert in Paragraph::getInset().
580 //inset = par.size() ? par.getInset(row.pos()) : 0;
581 if (row.pos() < par.size() && par.isInset(row.pos())) {
582 switch(par.getInset(row.pos())->display()) {
583 case Inset::AlignLeft:
584 align = LYX_ALIGN_BLOCK;
586 case Inset::AlignCenter:
587 align = LYX_ALIGN_CENTER;
590 case Inset::AlignRight:
591 // unchanged (use align)
597 case LYX_ALIGN_BLOCK: {
598 int const ns = numberOfSeparators(par, row);
599 bool disp_inset = false;
600 if (row.endpos() < par.size()) {
601 Inset const * in = par.getInset(row.endpos());
603 disp_inset = in->display();
605 // If we have separators, this is not the last row of a
606 // par, does not end in newline, and is not row above a
607 // display inset... then stretch it
609 && row.endpos() < par.size()
610 && !par.isNewline(row.endpos() - 1)
613 row.separator = w / ns;
614 //lyxerr << "row.separator " << row.separator << endl;
615 //lyxerr << "ns " << ns << endl;
621 case LYX_ALIGN_RIGHT:
624 case LYX_ALIGN_CENTER:
631 pos_type body_pos = par.beginOfBody();
632 pos_type end = row.endpos();
635 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
637 row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
638 width(layout->labelsep);
640 row.x += row.label_hfill;
646 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
648 Buffer & buffer = bv_->buffer();
649 Paragraph const & par = text_->getPar(pit);
651 pos_type last = par.beginOfBody();
652 BOOST_ASSERT(last > 0);
654 // -1 because a label ends with a space that is in the label
657 // a separator at this end does not count
658 if (par.isLineSeparator(last))
662 for (pos_type i = row.pos(); i <= last; ++i)
663 w += singleWidth(pit, i);
665 docstring const & label = par.params().labelWidthString();
669 FontMetrics const & fm
670 = theFontMetrics(text_->getLabelFont(buffer, par));
672 return max(0, fm.width(label) - w);
676 // this needs special handling - only newlines count as a break point
677 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
679 pos_type const end = par.size();
682 if (par.isNewline(i))
689 int TextMetrics::labelEnd(pit_type const pit) const
691 // labelEnd is only needed if the layout fills a flushleft label.
692 if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
694 // return the beginning of the body
695 return leftMargin(max_width_, pit);
699 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
702 Buffer & buffer = bv_->buffer();
703 ParagraphMetrics const & pm = par_metrics_[pit];
704 Paragraph const & par = text_->getPar(pit);
705 pos_type const end = par.size();
706 if (pos == end || width < 0)
709 LayoutPtr const & layout = par.layout();
711 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
712 return addressBreakPoint(pos, par);
714 pos_type const body_pos = par.beginOfBody();
717 // Now we iterate through until we reach the right margin
718 // or the end of the par, then choose the possible break
721 int label_end = labelEnd(pit);
722 int const left = leftMargin(max_width_, pit, pos);
725 // pixel width since last breakpoint
728 FontIterator fi = FontIterator(*this, par, pit, pos);
729 pos_type point = end;
731 for ( ; i < end; ++i, ++fi) {
732 int thiswidth = pm.singleWidth(i, *fi);
734 // add the auto-hfill from label end to the body
735 if (body_pos && i == body_pos) {
736 FontMetrics const & fm = theFontMetrics(
737 text_->getLabelFont(buffer, par));
738 int add = fm.width(layout->labelsep);
739 if (par.isLineSeparator(i - 1))
740 add -= singleWidth(pit, i - 1);
742 add = std::max(add, label_end - x);
747 chunkwidth += thiswidth;
749 // break before a character that will fall off
750 // the right of the row
752 // if no break before, break here
753 if (point == end || chunkwidth >= width - left) {
759 // exit on last registered breakpoint:
763 if (par.isNewline(i)) {
769 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
774 if (par.isInset(i) && par.getInset(i)->display()) {
780 if (!par.isInset(i) || par.getInset(i)->isChar()) {
781 // some insets are line separators too
782 if (par.isLineSeparator(i)) {
783 // register breakpoint:
790 // maybe found one, but the par is short enough.
791 if (i == end && x < width)
794 // manual labels cannot be broken in LaTeX. But we
795 // want to make our on-screen rendering of footnotes
797 if (body_pos && point < body_pos)
804 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
805 pos_type const first, pos_type const end) const
807 Buffer & buffer = bv_->buffer();
808 // get the pure distance
809 ParagraphMetrics const & pm = par_metrics_[pit];
810 Paragraph const & par = text_->getPar(pit);
811 int w = leftMargin(max_width_, pit, first);
812 int label_end = labelEnd(pit);
814 pos_type const body_pos = par.beginOfBody();
818 FontIterator fi = FontIterator(*this, par, pit, i);
819 for ( ; i < end; ++i, ++fi) {
820 if (body_pos > 0 && i == body_pos) {
821 FontMetrics const & fm = theFontMetrics(
822 text_->getLabelFont(buffer, par));
823 w += fm.width(par.layout()->labelsep);
824 if (par.isLineSeparator(i - 1))
825 w -= singleWidth(pit, i - 1);
826 w = max(w, label_end);
828 w += pm.singleWidth(i, *fi);
832 if (body_pos > 0 && body_pos >= end) {
833 FontMetrics const & fm = theFontMetrics(
834 text_->getLabelFont(buffer, par));
835 w += fm.width(par.layout()->labelsep);
836 if (end > 0 && par.isLineSeparator(end - 1))
837 w -= singleWidth(pit, end - 1);
838 w = max(w, label_end);
841 return w + right_margin;
845 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
846 pos_type const end) const
848 Paragraph const & par = text_->getPar(pit);
849 // get the maximum ascent and the maximum descent
850 double layoutasc = 0;
851 double layoutdesc = 0;
852 double const dh = defaultRowHeight();
854 // ok, let us initialize the maxasc and maxdesc value.
855 // Only the fontsize count. The other properties
856 // are taken from the layoutfont. Nicer on the screen :)
857 LayoutPtr const & layout = par.layout();
859 // as max get the first character of this row then it can
860 // increase but not decrease the height. Just some point to
861 // start with so we don't have to do the assignment below too
863 Buffer const & buffer = bv_->buffer();
864 Font font = getDisplayFont(pit, first);
865 FontSize const tmpsize = font.fontInfo().size();
866 font.fontInfo() = text_->getLayoutFont(buffer, pit);
867 FontSize const size = font.fontInfo().size();
868 font.fontInfo().setSize(tmpsize);
870 FontInfo labelfont = text_->getLabelFont(buffer, par);
872 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
873 FontMetrics const & fontmetrics = theFontMetrics(font);
875 // these are minimum values
876 double const spacing_val = layout->spacing.getValue()
877 * text_->spacing(buffer, par);
878 //lyxerr << "spacing_val = " << spacing_val << endl;
879 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
880 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
882 // insets may be taller
883 ParagraphMetrics const & pm = par_metrics_[pit];
884 InsetList::const_iterator ii = par.insetList().begin();
885 InsetList::const_iterator iend = par.insetList().end();
886 for ( ; ii != iend; ++ii) {
887 Dimension const & dim = pm.insetDimension(ii->inset);
888 if (ii->pos >= first && ii->pos < end) {
889 maxasc = max(maxasc, dim.ascent());
890 maxdesc = max(maxdesc, dim.descent());
894 // Check if any custom fonts are larger (Asger)
895 // This is not completely correct, but we can live with the small,
896 // cosmetic error for now.
900 par.highestFontInRange(first, end, size);
901 if (maxsize > font.fontInfo().size()) {
902 // use standard paragraph font with the maximal size
903 FontInfo maxfont = font.fontInfo();
904 maxfont.setSize(maxsize);
905 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
906 maxasc = max(maxasc, maxfontmetrics.maxAscent());
907 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
910 // This is nicer with box insets:
914 ParagraphList const & pars = text_->paragraphs();
918 BufferParams const & bufparams = buffer.params();
919 // some parskips VERY EASY IMPLEMENTATION
920 if (bufparams.paragraph_separation
921 == BufferParams::PARSEP_SKIP
922 && par.ownerCode() != ERT_CODE
923 && par.ownerCode() != LISTINGS_CODE
925 && ((layout->isParagraph() && par.getDepth() == 0)
926 || (pars[pit - 1].layout()->isParagraph()
927 && pars[pit - 1].getDepth() == 0)))
929 maxasc += bufparams.getDefSkip().inPixels(*bv_);
932 if (par.params().startOfAppendix())
933 maxasc += int(3 * dh);
935 // This is special code for the chapter, since the label of this
936 // layout is printed in an extra row
937 if (layout->counter == "chapter"
938 && !par.params().labelString().empty()) {
939 labeladdon = int(labelfont_metrics.maxHeight()
940 * layout->spacing.getValue()
941 * text_->spacing(buffer, par));
944 // special code for the top label
945 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
946 || layout->labeltype == LABEL_BIBLIO
947 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
948 && isFirstInSequence(pit, pars)
949 && !par.getLabelstring().empty())
952 labelfont_metrics.maxHeight()
953 * layout->spacing.getValue()
954 * text_->spacing(buffer, par)
955 + (layout->topsep + layout->labelbottomsep) * dh);
958 // Add the layout spaces, for example before and after
959 // a section, or between the items of a itemize or enumerate
962 pit_type prev = depthHook(pit, pars, par.getDepth());
963 Paragraph const & prevpar = pars[prev];
965 && prevpar.layout() == layout
966 && prevpar.getDepth() == par.getDepth()
967 && prevpar.getLabelWidthString()
968 == par.getLabelWidthString()) {
969 layoutasc = layout->itemsep * dh;
970 } else if (pit != 0 || first != 0) {
971 if (layout->topsep > 0)
972 layoutasc = layout->topsep * dh;
975 prev = outerHook(pit, pars);
976 if (prev != pit_type(pars.size())) {
977 maxasc += int(pars[prev].layout()->parsep * dh);
978 } else if (pit != 0) {
979 Paragraph const & prevpar = pars[pit - 1];
980 if (prevpar.getDepth() != 0 ||
981 prevpar.layout() == layout) {
982 maxasc += int(layout->parsep * dh);
987 // is it a bottom line?
988 if (end >= par.size()) {
989 // add the layout spaces, for example before and after
990 // a section, or between the items of a itemize or enumerate
992 pit_type nextpit = pit + 1;
993 if (nextpit != pit_type(pars.size())) {
998 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
999 usual = pars[cpit].layout()->bottomsep * dh;
1000 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1001 if (pars[cpit].layout() != pars[nextpit].layout()
1002 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1004 unusual = pars[cpit].layout()->bottomsep * dh;
1006 layoutdesc = max(unusual, usual);
1007 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1008 if (pars[cpit].layout() != pars[nextpit].layout()
1009 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1010 layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
1015 // incalculate the layout spaces
1016 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1017 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1019 // FIXME: the correct way is to do the following is to move the
1020 // following code in another method specially tailored for the
1021 // main Text. The following test is thus bogus.
1022 // Top and bottom margin of the document (only at top-level)
1024 if (pit == 0 && first == 0)
1026 if (pit + 1 == pit_type(pars.size()) &&
1027 end == par.size() &&
1028 !(end > 0 && par.isNewline(end - 1)))
1032 return Dimension(0, maxasc + labeladdon, maxdesc);
1036 // x is an absolute screen coord
1037 // returns the column near the specified x-coordinate of the row
1038 // x is set to the real beginning of this column
1039 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1040 Row const & row, int & x, bool & boundary) const
1042 Buffer const & buffer = bv_->buffer();
1044 /// For the main Text, it is possible that this pit is not
1045 /// yet in the CoordCache when moving cursor up.
1046 /// x Paragraph coordinate is always 0 for main text anyway.
1047 int const xo = origin_.x_;
1049 Paragraph const & par = text_->getPar(pit);
1050 ParagraphMetrics const & pm = par_metrics_[pit];
1052 bidi.computeTables(par, buffer, row);
1054 pos_type vc = row.pos();
1055 pos_type end = row.endpos();
1057 LayoutPtr const & layout = par.layout();
1059 bool left_side = false;
1061 pos_type body_pos = par.beginOfBody();
1063 double tmpx = row.x;
1064 double last_tmpx = tmpx;
1067 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1070 // check for empty row
1076 while (vc < end && tmpx <= x) {
1077 c = bidi.vis2log(vc);
1079 if (body_pos > 0 && c == body_pos - 1) {
1080 FontMetrics const & fm = theFontMetrics(
1081 text_->getLabelFont(buffer, par));
1082 tmpx += row.label_hfill + fm.width(layout->labelsep);
1083 if (par.isLineSeparator(body_pos - 1))
1084 tmpx -= singleWidth(pit, body_pos - 1);
1087 if (pm.hfillExpansion(row, c)) {
1088 tmpx += singleWidth(pit, c);
1092 tmpx += row.label_hfill;
1093 } else if (par.isSeparator(c)) {
1094 tmpx += singleWidth(pit, c);
1096 tmpx += row.separator;
1098 tmpx += singleWidth(pit, c);
1103 if ((tmpx + last_tmpx) / 2 > x) {
1108 BOOST_ASSERT(vc <= end); // This shouldn't happen.
1111 // This (rtl_support test) is not needed, but gives
1112 // some speedup if rtl_support == false
1113 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1115 // If lastrow is false, we don't need to compute
1116 // the value of rtl.
1117 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1119 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1120 (!rtl && !left_side && vc == end && x > tmpx + 5)))
1122 else if (vc == row.pos()) {
1123 c = bidi.vis2log(vc);
1124 if (bidi.level(c) % 2 == 1)
1127 c = bidi.vis2log(vc - 1);
1128 bool const rtl = (bidi.level(c) % 2 == 1);
1129 if (left_side == rtl) {
1131 boundary = isRTLBoundary(pit, c);
1135 // I believe this code is not needed anymore (Jug 20050717)
1137 // The following code is necessary because the cursor position past
1138 // the last char in a row is logically equivalent to that before
1139 // the first char in the next row. That's why insets causing row
1140 // divisions -- Newline and display-style insets -- must be treated
1141 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1142 // Newline inset, air gap below:
1143 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1144 if (bidi.level(end -1) % 2 == 0)
1145 tmpx -= singleWidth(pit, end - 1);
1147 tmpx += singleWidth(pit, end - 1);
1151 // Air gap above display inset:
1152 if (row.pos() < end && c >= end && end < par.size()
1153 && par.isInset(end) && par.getInset(end)->display()) {
1156 // Air gap below display inset:
1157 if (row.pos() < end && c >= end && par.isInset(end - 1)
1158 && par.getInset(end - 1)->display()) {
1164 pos_type const col = c - row.pos();
1166 if (!c || end == par.size())
1169 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1174 return min(col, end - 1 - row.pos());
1178 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1180 // We play safe and use parMetrics(pit) to make sure the
1181 // ParagraphMetrics will be redone and OK to use if needed.
1182 // Otherwise we would use an empty ParagraphMetrics in
1183 // upDownInText() while in selection mode.
1184 ParagraphMetrics const & pm = parMetrics(pit);
1186 BOOST_ASSERT(row < int(pm.rows().size()));
1188 Row const & r = pm.rows()[row];
1189 return r.pos() + getColumnNearX(pit, r, x, bound);
1193 void TextMetrics::newParMetricsDown()
1195 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1196 pit_type const pit = last.first + 1;
1197 if (pit == int(text_->paragraphs().size()))
1200 // do it and update its position.
1202 par_metrics_[pit].setPosition(last.second.position()
1203 + last.second.descent());
1207 void TextMetrics::newParMetricsUp()
1209 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1210 if (first.first == 0)
1213 pit_type const pit = first.first - 1;
1214 // do it and update its position.
1216 par_metrics_[pit].setPosition(first.second.position()
1217 - first.second.ascent());
1220 // y is screen coordinate
1221 pit_type TextMetrics::getPitNearY(int y)
1223 BOOST_ASSERT(!text_->paragraphs().empty());
1224 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1225 << ": y: " << y << " cache size: " << par_metrics_.size());
1227 // look for highest numbered paragraph with y coordinate less than given y
1230 ParMetricsCache::const_iterator it = par_metrics_.begin();
1231 ParMetricsCache::const_iterator et = par_metrics_.end();
1232 ParMetricsCache::const_iterator last = et; last--;
1234 ParagraphMetrics const & pm = it->second;
1236 if (y < it->second.position() - int(pm.ascent())) {
1237 // We are looking for a position that is before the first paragraph in
1238 // the cache (which is in priciple off-screen, that is before the
1241 // We are already at the first paragraph in the inset.
1243 // OK, this is the paragraph we are looking for.
1244 pit = it->first - 1;
1249 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1251 if (y >= last->second.position() + int(pm_last.descent())) {
1252 // We are looking for a position that is after the last paragraph in
1253 // the cache (which is in priciple off-screen, that is before the
1255 pit = last->first + 1;
1256 if (pit == int(text_->paragraphs().size()))
1257 // We are already at the last paragraph in the inset.
1259 // OK, this is the paragraph we are looking for.
1260 newParMetricsDown();
1264 for (; it != et; ++it) {
1265 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1266 << " examining: pit: " << it->first
1267 << " y: " << it->second.position());
1269 ParagraphMetrics const & pm = par_metrics_[it->first];
1271 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1273 yy = it->second.position();
1277 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1278 << ": found best y: " << yy << " for pit: " << pit);
1284 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1286 ParagraphMetrics const & pm = par_metrics_[pit];
1288 int yy = pm.position() - pm.ascent();
1289 BOOST_ASSERT(!pm.rows().empty());
1290 RowList::const_iterator rit = pm.rows().begin();
1291 RowList::const_iterator rlast = pm.rows().end();
1293 for (; rit != rlast; yy += rit->height(), ++rit)
1294 if (yy + rit->height() > y)
1300 // x,y are absolute screen coordinates
1301 // sets cursor recursively descending into nested editable insets
1302 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1304 if (lyxerr.debugging(Debug::WORKAREA)) {
1305 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1306 cur.bv().coordCache().dump();
1308 pit_type pit = getPitNearY(y);
1309 BOOST_ASSERT(pit != -1);
1311 Row const & row = getRowNearY(y, pit);
1314 int xx = x; // is modified by getColumnNearX
1315 pos_type const pos = row.pos()
1316 + getColumnNearX(pit, row, xx, bound);
1319 cur.boundary(bound);
1322 // try to descend into nested insets
1323 Inset * inset = checkInsetHit(x, y);
1324 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1326 // Either we deconst editXY or better we move current_font
1327 // and real_current_font to Cursor
1328 // FIXME: what is needed now that current_font and real_current_font
1330 cur.setCurrentFont();
1334 ParagraphList const & pars = text_->paragraphs();
1335 Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1336 //Inset * insetBehind = pars[pit].getInset(pos);
1338 // This should be just before or just behind the
1339 // cursor position set above.
1340 BOOST_ASSERT((pos != 0 && inset == insetBefore)
1341 || inset == pars[pit].getInset(pos));
1343 // Make sure the cursor points to the position before
1345 if (inset == insetBefore) {
1347 cur.boundary(false);
1350 // Try to descend recursively inside the inset.
1351 inset = inset->editXY(cur, x, y);
1353 if (cur.top().text() == text_)
1354 cur.setCurrentFont();
1359 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1361 BOOST_ASSERT(text_ == cur.text());
1362 pit_type pit = getPitNearY(y);
1364 ParagraphMetrics const & pm = par_metrics_[pit];
1366 int yy = pm.position() - pm.ascent();
1367 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1368 << ": x: " << x << " y: " << y << " pit: " << pit << " yy: " << yy);
1371 BOOST_ASSERT(pm.rows().size());
1372 for (; r < int(pm.rows().size()) - 1; ++r) {
1373 Row const & row = pm.rows()[r];
1374 if (int(yy + row.height()) > y)
1379 Row const & row = pm.rows()[r];
1381 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1382 << ": row " << r << " from pos: " << row.pos());
1386 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1388 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1389 << ": setting cursor pit: " << pit << " pos: " << pos);
1391 text_->setCursor(cur, pit, pos, true, bound);
1392 // remember new position.
1397 //takes screen x,y coordinates
1398 Inset * TextMetrics::checkInsetHit(int x, int y)
1400 pit_type pit = getPitNearY(y);
1401 BOOST_ASSERT(pit != -1);
1403 Paragraph const & par = text_->paragraphs()[pit];
1404 ParagraphMetrics const & pm = par_metrics_[pit];
1406 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1407 << ": x: " << x << " y: " << y << " pit: " << pit);
1409 InsetList::const_iterator iit = par.insetList().begin();
1410 InsetList::const_iterator iend = par.insetList().end();
1411 for (; iit != iend; ++iit) {
1412 Inset * inset = iit->inset;
1414 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1415 << ": examining inset " << inset);
1417 if (!bv_->coordCache().getInsets().has(inset)) {
1418 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1419 << ": inset has no cached position");
1423 Dimension const & dim = pm.insetDimension(inset);
1424 Point p = bv_->coordCache().getInsets().xy(inset);
1426 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1427 << ": xo: " << p.x_ << "..." << p.x_ + dim.wid
1428 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1431 && x <= p.x_ + dim.wid
1432 && y >= p.y_ - dim.asc
1433 && y <= p.y_ + dim.des) {
1434 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1435 << ": Hit inset: " << inset);
1440 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION << ": No inset hit. ");
1445 int TextMetrics::cursorX(CursorSlice const & sl,
1446 bool boundary) const
1448 BOOST_ASSERT(sl.text() == text_);
1449 pit_type const pit = sl.pit();
1450 Paragraph const & par = text_->paragraphs()[pit];
1451 ParagraphMetrics const & pm = par_metrics_[pit];
1452 if (pm.rows().empty())
1455 pos_type ppos = sl.pos();
1456 // Correct position in front of big insets
1457 bool const boundary_correction = ppos != 0 && boundary;
1458 if (boundary_correction)
1461 Row const & row = pm.getRow(sl.pos(), boundary);
1463 pos_type cursor_vpos = 0;
1465 Buffer const & buffer = bv_->buffer();
1468 bidi.computeTables(par, buffer, row);
1470 pos_type const row_pos = row.pos();
1471 pos_type const end = row.endpos();
1472 // Spaces at logical line breaks in bidi text must be skipped during
1473 // cursor positioning. However, they may appear visually in the middle
1474 // of a row; they must be skipped, wherever they are...
1475 // * logically "abc_[HEBREW_\nHEBREW]"
1476 // * visually "abc_[_WERBEH\nWERBEH]"
1477 pos_type skipped_sep_vpos = -1;
1480 cursor_vpos = row_pos;
1481 else if (ppos >= end)
1482 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1483 else if (ppos > row_pos && ppos >= end)
1484 // Place cursor after char at (logical) position pos - 1
1485 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1486 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1488 // Place cursor before char at (logical) position ppos
1489 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1490 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1492 pos_type body_pos = par.beginOfBody();
1494 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1497 // Use font span to speed things up, see below
1501 // If the last logical character is a separator, skip it, unless
1502 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1503 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1504 skipped_sep_vpos = bidi.log2vis(end - 1);
1506 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1507 // Skip the separator which is at the logical end of the row
1508 if (vpos == skipped_sep_vpos)
1510 pos_type pos = bidi.vis2log(vpos);
1511 if (body_pos > 0 && pos == body_pos - 1) {
1512 FontMetrics const & labelfm = theFontMetrics(
1513 text_->getLabelFont(buffer, par));
1514 x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1515 if (par.isLineSeparator(body_pos - 1))
1516 x -= singleWidth(pit, body_pos - 1);
1519 // Use font span to speed things up, see above
1520 if (pos < font_span.first || pos > font_span.last) {
1521 font_span = par.fontSpan(pos);
1522 font = getDisplayFont(pit, pos);
1525 x += pm.singleWidth(pos, font);
1527 if (pm.hfillExpansion(row, pos))
1528 x += (pos >= body_pos) ? row.hfill : row.label_hfill;
1529 else if (par.isSeparator(pos) && pos >= body_pos)
1533 // see correction above
1534 if (boundary_correction) {
1535 if (isRTL(sl, boundary))
1536 x -= singleWidth(pit, ppos);
1538 x += singleWidth(pit, ppos);
1545 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1547 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << std::endl;
1548 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1549 if (pm.rows().empty())
1553 h -= par_metrics_[0].rows()[0].ascent();
1554 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1555 h += par_metrics_[pit].height();
1558 if (pos && boundary)
1560 size_t const rend = pm.pos2row(pos);
1561 for (size_t rit = 0; rit != rend; ++rit)
1562 h += pm.rows()[rit].height();
1563 h += pm.rows()[rend].ascent();
1568 void TextMetrics::cursorPrevious(Cursor & cur)
1570 pos_type cpos = cur.pos();
1571 pit_type cpar = cur.pit();
1573 int x = cur.x_target();
1574 setCursorFromCoordinates(cur, x, 0);
1575 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1577 if (cpar == cur.pit() && cpos == cur.pos())
1578 // we have a row which is taller than the workarea. The
1579 // simplest solution is to move to the previous row instead.
1580 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1583 cur.updateFlags(Update::Force | Update::FitCursor);
1587 void TextMetrics::cursorNext(Cursor & cur)
1589 pos_type cpos = cur.pos();
1590 pit_type cpar = cur.pit();
1592 int x = cur.x_target();
1593 setCursorFromCoordinates(cur, x, cur.bv().workHeight() - 1);
1594 cur.dispatch(FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1596 if (cpar == cur.pit() && cpos == cur.pos())
1597 // we have a row which is taller than the workarea. The
1598 // simplest solution is to move to the next row instead.
1600 FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1603 cur.updateFlags(Update::Force | Update::FitCursor);
1607 // the cursor set functions have a special mechanism. When they
1608 // realize you left an empty paragraph, they will delete it.
1610 bool TextMetrics::cursorHome(Cursor & cur)
1612 BOOST_ASSERT(text_ == cur.text());
1613 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1614 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1615 return text_->setCursor(cur, cur.pit(), row.pos());
1619 bool TextMetrics::cursorEnd(Cursor & cur)
1621 BOOST_ASSERT(text_ == cur.text());
1622 // if not on the last row of the par, put the cursor before
1623 // the final space exept if I have a spanning inset or one string
1624 // is so long that we force a break.
1625 pos_type end = cur.textRow().endpos();
1627 // empty text, end-1 is no valid position
1629 bool boundary = false;
1630 if (end != cur.lastpos()) {
1631 if (!cur.paragraph().isLineSeparator(end-1)
1632 && !cur.paragraph().isNewline(end-1))
1637 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1641 void TextMetrics::deleteLineForward(Cursor & cur)
1643 BOOST_ASSERT(text_ == cur.text());
1644 if (cur.lastpos() == 0) {
1645 // Paragraph is empty, so we just go forward
1646 text_->cursorForward(cur);
1649 cur.selection() = true; // to avoid deletion
1652 // What is this test for ??? (JMarc)
1653 if (!cur.selection())
1654 text_->deleteWordForward(cur);
1656 cap::cutSelection(cur, true, false);
1657 checkBufferStructure(cur.buffer(), cur);
1662 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1664 ParagraphList const & pars = text_->paragraphs();
1665 return row.endpos() >= pars[pit].size()
1666 && pit + 1 == pit_type(pars.size());
1670 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1672 return row.pos() == 0 && pit == 0;
1676 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1678 BOOST_ASSERT(pit >= 0);
1679 BOOST_ASSERT(pit < int(text_->paragraphs().size()));
1680 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1684 int TextMetrics::leftMargin(int max_width,
1685 pit_type const pit, pos_type const pos) const
1687 ParagraphList const & pars = text_->paragraphs();
1689 BOOST_ASSERT(pit >= 0);
1690 BOOST_ASSERT(pit < int(pars.size()));
1691 Paragraph const & par = pars[pit];
1692 BOOST_ASSERT(pos >= 0);
1693 BOOST_ASSERT(pos <= par.size());
1694 Buffer const & buffer = bv_->buffer();
1695 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1696 TextClass const & tclass = buffer.params().getTextClass();
1697 LayoutPtr const & layout = par.layout();
1699 docstring parindent = layout->parindent;
1703 if (text_->isMainText(buffer))
1704 l_margin += changebarMargin();
1706 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1707 tclass.leftmargin());
1709 if (par.getDepth() != 0) {
1710 // find the next level paragraph
1711 pit_type newpar = outerHook(pit, pars);
1712 if (newpar != pit_type(pars.size())) {
1713 if (pars[newpar].layout()->isEnvironment()) {
1714 l_margin = leftMargin(max_width, newpar);
1716 if (par.layout() == tclass.defaultLayout()) {
1717 if (pars[newpar].params().noindent())
1720 parindent = pars[newpar].layout()->parindent;
1725 // This happens after sections in standard classes. The 1.3.x
1726 // code compared depths too, but it does not seem necessary
1728 if (par.layout() == tclass.defaultLayout()
1729 && pit > 0 && pars[pit - 1].layout()->nextnoindent)
1732 FontInfo const labelfont = text_->getLabelFont(buffer, par);
1733 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1735 switch (layout->margintype) {
1736 case MARGIN_DYNAMIC:
1737 if (!layout->leftmargin.empty()) {
1738 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1739 layout->leftmargin);
1741 if (!par.getLabelstring().empty()) {
1742 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1743 l_margin += labelfont_metrics.width(par.getLabelstring());
1744 l_margin += labelfont_metrics.width(layout->labelsep);
1748 case MARGIN_MANUAL: {
1749 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1750 // The width of an empty par, even with manual label, should be 0
1751 if (!par.empty() && pos >= par.beginOfBody()) {
1752 if (!par.getLabelWidthString().empty()) {
1753 docstring labstr = par.getLabelWidthString();
1754 l_margin += labelfont_metrics.width(labstr);
1755 l_margin += labelfont_metrics.width(layout->labelsep);
1761 case MARGIN_STATIC: {
1762 l_margin += theFontMetrics(buffer.params().getFont()).
1763 signedWidth(layout->leftmargin) * 4 / (par.getDepth() + 4);
1767 case MARGIN_FIRST_DYNAMIC:
1768 if (layout->labeltype == LABEL_MANUAL) {
1769 if (pos >= par.beginOfBody()) {
1770 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1772 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1775 // Special case to fix problems with
1777 || (layout->labeltype == LABEL_STATIC
1778 && layout->latextype == LATEX_ENVIRONMENT
1779 && !isFirstInSequence(pit, pars))) {
1780 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1781 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
1782 && layout->labeltype != LABEL_BIBLIO
1783 && layout->labeltype !=
1784 LABEL_CENTERED_TOP_ENVIRONMENT) {
1785 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1786 l_margin += labelfont_metrics.width(layout->labelsep);
1787 l_margin += labelfont_metrics.width(par.getLabelstring());
1791 case MARGIN_RIGHT_ADDRESS_BOX: {
1793 // ok, a terrible hack. The left margin depends on the widest
1794 // row in this paragraph.
1795 RowList::iterator rit = par.rows().begin();
1796 RowList::iterator end = par.rows().end();
1797 // FIXME: This is wrong.
1798 int minfill = max_width;
1799 for ( ; rit != end; ++rit)
1800 if (rit->fill() < minfill)
1801 minfill = rit->fill();
1802 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
1803 l_margin += minfill;
1805 // also wrong, but much shorter.
1806 l_margin += max_width / 2;
1811 if (!par.params().leftIndent().zero())
1812 l_margin += par.params().leftIndent().inPixels(max_width);
1816 if (par.params().align() == LYX_ALIGN_LAYOUT)
1817 align = layout->align;
1819 align = par.params().align();
1821 // set the correct parindent
1823 && (layout->labeltype == LABEL_NO_LABEL
1824 || layout->labeltype == LABEL_TOP_ENVIRONMENT
1825 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1826 || (layout->labeltype == LABEL_STATIC
1827 && layout->latextype == LATEX_ENVIRONMENT
1828 && !isFirstInSequence(pit, pars)))
1829 && align == LYX_ALIGN_BLOCK
1830 && !par.params().noindent()
1831 // in some insets, paragraphs are never indented
1832 && !(par.inInset() && par.inInset()->neverIndent(buffer))
1833 // display style insets are always centered, omit indentation
1836 && par.getInset(pos)->display())
1837 && (par.layout() != tclass.defaultLayout()
1838 || buffer.params().paragraph_separation ==
1839 BufferParams::PARSEP_INDENT))
1841 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1849 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1851 ParagraphMetrics const & pm = par_metrics_[pit];
1853 return pm.singleWidth(pos, getDisplayFont(pit, pos));
1857 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1859 if (par_metrics_.empty())
1865 ParMetricsCache::iterator it = par_metrics_.begin();
1866 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1867 y -= it->second.ascent();
1868 for (; it != pm_end; ++it) {
1869 ParagraphMetrics const & pmi = it->second;
1871 pit_type const pit = it->first;
1872 // Save the paragraph position in the cache.
1873 it->second.setPosition(y);
1874 drawParagraph(pi, pit, x, y);
1880 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1882 BufferParams const & bparams = bv_->buffer().params();
1883 ParagraphMetrics const & pm = par_metrics_[pit];
1884 if (pm.rows().empty())
1888 bool const original_drawing_state = pi.pain.isDrawingEnabled();
1889 int const ww = bv_->workHeight();
1890 size_t const nrows = pm.rows().size();
1892 for (size_t i = 0; i != nrows; ++i) {
1894 Row const & row = pm.rows()[i];
1898 bool const inside = (y + row.descent() >= 0
1899 && y - row.ascent() < ww);
1900 // It is not needed to draw on screen if we are not inside.
1901 pi.pain.setDrawingEnabled(inside && original_drawing_state);
1902 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
1904 // Row signature; has row changed since last paint?
1905 row.setCrc(pm.computeRowSignature(row, bparams));
1906 bool row_has_changed = row.changed();
1908 // Don't paint the row if a full repaint has not been requested
1909 // and if it has not changed.
1910 if (!pi.full_repaint && !row_has_changed) {
1911 // Paint only the insets if the text itself is
1913 rp.paintOnlyInsets();
1918 // Clear background of this row if paragraph background was not
1919 // already cleared because of a full repaint.
1920 if (!pi.full_repaint && row_has_changed) {
1921 pi.pain.fillRectangle(x, y - row.ascent(),
1922 width(), row.height(), pi.background_color);
1925 bool row_selection = row.sel_beg != -1 && row.sel_end != -1;
1926 if (row_selection) {
1927 DocIterator beg = bv_->cursor().selectionBegin();
1928 DocIterator end = bv_->cursor().selectionEnd();
1929 bool const beg_margin = beg.pit() < pit && i == 0;
1930 bool const end_margin = end.pit() > pit && i == nrows - 1;
1932 beg.pos() = row.sel_beg;
1934 end.pos() = row.sel_end;
1935 drawRowSelection(pi, x, row, beg, end, beg_margin, end_margin);
1938 // Instrumentation for testing row cache (see also
1940 if (lyxerr.debugging(Debug::PAINTING) && inside
1941 && (row_selection || pi.full_repaint || row_has_changed)) {
1942 std::string const foreword = text_->isMainText(bv_->buffer()) ?
1943 "main text redraw " : "inset text redraw: ";
1944 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
1945 << " row_selection=" << row_selection
1946 << " full_repaint=" << pi.full_repaint
1947 << " row_has_changed=" << row_has_changed);
1950 // Backup full_repaint status and force full repaint
1951 // for inner insets as the Row has been cleared out.
1952 bool tmp = pi.full_repaint;
1953 pi.full_repaint = true;
1956 rp.paintChangeBar();
1963 // Restore full_repaint status.
1964 pi.full_repaint = tmp;
1966 // Re-enable screen drawing for future use of the painter.
1967 pi.pain.setDrawingEnabled(original_drawing_state);
1969 //LYXERR(Debug::PAINTING, ".");
1973 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
1974 DocIterator const & beg, DocIterator const & end,
1975 bool drawOnBegMargin, bool drawOnEndMargin) const
1977 Buffer & buffer = bv_->buffer();
1978 DocIterator cur = beg;
1979 int x1 = cursorX(beg.top(), beg.boundary());
1980 int x2 = cursorX(end.top(), end.boundary());
1981 int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
1982 int y2 = y1 + row.height();
1985 if (drawOnBegMargin) {
1986 if (text_->isRTL(buffer, beg.paragraph()))
1987 pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color_selection);
1989 pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color_selection);
1992 if (drawOnEndMargin) {
1993 if (text_->isRTL(buffer, beg.paragraph()))
1994 pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color_selection);
1996 pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color_selection);
1999 // if we are on a boundary from the beginning, it's probably
2000 // a RTL boundary and we jump to the other side directly as this
2001 // segement is 0-size and confuses the logic below
2003 cur.boundary(false);
2005 // go through row and draw from RTL boundary to RTL boundary
2007 bool drawNow = false;
2009 // simplified cursorForward code below which does not
2010 // descend into insets and which does not go into the
2011 // next line. Compare the logic with the original cursorForward
2013 // if left of boundary -> just jump to right side
2014 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2015 if (cur.boundary()) {
2016 cur.boundary(false);
2017 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2018 // in front of RTL boundary -> Stay on this side of the boundary because:
2019 // ab|cDDEEFFghi -> abc|DDEEFFghi
2028 if (cur.pos() == row.endpos())
2033 // the previous segment was just drawn, now the next starts
2034 x1 = cursorX(cur.top(), cur.boundary());
2037 if (!(cur < end) || drawNow) {
2038 x2 = cursorX(cur.top(), cur.boundary());
2039 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2042 // reset x1, so it is set again next round (which will be on the
2043 // right side of a boundary or at the selection end)
2049 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2051 // ParagraphMetrics const & pm = par_metrics_[pit];
2052 // Row const & r = pm.rows()[row];
2058 int defaultRowHeight()
2060 return int(theFontMetrics(sane_font).maxHeight() * 1.2);