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"
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>
62 using frontend::FontMetrics;
66 int numberOfSeparators(Paragraph const & par, Row const & row)
68 pos_type const first = max(row.pos(), par.beginOfBody());
69 pos_type const last = row.endpos() - 1;
71 for (pos_type p = first; p < last; ++p) {
72 if (par.isSeparator(p))
79 int numberOfLabelHfills(Paragraph const & par, Row const & row)
81 pos_type last = row.endpos() - 1;
82 pos_type first = row.pos();
84 // hfill *DO* count at the beginning of paragraphs!
86 while (first < last && par.isHfill(first))
90 last = min(last, par.beginOfBody());
92 for (pos_type p = first; p < last; ++p) {
100 int numberOfHfills(Paragraph const & par, Row const & row)
102 pos_type const last = row.endpos();
103 pos_type first = row.pos();
105 // hfill *DO* count at the beginning of paragraphs!
107 while (first < last && par.isHfill(first))
111 first = max(first, par.beginOfBody());
114 for (pos_type p = first; p < last; ++p) {
123 TextMetrics::TextMetrics(BufferView * bv, Text * text)
124 : bv_(bv), text_(text)
127 max_width_ = bv_->workWidth();
128 dim_.wid = max_width_;
132 //text_->updateLabels(bv->buffer());
136 bool TextMetrics::has(pit_type pit) const
138 return par_metrics_.find(pit) != par_metrics_.end();
142 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
144 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
149 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
151 ParMetricsCache::const_iterator it = par_metrics_.begin();
152 return make_pair(it->first, &it->second);
156 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
158 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
159 return make_pair(it->first, &it->second);
163 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
165 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
166 if (pmc_it == par_metrics_.end()) {
167 pmc_it = par_metrics_.insert(
168 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
170 if (pmc_it->second.rows().empty() && redo)
172 return pmc_it->second;
176 int TextMetrics::parPosition(pit_type pit) const
178 if (pit < par_metrics_.begin()->first)
180 if (pit > par_metrics_.rbegin()->first)
183 return par_metrics_[pit].position();
187 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
189 BOOST_ASSERT(mi.base.textwidth);
190 max_width_ = mi.base.textwidth;
191 // backup old dimension.
192 Dimension const old_dim = dim_;
195 dim_.wid = min_width;
196 pit_type const npar = text_->paragraphs().size();
198 // If there is more than one row, expand the text to
199 // the full allowable width.
200 dim_.wid = max_width_;
202 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
203 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
205 bool changed = false;
207 for (pit_type pit = 0; pit != npar; ++pit) {
208 changed |= redoParagraph(pit);
209 ParagraphMetrics const & pm = par_metrics_[pit];
211 if (dim_.wid < pm.width())
212 dim_.wid = pm.width();
215 dim_.asc = par_metrics_[0].ascent();
216 dim_.des = h - dim_.asc;
217 //lyxerr << "dim_.wid " << dim_.wid << endl;
218 //lyxerr << "dim_.asc " << dim_.asc << endl;
219 //lyxerr << "dim_.des " << dim_.des << endl;
221 changed |= dim_ != old_dim;
227 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
229 return main_text_? pm.rightMargin(bv_->buffer()) : 0;
233 int TextMetrics::rightMargin(pit_type const pit) const
235 return main_text_? par_metrics_[pit].rightMargin(bv_->buffer()) : 0;
239 void TextMetrics::applyOuterFont(Font & font) const
242 lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
243 lf.fontInfo().realize(font.fontInfo());
244 lf.setLanguage(font.language());
249 Font TextMetrics::getDisplayFont(pit_type pit, pos_type pos) const
251 BOOST_ASSERT(pos >= 0);
253 ParagraphList const & pars = text_->paragraphs();
254 Paragraph const & par = pars[pit];
255 LayoutPtr const & layout = par.layout();
256 Buffer const & buffer = bv_->buffer();
258 BufferParams const & params = buffer.params();
259 pos_type const body_pos = par.beginOfBody();
261 // We specialize the 95% common case:
262 if (!par.getDepth()) {
263 Font f = par.getFontSettings(params, pos);
264 if (!text_->isMainText(buffer))
266 bool lab = layout->labeltype == LABEL_MANUAL && pos < body_pos;
268 FontInfo const & lf = lab ? layout->labelfont : layout->font;
269 FontInfo rlf = lab ? layout->reslabelfont : layout->resfont;
271 // In case the default family has been customized
272 if (lf.family() == INHERIT_FAMILY)
273 rlf.setFamily(params.getFont().fontInfo().family());
274 f.fontInfo().realize(rlf);
278 // The uncommon case need not be optimized as much
279 FontInfo const & layoutfont = pos < body_pos ?
280 layout->labelfont : layout->font;
282 Font font = par.getFontSettings(params, pos);
283 font.fontInfo().realize(layoutfont);
285 if (!text_->isMainText(buffer))
286 applyOuterFont(font);
288 // Realize against environment font information
289 // NOTE: the cast to pit_type should be removed when pit_type
290 // changes to a unsigned integer.
291 if (pit < pit_type(pars.size()))
292 font.fontInfo().realize(outerFont(pit, pars).fontInfo());
294 // Realize with the fonts of lesser depth.
295 font.fontInfo().realize(params.getFont().fontInfo());
301 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
303 if (!lyxrc.rtl_support || !sl.text())
307 if (boundary && sl.pos() > 0)
310 return getDisplayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
314 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
316 if (!lyxrc.rtl_support)
319 // no RTL boundary at line start
323 Paragraph const & par = text_->getPar(pit);
325 bool left = getDisplayFont(pit, pos - 1).isVisibleRightToLeft();
327 if (pos == par.size())
328 right = par.isRTL(bv_->buffer().params());
330 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
331 return left != right;
335 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
336 Font const & font) const
338 if (!lyxrc.rtl_support)
341 Paragraph const & par = text_->getPar(pit);
342 bool left = font.isVisibleRightToLeft();
344 if (pos == par.size())
345 right = par.isRTL(bv_->buffer().params());
347 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
348 return left != right;
352 bool TextMetrics::redoParagraph(pit_type const pit)
354 Paragraph & par = text_->getPar(pit);
355 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
356 // redoParagraph() recursively inside parMetrics.
357 Dimension old_dim = parMetrics(pit, false).dim();
358 ParagraphMetrics & pm = par_metrics_[pit];
361 Buffer & buffer = bv_->buffer();
362 BufferParams const & bparams = buffer.params();
363 main_text_ = (text_ == &buffer.text());
364 bool changed = false;
366 // FIXME This check ought to be done somewhere else. It is the reason
367 // why text_ is not const. But then, where else to do it?
368 // Well, how can you end up with either (a) a biblio environment that
369 // has no InsetBibitem or (b) a biblio environment with more than one
370 // InsetBibitem? I think the answer is: when paragraphs are merged;
371 // when layout is set; when material is pasted.
372 int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
374 const_cast<Cursor &>(bv_->cursor()).posForward();
375 else if (moveCursor < 0) {
376 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
377 if (cursor.pos() >= -moveCursor)
378 cursor.posBackward();
381 // Optimisation: this is used in the next two loops
382 // so better to calculate that once here.
383 int const right_margin = rightMargin(pm);
386 // FIXME: We should always use getFont(), see documentation of
387 // noFontChange() in Inset.h.
388 Font const bufferfont = buffer.params().getFont();
389 MacroContext mc(buffer, par);
390 InsetList::const_iterator ii = par.insetList().begin();
391 InsetList::const_iterator iend = par.insetList().end();
392 for (; ii != iend; ++ii) {
393 // the macro must come here, _before_ the metric call, because
394 // the macro should see itself to detect recursions. To find out
395 // whether the macro definition is a redefinition it will look
396 // at the MacroData::redefinition_. So it doesn't get confused
397 // by the already existing macro definition of itself in the
399 if (ii->inset->lyxCode() == MATHMACRO_CODE) {
401 MathMacroTemplate const & macroTemplate
402 = static_cast<MathMacroTemplate const &>(*ii->inset);
405 if (macroTemplate.validMacro()) {
406 MacroData macro = macroTemplate.asMacroData();
409 macro.setRedefinition(mc.has(macroTemplate.name()));
411 // register macro (possibly overwrite the previous one of this paragraph)
412 mc.insert(macroTemplate.name(), macro);
416 // do the metric calculation
418 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
420 Font const & font = ii->inset->noFontChange() ?
421 bufferfont : getDisplayFont(pit, ii->pos);
422 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
423 ii->inset->metrics(mi, dim);
424 Dimension const old_dim = pm.insetDimension(ii->inset);
425 pm.setInsetDimension(ii->inset, dim);
426 changed |= (old_dim != dim);
429 Cursor const & cur = bv_->cursor();
430 DocIterator sel_beg = cur.selectionBegin();
431 DocIterator sel_end = cur.selectionEnd();
432 bool selection = cur.selection()
434 && cur.text() == text_
435 // if the anchor is outside, this is not our selection
436 && cur.anchor().text() == text_
437 && pit >= sel_beg.pit() && pit <= sel_end.pit();
439 // We care only about visible selection.
441 if (pit != sel_beg.pit()) {
445 if (pit != sel_end.pit()) {
447 sel_end.pos() = sel_end.lastpos();
451 par.setBeginOfBody();
453 size_t row_index = 0;
454 // maximum pixel width of a row
455 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
458 pos_type end = rowBreakPoint(width, pit, first);
459 if (row_index || end < par.size())
460 // If there is more than one row, expand the text to
461 // the full allowable width. This setting here is needed
462 // for the computeRowMetrics() below.
463 dim_.wid = max_width_;
465 dim = rowHeight(pit, first, end);
466 dim.wid = rowWidth(right_margin, pit, first, end);
467 if (row_index == pm.rows().size())
468 pm.rows().push_back(Row());
469 Row & row = pm.rows()[row_index];
470 row.setChanged(false);
474 row.setSelection(sel_beg.pos(), sel_end.pos());
476 row.setSelection(-1, -1);
477 row.setDimension(dim);
478 int const max_row_width = max(dim_.wid, dim.wid);
479 computeRowMetrics(pit, row, max_row_width);
480 pm.computeRowSignature(row, bparams);
484 pm.dim().wid = std::max(pm.dim().wid, dim.wid);
485 pm.dim().des += dim.height();
486 } while (first < par.size());
488 if (row_index < pm.rows().size())
489 pm.rows().resize(row_index);
491 // Make sure that if a par ends in newline, there is one more row
493 if (first > 0 && par.isNewline(first - 1)) {
494 Dimension dim = rowHeight(pit, first, first);
495 dim.wid = rowWidth(right_margin, pit, first, first);
496 if (row_index == pm.rows().size())
497 pm.rows().push_back(Row());
498 Row & row = pm.rows()[row_index];
499 row.setChanged(false);
502 row.setDimension(dim);
503 int const max_row_width = max(dim_.wid, dim.wid);
504 computeRowMetrics(pit, row, max_row_width);
505 pm.computeRowSignature(row, bparams);
506 pm.dim().des += dim.height();
509 pm.dim().asc += pm.rows()[0].ascent();
510 pm.dim().des -= pm.rows()[0].ascent();
512 changed |= old_dim.height() != pm.dim().height();
518 void TextMetrics::computeRowMetrics(pit_type const pit,
519 Row & row, int width) const
526 Buffer & buffer = bv_->buffer();
527 Paragraph const & par = text_->getPar(pit);
529 double w = width - row.width();
530 // FIXME: put back this assertion when the crash on new doc is solved.
531 //BOOST_ASSERT(w >= 0);
533 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
534 //lyxerr << "row.width() " << row.width() << endl;
535 //lyxerr << "w " << w << endl;
537 bool const is_rtl = text_->isRTL(buffer, par);
539 row.x = rightMargin(pit);
541 row.x = leftMargin(max_width_, pit, row.pos());
543 // is there a manual margin with a manual label
544 LayoutPtr const & layout = par.layout();
546 if (layout->margintype == MARGIN_MANUAL
547 && layout->labeltype == LABEL_MANUAL) {
548 /// We might have real hfills in the label part
549 int nlh = numberOfLabelHfills(par, row);
551 // A manual label par (e.g. List) has an auto-hfill
552 // between the label text and the body of the
554 // But we don't want to do this auto hfill if the par
559 if (nlh && !par.getLabelWidthString().empty())
560 row.label_hfill = labelFill(pit, row) / double(nlh);
563 // are there any hfills in the row?
564 int const nh = numberOfHfills(par, row);
569 // we don't have to look at the alignment if it is ALIGN_LEFT and
570 // if the row is already larger then the permitted width as then
571 // we force the LEFT_ALIGN'edness!
572 } else if (int(row.width()) < max_width_) {
573 // is it block, flushleft or flushright?
574 // set x how you need it
576 if (par.params().align() == LYX_ALIGN_LAYOUT)
577 align = layout->align;
579 align = par.params().align();
581 // Display-style insets should always be on a centred row
582 // The test on par.size() is to catch zero-size pars, which
583 // would trigger the assert in Paragraph::getInset().
584 //inset = par.size() ? par.getInset(row.pos()) : 0;
585 if (row.pos() < par.size() && par.isInset(row.pos())) {
586 switch(par.getInset(row.pos())->display()) {
587 case Inset::AlignLeft:
588 align = LYX_ALIGN_BLOCK;
590 case Inset::AlignCenter:
591 align = LYX_ALIGN_CENTER;
594 case Inset::AlignRight:
595 // unchanged (use align)
601 case LYX_ALIGN_BLOCK: {
602 int const ns = numberOfSeparators(par, row);
603 bool disp_inset = false;
604 if (row.endpos() < par.size()) {
605 Inset const * in = par.getInset(row.endpos());
607 disp_inset = in->display();
609 // If we have separators, this is not the last row of a
610 // par, does not end in newline, and is not row above a
611 // display inset... then stretch it
613 && row.endpos() < par.size()
614 && !par.isNewline(row.endpos() - 1)
617 row.separator = w / ns;
618 //lyxerr << "row.separator " << row.separator << endl;
619 //lyxerr << "ns " << ns << endl;
625 case LYX_ALIGN_RIGHT:
628 case LYX_ALIGN_CENTER:
635 pos_type body_pos = par.beginOfBody();
636 pos_type end = row.endpos();
639 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
641 row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
642 width(layout->labelsep);
644 row.x += row.label_hfill;
650 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
652 Buffer & buffer = bv_->buffer();
653 Paragraph const & par = text_->getPar(pit);
655 pos_type last = par.beginOfBody();
656 BOOST_ASSERT(last > 0);
658 // -1 because a label ends with a space that is in the label
661 // a separator at this end does not count
662 if (par.isLineSeparator(last))
666 for (pos_type i = row.pos(); i <= last; ++i)
667 w += singleWidth(pit, i);
669 docstring const & label = par.params().labelWidthString();
673 FontMetrics const & fm
674 = theFontMetrics(text_->getLabelFont(buffer, par));
676 return max(0, fm.width(label) - w);
680 // this needs special handling - only newlines count as a break point
681 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
683 pos_type const end = par.size();
686 if (par.isNewline(i))
693 int TextMetrics::labelEnd(pit_type const pit) const
695 // labelEnd is only needed if the layout fills a flushleft label.
696 if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
698 // return the beginning of the body
699 return leftMargin(max_width_, pit);
703 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
706 Buffer & buffer = bv_->buffer();
707 ParagraphMetrics const & pm = par_metrics_[pit];
708 Paragraph const & par = text_->getPar(pit);
709 pos_type const end = par.size();
710 if (pos == end || width < 0)
713 LayoutPtr const & layout = par.layout();
715 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
716 return addressBreakPoint(pos, par);
718 pos_type const body_pos = par.beginOfBody();
721 // Now we iterate through until we reach the right margin
722 // or the end of the par, then choose the possible break
725 int label_end = labelEnd(pit);
726 int const left = leftMargin(max_width_, pit, pos);
729 // pixel width since last breakpoint
732 FontIterator fi = FontIterator(*this, par, pit, pos);
733 pos_type point = end;
735 for ( ; i < end; ++i, ++fi) {
736 int thiswidth = pm.singleWidth(i, *fi);
738 // add the auto-hfill from label end to the body
739 if (body_pos && i == body_pos) {
740 FontMetrics const & fm = theFontMetrics(
741 text_->getLabelFont(buffer, par));
742 int add = fm.width(layout->labelsep);
743 if (par.isLineSeparator(i - 1))
744 add -= singleWidth(pit, i - 1);
746 add = std::max(add, label_end - x);
751 chunkwidth += thiswidth;
753 // break before a character that will fall off
754 // the right of the row
756 // if no break before, break here
757 if (point == end || chunkwidth >= width - left) {
763 // exit on last registered breakpoint:
767 if (par.isNewline(i)) {
773 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
778 if (par.isInset(i) && par.getInset(i)->display()) {
784 if (!par.isInset(i) || par.getInset(i)->isChar()) {
785 // some insets are line separators too
786 if (par.isLineSeparator(i)) {
787 // register breakpoint:
794 // maybe found one, but the par is short enough.
795 if (i == end && x < width)
798 // manual labels cannot be broken in LaTeX. But we
799 // want to make our on-screen rendering of footnotes
801 if (body_pos && point < body_pos)
808 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
809 pos_type const first, pos_type const end) const
811 Buffer & buffer = bv_->buffer();
812 // get the pure distance
813 ParagraphMetrics const & pm = par_metrics_[pit];
814 Paragraph const & par = text_->getPar(pit);
815 int w = leftMargin(max_width_, pit, first);
816 int label_end = labelEnd(pit);
818 pos_type const body_pos = par.beginOfBody();
822 FontIterator fi = FontIterator(*this, par, pit, i);
823 for ( ; i < end; ++i, ++fi) {
824 if (body_pos > 0 && i == body_pos) {
825 FontMetrics const & fm = theFontMetrics(
826 text_->getLabelFont(buffer, par));
827 w += fm.width(par.layout()->labelsep);
828 if (par.isLineSeparator(i - 1))
829 w -= singleWidth(pit, i - 1);
830 w = max(w, label_end);
832 w += pm.singleWidth(i, *fi);
836 if (body_pos > 0 && body_pos >= end) {
837 FontMetrics const & fm = theFontMetrics(
838 text_->getLabelFont(buffer, par));
839 w += fm.width(par.layout()->labelsep);
840 if (end > 0 && par.isLineSeparator(end - 1))
841 w -= singleWidth(pit, end - 1);
842 w = max(w, label_end);
845 return w + right_margin;
849 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
850 pos_type const end) const
852 Paragraph const & par = text_->getPar(pit);
853 // get the maximum ascent and the maximum descent
854 double layoutasc = 0;
855 double layoutdesc = 0;
856 double const dh = defaultRowHeight();
858 // ok, let us initialize the maxasc and maxdesc value.
859 // Only the fontsize count. The other properties
860 // are taken from the layoutfont. Nicer on the screen :)
861 LayoutPtr const & layout = par.layout();
863 // as max get the first character of this row then it can
864 // increase but not decrease the height. Just some point to
865 // start with so we don't have to do the assignment below too
867 Buffer const & buffer = bv_->buffer();
868 Font font = getDisplayFont(pit, first);
869 FontSize const tmpsize = font.fontInfo().size();
870 font.fontInfo() = text_->getLayoutFont(buffer, pit);
871 FontSize const size = font.fontInfo().size();
872 font.fontInfo().setSize(tmpsize);
874 FontInfo labelfont = text_->getLabelFont(buffer, par);
876 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
877 FontMetrics const & fontmetrics = theFontMetrics(font);
879 // these are minimum values
880 double const spacing_val = layout->spacing.getValue()
881 * text_->spacing(buffer, par);
882 //lyxerr << "spacing_val = " << spacing_val << endl;
883 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
884 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
886 // insets may be taller
887 ParagraphMetrics const & pm = par_metrics_[pit];
888 InsetList::const_iterator ii = par.insetList().begin();
889 InsetList::const_iterator iend = par.insetList().end();
890 for ( ; ii != iend; ++ii) {
891 Dimension const & dim = pm.insetDimension(ii->inset);
892 if (ii->pos >= first && ii->pos < end) {
893 maxasc = max(maxasc, dim.ascent());
894 maxdesc = max(maxdesc, dim.descent());
898 // Check if any custom fonts are larger (Asger)
899 // This is not completely correct, but we can live with the small,
900 // cosmetic error for now.
904 par.highestFontInRange(first, end, size);
905 if (maxsize > font.fontInfo().size()) {
906 // use standard paragraph font with the maximal size
907 FontInfo maxfont = font.fontInfo();
908 maxfont.setSize(maxsize);
909 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
910 maxasc = max(maxasc, maxfontmetrics.maxAscent());
911 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
914 // This is nicer with box insets:
918 ParagraphList const & pars = text_->paragraphs();
922 BufferParams const & bufparams = buffer.params();
923 // some parskips VERY EASY IMPLEMENTATION
924 if (bufparams.paragraph_separation
925 == BufferParams::PARSEP_SKIP
926 && par.ownerCode() != ERT_CODE
927 && par.ownerCode() != LISTINGS_CODE
929 && ((layout->isParagraph() && par.getDepth() == 0)
930 || (pars[pit - 1].layout()->isParagraph()
931 && pars[pit - 1].getDepth() == 0)))
933 maxasc += bufparams.getDefSkip().inPixels(*bv_);
936 if (par.params().startOfAppendix())
937 maxasc += int(3 * dh);
939 // This is special code for the chapter, since the label of this
940 // layout is printed in an extra row
941 if (layout->counter == "chapter"
942 && !par.params().labelString().empty()) {
943 labeladdon = int(labelfont_metrics.maxHeight()
944 * layout->spacing.getValue()
945 * text_->spacing(buffer, par));
948 // special code for the top label
949 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
950 || layout->labeltype == LABEL_BIBLIO
951 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
952 && isFirstInSequence(pit, pars)
953 && !par.getLabelstring().empty())
956 labelfont_metrics.maxHeight()
957 * layout->spacing.getValue()
958 * text_->spacing(buffer, par)
959 + (layout->topsep + layout->labelbottomsep) * dh);
962 // Add the layout spaces, for example before and after
963 // a section, or between the items of a itemize or enumerate
966 pit_type prev = depthHook(pit, pars, par.getDepth());
967 Paragraph const & prevpar = pars[prev];
969 && prevpar.layout() == layout
970 && prevpar.getDepth() == par.getDepth()
971 && prevpar.getLabelWidthString()
972 == par.getLabelWidthString()) {
973 layoutasc = layout->itemsep * dh;
974 } else if (pit != 0 || first != 0) {
975 if (layout->topsep > 0)
976 layoutasc = layout->topsep * dh;
979 prev = outerHook(pit, pars);
980 if (prev != pit_type(pars.size())) {
981 maxasc += int(pars[prev].layout()->parsep * dh);
982 } else if (pit != 0) {
983 Paragraph const & prevpar = pars[pit - 1];
984 if (prevpar.getDepth() != 0 ||
985 prevpar.layout() == layout) {
986 maxasc += int(layout->parsep * dh);
991 // is it a bottom line?
992 if (end >= par.size()) {
993 // add the layout spaces, for example before and after
994 // a section, or between the items of a itemize or enumerate
996 pit_type nextpit = pit + 1;
997 if (nextpit != pit_type(pars.size())) {
1002 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1003 usual = pars[cpit].layout()->bottomsep * dh;
1004 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1005 if (pars[cpit].layout() != pars[nextpit].layout()
1006 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1008 unusual = pars[cpit].layout()->bottomsep * dh;
1010 layoutdesc = max(unusual, usual);
1011 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1012 if (pars[cpit].layout() != pars[nextpit].layout()
1013 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1014 layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
1019 // incalculate the layout spaces
1020 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1021 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1023 // FIXME: the correct way is to do the following is to move the
1024 // following code in another method specially tailored for the
1025 // main Text. The following test is thus bogus.
1026 // Top and bottom margin of the document (only at top-level)
1028 if (pit == 0 && first == 0)
1030 if (pit + 1 == pit_type(pars.size()) &&
1031 end == par.size() &&
1032 !(end > 0 && par.isNewline(end - 1)))
1036 return Dimension(0, maxasc + labeladdon, maxdesc);
1040 // x is an absolute screen coord
1041 // returns the column near the specified x-coordinate of the row
1042 // x is set to the real beginning of this column
1043 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1044 Row const & row, int & x, bool & boundary) const
1046 Buffer const & buffer = bv_->buffer();
1048 /// For the main Text, it is possible that this pit is not
1049 /// yet in the CoordCache when moving cursor up.
1050 /// x Paragraph coordinate is always 0 for main text anyway.
1051 int const xo = origin_.x_;
1053 Paragraph const & par = text_->getPar(pit);
1054 ParagraphMetrics const & pm = par_metrics_[pit];
1056 bidi.computeTables(par, buffer, row);
1058 pos_type vc = row.pos();
1059 pos_type end = row.endpos();
1061 LayoutPtr const & layout = par.layout();
1063 bool left_side = false;
1065 pos_type body_pos = par.beginOfBody();
1067 double tmpx = row.x;
1068 double last_tmpx = tmpx;
1071 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1074 // check for empty row
1080 while (vc < end && tmpx <= x) {
1081 c = bidi.vis2log(vc);
1083 if (body_pos > 0 && c == body_pos - 1) {
1084 FontMetrics const & fm = theFontMetrics(
1085 text_->getLabelFont(buffer, par));
1086 tmpx += row.label_hfill + fm.width(layout->labelsep);
1087 if (par.isLineSeparator(body_pos - 1))
1088 tmpx -= singleWidth(pit, body_pos - 1);
1091 if (pm.hfillExpansion(row, c)) {
1092 tmpx += singleWidth(pit, c);
1096 tmpx += row.label_hfill;
1097 } else if (par.isSeparator(c)) {
1098 tmpx += singleWidth(pit, c);
1100 tmpx += row.separator;
1102 tmpx += singleWidth(pit, c);
1107 if ((tmpx + last_tmpx) / 2 > x) {
1112 BOOST_ASSERT(vc <= end); // This shouldn't happen.
1115 // This (rtl_support test) is not needed, but gives
1116 // some speedup if rtl_support == false
1117 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1119 // If lastrow is false, we don't need to compute
1120 // the value of rtl.
1121 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1123 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1124 (!rtl && !left_side && vc == end && x > tmpx + 5)))
1126 else if (vc == row.pos()) {
1127 c = bidi.vis2log(vc);
1128 if (bidi.level(c) % 2 == 1)
1131 c = bidi.vis2log(vc - 1);
1132 bool const rtl = (bidi.level(c) % 2 == 1);
1133 if (left_side == rtl) {
1135 boundary = isRTLBoundary(pit, c);
1139 // I believe this code is not needed anymore (Jug 20050717)
1141 // The following code is necessary because the cursor position past
1142 // the last char in a row is logically equivalent to that before
1143 // the first char in the next row. That's why insets causing row
1144 // divisions -- Newline and display-style insets -- must be treated
1145 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1146 // Newline inset, air gap below:
1147 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1148 if (bidi.level(end -1) % 2 == 0)
1149 tmpx -= singleWidth(pit, end - 1);
1151 tmpx += singleWidth(pit, end - 1);
1155 // Air gap above display inset:
1156 if (row.pos() < end && c >= end && end < par.size()
1157 && par.isInset(end) && par.getInset(end)->display()) {
1160 // Air gap below display inset:
1161 if (row.pos() < end && c >= end && par.isInset(end - 1)
1162 && par.getInset(end - 1)->display()) {
1168 pos_type const col = c - row.pos();
1170 if (!c || end == par.size())
1173 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1178 return min(col, end - 1 - row.pos());
1182 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1184 // We play safe and use parMetrics(pit) to make sure the
1185 // ParagraphMetrics will be redone and OK to use if needed.
1186 // Otherwise we would use an empty ParagraphMetrics in
1187 // upDownInText() while in selection mode.
1188 ParagraphMetrics const & pm = parMetrics(pit);
1190 BOOST_ASSERT(row < int(pm.rows().size()));
1192 Row const & r = pm.rows()[row];
1193 return r.pos() + getColumnNearX(pit, r, x, bound);
1197 void TextMetrics::newParMetricsDown()
1199 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1200 pit_type const pit = last.first + 1;
1201 if (pit == int(text_->paragraphs().size()))
1204 // do it and update its position.
1206 par_metrics_[pit].setPosition(last.second.position()
1207 + last.second.descent());
1211 void TextMetrics::newParMetricsUp()
1213 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1214 if (first.first == 0)
1217 pit_type const pit = first.first - 1;
1218 // do it and update its position.
1220 par_metrics_[pit].setPosition(first.second.position()
1221 - first.second.ascent());
1224 // y is screen coordinate
1225 pit_type TextMetrics::getPitNearY(int y)
1227 BOOST_ASSERT(!text_->paragraphs().empty());
1228 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1229 << ": y: " << y << " cache size: " << par_metrics_.size());
1231 // look for highest numbered paragraph with y coordinate less than given y
1234 ParMetricsCache::const_iterator it = par_metrics_.begin();
1235 ParMetricsCache::const_iterator et = par_metrics_.end();
1236 ParMetricsCache::const_iterator last = et; last--;
1238 ParagraphMetrics const & pm = it->second;
1240 // If we are off-screen (before the visible part)
1242 // and even before the first paragraph in the cache.
1243 && y < it->second.position() - int(pm.ascent())) {
1244 // and we are not at the first paragraph in the inset.
1247 // then this is the paragraph we are looking for.
1248 pit = it->first - 1;
1249 // rebreak it and update the CoordCache.
1251 par_metrics_[pit].setPosition(it->second.position() - pm.descent());
1255 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1257 // If we are off-screen (after the visible part)
1258 if (y > bv_->workHeight()
1259 // and even after the first paragraph in the cache.
1260 && y >= last->second.position() + int(pm_last.descent())) {
1261 pit = last->first + 1;
1262 // and we are not at the last paragraph in the inset.
1263 if (pit == int(text_->paragraphs().size()))
1265 // then this is the paragraph we are looking for.
1266 // rebreak it and update the CoordCache.
1268 par_metrics_[pit].setPosition(last->second.position() + pm_last.ascent());
1272 for (; it != et; ++it) {
1273 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1274 << " examining: pit: " << it->first
1275 << " y: " << it->second.position());
1277 ParagraphMetrics const & pm = par_metrics_[it->first];
1279 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1281 yy = it->second.position();
1285 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1286 << ": found best y: " << yy << " for pit: " << pit);
1292 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1294 ParagraphMetrics const & pm = par_metrics_[pit];
1296 int yy = pm.position() - pm.ascent();
1297 BOOST_ASSERT(!pm.rows().empty());
1298 RowList::const_iterator rit = pm.rows().begin();
1299 RowList::const_iterator rlast = pm.rows().end();
1301 for (; rit != rlast; yy += rit->height(), ++rit)
1302 if (yy + rit->height() > y)
1308 // x,y are absolute screen coordinates
1309 // sets cursor recursively descending into nested editable insets
1310 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1312 if (lyxerr.debugging(Debug::WORKAREA)) {
1313 lyxerr << "TextMetrics::editXY(cur, " << x << ", " << y << ")" << std::endl;
1314 cur.bv().coordCache().dump();
1316 pit_type pit = getPitNearY(y);
1317 BOOST_ASSERT(pit != -1);
1319 Row const & row = getRowNearY(y, pit);
1322 int xx = x; // is modified by getColumnNearX
1323 pos_type const pos = row.pos()
1324 + getColumnNearX(pit, row, xx, bound);
1327 cur.boundary(bound);
1330 // try to descend into nested insets
1331 Inset * inset = checkInsetHit(x, y);
1332 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1334 // Either we deconst editXY or better we move current_font
1335 // and real_current_font to Cursor
1336 // FIXME: what is needed now that current_font and real_current_font
1338 cur.setCurrentFont();
1342 ParagraphList const & pars = text_->paragraphs();
1343 Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1344 //Inset * insetBehind = pars[pit].getInset(pos);
1346 // This should be just before or just behind the
1347 // cursor position set above.
1348 BOOST_ASSERT((pos != 0 && inset == insetBefore)
1349 || inset == pars[pit].getInset(pos));
1351 // Make sure the cursor points to the position before
1353 if (inset == insetBefore) {
1355 cur.boundary(false);
1358 // Try to descend recursively inside the inset.
1359 inset = inset->editXY(cur, x, y);
1361 if (cur.top().text() == text_)
1362 cur.setCurrentFont();
1367 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1369 BOOST_ASSERT(text_ == cur.text());
1370 pit_type pit = getPitNearY(y);
1372 ParagraphMetrics const & pm = par_metrics_[pit];
1374 int yy = pm.position() - pm.ascent();
1375 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1376 << ": x: " << x << " y: " << y << " pit: " << pit << " yy: " << yy);
1379 BOOST_ASSERT(pm.rows().size());
1380 for (; r < int(pm.rows().size()) - 1; ++r) {
1381 Row const & row = pm.rows()[r];
1382 if (int(yy + row.height()) > y)
1387 Row const & row = pm.rows()[r];
1389 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1390 << ": row " << r << " from pos: " << row.pos());
1394 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1396 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1397 << ": setting cursor pit: " << pit << " pos: " << pos);
1399 text_->setCursor(cur, pit, pos, true, bound);
1400 // remember new position.
1405 //takes screen x,y coordinates
1406 Inset * TextMetrics::checkInsetHit(int x, int y)
1408 pit_type pit = getPitNearY(y);
1409 BOOST_ASSERT(pit != -1);
1411 Paragraph const & par = text_->paragraphs()[pit];
1412 ParagraphMetrics const & pm = par_metrics_[pit];
1414 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1415 << ": x: " << x << " y: " << y << " pit: " << pit);
1417 InsetList::const_iterator iit = par.insetList().begin();
1418 InsetList::const_iterator iend = par.insetList().end();
1419 for (; iit != iend; ++iit) {
1420 Inset * inset = iit->inset;
1422 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1423 << ": examining inset " << inset);
1425 if (!bv_->coordCache().getInsets().has(inset)) {
1426 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1427 << ": inset has no cached position");
1431 Dimension const & dim = pm.insetDimension(inset);
1432 Point p = bv_->coordCache().getInsets().xy(inset);
1434 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1435 << ": xo: " << p.x_ << "..." << p.x_ + dim.wid
1436 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1439 && x <= p.x_ + dim.wid
1440 && y >= p.y_ - dim.asc
1441 && y <= p.y_ + dim.des) {
1442 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
1443 << ": Hit inset: " << inset);
1448 LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION << ": No inset hit. ");
1453 int TextMetrics::cursorX(CursorSlice const & sl,
1454 bool boundary) const
1456 BOOST_ASSERT(sl.text() == text_);
1457 pit_type const pit = sl.pit();
1458 Paragraph const & par = text_->paragraphs()[pit];
1459 ParagraphMetrics const & pm = par_metrics_[pit];
1460 if (pm.rows().empty())
1463 pos_type ppos = sl.pos();
1464 // Correct position in front of big insets
1465 bool const boundary_correction = ppos != 0 && boundary;
1466 if (boundary_correction)
1469 Row const & row = pm.getRow(sl.pos(), boundary);
1471 pos_type cursor_vpos = 0;
1473 Buffer const & buffer = bv_->buffer();
1476 bidi.computeTables(par, buffer, row);
1478 pos_type const row_pos = row.pos();
1479 pos_type const end = row.endpos();
1480 // Spaces at logical line breaks in bidi text must be skipped during
1481 // cursor positioning. However, they may appear visually in the middle
1482 // of a row; they must be skipped, wherever they are...
1483 // * logically "abc_[HEBREW_\nHEBREW]"
1484 // * visually "abc_[_WERBEH\nWERBEH]"
1485 pos_type skipped_sep_vpos = -1;
1488 cursor_vpos = row_pos;
1489 else if (ppos >= end)
1490 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1491 else if (ppos > row_pos && ppos >= end)
1492 // Place cursor after char at (logical) position pos - 1
1493 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1494 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1496 // Place cursor before char at (logical) position ppos
1497 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1498 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1500 pos_type body_pos = par.beginOfBody();
1502 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1505 // Use font span to speed things up, see below
1509 // If the last logical character is a separator, skip it, unless
1510 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1511 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1512 skipped_sep_vpos = bidi.log2vis(end - 1);
1514 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1515 // Skip the separator which is at the logical end of the row
1516 if (vpos == skipped_sep_vpos)
1518 pos_type pos = bidi.vis2log(vpos);
1519 if (body_pos > 0 && pos == body_pos - 1) {
1520 FontMetrics const & labelfm = theFontMetrics(
1521 text_->getLabelFont(buffer, par));
1522 x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1523 if (par.isLineSeparator(body_pos - 1))
1524 x -= singleWidth(pit, body_pos - 1);
1527 // Use font span to speed things up, see above
1528 if (pos < font_span.first || pos > font_span.last) {
1529 font_span = par.fontSpan(pos);
1530 font = getDisplayFont(pit, pos);
1533 x += pm.singleWidth(pos, font);
1535 if (pm.hfillExpansion(row, pos))
1536 x += (pos >= body_pos) ? row.hfill : row.label_hfill;
1537 else if (par.isSeparator(pos) && pos >= body_pos)
1541 // see correction above
1542 if (boundary_correction) {
1543 if (isRTL(sl, boundary))
1544 x -= singleWidth(pit, ppos);
1546 x += singleWidth(pit, ppos);
1553 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1555 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << std::endl;
1556 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1557 if (pm.rows().empty())
1561 h -= par_metrics_[0].rows()[0].ascent();
1562 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1563 h += par_metrics_[pit].height();
1566 if (pos && boundary)
1568 size_t const rend = pm.pos2row(pos);
1569 for (size_t rit = 0; rit != rend; ++rit)
1570 h += pm.rows()[rit].height();
1571 h += pm.rows()[rend].ascent();
1576 void TextMetrics::cursorPrevious(Cursor & cur)
1578 pos_type cpos = cur.pos();
1579 pit_type cpar = cur.pit();
1581 int x = cur.x_target();
1582 setCursorFromCoordinates(cur, x, 0);
1583 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1585 if (cpar == cur.pit() && cpos == cur.pos())
1586 // we have a row which is taller than the workarea. The
1587 // simplest solution is to move to the previous row instead.
1588 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1591 cur.updateFlags(Update::Force | Update::FitCursor);
1595 void TextMetrics::cursorNext(Cursor & cur)
1597 pos_type cpos = cur.pos();
1598 pit_type cpar = cur.pit();
1600 int x = cur.x_target();
1601 setCursorFromCoordinates(cur, x, cur.bv().workHeight() - 1);
1602 cur.dispatch(FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1604 if (cpar == cur.pit() && cpos == cur.pos())
1605 // we have a row which is taller than the workarea. The
1606 // simplest solution is to move to the next row instead.
1608 FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1611 cur.updateFlags(Update::Force | Update::FitCursor);
1615 // the cursor set functions have a special mechanism. When they
1616 // realize you left an empty paragraph, they will delete it.
1618 bool TextMetrics::cursorHome(Cursor & cur)
1620 BOOST_ASSERT(text_ == cur.text());
1621 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1622 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1623 return text_->setCursor(cur, cur.pit(), row.pos());
1627 bool TextMetrics::cursorEnd(Cursor & cur)
1629 BOOST_ASSERT(text_ == cur.text());
1630 // if not on the last row of the par, put the cursor before
1631 // the final space exept if I have a spanning inset or one string
1632 // is so long that we force a break.
1633 pos_type end = cur.textRow().endpos();
1635 // empty text, end-1 is no valid position
1637 bool boundary = false;
1638 if (end != cur.lastpos()) {
1639 if (!cur.paragraph().isLineSeparator(end-1)
1640 && !cur.paragraph().isNewline(end-1))
1645 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1649 void TextMetrics::deleteLineForward(Cursor & cur)
1651 BOOST_ASSERT(text_ == cur.text());
1652 if (cur.lastpos() == 0) {
1653 // Paragraph is empty, so we just go forward
1654 text_->cursorForward(cur);
1657 cur.selection() = true; // to avoid deletion
1660 // What is this test for ??? (JMarc)
1661 if (!cur.selection())
1662 text_->deleteWordForward(cur);
1664 cap::cutSelection(cur, true, false);
1665 checkBufferStructure(cur.buffer(), cur);
1670 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1672 ParagraphList const & pars = text_->paragraphs();
1673 return row.endpos() >= pars[pit].size()
1674 && pit + 1 == pit_type(pars.size());
1678 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1680 return row.pos() == 0 && pit == 0;
1684 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1686 BOOST_ASSERT(pit >= 0);
1687 BOOST_ASSERT(pit < int(text_->paragraphs().size()));
1688 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1692 int TextMetrics::leftMargin(int max_width,
1693 pit_type const pit, pos_type const pos) const
1695 ParagraphList const & pars = text_->paragraphs();
1697 BOOST_ASSERT(pit >= 0);
1698 BOOST_ASSERT(pit < int(pars.size()));
1699 Paragraph const & par = pars[pit];
1700 BOOST_ASSERT(pos >= 0);
1701 BOOST_ASSERT(pos <= par.size());
1702 Buffer const & buffer = bv_->buffer();
1703 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1704 TextClass const & tclass = buffer.params().getTextClass();
1705 LayoutPtr const & layout = par.layout();
1707 docstring parindent = layout->parindent;
1711 if (text_->isMainText(buffer))
1712 l_margin += changebarMargin();
1714 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1715 tclass.leftmargin());
1717 if (par.getDepth() != 0) {
1718 // find the next level paragraph
1719 pit_type newpar = outerHook(pit, pars);
1720 if (newpar != pit_type(pars.size())) {
1721 if (pars[newpar].layout()->isEnvironment()) {
1722 l_margin = leftMargin(max_width, newpar);
1724 if (par.layout() == tclass.defaultLayout()) {
1725 if (pars[newpar].params().noindent())
1728 parindent = pars[newpar].layout()->parindent;
1733 // This happens after sections in standard classes. The 1.3.x
1734 // code compared depths too, but it does not seem necessary
1736 if (par.layout() == tclass.defaultLayout()
1737 && pit > 0 && pars[pit - 1].layout()->nextnoindent)
1740 FontInfo const labelfont = text_->getLabelFont(buffer, par);
1741 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1743 switch (layout->margintype) {
1744 case MARGIN_DYNAMIC:
1745 if (!layout->leftmargin.empty()) {
1746 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1747 layout->leftmargin);
1749 if (!par.getLabelstring().empty()) {
1750 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1751 l_margin += labelfont_metrics.width(par.getLabelstring());
1752 l_margin += labelfont_metrics.width(layout->labelsep);
1756 case MARGIN_MANUAL: {
1757 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1758 // The width of an empty par, even with manual label, should be 0
1759 if (!par.empty() && pos >= par.beginOfBody()) {
1760 if (!par.getLabelWidthString().empty()) {
1761 docstring labstr = par.getLabelWidthString();
1762 l_margin += labelfont_metrics.width(labstr);
1763 l_margin += labelfont_metrics.width(layout->labelsep);
1769 case MARGIN_STATIC: {
1770 l_margin += theFontMetrics(buffer.params().getFont()).
1771 signedWidth(layout->leftmargin) * 4 / (par.getDepth() + 4);
1775 case MARGIN_FIRST_DYNAMIC:
1776 if (layout->labeltype == LABEL_MANUAL) {
1777 if (pos >= par.beginOfBody()) {
1778 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1780 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1783 // Special case to fix problems with
1785 || (layout->labeltype == LABEL_STATIC
1786 && layout->latextype == LATEX_ENVIRONMENT
1787 && !isFirstInSequence(pit, pars))) {
1788 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1789 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
1790 && layout->labeltype != LABEL_BIBLIO
1791 && layout->labeltype !=
1792 LABEL_CENTERED_TOP_ENVIRONMENT) {
1793 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1794 l_margin += labelfont_metrics.width(layout->labelsep);
1795 l_margin += labelfont_metrics.width(par.getLabelstring());
1799 case MARGIN_RIGHT_ADDRESS_BOX: {
1801 // ok, a terrible hack. The left margin depends on the widest
1802 // row in this paragraph.
1803 RowList::iterator rit = par.rows().begin();
1804 RowList::iterator end = par.rows().end();
1805 // FIXME: This is wrong.
1806 int minfill = max_width;
1807 for ( ; rit != end; ++rit)
1808 if (rit->fill() < minfill)
1809 minfill = rit->fill();
1810 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
1811 l_margin += minfill;
1813 // also wrong, but much shorter.
1814 l_margin += max_width / 2;
1819 if (!par.params().leftIndent().zero())
1820 l_margin += par.params().leftIndent().inPixels(max_width);
1824 if (par.params().align() == LYX_ALIGN_LAYOUT)
1825 align = layout->align;
1827 align = par.params().align();
1829 // set the correct parindent
1831 && (layout->labeltype == LABEL_NO_LABEL
1832 || layout->labeltype == LABEL_TOP_ENVIRONMENT
1833 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1834 || (layout->labeltype == LABEL_STATIC
1835 && layout->latextype == LATEX_ENVIRONMENT
1836 && !isFirstInSequence(pit, pars)))
1837 && align == LYX_ALIGN_BLOCK
1838 && !par.params().noindent()
1839 // in some insets, paragraphs are never indented
1840 && !(par.inInset() && par.inInset()->neverIndent(buffer))
1841 // display style insets are always centered, omit indentation
1844 && par.getInset(pos)->display())
1845 && (par.layout() != tclass.defaultLayout()
1846 || buffer.params().paragraph_separation ==
1847 BufferParams::PARSEP_INDENT))
1849 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1857 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1859 ParagraphMetrics const & pm = par_metrics_[pit];
1861 return pm.singleWidth(pos, getDisplayFont(pit, pos));
1865 // only used for inset right now. should also be used for main text
1866 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1868 if (par_metrics_.empty())
1874 ParMetricsCache::iterator it = par_metrics_.begin();
1875 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1876 y -= it->second.ascent();
1877 for (; it != pm_end; ++it) {
1878 ParagraphMetrics const & pmi = it->second;
1880 pit_type const pit = it->first;
1881 // Save the paragraph position in the cache.
1882 it->second.setPosition(y);
1883 drawParagraph(pi, pit, x, y);
1889 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1891 ParagraphMetrics const & pm = par_metrics_[pit];
1892 if (pm.rows().empty())
1896 bool const original_drawing_state = pi.pain.isDrawingEnabled();
1897 int const ww = bv_->workHeight();
1898 size_t const nrows = pm.rows().size();
1900 for (size_t i = 0; i != nrows; ++i) {
1902 Row const & row = pm.rows()[i];
1906 bool const inside = (y + row.descent() >= 0
1907 && y - row.ascent() < ww);
1908 // It is not needed to draw on screen if we are not inside.
1909 pi.pain.setDrawingEnabled(inside && original_drawing_state);
1910 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
1912 // Row signature; has row changed since last paint?
1913 bool row_has_changed = row.changed();
1915 bool row_selection = row.sel_beg != -1 && row.sel_end != -1;
1917 if (!row_selection && !pi.full_repaint && !row_has_changed) {
1918 // Paint the only the insets if the text itself is
1920 rp.paintOnlyInsets();
1925 // Paint the row if a full repaint has been requested or it has
1927 // Clear background of this row
1928 // (if paragraph background was not cleared)
1929 if (row_selection || (!pi.full_repaint && row_has_changed)) {
1930 pi.pain.fillRectangle(x, y - row.ascent(),
1931 width(), row.height(), pi.background_color);
1933 if (row_selection) {
1934 DocIterator beg = bv_->cursor().selectionBegin();
1935 DocIterator end = bv_->cursor().selectionEnd();
1936 bool const beg_margin = beg.pit() < pit && i == 0;
1937 bool const end_margin = end.pit() > pit && i == nrows - 1;
1939 beg.pos() = row.sel_beg;
1941 end.pos() = row.sel_end;
1942 drawRowSelection(pi, x, row, beg, end, beg_margin, end_margin);
1945 // Instrumentation for testing row cache (see also
1947 if (lyxerr.debugging(Debug::PAINTING)) {
1948 if (text_->isMainText(bv_->buffer()))
1949 LYXERR(Debug::PAINTING, "\n{" << inside <<
1950 pi.full_repaint << row_has_changed << "}");
1952 LYXERR(Debug::PAINTING, "[" << inside <<
1953 pi.full_repaint << row_has_changed << "]");
1956 // Backup full_repaint status and force full repaint
1957 // for inner insets as the Row has been cleared out.
1958 bool tmp = pi.full_repaint;
1959 pi.full_repaint = true;
1962 rp.paintChangeBar();
1969 // Restore full_repaint status.
1970 pi.full_repaint = tmp;
1972 // Re-enable screen drawing for future use of the painter.
1973 pi.pain.setDrawingEnabled(original_drawing_state);
1975 //LYXERR(Debug::PAINTING) << "." << endl;
1979 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
1980 DocIterator const & beg, DocIterator const & end,
1981 bool drawOnBegMargin, bool drawOnEndMargin) const
1983 Buffer & buffer = bv_->buffer();
1984 DocIterator cur = beg;
1985 int x1 = cursorX(beg.top(), beg.boundary());
1986 int x2 = cursorX(end.top(), end.boundary());
1987 int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
1988 int y2 = y1 + row.height();
1991 if (drawOnBegMargin) {
1992 if (text_->isRTL(buffer, beg.paragraph()))
1993 pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color_selection);
1995 pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color_selection);
1998 if (drawOnEndMargin) {
1999 if (text_->isRTL(buffer, beg.paragraph()))
2000 pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color_selection);
2002 pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color_selection);
2005 // if we are on a boundary from the beginning, it's probably
2006 // a RTL boundary and we jump to the other side directly as this
2007 // segement is 0-size and confuses the logic below
2009 cur.boundary(false);
2011 // go through row and draw from RTL boundary to RTL boundary
2013 bool drawNow = false;
2015 // simplified cursorForward code below which does not
2016 // descend into insets and which does not go into the
2017 // next line. Compare the logic with the original cursorForward
2019 // if left of boundary -> just jump to right side
2020 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2021 if (cur.boundary()) {
2022 cur.boundary(false);
2023 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2024 // in front of RTL boundary -> Stay on this side of the boundary because:
2025 // ab|cDDEEFFghi -> abc|DDEEFFghi
2034 if (cur.pos() == row.endpos())
2039 // the previous segment was just drawn, now the next starts
2040 x1 = cursorX(cur.top(), cur.boundary());
2043 if (!(cur < end) || drawNow) {
2044 x2 = cursorX(cur.top(), cur.boundary());
2045 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2048 // reset x1, so it is set again next round (which will be on the
2049 // right side of a boundary or at the selection end)
2055 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2057 // ParagraphMetrics const & pm = par_metrics_[pit];
2058 // Row const & r = pm.rows()[row];
2064 int defaultRowHeight()
2066 return int(theFontMetrics(sane_font).maxHeight() * 1.2);