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"
28 #include "CutAndPaste.h"
30 #include "FontIterator.h"
31 #include "FuncRequest.h"
32 #include "InsetList.h"
36 #include "MetricsInfo.h"
37 #include "paragraph_funcs.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
40 #include "rowpainter.h"
44 #include "mathed/MacroTable.h"
45 #include "mathed/MathMacroTemplate.h"
47 #include "frontends/FontMetrics.h"
48 #include "frontends/Painter.h"
50 #include <boost/current_function.hpp>
60 using frontend::FontMetrics;
64 int numberOfSeparators(Paragraph const & par, Row const & row)
66 pos_type const first = max(row.pos(), par.beginOfBody());
67 pos_type const last = row.endpos() - 1;
69 for (pos_type p = first; p < last; ++p) {
70 if (par.isSeparator(p))
77 int numberOfLabelHfills(Paragraph const & par, Row const & row)
79 pos_type last = row.endpos() - 1;
80 pos_type first = row.pos();
82 // hfill *DO* count at the beginning of paragraphs!
84 while (first < last && par.isHfill(first))
88 last = min(last, par.beginOfBody());
90 for (pos_type p = first; p < last; ++p) {
98 int numberOfHfills(Paragraph const & par, Row const & row)
100 pos_type const last = row.endpos();
101 pos_type first = row.pos();
103 // hfill *DO* count at the beginning of paragraphs!
105 while (first < last && par.isHfill(first))
109 first = max(first, par.beginOfBody());
112 for (pos_type p = first; p < last; ++p) {
121 TextMetrics::TextMetrics(BufferView * bv, Text * text)
122 : bv_(bv), text_(text)
125 max_width_ = bv_->workWidth();
126 dim_.wid = max_width_;
130 //text_->updateLabels(bv->buffer());
134 bool TextMetrics::has(pit_type pit) const
136 return par_metrics_.find(pit) != par_metrics_.end();
140 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
142 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
147 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
149 ParMetricsCache::const_iterator it = par_metrics_.begin();
150 return make_pair(it->first, &it->second);
154 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
156 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
157 return make_pair(it->first, &it->second);
161 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
163 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
164 if (pmc_it == par_metrics_.end()) {
165 pmc_it = par_metrics_.insert(
166 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
168 if (pmc_it->second.rows().empty() && redo)
170 return pmc_it->second;
174 int TextMetrics::parPosition(pit_type pit) const
176 if (pit < par_metrics_.begin()->first)
178 if (pit > par_metrics_.rbegin()->first)
181 return par_metrics_[pit].position();
185 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
187 BOOST_ASSERT(mi.base.textwidth);
188 max_width_ = mi.base.textwidth;
189 // backup old dimension.
190 Dimension const old_dim = dim_;
193 dim_.wid = min_width;
194 pit_type const npar = text_->paragraphs().size();
196 // If there is more than one row, expand the text to
197 // the full allowable width.
198 dim_.wid = max_width_;
200 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
201 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
203 bool changed = false;
205 for (pit_type pit = 0; pit != npar; ++pit) {
206 changed |= redoParagraph(pit);
207 ParagraphMetrics const & pm = par_metrics_[pit];
209 if (dim_.wid < pm.width())
210 dim_.wid = pm.width();
213 dim_.asc = par_metrics_[0].ascent();
214 dim_.des = h - dim_.asc;
215 //lyxerr << "dim_.wid " << dim_.wid << endl;
216 //lyxerr << "dim_.asc " << dim_.asc << endl;
217 //lyxerr << "dim_.des " << dim_.des << endl;
219 changed |= dim_ != old_dim;
225 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
227 return main_text_? pm.rightMargin(bv_->buffer()) : 0;
231 int TextMetrics::rightMargin(pit_type const pit) const
233 return main_text_? par_metrics_[pit].rightMargin(bv_->buffer()) : 0;
237 void TextMetrics::applyOuterFont(Font & font) const
240 lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
241 lf.fontInfo().realize(font.fontInfo());
242 lf.setLanguage(font.language());
247 Font TextMetrics::getDisplayFont(pit_type pit, pos_type pos) const
249 BOOST_ASSERT(pos >= 0);
251 ParagraphList const & pars = text_->paragraphs();
252 Paragraph const & par = pars[pit];
253 LayoutPtr const & layout = par.layout();
254 Buffer const & buffer = bv_->buffer();
256 BufferParams const & params = buffer.params();
257 pos_type const body_pos = par.beginOfBody();
259 // We specialize the 95% common case:
260 if (!par.getDepth()) {
261 Font f = par.getFontSettings(params, pos);
262 if (!text_->isMainText(buffer))
264 bool lab = layout->labeltype == LABEL_MANUAL && pos < body_pos;
266 FontInfo const & lf = lab ? layout->labelfont : layout->font;
267 FontInfo rlf = lab ? layout->reslabelfont : layout->resfont;
269 // In case the default family has been customized
270 if (lf.family() == INHERIT_FAMILY)
271 rlf.setFamily(params.getFont().fontInfo().family());
272 f.fontInfo().realize(rlf);
276 // The uncommon case need not be optimized as much
277 FontInfo const & layoutfont = pos < body_pos ?
278 layout->labelfont : layout->font;
280 Font font = par.getFontSettings(params, pos);
281 font.fontInfo().realize(layoutfont);
283 if (!text_->isMainText(buffer))
284 applyOuterFont(font);
286 // Realize against environment font information
287 // NOTE: the cast to pit_type should be removed when pit_type
288 // changes to a unsigned integer.
289 if (pit < pit_type(pars.size()))
290 font.fontInfo().realize(outerFont(pit, pars).fontInfo());
292 // Realize with the fonts of lesser depth.
293 font.fontInfo().realize(params.getFont().fontInfo());
299 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
301 if (!lyxrc.rtl_support || !sl.text())
305 if (boundary && sl.pos() > 0)
308 return getDisplayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
312 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
314 if (!lyxrc.rtl_support)
317 // no RTL boundary at line start
321 Paragraph const & par = text_->getPar(pit);
323 bool left = getDisplayFont(pit, pos - 1).isVisibleRightToLeft();
325 if (pos == par.size())
326 right = par.isRTL(bv_->buffer().params());
328 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
329 return left != right;
333 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
334 Font const & font) const
336 if (!lyxrc.rtl_support)
339 Paragraph const & par = text_->getPar(pit);
340 bool left = font.isVisibleRightToLeft();
342 if (pos == par.size())
343 right = par.isRTL(bv_->buffer().params());
345 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
346 return left != right;
350 bool TextMetrics::redoParagraph(pit_type const pit)
352 Paragraph & par = text_->getPar(pit);
353 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
354 // redoParagraph() recursively inside parMetrics.
355 Dimension old_dim = parMetrics(pit, false).dim();
356 ParagraphMetrics & pm = par_metrics_[pit];
359 Buffer & buffer = bv_->buffer();
360 BufferParams const & bparams = buffer.params();
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);
478 pm.computeRowSignature(row, bparams);
482 pm.dim().wid = std::max(pm.dim().wid, dim.wid);
483 pm.dim().des += dim.height();
484 } while (first < par.size());
486 if (row_index < pm.rows().size())
487 pm.rows().resize(row_index);
489 // Make sure that if a par ends in newline, there is one more row
491 if (first > 0 && par.isNewline(first - 1)) {
492 Dimension dim = rowHeight(pit, first, first);
493 dim.wid = rowWidth(right_margin, pit, first, first);
494 if (row_index == pm.rows().size())
495 pm.rows().push_back(Row());
496 Row & row = pm.rows()[row_index];
497 row.setChanged(false);
500 row.setDimension(dim);
501 int const max_row_width = max(dim_.wid, dim.wid);
502 computeRowMetrics(pit, row, max_row_width);
503 pm.computeRowSignature(row, bparams);
504 pm.dim().des += dim.height();
507 pm.dim().asc += pm.rows()[0].ascent();
508 pm.dim().des -= pm.rows()[0].ascent();
510 changed |= old_dim.height() != pm.dim().height();
516 void TextMetrics::computeRowMetrics(pit_type const pit,
517 Row & row, int width) const
524 Buffer & buffer = bv_->buffer();
525 Paragraph const & par = text_->getPar(pit);
527 double w = width - row.width();
528 // FIXME: put back this assertion when the crash on new doc is solved.
529 //BOOST_ASSERT(w >= 0);
531 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
532 //lyxerr << "row.width() " << row.width() << endl;
533 //lyxerr << "w " << w << endl;
535 bool const is_rtl = text_->isRTL(buffer, par);
537 row.x = rightMargin(pit);
539 row.x = leftMargin(max_width_, pit, row.pos());
541 // is there a manual margin with a manual label
542 LayoutPtr const & layout = par.layout();
544 if (layout->margintype == MARGIN_MANUAL
545 && layout->labeltype == LABEL_MANUAL) {
546 /// We might have real hfills in the label part
547 int nlh = numberOfLabelHfills(par, row);
549 // A manual label par (e.g. List) has an auto-hfill
550 // between the label text and the body of the
552 // But we don't want to do this auto hfill if the par
557 if (nlh && !par.getLabelWidthString().empty())
558 row.label_hfill = labelFill(pit, row) / double(nlh);
561 // are there any hfills in the row?
562 int const nh = numberOfHfills(par, row);
567 // we don't have to look at the alignment if it is ALIGN_LEFT and
568 // if the row is already larger then the permitted width as then
569 // we force the LEFT_ALIGN'edness!
570 } else if (int(row.width()) < max_width_) {
571 // is it block, flushleft or flushright?
572 // set x how you need it
574 if (par.params().align() == LYX_ALIGN_LAYOUT)
575 align = layout->align;
577 align = par.params().align();
579 // Display-style insets should always be on a centred row
580 // The test on par.size() is to catch zero-size pars, which
581 // would trigger the assert in Paragraph::getInset().
582 //inset = par.size() ? par.getInset(row.pos()) : 0;
583 if (row.pos() < par.size() && par.isInset(row.pos())) {
584 switch(par.getInset(row.pos())->display()) {
585 case Inset::AlignLeft:
586 align = LYX_ALIGN_BLOCK;
588 case Inset::AlignCenter:
589 align = LYX_ALIGN_CENTER;
592 case Inset::AlignRight:
593 // unchanged (use align)
599 case LYX_ALIGN_BLOCK: {
600 int const ns = numberOfSeparators(par, row);
601 bool disp_inset = false;
602 if (row.endpos() < par.size()) {
603 Inset const * in = par.getInset(row.endpos());
605 disp_inset = in->display();
607 // If we have separators, this is not the last row of a
608 // par, does not end in newline, and is not row above a
609 // display inset... then stretch it
611 && row.endpos() < par.size()
612 && !par.isNewline(row.endpos() - 1)
615 row.separator = w / ns;
616 //lyxerr << "row.separator " << row.separator << endl;
617 //lyxerr << "ns " << ns << endl;
623 case LYX_ALIGN_RIGHT:
626 case LYX_ALIGN_CENTER:
633 pos_type body_pos = par.beginOfBody();
634 pos_type end = row.endpos();
637 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
639 row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
640 width(layout->labelsep);
642 row.x += row.label_hfill;
648 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
650 Buffer & buffer = bv_->buffer();
651 Paragraph const & par = text_->getPar(pit);
653 pos_type last = par.beginOfBody();
654 BOOST_ASSERT(last > 0);
656 // -1 because a label ends with a space that is in the label
659 // a separator at this end does not count
660 if (par.isLineSeparator(last))
664 for (pos_type i = row.pos(); i <= last; ++i)
665 w += singleWidth(pit, i);
667 docstring const & label = par.params().labelWidthString();
671 FontMetrics const & fm
672 = theFontMetrics(text_->getLabelFont(buffer, par));
674 return max(0, fm.width(label) - w);
678 // this needs special handling - only newlines count as a break point
679 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
681 pos_type const end = par.size();
684 if (par.isNewline(i))
691 int TextMetrics::labelEnd(pit_type const pit) const
693 // labelEnd is only needed if the layout fills a flushleft label.
694 if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
696 // return the beginning of the body
697 return leftMargin(max_width_, pit);
701 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
704 Buffer & buffer = bv_->buffer();
705 ParagraphMetrics const & pm = par_metrics_[pit];
706 Paragraph const & par = text_->getPar(pit);
707 pos_type const end = par.size();
708 if (pos == end || width < 0)
711 LayoutPtr const & layout = par.layout();
713 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
714 return addressBreakPoint(pos, par);
716 pos_type const body_pos = par.beginOfBody();
719 // Now we iterate through until we reach the right margin
720 // or the end of the par, then choose the possible break
723 int label_end = labelEnd(pit);
724 int const left = leftMargin(max_width_, pit, pos);
727 // pixel width since last breakpoint
730 FontIterator fi = FontIterator(*this, par, pit, pos);
731 pos_type point = end;
733 for ( ; i < end; ++i, ++fi) {
734 int thiswidth = pm.singleWidth(i, *fi);
736 // add the auto-hfill from label end to the body
737 if (body_pos && i == body_pos) {
738 FontMetrics const & fm = theFontMetrics(
739 text_->getLabelFont(buffer, par));
740 int add = fm.width(layout->labelsep);
741 if (par.isLineSeparator(i - 1))
742 add -= singleWidth(pit, i - 1);
744 add = std::max(add, label_end - x);
749 chunkwidth += thiswidth;
751 // break before a character that will fall off
752 // the right of the row
754 // if no break before, break here
755 if (point == end || chunkwidth >= width - left) {
761 // exit on last registered breakpoint:
765 if (par.isNewline(i)) {
771 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
776 if (par.isInset(i) && par.getInset(i)->display()) {
782 if (!par.isInset(i) || par.getInset(i)->isChar()) {
783 // some insets are line separators too
784 if (par.isLineSeparator(i)) {
785 // register breakpoint:
792 // maybe found one, but the par is short enough.
793 if (i == end && x < width)
796 // manual labels cannot be broken in LaTeX. But we
797 // want to make our on-screen rendering of footnotes
799 if (body_pos && point < body_pos)
806 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
807 pos_type const first, pos_type const end) const
809 Buffer & buffer = bv_->buffer();
810 // get the pure distance
811 ParagraphMetrics const & pm = par_metrics_[pit];
812 Paragraph const & par = text_->getPar(pit);
813 int w = leftMargin(max_width_, pit, first);
814 int label_end = labelEnd(pit);
816 pos_type const body_pos = par.beginOfBody();
820 FontIterator fi = FontIterator(*this, par, pit, i);
821 for ( ; i < end; ++i, ++fi) {
822 if (body_pos > 0 && i == body_pos) {
823 FontMetrics const & fm = theFontMetrics(
824 text_->getLabelFont(buffer, par));
825 w += fm.width(par.layout()->labelsep);
826 if (par.isLineSeparator(i - 1))
827 w -= singleWidth(pit, i - 1);
828 w = max(w, label_end);
830 w += pm.singleWidth(i, *fi);
834 if (body_pos > 0 && body_pos >= end) {
835 FontMetrics const & fm = theFontMetrics(
836 text_->getLabelFont(buffer, par));
837 w += fm.width(par.layout()->labelsep);
838 if (end > 0 && par.isLineSeparator(end - 1))
839 w -= singleWidth(pit, end - 1);
840 w = max(w, label_end);
843 return w + right_margin;
847 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
848 pos_type const end) const
850 Paragraph const & par = text_->getPar(pit);
851 // get the maximum ascent and the maximum descent
852 double layoutasc = 0;
853 double layoutdesc = 0;
854 double const dh = defaultRowHeight();
856 // ok, let us initialize the maxasc and maxdesc value.
857 // Only the fontsize count. The other properties
858 // are taken from the layoutfont. Nicer on the screen :)
859 LayoutPtr const & layout = par.layout();
861 // as max get the first character of this row then it can
862 // increase but not decrease the height. Just some point to
863 // start with so we don't have to do the assignment below too
865 Buffer const & buffer = bv_->buffer();
866 Font font = getDisplayFont(pit, first);
867 FontSize const tmpsize = font.fontInfo().size();
868 font.fontInfo() = text_->getLayoutFont(buffer, pit);
869 FontSize const size = font.fontInfo().size();
870 font.fontInfo().setSize(tmpsize);
872 FontInfo labelfont = text_->getLabelFont(buffer, par);
874 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
875 FontMetrics const & fontmetrics = theFontMetrics(font);
877 // these are minimum values
878 double const spacing_val = layout->spacing.getValue()
879 * text_->spacing(buffer, par);
880 //lyxerr << "spacing_val = " << spacing_val << endl;
881 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
882 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
884 // insets may be taller
885 ParagraphMetrics const & pm = par_metrics_[pit];
886 InsetList::const_iterator ii = par.insetList().begin();
887 InsetList::const_iterator iend = par.insetList().end();
888 for ( ; ii != iend; ++ii) {
889 Dimension const & dim = pm.insetDimension(ii->inset);
890 if (ii->pos >= first && ii->pos < end) {
891 maxasc = max(maxasc, dim.ascent());
892 maxdesc = max(maxdesc, dim.descent());
896 // Check if any custom fonts are larger (Asger)
897 // This is not completely correct, but we can live with the small,
898 // cosmetic error for now.
902 par.highestFontInRange(first, end, size);
903 if (maxsize > font.fontInfo().size()) {
904 // use standard paragraph font with the maximal size
905 FontInfo maxfont = font.fontInfo();
906 maxfont.setSize(maxsize);
907 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
908 maxasc = max(maxasc, maxfontmetrics.maxAscent());
909 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
912 // This is nicer with box insets:
916 ParagraphList const & pars = text_->paragraphs();
920 BufferParams const & bufparams = buffer.params();
921 // some parskips VERY EASY IMPLEMENTATION
922 if (bufparams.paragraph_separation
923 == BufferParams::PARSEP_SKIP
924 && par.ownerCode() != ERT_CODE
925 && par.ownerCode() != LISTINGS_CODE
927 && ((layout->isParagraph() && par.getDepth() == 0)
928 || (pars[pit - 1].layout()->isParagraph()
929 && pars[pit - 1].getDepth() == 0)))
931 maxasc += bufparams.getDefSkip().inPixels(*bv_);
934 if (par.params().startOfAppendix())
935 maxasc += int(3 * dh);
937 // This is special code for the chapter, since the label of this
938 // layout is printed in an extra row
939 if (layout->counter == "chapter"
940 && !par.params().labelString().empty()) {
941 labeladdon = int(labelfont_metrics.maxHeight()
942 * layout->spacing.getValue()
943 * text_->spacing(buffer, par));
946 // special code for the top label
947 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
948 || layout->labeltype == LABEL_BIBLIO
949 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
950 && isFirstInSequence(pit, pars)
951 && !par.getLabelstring().empty())
954 labelfont_metrics.maxHeight()
955 * layout->spacing.getValue()
956 * text_->spacing(buffer, par)
957 + (layout->topsep + layout->labelbottomsep) * dh);
960 // Add the layout spaces, for example before and after
961 // a section, or between the items of a itemize or enumerate
964 pit_type prev = depthHook(pit, pars, par.getDepth());
965 Paragraph const & prevpar = pars[prev];
967 && prevpar.layout() == layout
968 && prevpar.getDepth() == par.getDepth()
969 && prevpar.getLabelWidthString()
970 == par.getLabelWidthString()) {
971 layoutasc = layout->itemsep * dh;
972 } else if (pit != 0 || first != 0) {
973 if (layout->topsep > 0)
974 layoutasc = layout->topsep * dh;
977 prev = outerHook(pit, pars);
978 if (prev != pit_type(pars.size())) {
979 maxasc += int(pars[prev].layout()->parsep * dh);
980 } else if (pit != 0) {
981 Paragraph const & prevpar = pars[pit - 1];
982 if (prevpar.getDepth() != 0 ||
983 prevpar.layout() == layout) {
984 maxasc += int(layout->parsep * dh);
989 // is it a bottom line?
990 if (end >= par.size()) {
991 // add the layout spaces, for example before and after
992 // a section, or between the items of a itemize or enumerate
994 pit_type nextpit = pit + 1;
995 if (nextpit != pit_type(pars.size())) {
1000 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1001 usual = pars[cpit].layout()->bottomsep * dh;
1002 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1003 if (pars[cpit].layout() != pars[nextpit].layout()
1004 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1006 unusual = pars[cpit].layout()->bottomsep * dh;
1008 layoutdesc = max(unusual, usual);
1009 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1010 if (pars[cpit].layout() != pars[nextpit].layout()
1011 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1012 layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
1017 // incalculate the layout spaces
1018 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1019 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1021 // FIXME: the correct way is to do the following is to move the
1022 // following code in another method specially tailored for the
1023 // main Text. The following test is thus bogus.
1024 // Top and bottom margin of the document (only at top-level)
1026 if (pit == 0 && first == 0)
1028 if (pit + 1 == pit_type(pars.size()) &&
1029 end == par.size() &&
1030 !(end > 0 && par.isNewline(end - 1)))
1034 return Dimension(0, maxasc + labeladdon, maxdesc);
1038 // x is an absolute screen coord
1039 // returns the column near the specified x-coordinate of the row
1040 // x is set to the real beginning of this column
1041 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1042 Row const & row, int & x, bool & boundary) const
1044 Buffer const & buffer = bv_->buffer();
1046 /// For the main Text, it is possible that this pit is not
1047 /// yet in the CoordCache when moving cursor up.
1048 /// x Paragraph coordinate is always 0 for main text anyway.
1049 int const xo = origin_.x_;
1051 Paragraph const & par = text_->getPar(pit);
1052 ParagraphMetrics const & pm = par_metrics_[pit];
1054 bidi.computeTables(par, buffer, row);
1056 pos_type vc = row.pos();
1057 pos_type end = row.endpos();
1059 LayoutPtr const & layout = par.layout();
1061 bool left_side = false;
1063 pos_type body_pos = par.beginOfBody();
1065 double tmpx = row.x;
1066 double last_tmpx = tmpx;
1069 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1072 // check for empty row
1078 while (vc < end && tmpx <= x) {
1079 c = bidi.vis2log(vc);
1081 if (body_pos > 0 && c == body_pos - 1) {
1082 FontMetrics const & fm = theFontMetrics(
1083 text_->getLabelFont(buffer, par));
1084 tmpx += row.label_hfill + fm.width(layout->labelsep);
1085 if (par.isLineSeparator(body_pos - 1))
1086 tmpx -= singleWidth(pit, body_pos - 1);
1089 if (pm.hfillExpansion(row, c)) {
1090 tmpx += singleWidth(pit, c);
1094 tmpx += row.label_hfill;
1095 } else if (par.isSeparator(c)) {
1096 tmpx += singleWidth(pit, c);
1098 tmpx += row.separator;
1100 tmpx += singleWidth(pit, c);
1105 if ((tmpx + last_tmpx) / 2 > x) {
1110 BOOST_ASSERT(vc <= end); // This shouldn't happen.
1113 // This (rtl_support test) is not needed, but gives
1114 // some speedup if rtl_support == false
1115 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1117 // If lastrow is false, we don't need to compute
1118 // the value of rtl.
1119 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1121 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1122 (!rtl && !left_side && vc == end && x > tmpx + 5)))
1124 else if (vc == row.pos()) {
1125 c = bidi.vis2log(vc);
1126 if (bidi.level(c) % 2 == 1)
1129 c = bidi.vis2log(vc - 1);
1130 bool const rtl = (bidi.level(c) % 2 == 1);
1131 if (left_side == rtl) {
1133 boundary = isRTLBoundary(pit, c);
1137 // I believe this code is not needed anymore (Jug 20050717)
1139 // The following code is necessary because the cursor position past
1140 // the last char in a row is logically equivalent to that before
1141 // the first char in the next row. That's why insets causing row
1142 // divisions -- Newline and display-style insets -- must be treated
1143 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1144 // Newline inset, air gap below:
1145 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1146 if (bidi.level(end -1) % 2 == 0)
1147 tmpx -= singleWidth(pit, end - 1);
1149 tmpx += singleWidth(pit, end - 1);
1153 // Air gap above display inset:
1154 if (row.pos() < end && c >= end && end < par.size()
1155 && par.isInset(end) && par.getInset(end)->display()) {
1158 // Air gap below display inset:
1159 if (row.pos() < end && c >= end && par.isInset(end - 1)
1160 && par.getInset(end - 1)->display()) {
1166 pos_type const col = c - row.pos();
1168 if (!c || end == par.size())
1171 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1176 return min(col, end - 1 - row.pos());
1180 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1182 // We play safe and use parMetrics(pit) to make sure the
1183 // ParagraphMetrics will be redone and OK to use if needed.
1184 // Otherwise we would use an empty ParagraphMetrics in
1185 // upDownInText() while in selection mode.
1186 ParagraphMetrics const & pm = parMetrics(pit);
1188 BOOST_ASSERT(row < int(pm.rows().size()));
1190 Row const & r = pm.rows()[row];
1191 return r.pos() + getColumnNearX(pit, r, x, bound);
1195 void TextMetrics::newParMetricsDown()
1197 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1198 pit_type const pit = last.first + 1;
1199 if (pit == int(text_->paragraphs().size()))
1202 // do it and update its position.
1204 par_metrics_[pit].setPosition(last.second.position()
1205 + last.second.descent());
1209 void TextMetrics::newParMetricsUp()
1211 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1212 if (first.first == 0)
1215 pit_type const pit = first.first - 1;
1216 // do it and update its position.
1218 par_metrics_[pit].setPosition(first.second.position()
1219 - first.second.ascent());
1222 // y is screen coordinate
1223 pit_type TextMetrics::getPitNearY(int y)
1225 BOOST_ASSERT(!text_->paragraphs().empty());
1226 LYXERR(Debug::DEBUG)
1227 << BOOST_CURRENT_FUNCTION
1228 << ": 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)
1274 << BOOST_CURRENT_FUNCTION
1275 << " examining: pit: " << it->first
1276 << " y: " << it->second.position()
1279 ParagraphMetrics const & pm = par_metrics_[it->first];
1281 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1283 yy = it->second.position();
1287 LYXERR(Debug::DEBUG)
1288 << BOOST_CURRENT_FUNCTION
1289 << ": found best y: " << yy << " for pit: " << pit
1296 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1298 ParagraphMetrics const & pm = par_metrics_[pit];
1300 int yy = pm.position() - pm.ascent();
1301 BOOST_ASSERT(!pm.rows().empty());
1302 RowList::const_iterator rit = pm.rows().begin();
1303 RowList::const_iterator rlast = pm.rows().end();
1305 for (; rit != rlast; yy += rit->height(), ++rit)
1306 if (yy + rit->height() > y)
1312 // x,y are absolute screen coordinates
1313 // sets cursor recursively descending into nested editable insets
1314 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1316 if (lyxerr.debugging(Debug::WORKAREA)) {
1317 lyxerr << "TextMetrics::editXY(cur, " << x << ", " << y << ")" << std::endl;
1318 cur.bv().coordCache().dump();
1320 pit_type pit = getPitNearY(y);
1321 BOOST_ASSERT(pit != -1);
1323 Row const & row = getRowNearY(y, pit);
1326 int xx = x; // is modified by getColumnNearX
1327 pos_type const pos = row.pos()
1328 + getColumnNearX(pit, row, xx, bound);
1331 cur.boundary(bound);
1334 // try to descend into nested insets
1335 Inset * inset = checkInsetHit(x, y);
1336 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1338 // Either we deconst editXY or better we move current_font
1339 // and real_current_font to Cursor
1340 // FIXME: what is needed now that current_font and real_current_font
1342 cur.setCurrentFont();
1346 ParagraphList const & pars = text_->paragraphs();
1347 Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1348 //Inset * insetBehind = pars[pit].getInset(pos);
1350 // This should be just before or just behind the
1351 // cursor position set above.
1352 BOOST_ASSERT((pos != 0 && inset == insetBefore)
1353 || inset == pars[pit].getInset(pos));
1355 // Make sure the cursor points to the position before
1357 if (inset == insetBefore) {
1359 cur.boundary(false);
1362 // Try to descend recursively inside the inset.
1363 inset = inset->editXY(cur, x, y);
1365 if (cur.top().text() == text_)
1366 cur.setCurrentFont();
1371 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1373 BOOST_ASSERT(text_ == cur.text());
1374 pit_type pit = getPitNearY(y);
1376 ParagraphMetrics const & pm = par_metrics_[pit];
1378 int yy = pm.position() - pm.ascent();
1379 LYXERR(Debug::DEBUG)
1380 << BOOST_CURRENT_FUNCTION
1384 << " yy: " << yy << endl;
1387 BOOST_ASSERT(pm.rows().size());
1388 for (; r < int(pm.rows().size()) - 1; ++r) {
1389 Row const & row = pm.rows()[r];
1390 if (int(yy + row.height()) > y)
1395 Row const & row = pm.rows()[r];
1397 LYXERR(Debug::DEBUG)
1398 << BOOST_CURRENT_FUNCTION
1400 << " from pos: " << row.pos()
1405 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1407 LYXERR(Debug::DEBUG)
1408 << BOOST_CURRENT_FUNCTION
1409 << ": setting cursor pit: " << pit
1413 text_->setCursor(cur, pit, pos, true, bound);
1414 // remember new position.
1419 //takes screen x,y coordinates
1420 Inset * TextMetrics::checkInsetHit(int x, int y)
1422 pit_type pit = getPitNearY(y);
1423 BOOST_ASSERT(pit != -1);
1425 Paragraph const & par = text_->paragraphs()[pit];
1426 ParagraphMetrics const & pm = par_metrics_[pit];
1428 LYXERR(Debug::DEBUG)
1429 << BOOST_CURRENT_FUNCTION
1434 InsetList::const_iterator iit = par.insetList().begin();
1435 InsetList::const_iterator iend = par.insetList().end();
1436 for (; iit != iend; ++iit) {
1437 Inset * inset = iit->inset;
1439 LYXERR(Debug::DEBUG)
1440 << BOOST_CURRENT_FUNCTION
1441 << ": examining inset " << inset << endl;
1443 if (!bv_->coordCache().getInsets().has(inset)) {
1444 LYXERR(Debug::DEBUG)
1445 << BOOST_CURRENT_FUNCTION
1446 << ": inset has no cached position" << endl;
1450 Dimension const & dim = pm.insetDimension(inset);
1451 Point p = bv_->coordCache().getInsets().xy(inset);
1453 LYXERR(Debug::DEBUG)
1454 << BOOST_CURRENT_FUNCTION
1455 << ": xo: " << p.x_ << "..." << p.x_ + dim.wid
1456 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des
1460 && x <= p.x_ + dim.wid
1461 && y >= p.y_ - dim.asc
1462 && y <= p.y_ + dim.des) {
1463 LYXERR(Debug::DEBUG)
1464 << BOOST_CURRENT_FUNCTION
1465 << ": Hit inset: " << inset << endl;
1470 LYXERR(Debug::DEBUG)
1471 << BOOST_CURRENT_FUNCTION
1472 << ": No inset hit. " << endl;
1477 int TextMetrics::cursorX(CursorSlice const & sl,
1478 bool boundary) const
1480 BOOST_ASSERT(sl.text() == text_);
1481 pit_type const pit = sl.pit();
1482 Paragraph const & par = text_->paragraphs()[pit];
1483 ParagraphMetrics const & pm = par_metrics_[pit];
1484 if (pm.rows().empty())
1487 pos_type ppos = sl.pos();
1488 // Correct position in front of big insets
1489 bool const boundary_correction = ppos != 0 && boundary;
1490 if (boundary_correction)
1493 Row const & row = pm.getRow(sl.pos(), boundary);
1495 pos_type cursor_vpos = 0;
1497 Buffer const & buffer = bv_->buffer();
1500 bidi.computeTables(par, buffer, row);
1502 pos_type const row_pos = row.pos();
1503 pos_type const end = row.endpos();
1504 // Spaces at logical line breaks in bidi text must be skipped during
1505 // cursor positioning. However, they may appear visually in the middle
1506 // of a row; they must be skipped, wherever they are...
1507 // * logically "abc_[HEBREW_\nHEBREW]"
1508 // * visually "abc_[_WERBEH\nWERBEH]"
1509 pos_type skipped_sep_vpos = -1;
1512 cursor_vpos = row_pos;
1513 else if (ppos >= end)
1514 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1515 else if (ppos > row_pos && ppos >= end)
1516 // Place cursor after char at (logical) position pos - 1
1517 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1518 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1520 // Place cursor before char at (logical) position ppos
1521 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1522 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1524 pos_type body_pos = par.beginOfBody();
1526 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1529 // Use font span to speed things up, see below
1533 // If the last logical character is a separator, skip it, unless
1534 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1535 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1536 skipped_sep_vpos = bidi.log2vis(end - 1);
1538 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1539 // Skip the separator which is at the logical end of the row
1540 if (vpos == skipped_sep_vpos)
1542 pos_type pos = bidi.vis2log(vpos);
1543 if (body_pos > 0 && pos == body_pos - 1) {
1544 FontMetrics const & labelfm = theFontMetrics(
1545 text_->getLabelFont(buffer, par));
1546 x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1547 if (par.isLineSeparator(body_pos - 1))
1548 x -= singleWidth(pit, body_pos - 1);
1551 // Use font span to speed things up, see above
1552 if (pos < font_span.first || pos > font_span.last) {
1553 font_span = par.fontSpan(pos);
1554 font = getDisplayFont(pit, pos);
1557 x += pm.singleWidth(pos, font);
1559 if (pm.hfillExpansion(row, pos))
1560 x += (pos >= body_pos) ? row.hfill : row.label_hfill;
1561 else if (par.isSeparator(pos) && pos >= body_pos)
1565 // see correction above
1566 if (boundary_correction) {
1567 if (isRTL(sl, boundary))
1568 x -= singleWidth(pit, ppos);
1570 x += singleWidth(pit, ppos);
1577 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1579 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << std::endl;
1580 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1581 if (pm.rows().empty())
1585 h -= par_metrics_[0].rows()[0].ascent();
1586 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1587 h += par_metrics_[pit].height();
1590 if (pos && boundary)
1592 size_t const rend = pm.pos2row(pos);
1593 for (size_t rit = 0; rit != rend; ++rit)
1594 h += pm.rows()[rit].height();
1595 h += pm.rows()[rend].ascent();
1600 void TextMetrics::cursorPrevious(Cursor & cur)
1602 pos_type cpos = cur.pos();
1603 pit_type cpar = cur.pit();
1605 int x = cur.x_target();
1606 setCursorFromCoordinates(cur, x, 0);
1607 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1609 if (cpar == cur.pit() && cpos == cur.pos())
1610 // we have a row which is taller than the workarea. The
1611 // simplest solution is to move to the previous row instead.
1612 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1615 cur.updateFlags(Update::Force | Update::FitCursor);
1619 void TextMetrics::cursorNext(Cursor & cur)
1621 pos_type cpos = cur.pos();
1622 pit_type cpar = cur.pit();
1624 int x = cur.x_target();
1625 setCursorFromCoordinates(cur, x, cur.bv().workHeight() - 1);
1626 cur.dispatch(FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1628 if (cpar == cur.pit() && cpos == cur.pos())
1629 // we have a row which is taller than the workarea. The
1630 // simplest solution is to move to the next row instead.
1632 FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1635 cur.updateFlags(Update::Force | Update::FitCursor);
1639 // the cursor set functions have a special mechanism. When they
1640 // realize you left an empty paragraph, they will delete it.
1642 bool TextMetrics::cursorHome(Cursor & cur)
1644 BOOST_ASSERT(text_ == cur.text());
1645 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1646 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1647 return text_->setCursor(cur, cur.pit(), row.pos());
1651 bool TextMetrics::cursorEnd(Cursor & cur)
1653 BOOST_ASSERT(text_ == cur.text());
1654 // if not on the last row of the par, put the cursor before
1655 // the final space exept if I have a spanning inset or one string
1656 // is so long that we force a break.
1657 pos_type end = cur.textRow().endpos();
1659 // empty text, end-1 is no valid position
1661 bool boundary = false;
1662 if (end != cur.lastpos()) {
1663 if (!cur.paragraph().isLineSeparator(end-1)
1664 && !cur.paragraph().isNewline(end-1))
1669 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1673 void TextMetrics::deleteLineForward(Cursor & cur)
1675 BOOST_ASSERT(text_ == cur.text());
1676 if (cur.lastpos() == 0) {
1677 // Paragraph is empty, so we just go forward
1678 text_->cursorForward(cur);
1681 cur.selection() = true; // to avoid deletion
1684 // What is this test for ??? (JMarc)
1685 if (!cur.selection())
1686 text_->deleteWordForward(cur);
1688 cap::cutSelection(cur, true, false);
1689 checkBufferStructure(cur.buffer(), cur);
1694 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1696 ParagraphList const & pars = text_->paragraphs();
1697 return row.endpos() >= pars[pit].size()
1698 && pit + 1 == pit_type(pars.size());
1702 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1704 return row.pos() == 0 && pit == 0;
1708 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1710 BOOST_ASSERT(pit >= 0);
1711 BOOST_ASSERT(pit < int(text_->paragraphs().size()));
1712 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1716 int TextMetrics::leftMargin(int max_width,
1717 pit_type const pit, pos_type const pos) const
1719 ParagraphList const & pars = text_->paragraphs();
1721 BOOST_ASSERT(pit >= 0);
1722 BOOST_ASSERT(pit < int(pars.size()));
1723 Paragraph const & par = pars[pit];
1724 BOOST_ASSERT(pos >= 0);
1725 BOOST_ASSERT(pos <= par.size());
1726 Buffer const & buffer = bv_->buffer();
1727 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1728 TextClass const & tclass = buffer.params().getTextClass();
1729 LayoutPtr const & layout = par.layout();
1731 docstring parindent = layout->parindent;
1735 if (text_->isMainText(buffer))
1736 l_margin += changebarMargin();
1738 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1739 tclass.leftmargin());
1741 if (par.getDepth() != 0) {
1742 // find the next level paragraph
1743 pit_type newpar = outerHook(pit, pars);
1744 if (newpar != pit_type(pars.size())) {
1745 if (pars[newpar].layout()->isEnvironment()) {
1746 l_margin = leftMargin(max_width, newpar);
1748 if (par.layout() == tclass.defaultLayout()) {
1749 if (pars[newpar].params().noindent())
1752 parindent = pars[newpar].layout()->parindent;
1757 // This happens after sections in standard classes. The 1.3.x
1758 // code compared depths too, but it does not seem necessary
1760 if (par.layout() == tclass.defaultLayout()
1761 && pit > 0 && pars[pit - 1].layout()->nextnoindent)
1764 FontInfo const labelfont = text_->getLabelFont(buffer, par);
1765 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1767 switch (layout->margintype) {
1768 case MARGIN_DYNAMIC:
1769 if (!layout->leftmargin.empty()) {
1770 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1771 layout->leftmargin);
1773 if (!par.getLabelstring().empty()) {
1774 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1775 l_margin += labelfont_metrics.width(par.getLabelstring());
1776 l_margin += labelfont_metrics.width(layout->labelsep);
1780 case MARGIN_MANUAL: {
1781 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1782 // The width of an empty par, even with manual label, should be 0
1783 if (!par.empty() && pos >= par.beginOfBody()) {
1784 if (!par.getLabelWidthString().empty()) {
1785 docstring labstr = par.getLabelWidthString();
1786 l_margin += labelfont_metrics.width(labstr);
1787 l_margin += labelfont_metrics.width(layout->labelsep);
1793 case MARGIN_STATIC: {
1794 l_margin += theFontMetrics(buffer.params().getFont()).
1795 signedWidth(layout->leftmargin) * 4 / (par.getDepth() + 4);
1799 case MARGIN_FIRST_DYNAMIC:
1800 if (layout->labeltype == LABEL_MANUAL) {
1801 if (pos >= par.beginOfBody()) {
1802 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1804 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1807 // Special case to fix problems with
1809 || (layout->labeltype == LABEL_STATIC
1810 && layout->latextype == LATEX_ENVIRONMENT
1811 && !isFirstInSequence(pit, pars))) {
1812 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1813 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
1814 && layout->labeltype != LABEL_BIBLIO
1815 && layout->labeltype !=
1816 LABEL_CENTERED_TOP_ENVIRONMENT) {
1817 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1818 l_margin += labelfont_metrics.width(layout->labelsep);
1819 l_margin += labelfont_metrics.width(par.getLabelstring());
1823 case MARGIN_RIGHT_ADDRESS_BOX: {
1825 // ok, a terrible hack. The left margin depends on the widest
1826 // row in this paragraph.
1827 RowList::iterator rit = par.rows().begin();
1828 RowList::iterator end = par.rows().end();
1829 // FIXME: This is wrong.
1830 int minfill = max_width;
1831 for ( ; rit != end; ++rit)
1832 if (rit->fill() < minfill)
1833 minfill = rit->fill();
1834 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
1835 l_margin += minfill;
1837 // also wrong, but much shorter.
1838 l_margin += max_width / 2;
1843 if (!par.params().leftIndent().zero())
1844 l_margin += par.params().leftIndent().inPixels(max_width);
1848 if (par.params().align() == LYX_ALIGN_LAYOUT)
1849 align = layout->align;
1851 align = par.params().align();
1853 // set the correct parindent
1855 && (layout->labeltype == LABEL_NO_LABEL
1856 || layout->labeltype == LABEL_TOP_ENVIRONMENT
1857 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1858 || (layout->labeltype == LABEL_STATIC
1859 && layout->latextype == LATEX_ENVIRONMENT
1860 && !isFirstInSequence(pit, pars)))
1861 && align == LYX_ALIGN_BLOCK
1862 && !par.params().noindent()
1863 // in some insets, paragraphs are never indented
1864 && !(par.inInset() && par.inInset()->neverIndent(buffer))
1865 // display style insets are always centered, omit indentation
1868 && par.getInset(pos)->display())
1869 && (par.layout() != tclass.defaultLayout()
1870 || buffer.params().paragraph_separation ==
1871 BufferParams::PARSEP_INDENT))
1873 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1881 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1883 ParagraphMetrics const & pm = par_metrics_[pit];
1885 return pm.singleWidth(pos, getDisplayFont(pit, pos));
1889 // only used for inset right now. should also be used for main text
1890 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1892 if (par_metrics_.empty())
1898 ParMetricsCache::iterator it = par_metrics_.begin();
1899 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1900 y -= it->second.ascent();
1901 for (; it != pm_end; ++it) {
1902 ParagraphMetrics const & pmi = it->second;
1904 pit_type const pit = it->first;
1905 // Save the paragraph position in the cache.
1906 it->second.setPosition(y);
1907 drawParagraph(pi, pit, x, y);
1913 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1915 // lyxerr << " paintPar: pit: " << pit << " at y: " << y << endl;
1916 int const ww = bv_->workHeight();
1918 ParagraphMetrics const & pm = par_metrics_[pit];
1919 if (pm.rows().empty())
1922 RowList::const_iterator const rb = pm.rows().begin();
1923 RowList::const_iterator const re = pm.rows().end();
1928 for (RowList::const_iterator rit = rb; rit != re; ++rit) {
1931 bool const inside = (y + rit->descent() >= 0
1932 && y - rit->ascent() < ww);
1933 // it is not needed to draw on screen if we are not inside.
1934 pi.pain.setDrawingEnabled(inside);
1935 RowPainter rp(pi, *text_, pit, *rit, bidi, x, y);
1937 // Row signature; has row changed since last paint?
1938 bool row_has_changed = rit->changed();
1940 bool row_selection = rit->sel_beg != -1 && rit->sel_end != -1;
1942 if (!row_selection && !pi.full_repaint && !row_has_changed) {
1943 // Paint the only the insets if the text itself is
1945 rp.paintOnlyInsets();
1946 y += rit->descent();
1950 // Paint the row if a full repaint has been requested or it has
1952 // Clear background of this row
1953 // (if paragraph background was not cleared)
1954 if (row_selection || (!pi.full_repaint && row_has_changed)) {
1955 pi.pain.fillRectangle(x, y - rit->ascent(),
1956 width(), rit->height(), pi.background_color);
1958 if (row_selection) {
1959 DocIterator beg = bv_->cursor().selectionBegin();
1960 DocIterator end = bv_->cursor().selectionEnd();
1962 beg.pos() = rit->sel_beg;
1963 if (pit == end.pit()) {
1964 end.pos() = rit->sel_end;
1966 end.pit() = pit + 1;
1969 drawSelection(pi, beg, end, x);
1972 // Instrumentation for testing row cache (see also
1974 if (lyxerr.debugging(Debug::PAINTING)) {
1975 if (text_->isMainText(bv_->buffer()))
1976 LYXERR(Debug::PAINTING) << "\n{" << inside <<
1977 pi.full_repaint << row_has_changed << "}";
1979 LYXERR(Debug::PAINTING) << "[" << inside <<
1980 pi.full_repaint << row_has_changed << "]";
1983 // Backup full_repaint status and force full repaint
1984 // for inner insets as the Row has been cleared out.
1985 bool tmp = pi.full_repaint;
1986 pi.full_repaint = true;
1989 rp.paintChangeBar();
1995 y += rit->descent();
1996 // Restore full_repaint status.
1997 pi.full_repaint = tmp;
1999 // Re-enable screen drawing for future use of the painter.
2000 pi.pain.setDrawingEnabled(true);
2002 //LYXERR(Debug::PAINTING) << "." << endl;
2006 // FIXME: only take care of one row!
2007 void TextMetrics::drawSelection(PainterInfo & pi,
2008 DocIterator const & beg, DocIterator const & end, int x) const
2010 ParagraphMetrics const & pm1 = parMetrics(beg.pit());
2011 ParagraphMetrics const & pm2 = parMetrics(end.pit());
2012 Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
2013 Row const & row2 = pm2.getRow(end.pos(), end.boundary());
2017 bool const clipAbove = (bv_->cursorStatus(beg) == CUR_ABOVE);
2021 middleTop = bv_->getPos(beg, beg.boundary()).y_ + row1.descent();
2025 bool const clipBelow = (bv_->cursorStatus(end) == CUR_BELOW);
2027 middleBottom = bv_->workHeight();
2029 middleBottom = bv_->getPos(end, end.boundary()).y_ - row2.ascent();
2031 // start and end in the same line?
2032 if (!clipAbove && !clipBelow && &row1 == &row2)
2033 // then only draw this row's selection
2034 drawRowSelection(pi, x, row1, beg, end, false, false);
2038 DocIterator begRowEnd = beg;
2039 begRowEnd.pos() = row1.endpos();
2040 begRowEnd.boundary(true);
2042 // draw upper rectangle
2043 drawRowSelection(pi, x, row1, beg, begRowEnd, false, true);
2046 if (middleTop < middleBottom) {
2047 // draw middle rectangle
2048 pi.pain.fillRectangle(x, middleTop, width(), middleBottom - middleTop,
2054 DocIterator endRowBeg = end;
2055 endRowBeg.pos() = row2.pos();
2056 endRowBeg.boundary(false);
2058 // draw low rectangle
2059 drawRowSelection(pi, x, row2, endRowBeg, end, true, false);
2065 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2066 DocIterator const & beg, DocIterator const & end,
2067 bool drawOnBegMargin, bool drawOnEndMargin) const
2069 Buffer & buffer = bv_->buffer();
2070 DocIterator cur = beg;
2071 int x1 = cursorX(beg.top(), beg.boundary());
2072 int x2 = cursorX(end.top(), end.boundary());
2073 int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2074 int y2 = y1 + row.height();
2077 if (drawOnBegMargin) {
2078 if (text_->isRTL(buffer, beg.paragraph()))
2079 pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color_selection);
2081 pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color_selection);
2084 if (drawOnEndMargin) {
2085 if (text_->isRTL(buffer, beg.paragraph()))
2086 pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color_selection);
2088 pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color_selection);
2091 // if we are on a boundary from the beginning, it's probably
2092 // a RTL boundary and we jump to the other side directly as this
2093 // segement is 0-size and confuses the logic below
2095 cur.boundary(false);
2097 // go through row and draw from RTL boundary to RTL boundary
2099 bool drawNow = false;
2101 // simplified cursorForward code below which does not
2102 // descend into insets and which does not go into the
2103 // next line. Compare the logic with the original cursorForward
2105 // if left of boundary -> just jump to right side
2106 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2107 if (cur.boundary()) {
2108 cur.boundary(false);
2109 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2110 // in front of RTL boundary -> Stay on this side of the boundary because:
2111 // ab|cDDEEFFghi -> abc|DDEEFFghi
2120 if (cur.pos() == row.endpos())
2125 // the previous segment was just drawn, now the next starts
2126 x1 = cursorX(cur.top(), cur.boundary());
2129 if (!(cur < end) || drawNow) {
2130 x2 = cursorX(cur.top(), cur.boundary());
2131 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2134 // reset x1, so it is set again next round (which will be on the
2135 // right side of a boundary or at the selection end)
2141 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2143 // ParagraphMetrics const & pm = par_metrics_[pit];
2144 // Row const & r = pm.rows()[row];
2150 int defaultRowHeight()
2152 return int(theFontMetrics(sane_font).maxHeight() * 1.2);