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"
32 #include "InsetList.h"
36 #include "MetricsInfo.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.h"
39 #include "rowpainter.h"
41 #include "TextClass.h"
43 #include "WordLangTuple.h"
45 #include "insets/InsetText.h"
47 #include "mathed/MacroTable.h"
48 #include "mathed/MathMacroTemplate.h"
50 #include "frontends/FontMetrics.h"
51 #include "frontends/Painter.h"
53 #include "support/debug.h"
54 #include "support/docstring_list.h"
55 #include "support/gettext.h"
56 #include "support/lassert.h"
65 using frontend::FontMetrics;
67 static int numberOfSeparators(Paragraph const & par, Row const & row)
69 pos_type const first = max(row.pos(), par.beginOfBody());
70 pos_type const last = row.endpos() - 1;
72 for (pos_type p = first; p < last; ++p) {
73 if (par.isSeparator(p))
80 static int numberOfLabelHfills(Paragraph const & par, Row const & row)
82 pos_type last = row.endpos() - 1;
83 pos_type first = row.pos();
85 // hfill *DO* count at the beginning of paragraphs!
87 while (first < last && par.isHfill(first))
91 last = min(last, par.beginOfBody());
93 for (pos_type p = first; p < last; ++p) {
101 static int numberOfHfills(Paragraph const & par, Row const & row)
103 pos_type const last = row.endpos();
104 pos_type first = row.pos();
106 // hfill *DO* count at the beginning of paragraphs!
108 while (first < last && par.isHfill(first))
112 first = max(first, par.beginOfBody());
115 for (pos_type p = first; p < last; ++p) {
123 /////////////////////////////////////////////////////////////////////
127 /////////////////////////////////////////////////////////////////////
130 TextMetrics::TextMetrics(BufferView * bv, Text * text)
131 : bv_(bv), text_(text)
134 max_width_ = bv_->workWidth();
135 dim_.wid = max_width_;
141 bool TextMetrics::contains(pit_type pit) const
143 return par_metrics_.find(pit) != par_metrics_.end();
147 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
149 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
154 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
156 ParMetricsCache::const_iterator it = par_metrics_.begin();
157 return make_pair(it->first, &it->second);
161 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
163 LBUFERR(!par_metrics_.empty());
164 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
165 return make_pair(it->first, &it->second);
169 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
171 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
172 if (pmc_it == par_metrics_.end()) {
173 pmc_it = par_metrics_.insert(
174 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
176 if (pmc_it->second.rows().empty() && redo)
178 return pmc_it->second;
182 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
184 LBUFERR(mi.base.textwidth > 0);
185 max_width_ = mi.base.textwidth;
186 // backup old dimension.
187 Dimension const old_dim = dim_;
190 dim_.wid = min_width;
191 pit_type const npar = text_->paragraphs().size();
193 // If there is more than one row, expand the text to
194 // the full allowable width.
195 dim_.wid = max_width_;
197 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
198 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
200 bool changed = false;
202 for (pit_type pit = 0; pit != npar; ++pit) {
203 changed |= redoParagraph(pit);
204 ParagraphMetrics const & pm = par_metrics_[pit];
206 if (dim_.wid < pm.width())
207 dim_.wid = pm.width();
210 dim_.asc = par_metrics_[0].ascent();
211 dim_.des = h - dim_.asc;
212 //lyxerr << "dim_.wid " << dim_.wid << endl;
213 //lyxerr << "dim_.asc " << dim_.asc << endl;
214 //lyxerr << "dim_.des " << dim_.des << endl;
216 changed |= dim_ != old_dim;
222 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
224 return main_text_? pm.rightMargin(*bv_) : 0;
228 int TextMetrics::rightMargin(pit_type const pit) const
230 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
234 void TextMetrics::applyOuterFont(Font & font) const
236 FontInfo lf(font_.fontInfo());
237 lf.reduce(bv_->buffer().params().getFont().fontInfo());
238 font.fontInfo().realize(lf);
242 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
244 LASSERT(pos >= 0, { static Font f; return f; });
246 ParagraphList const & pars = text_->paragraphs();
247 Paragraph const & par = pars[pit];
248 Layout const & layout = par.layout();
249 Buffer const & buffer = bv_->buffer();
251 BufferParams const & params = buffer.params();
252 pos_type const body_pos = par.beginOfBody();
254 // We specialize the 95% common case:
255 if (!par.getDepth()) {
256 Font f = par.getFontSettings(params, pos);
257 if (!text_->isMainText())
259 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
261 FontInfo const & lf = lab ? layout.labelfont : layout.font;
262 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
264 // In case the default family has been customized
265 if (lf.family() == INHERIT_FAMILY)
266 rlf.setFamily(params.getFont().fontInfo().family());
267 f.fontInfo().realize(rlf);
271 // The uncommon case need not be optimized as much
272 FontInfo const & layoutfont = pos < body_pos ?
273 layout.labelfont : layout.font;
275 Font font = par.getFontSettings(params, pos);
276 font.fontInfo().realize(layoutfont);
278 if (!text_->isMainText())
279 applyOuterFont(font);
281 // Realize against environment font information
282 // NOTE: the cast to pit_type should be removed when pit_type
283 // changes to a unsigned integer.
284 if (pit < pit_type(pars.size()))
285 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
287 // Realize with the fonts of lesser depth.
288 font.fontInfo().realize(params.getFont().fontInfo());
294 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
296 if (!lyxrc.rtl_support || !sl.text())
300 if (boundary && sl.pos() > 0)
303 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
307 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
309 // no RTL boundary at paragraph start
310 if (!lyxrc.rtl_support || pos == 0)
313 Font const & left_font = displayFont(pit, pos - 1);
315 return isRTLBoundary(pit, pos, left_font);
319 // isRTLBoundary returns false on a real end-of-line boundary,
320 // because otherwise the two boundary types get mixed up.
321 // This is the whole purpose of this being in TextMetrics.
322 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
323 Font const & font) const
325 if (!lyxrc.rtl_support
326 // no RTL boundary at paragraph start
328 // if the metrics have not been calculated, then we are not
329 // on screen and can safely ignore issues about boundaries.
333 ParagraphMetrics & pm = par_metrics_[pit];
334 // no RTL boundary in empty paragraph
335 if (pm.rows().empty())
338 pos_type endpos = pm.getRow(pos - 1, false).endpos();
339 pos_type startpos = pm.getRow(pos, false).pos();
340 // no RTL boundary at line start:
341 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
343 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
346 Paragraph const & par = text_->getPar(pit);
347 // no RTL boundary at line break:
348 // abc|\n -> move right -> abc\n (and not: abc\n|
350 if (startpos == pos && endpos == pos && endpos != par.size()
351 && (par.isNewline(pos - 1)
352 || par.isLineSeparator(pos - 1)
353 || par.isSeparator(pos - 1)))
356 bool left = font.isVisibleRightToLeft();
358 if (pos == par.size())
359 right = par.isRTL(bv_->buffer().params());
361 right = displayFont(pit, pos).isVisibleRightToLeft();
363 return left != right;
367 bool TextMetrics::redoParagraph(pit_type const pit)
369 Paragraph & par = text_->getPar(pit);
370 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
371 // redoParagraph() recursively inside parMetrics.
372 Dimension old_dim = parMetrics(pit, false).dim();
373 ParagraphMetrics & pm = par_metrics_[pit];
376 Buffer & buffer = bv_->buffer();
377 main_text_ = (text_ == &buffer.text());
378 bool changed = false;
380 // Check whether there are InsetBibItems that need fixing
381 // FIXME: This check ought to be done somewhere else. It is the reason
382 // why text_ is not const. But then, where else to do it?
383 // Well, how can you end up with either (a) a biblio environment that
384 // has no InsetBibitem or (b) a biblio environment with more than one
385 // InsetBibitem? I think the answer is: when paragraphs are merged;
386 // when layout is set; when material is pasted.
387 if (par.brokenBiblio()) {
388 Cursor & cur = const_cast<Cursor &>(bv_->cursor());
389 // In some cases, we do not know how to record undo
390 if (&cur.inset() == &text_->inset())
391 cur.recordUndo(ATOMIC_UNDO, pit, pit);
393 int const moveCursor = par.fixBiblio(buffer);
395 // Is it necessary to update the cursor?
396 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
399 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
404 // Optimisation: this is used in the next two loops
405 // so better to calculate that once here.
406 int const right_margin = rightMargin(pm);
408 // iterator pointing to paragraph to resolve macros
409 DocIterator parPos = text_->macrocontextPosition();
413 LYXERR(Debug::INFO, "MacroContext not initialised!"
414 << " Going through the buffer again and hope"
415 << " the context is better then.");
416 // FIXME audit updateBuffer calls
417 // This should not be here, but it is not clear yet where else it
419 bv_->buffer().updateBuffer();
420 parPos = text_->macrocontextPosition();
421 LBUFERR(!parPos.empty());
426 Font const bufferfont = buffer.params().getFont();
427 InsetList::const_iterator ii = par.insetList().begin();
428 InsetList::const_iterator iend = par.insetList().end();
429 for (; ii != iend; ++ii) {
430 // FIXME Doesn't this HAVE to be non-empty?
431 // position already initialized?
432 if (!parPos.empty()) {
433 parPos.pos() = ii->pos;
435 // A macro template would normally not be visible
436 // by itself. But the tex macro semantics allow
437 // recursion, so we artifically take the context
438 // after the macro template to simulate this.
439 if (ii->inset->lyxCode() == MATHMACRO_CODE)
443 // do the metric calculation
445 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
447 Font const & font = ii->inset->inheritFont() ?
448 displayFont(pit, ii->pos) : bufferfont;
449 MacroContext mc(&buffer, parPos);
450 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
451 ii->inset->metrics(mi, dim);
452 Dimension const old_dim = pm.insetDimension(ii->inset);
453 if (old_dim != dim) {
454 pm.setInsetDimension(ii->inset, dim);
459 par.setBeginOfBody();
461 size_t row_index = 0;
462 // maximum pixel width of a row
464 if (row_index == pm.rows().size())
465 pm.rows().push_back(Row());
466 Row & row = pm.rows()[row_index];
468 breakRow(row, right_margin, pit);
469 setRowHeight(row, pit);
470 row.dimension().wid = rowWidth(right_margin, pit, first, row.endpos());
471 row.setChanged(false);
472 if (row_index || row.endpos() < par.size())
473 // If there is more than one row, expand the text to
474 // the full allowable width. This setting here is needed
475 // for the computeRowMetrics() below.
476 dim_.wid = max_width_;
477 int const max_row_width = max(dim_.wid, row.width());
478 computeRowMetrics(pit, row, max_row_width);
479 first = row.endpos();
482 pm.dim().wid = max(pm.dim().wid, row.width());
483 pm.dim().des += row.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 if (row_index == pm.rows().size())
493 pm.rows().push_back(Row());
494 Row & row = pm.rows()[row_index];
497 row.dimension().wid = rowWidth(right_margin, pit, first, first);
498 setRowHeight(row, pit);
499 row.setChanged(false);
500 int const max_row_width = max(dim_.wid, row.width());
501 computeRowMetrics(pit, row, max_row_width);
502 pm.dim().des += row.height();
505 pm.dim().asc += pm.rows()[0].ascent();
506 pm.dim().des -= pm.rows()[0].ascent();
508 changed |= old_dim.height() != pm.dim().height();
514 void TextMetrics::computeRowMetrics(pit_type const pit,
515 Row & row, int width) const
520 Paragraph const & par = text_->getPar(pit);
522 double w = width - row.width();
523 // FIXME: put back this assertion when the crash on new doc is solved.
524 //LASSERT(w >= 0, /**/);
526 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
527 //lyxerr << "row.width() " << row.width() << endl;
528 //lyxerr << "w " << w << endl;
530 bool const is_rtl = text_->isRTL(par);
532 row.x = rightMargin(pit);
534 row.x = leftMargin(max_width_, pit, row.pos());
536 // is there a manual margin with a manual label
537 Layout const & layout = par.layout();
539 if (layout.margintype == MARGIN_MANUAL
540 && layout.labeltype == LABEL_MANUAL) {
541 /// We might have real hfills in the label part
542 int nlh = numberOfLabelHfills(par, row);
544 // A manual label par (e.g. List) has an auto-hfill
545 // between the label text and the body of the
547 // But we don't want to do this auto hfill if the par
552 if (nlh && !par.getLabelWidthString().empty())
553 row.label_hfill = labelFill(pit, row) / double(nlh);
557 // are there any hfills in the row?
558 if (int const nh = numberOfHfills(par, row)) {
560 hfill = w / double(nh);
561 // we don't have to look at the alignment if it is ALIGN_LEFT and
562 // if the row is already larger then the permitted width as then
563 // we force the LEFT_ALIGN'edness!
564 } else if (int(row.width()) < max_width_) {
565 // is it block, flushleft or flushright?
566 // set x how you need it
568 if (par.params().align() == LYX_ALIGN_LAYOUT)
569 align = layout.align;
571 align = par.params().align();
573 // handle alignment inside tabular cells
574 Inset const & owner = text_->inset();
575 switch (owner.contentAlignment()) {
576 case LYX_ALIGN_CENTER:
578 case LYX_ALIGN_RIGHT:
579 if (align == LYX_ALIGN_NONE
580 || align == LYX_ALIGN_BLOCK)
581 align = owner.contentAlignment();
584 // unchanged (use align)
588 // Display-style insets should always be on a centered row
589 if (Inset const * inset = par.getInset(row.pos())) {
590 switch (inset->display()) {
591 case Inset::AlignLeft:
592 align = LYX_ALIGN_BLOCK;
594 case Inset::AlignCenter:
595 align = LYX_ALIGN_CENTER;
598 // unchanged (use align)
600 case Inset::AlignRight:
601 align = LYX_ALIGN_RIGHT;
606 // Has the user requested we not justify stuff?
607 if (!bv_->buffer().params().justification
608 && align == LYX_ALIGN_BLOCK)
609 align = LYX_ALIGN_LEFT;
612 case LYX_ALIGN_BLOCK: {
613 int const ns = numberOfSeparators(par, row);
614 bool disp_inset = false;
615 if (row.endpos() < par.size()) {
616 Inset const * in = par.getInset(row.endpos());
618 disp_inset = in->display();
620 // If we have separators, this is not the last row of a
621 // par, does not end in newline, and is not row above a
622 // display inset... then stretch it
624 && row.endpos() < par.size()
625 && !par.isNewline(row.endpos() - 1)
628 row.separator = w / ns;
629 //lyxerr << "row.separator " << row.separator << endl;
630 //lyxerr << "ns " << ns << endl;
636 case LYX_ALIGN_RIGHT:
639 case LYX_ALIGN_CENTER:
646 pos_type body_pos = par.beginOfBody();
647 pos_type end = row.endpos();
650 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
652 row.x += theFontMetrics(text_->labelFont(par)).
653 width(layout.labelsep);
655 row.x += row.label_hfill;
659 pos_type const endpos = row.endpos();
660 pos_type body_pos = par.beginOfBody();
662 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
665 ParagraphMetrics & pm = par_metrics_[pit];
666 InsetList::const_iterator ii = par.insetList().begin();
667 InsetList::const_iterator iend = par.insetList().end();
668 for ( ; ii != iend; ++ii) {
669 if (ii->pos >= endpos || ii->pos < row.pos()
670 || (ii->inset->lyxCode() != SPACE_CODE ||
671 !ii->inset->isStretchableSpace()))
673 Dimension dim = row.dimension();
674 if (pm.hfillExpansion(row, ii->pos))
675 dim.wid = int(ii->pos >= body_pos ?
676 max(hfill, 5.0) : row.label_hfill);
679 // Cache the inset dimension.
680 bv_->coordCache().insets().add(ii->inset, dim);
681 pm.setInsetDimension(ii->inset, dim);
686 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
688 Paragraph const & par = text_->getPar(pit);
690 pos_type last = par.beginOfBody();
693 // -1 because a label ends with a space that is in the label
696 // a separator at this end does not count
697 if (par.isLineSeparator(last))
701 for (pos_type i = row.pos(); i <= last; ++i)
702 w += singleWidth(pit, i);
704 docstring const & label = par.params().labelWidthString();
708 FontMetrics const & fm
709 = theFontMetrics(text_->labelFont(par));
711 return max(0, fm.width(label) - w);
716 // Not used, see TextMetrics::breakRow
717 // this needs special handling - only newlines count as a break point
718 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
720 pos_type const end = par.size();
723 if (par.isNewline(i))
731 int TextMetrics::labelEnd(pit_type const pit) const
733 // labelEnd is only needed if the layout fills a flushleft label.
734 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
736 // return the beginning of the body
737 return leftMargin(max_width_, pit);
743 * Calling Text::getFont is slow. While rebreaking we scan a
744 * paragraph from left to right calling getFont for every char. This
745 * simple class address this problem by hidding an optimization trick
746 * (not mine btw -AB): the font is reused in the whole font span. The
747 * class handles transparently the "hidden" (not part of the fontlist)
748 * label font (as getFont does).
754 FontIterator(TextMetrics const & tm,
755 Paragraph const & par, pit_type pit, pos_type pos)
756 : tm_(tm), par_(par), pit_(pit), pos_(pos),
757 font_(tm.displayFont(pit, pos)),
758 endspan_(par.fontSpan(pos).last),
759 bodypos_(par.beginOfBody())
763 Font const & operator*() const { return font_; }
766 FontIterator & operator++()
769 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
770 font_ = tm_.displayFont(pit_, pos_);
771 endspan_ = par_.fontSpan(pos_).last;
777 Font * operator->() { return &font_; }
781 TextMetrics const & tm_;
783 Paragraph const & par_;
798 void TextMetrics::breakRow(Row & row, int const right_margin, pit_type const pit) const
800 Paragraph const & par = text_->getPar(pit);
801 pos_type const end = par.size();
802 pos_type const pos = row.pos();
803 int const left = leftMargin(max_width_, pit, pos);
804 int const width = max_width_ - right_margin;
805 if (pos == end || width < 0) {
810 ParagraphMetrics const & pm = par_metrics_[pit];
811 ParagraphList const & pars = text_->paragraphs();
814 //FIXME: As long as leftMargin() is not correctly implemented for
815 // MARGIN_RIGHT_ADDRESS_BOX, we should also not do this here.
816 // Otherwise, long rows will be painted off the screen.
817 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX)
818 return addressBreakPoint(pos, par);
822 // check for possible inline completion
823 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
824 pos_type inlineCompletionLPos = -1;
825 if (inlineCompletionPos.inTexted()
826 && inlineCompletionPos.text() == text_
827 && inlineCompletionPos.pit() == pit) {
828 // draw logically behind the previous character
829 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
832 pos_type const body_pos = par.beginOfBody();
834 pos_type point = end;
836 FontIterator fi = FontIterator(*this, par, pit, pos);
837 // Accumulator for character strings
839 Font chunkfont = *fi;
841 // Now we iterate through until we reach the right margin
842 // or the end of the par, then choose the possible break
846 for ( ; i < end; ++i, ++fi) {
847 // Add the chunk width when it is finished
848 if (par.isInset(i) || *fi != chunkfont
849 || (body_pos && i == body_pos)) {
850 x += theFontMetrics(chunkfont).width(chunkstr);
855 char_type c = par.getChar(i);
856 Language const * language = fi->language();
857 // The most special cases are handled first.
858 if (par.isInset(i)) {
859 x += pm.insetDimension(par.getInset(i)).wid;
860 } else if (c == '\t')
862 else if (language->rightToLeft()) {
863 if (language->lang() == "arabic_arabtex" ||
864 language->lang() == "arabic_arabi" ||
865 language->lang() == "farsi") {
866 if (!Encodings::isArabicComposeChar(c))
867 chunkstr += par.transformChar(c, i);
868 } else if (language->lang() == "hebrew" &&
869 !Encodings::isHebrewComposeChar(c)) {
875 if (lyxrc.paragraph_markers
876 && i == end - 1 && size_type(pit + 1) < pars.size())
877 // enlarge the last character to hold the end-of-par marker
878 chunkstr += char_type(0x00B6);
880 // add inline completion width
881 if (inlineCompletionLPos == i)
882 chunkstr += bv_->inlineCompletion();
884 // add the auto-hfill from label end to the body
885 if (body_pos && i == body_pos) {
886 FontMetrics const & fm = theFontMetrics(
887 text_->labelFont(par));
888 int add = fm.width(par.layout().labelsep);
889 //if (par.isLineSeparator(i - 1))
890 // add -= singleWidth(pit, i - 1);
892 add = max(add, labelEnd(pit) - x);
896 if (par.isNewline(i)) {
900 Inset const * inset = 0;
903 if ((inset = par.getInset(i + 1)) && inset->display()) {
908 if ((inset = par.getInset(i)) && inset->display()) {
914 if (par.isLineSeparator(i)) {
915 x += theFontMetrics(chunkfont).width(chunkstr);
919 // exit on last registered breakpoint:
922 // register breakpoint:
928 x += theFontMetrics(chunkfont).width(chunkstr);
929 // maybe found one, but the par is short enough.
934 // manual labels cannot be broken in LaTeX. But we
935 // want to make our on-screen rendering of footnotes
937 if (body_pos && point < body_pos)
944 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
945 pos_type const first, pos_type const end) const
947 // get the pure distance
948 ParagraphMetrics const & pm = par_metrics_[pit];
949 Paragraph const & par = text_->getPar(pit);
950 int w = leftMargin(max_width_, pit, first);
951 int label_end = labelEnd(pit);
953 // check for possible inline completion
954 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
955 pos_type inlineCompletionLPos = -1;
956 if (inlineCompletionPos.inTexted()
957 && inlineCompletionPos.text() == text_
958 && inlineCompletionPos.pit() == pit) {
959 // draw logically behind the previous character
960 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
963 pos_type const body_pos = par.beginOfBody();
967 FontIterator fi = FontIterator(*this, par, pit, i);
968 for ( ; i < end; ++i, ++fi) {
969 if (body_pos > 0 && i == body_pos) {
970 FontMetrics const & fm = theFontMetrics(
971 text_->labelFont(par));
972 w += fm.width(par.layout().labelsep);
973 if (par.isLineSeparator(i - 1))
974 w -= singleWidth(pit, i - 1);
975 w = max(w, label_end);
978 // a line separator at the end of a line (but not at the end of a
979 // paragraph) will not be drawn and should therefore not count for
981 if (!par.isLineSeparator(i) || i != end - 1 || end == par.size())
982 w += pm.singleWidth(i, *fi);
984 // add inline completion width
985 if (inlineCompletionLPos == i) {
986 docstring const & completion = bv_->inlineCompletion();
987 if (completion.length() > 0)
988 w += theFontMetrics(*fi).width(completion);
993 // count the paragraph end marker.
994 if (end == par.size() && lyxrc.paragraph_markers) {
995 ParagraphList const & pars_ = text_->paragraphs();
996 if (size_type(pit + 1) < pars_.size()) {
997 // enlarge the last character to hold the
999 docstring const s(1, char_type(0x00B6));
1001 w += theFontMetrics(f).width(s);
1005 if (body_pos > 0 && body_pos >= end) {
1006 FontMetrics const & fm = theFontMetrics(
1007 text_->labelFont(par));
1008 w += fm.width(par.layout().labelsep);
1009 if (end > 0 && par.isLineSeparator(end - 1))
1010 w -= singleWidth(pit, end - 1);
1011 w = max(w, label_end);
1014 return w + right_margin;
1018 void TextMetrics::setRowHeight(Row & row, pit_type const pit,
1019 bool topBottomSpace) const
1021 Paragraph const & par = text_->getPar(pit);
1022 // get the maximum ascent and the maximum descent
1023 double layoutasc = 0;
1024 double layoutdesc = 0;
1025 double const dh = defaultRowHeight();
1027 // ok, let us initialize the maxasc and maxdesc value.
1028 // Only the fontsize count. The other properties
1029 // are taken from the layoutfont. Nicer on the screen :)
1030 Layout const & layout = par.layout();
1032 // as max get the first character of this row then it can
1033 // increase but not decrease the height. Just some point to
1034 // start with so we don't have to do the assignment below too
1036 Buffer const & buffer = bv_->buffer();
1037 Font font = displayFont(pit, row.pos());
1038 FontSize const tmpsize = font.fontInfo().size();
1039 font.fontInfo() = text_->layoutFont(pit);
1040 FontSize const size = font.fontInfo().size();
1041 font.fontInfo().setSize(tmpsize);
1043 FontInfo labelfont = text_->labelFont(par);
1045 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1046 FontMetrics const & fontmetrics = theFontMetrics(font);
1048 // these are minimum values
1049 double const spacing_val = layout.spacing.getValue()
1050 * text_->spacing(par);
1051 //lyxerr << "spacing_val = " << spacing_val << endl;
1052 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
1053 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
1055 // insets may be taller
1056 ParagraphMetrics const & pm = par_metrics_[pit];
1057 InsetList::const_iterator ii = par.insetList().begin();
1058 InsetList::const_iterator iend = par.insetList().end();
1059 for ( ; ii != iend; ++ii) {
1060 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
1061 Dimension const & dim = pm.insetDimension(ii->inset);
1062 maxasc = max(maxasc, dim.ascent());
1063 maxdesc = max(maxdesc, dim.descent());
1067 // Check if any custom fonts are larger (Asger)
1068 // This is not completely correct, but we can live with the small,
1069 // cosmetic error for now.
1073 par.highestFontInRange(row.pos(), row.endpos(), size);
1074 if (maxsize > font.fontInfo().size()) {
1075 // use standard paragraph font with the maximal size
1076 FontInfo maxfont = font.fontInfo();
1077 maxfont.setSize(maxsize);
1078 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
1079 maxasc = max(maxasc, maxfontmetrics.maxAscent());
1080 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
1083 // This is nicer with box insets:
1087 ParagraphList const & pars = text_->paragraphs();
1088 Inset const & inset = text_->inset();
1090 // is it a top line?
1091 if (row.pos() == 0 && topBottomSpace) {
1092 BufferParams const & bufparams = buffer.params();
1093 // some parskips VERY EASY IMPLEMENTATION
1094 if (bufparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1095 && !inset.getLayout().parbreakIsNewline()
1096 && !par.layout().parbreak_is_newline
1098 && ((layout.isParagraph() && par.getDepth() == 0)
1099 || (pars[pit - 1].layout().isParagraph()
1100 && pars[pit - 1].getDepth() == 0))) {
1101 maxasc += bufparams.getDefSkip().inPixels(*bv_);
1104 if (par.params().startOfAppendix())
1105 maxasc += int(3 * dh);
1107 // special code for the top label
1108 if (layout.labelIsAbove()
1109 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1110 && !par.labelString().empty())
1113 labelfont_metrics.maxHeight()
1114 * layout.spacing.getValue()
1115 * text_->spacing(par)
1116 + (layout.topsep + layout.labelbottomsep) * dh);
1119 // Add the layout spaces, for example before and after
1120 // a section, or between the items of a itemize or enumerate
1123 pit_type prev = text_->depthHook(pit, par.getDepth());
1124 Paragraph const & prevpar = pars[prev];
1126 && prevpar.layout() == layout
1127 && prevpar.getDepth() == par.getDepth()
1128 && prevpar.getLabelWidthString()
1129 == par.getLabelWidthString()) {
1130 layoutasc = layout.itemsep * dh;
1131 } else if (pit != 0 || row.pos() != 0) {
1132 if (layout.topsep > 0)
1133 layoutasc = layout.topsep * dh;
1136 prev = text_->outerHook(pit);
1137 if (prev != pit_type(pars.size())) {
1138 maxasc += int(pars[prev].layout().parsep * dh);
1139 } else if (pit != 0) {
1140 Paragraph const & prevpar = pars[pit - 1];
1141 if (prevpar.getDepth() != 0 ||
1142 prevpar.layout() == layout) {
1143 maxasc += int(layout.parsep * dh);
1148 // is it a bottom line?
1149 if (row.endpos() >= par.size() && topBottomSpace) {
1150 // add the layout spaces, for example before and after
1151 // a section, or between the items of a itemize or enumerate
1153 pit_type nextpit = pit + 1;
1154 if (nextpit != pit_type(pars.size())) {
1155 pit_type cpit = pit;
1157 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1158 double usual = pars[cpit].layout().bottomsep * dh;
1160 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1161 if (pars[cpit].layout() != pars[nextpit].layout()
1162 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1164 unusual = pars[cpit].layout().bottomsep * dh;
1166 layoutdesc = max(unusual, usual);
1167 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1168 if (pars[cpit].layout() != pars[nextpit].layout()
1169 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1170 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1175 // incalculate the layout spaces
1176 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1177 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1179 // FIXME: the correct way is to do the following is to move the
1180 // following code in another method specially tailored for the
1181 // main Text. The following test is thus bogus.
1182 // Top and bottom margin of the document (only at top-level)
1183 if (main_text_ && topBottomSpace) {
1184 if (pit == 0 && row.pos() == 0)
1186 if (pit + 1 == pit_type(pars.size()) &&
1187 row.endpos() == par.size() &&
1188 !(row.endpos() > 0 && par.isNewline(row.endpos() - 1)))
1192 row.dimension().asc = maxasc + labeladdon;
1193 row.dimension().des = maxdesc;
1197 // x is an absolute screen coord
1198 // returns the column near the specified x-coordinate of the row
1199 // x is set to the real beginning of this column
1200 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1201 Row const & row, int & x, bool & boundary) const
1203 Buffer const & buffer = bv_->buffer();
1205 /// For the main Text, it is possible that this pit is not
1206 /// yet in the CoordCache when moving cursor up.
1207 /// x Paragraph coordinate is always 0 for main text anyway.
1208 int const xo = origin_.x_;
1210 Paragraph const & par = text_->getPar(pit);
1212 bidi.computeTables(par, buffer, row);
1214 pos_type vc = row.pos();
1215 pos_type const end = row.endpos();
1217 Layout const & layout = par.layout();
1219 bool left_side = false;
1221 pos_type body_pos = par.beginOfBody();
1223 double tmpx = row.x;
1224 double last_tmpx = tmpx;
1227 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1230 // check for empty row
1236 // This (rtl_support test) is not needed, but gives
1237 // some speedup if rtl_support == false
1238 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1240 // If lastrow is false, we don't need to compute
1241 // the value of rtl.
1242 bool const rtl_on_lastrow = lastrow ? text_->isRTL(par) : false;
1244 while (vc < end && tmpx <= x) {
1245 c = bidi.vis2log(vc);
1247 if (body_pos > 0 && c == body_pos - 1) {
1248 FontMetrics const & fm = theFontMetrics(
1249 text_->labelFont(par));
1250 tmpx += row.label_hfill + fm.width(layout.labelsep);
1251 if (par.isLineSeparator(body_pos - 1))
1252 tmpx -= singleWidth(pit, body_pos - 1);
1255 tmpx += singleWidth(pit, c);
1256 if (par.isSeparator(c) && c >= body_pos)
1257 tmpx += row.separator;
1261 if ((tmpx + last_tmpx) / 2 > x) {
1266 // This shouldn't happen. But we can reset and try to continue.
1267 LASSERT(vc <= end, vc = end);
1272 ((rtl_on_lastrow && left_side && vc == row.pos() && x < tmpx - 5) ||
1273 (!rtl_on_lastrow && !left_side && vc == end && x > tmpx + 5))) {
1274 if (!par.isNewline(end - 1))
1276 } else if (vc == row.pos()) {
1277 c = bidi.vis2log(vc);
1278 if (bidi.level(c) % 2 == 1)
1281 c = bidi.vis2log(vc - 1);
1282 bool const rtl = (bidi.level(c) % 2 == 1);
1283 if (left_side == rtl) {
1285 boundary = isRTLBoundary(pit, c);
1289 // I believe this code is not needed anymore (Jug 20050717)
1291 // The following code is necessary because the cursor position past
1292 // the last char in a row is logically equivalent to that before
1293 // the first char in the next row. That's why insets causing row
1294 // divisions -- Newline and display-style insets -- must be treated
1295 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1296 // Newline inset, air gap below:
1297 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1298 if (bidi.level(end -1) % 2 == 0)
1299 tmpx -= singleWidth(pit, end - 1);
1301 tmpx += singleWidth(pit, end - 1);
1305 // Air gap above display inset:
1306 if (row.pos() < end && c >= end && end < par.size()
1307 && par.isInset(end) && par.getInset(end)->display()) {
1310 // Air gap below display inset:
1311 if (row.pos() < end && c >= end && par.isInset(end - 1)
1312 && par.getInset(end - 1)->display()) {
1318 pos_type const col = c - row.pos();
1320 if (!c || end == par.size())
1323 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1328 return min(col, end - 1 - row.pos());
1332 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1334 // We play safe and use parMetrics(pit) to make sure the
1335 // ParagraphMetrics will be redone and OK to use if needed.
1336 // Otherwise we would use an empty ParagraphMetrics in
1337 // upDownInText() while in selection mode.
1338 ParagraphMetrics const & pm = parMetrics(pit);
1340 LBUFERR(row < int(pm.rows().size()));
1342 Row const & r = pm.rows()[row];
1343 return r.pos() + getColumnNearX(pit, r, x, bound);
1347 void TextMetrics::newParMetricsDown()
1349 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1350 pit_type const pit = last.first + 1;
1351 if (pit == int(text_->paragraphs().size()))
1354 // do it and update its position.
1356 par_metrics_[pit].setPosition(last.second.position()
1357 + last.second.descent() + par_metrics_[pit].ascent());
1361 void TextMetrics::newParMetricsUp()
1363 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1364 if (first.first == 0)
1367 pit_type const pit = first.first - 1;
1368 // do it and update its position.
1370 par_metrics_[pit].setPosition(first.second.position()
1371 - first.second.ascent() - par_metrics_[pit].descent());
1374 // y is screen coordinate
1375 pit_type TextMetrics::getPitNearY(int y)
1377 LASSERT(!text_->paragraphs().empty(), return -1);
1378 LASSERT(!par_metrics_.empty(), return -1);
1379 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1381 // look for highest numbered paragraph with y coordinate less than given y
1384 ParMetricsCache::const_iterator it = par_metrics_.begin();
1385 ParMetricsCache::const_iterator et = par_metrics_.end();
1386 ParMetricsCache::const_iterator last = et;
1389 ParagraphMetrics const & pm = it->second;
1391 if (y < it->second.position() - int(pm.ascent())) {
1392 // We are looking for a position that is before the first paragraph in
1393 // the cache (which is in priciple off-screen, that is before the
1396 // We are already at the first paragraph in the inset.
1398 // OK, this is the paragraph we are looking for.
1399 pit = it->first - 1;
1404 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1406 if (y >= last->second.position() + int(pm_last.descent())) {
1407 // We are looking for a position that is after the last paragraph in
1408 // the cache (which is in priciple off-screen), that is before the
1410 pit = last->first + 1;
1411 if (pit == int(text_->paragraphs().size()))
1412 // We are already at the last paragraph in the inset.
1414 // OK, this is the paragraph we are looking for.
1415 newParMetricsDown();
1419 for (; it != et; ++it) {
1420 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1421 << " y: " << it->second.position());
1423 ParagraphMetrics const & pm = par_metrics_[it->first];
1425 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1427 yy = it->second.position();
1431 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1437 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1438 bool assert_in_view, bool up)
1440 ParagraphMetrics const & pm = par_metrics_[pit];
1442 int yy = pm.position() - pm.ascent();
1443 LBUFERR(!pm.rows().empty());
1444 RowList::const_iterator rit = pm.rows().begin();
1445 RowList::const_iterator rlast = pm.rows().end();
1447 for (; rit != rlast; yy += rit->height(), ++rit)
1448 if (yy + rit->height() > y)
1451 if (assert_in_view) {
1452 if (!up && yy + rit->height() > y) {
1453 if (rit != pm.rows().begin()) {
1456 } else if (pit != 0) {
1459 ParagraphMetrics const & pm2 = par_metrics_[pit];
1460 rit = pm2.rows().end();
1464 } else if (up && yy != y) {
1466 y = yy + rit->height();
1468 } else if (pit < int(text_->paragraphs().size()) - 1) {
1470 newParMetricsDown();
1471 ParagraphMetrics const & pm2 = par_metrics_[pit];
1472 rit = pm2.rows().begin();
1481 // x,y are absolute screen coordinates
1482 // sets cursor recursively descending into nested editable insets
1483 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1484 bool assert_in_view, bool up)
1486 if (lyxerr.debugging(Debug::WORKAREA)) {
1487 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1488 cur.bv().coordCache().dump();
1490 pit_type pit = getPitNearY(y);
1491 LASSERT(pit != -1, return 0);
1493 int yy = y; // is modified by getPitAndRowNearY
1494 Row const & row = getPitAndRowNearY(yy, pit, assert_in_view, up);
1498 // Do we cover an inset?
1499 InsetList::InsetTable * it = checkInsetHit(pit, x, yy);
1502 // No inset, set position in the text
1503 bool bound = false; // is modified by getColumnNearX
1504 int xx = x; // is modified by getColumnNearX
1505 cur.pos() = row.pos()
1506 + getColumnNearX(pit, row, xx, bound);
1507 cur.boundary(bound);
1508 cur.setCurrentFont();
1513 Inset * inset = it->inset;
1514 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1516 // Set position in front of inset
1517 cur.pos() = it->pos;
1518 cur.boundary(false);
1521 // Try to descend recursively inside the inset.
1522 inset = inset->editXY(cur, x, yy);
1524 if (cur.top().text() == text_)
1525 cur.setCurrentFont();
1530 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1532 LASSERT(text_ == cur.text(), return);
1533 pit_type const pit = getPitNearY(y);
1534 LASSERT(pit != -1, return);
1536 ParagraphMetrics const & pm = par_metrics_[pit];
1538 int yy = pm.position() - pm.ascent();
1539 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1540 " pit: " << pit << " yy: " << yy);
1543 LBUFERR(pm.rows().size());
1544 for (; r < int(pm.rows().size()) - 1; ++r) {
1545 Row const & row = pm.rows()[r];
1546 if (int(yy + row.height()) > y)
1551 Row const & row = pm.rows()[r];
1553 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1557 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1559 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1561 text_->setCursor(cur, pit, pos, true, bound);
1562 // remember new position.
1567 //takes screen x,y coordinates
1568 InsetList::InsetTable * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1570 Paragraph const & par = text_->paragraphs()[pit];
1571 ParagraphMetrics const & pm = par_metrics_[pit];
1573 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1575 InsetList::const_iterator iit = par.insetList().begin();
1576 InsetList::const_iterator iend = par.insetList().end();
1577 for (; iit != iend; ++iit) {
1578 Inset * inset = iit->inset;
1580 LYXERR(Debug::DEBUG, "examining inset " << inset);
1582 if (!bv_->coordCache().getInsets().has(inset)) {
1583 LYXERR(Debug::DEBUG, "inset has no cached position");
1587 Dimension const & dim = pm.insetDimension(inset);
1588 Point p = bv_->coordCache().getInsets().xy(inset);
1590 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1591 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1594 && x <= p.x_ + dim.wid
1595 && y >= p.y_ - dim.asc
1596 && y <= p.y_ + dim.des) {
1597 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1598 return const_cast<InsetList::InsetTable *>(&(*iit));
1602 LYXERR(Debug::DEBUG, "No inset hit. ");
1607 //takes screen x,y coordinates
1608 Inset * TextMetrics::checkInsetHit(int x, int y)
1610 pit_type const pit = getPitNearY(y);
1611 LASSERT(pit != -1, return 0);
1612 InsetList::InsetTable * it = checkInsetHit(pit, x, y);
1621 int TextMetrics::cursorX(CursorSlice const & sl,
1622 bool boundary) const
1624 LASSERT(sl.text() == text_, return 0);
1625 pit_type const pit = sl.pit();
1626 Paragraph const & par = text_->paragraphs()[pit];
1627 ParagraphMetrics const & pm = par_metrics_[pit];
1628 if (pm.rows().empty())
1631 pos_type ppos = sl.pos();
1632 // Correct position in front of big insets
1633 bool const boundary_correction = ppos != 0 && boundary;
1634 if (boundary_correction)
1637 Row const & row = pm.getRow(sl.pos(), boundary);
1639 pos_type cursor_vpos = 0;
1641 Buffer const & buffer = bv_->buffer();
1644 bidi.computeTables(par, buffer, row);
1646 pos_type const row_pos = row.pos();
1647 pos_type const end = row.endpos();
1648 // Spaces at logical line breaks in bidi text must be skipped during
1649 // cursor positioning. However, they may appear visually in the middle
1650 // of a row; they must be skipped, wherever they are...
1651 // * logically "abc_[HEBREW_\nHEBREW]"
1652 // * visually "abc_[_WERBEH\nWERBEH]"
1653 pos_type skipped_sep_vpos = -1;
1656 cursor_vpos = row_pos;
1657 else if (ppos >= end)
1658 cursor_vpos = text_->isRTL(par) ? row_pos : end;
1659 else if (ppos > row_pos && ppos >= end)
1660 //FIXME: this code is never reached!
1661 // (see http://www.lyx.org/trac/changeset/8251)
1662 // Place cursor after char at (logical) position pos - 1
1663 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1664 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1666 // Place cursor before char at (logical) position ppos
1667 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1668 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1670 pos_type body_pos = par.beginOfBody();
1672 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1675 // check for possible inline completion in this row
1676 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1677 pos_type inlineCompletionVPos = -1;
1678 if (inlineCompletionPos.inTexted()
1679 && inlineCompletionPos.text() == text_
1680 && inlineCompletionPos.pit() == pit
1681 && inlineCompletionPos.pos() - 1 >= row_pos
1682 && inlineCompletionPos.pos() - 1 < end) {
1683 // draw logically behind the previous character
1684 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1687 // Use font span to speed things up, see below
1691 // If the last logical character is a separator, skip it, unless
1692 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1693 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1694 skipped_sep_vpos = bidi.log2vis(end - 1);
1696 if (lyxrc.paragraph_markers && text_->isRTL(par)) {
1697 ParagraphList const & pars_ = text_->paragraphs();
1698 if (size_type(pit + 1) < pars_.size()) {
1700 docstring const s = docstring(1, char_type(0x00B6));
1701 x += theFontMetrics(f).width(s);
1705 // Inline completion RTL special case row_pos == cursor_pos:
1706 // "__|b" => cursor_pos is right of __
1707 if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1708 font = displayFont(pit, row_pos + 1);
1709 docstring const & completion = bv_->inlineCompletion();
1710 if (font.isRightToLeft() && completion.length() > 0)
1711 x += theFontMetrics(font.fontInfo()).width(completion);
1714 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1715 // Skip the separator which is at the logical end of the row
1716 if (vpos == skipped_sep_vpos)
1718 pos_type pos = bidi.vis2log(vpos);
1719 if (body_pos > 0 && pos == body_pos - 1) {
1720 FontMetrics const & labelfm = theFontMetrics(
1721 text_->labelFont(par));
1722 x += row.label_hfill + labelfm.width(par.layout().labelsep);
1723 if (par.isLineSeparator(body_pos - 1))
1724 x -= singleWidth(pit, body_pos - 1);
1727 // Use font span to speed things up, see above
1728 if (pos < font_span.first || pos > font_span.last) {
1729 font_span = par.fontSpan(pos);
1730 font = displayFont(pit, pos);
1733 x += pm.singleWidth(pos, font);
1735 // Inline completion RTL case:
1736 // "a__|b", __ of b => non-boundary a-pos is right of __
1737 if (vpos + 1 == inlineCompletionVPos
1738 && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1739 font = displayFont(pit, vpos + 1);
1740 docstring const & completion = bv_->inlineCompletion();
1741 if (font.isRightToLeft() && completion.length() > 0)
1742 x += theFontMetrics(font.fontInfo()).width(completion);
1745 // Inline completion LTR case:
1746 // "b|__a", __ of b => non-boundary a-pos is in front of __
1747 if (vpos == inlineCompletionVPos
1748 && (vpos + 1 < cursor_vpos || boundary_correction)) {
1749 font = displayFont(pit, vpos);
1750 docstring const & completion = bv_->inlineCompletion();
1751 if (!font.isRightToLeft() && completion.length() > 0)
1752 x += theFontMetrics(font.fontInfo()).width(completion);
1755 if (par.isSeparator(pos) && pos >= body_pos)
1759 // see correction above
1760 if (boundary_correction) {
1761 if (isRTL(sl, boundary))
1762 x -= singleWidth(pit, ppos);
1764 x += singleWidth(pit, ppos);
1771 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1773 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1774 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1775 if (pm.rows().empty())
1779 h -= par_metrics_[0].rows()[0].ascent();
1780 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1781 h += par_metrics_[pit].height();
1784 if (pos && boundary)
1786 size_t const rend = pm.pos2row(pos);
1787 for (size_t rit = 0; rit != rend; ++rit)
1788 h += pm.rows()[rit].height();
1789 h += pm.rows()[rend].ascent();
1794 // the cursor set functions have a special mechanism. When they
1795 // realize you left an empty paragraph, they will delete it.
1797 bool TextMetrics::cursorHome(Cursor & cur)
1799 LASSERT(text_ == cur.text(), return false);
1800 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1801 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1802 return text_->setCursor(cur, cur.pit(), row.pos());
1806 bool TextMetrics::cursorEnd(Cursor & cur)
1808 LASSERT(text_ == cur.text(), return false);
1809 // if not on the last row of the par, put the cursor before
1810 // the final space exept if I have a spanning inset or one string
1811 // is so long that we force a break.
1812 pos_type end = cur.textRow().endpos();
1814 // empty text, end-1 is no valid position
1816 bool boundary = false;
1817 if (end != cur.lastpos()) {
1818 if (!cur.paragraph().isLineSeparator(end-1)
1819 && !cur.paragraph().isNewline(end-1))
1824 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1828 void TextMetrics::deleteLineForward(Cursor & cur)
1830 LASSERT(text_ == cur.text(), return);
1831 if (cur.lastpos() == 0) {
1832 // Paragraph is empty, so we just go forward
1833 text_->cursorForward(cur);
1836 cur.setSelection(true); // to avoid deletion
1839 // What is this test for ??? (JMarc)
1840 if (!cur.selection())
1841 text_->deleteWordForward(cur);
1843 cap::cutSelection(cur, true, false);
1844 cur.checkBufferStructure();
1849 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1851 ParagraphList const & pars = text_->paragraphs();
1852 return row.endpos() >= pars[pit].size()
1853 && pit + 1 == pit_type(pars.size());
1857 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1859 return row.pos() == 0 && pit == 0;
1863 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1865 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1869 int TextMetrics::leftMargin(int max_width,
1870 pit_type const pit, pos_type const pos) const
1872 ParagraphList const & pars = text_->paragraphs();
1874 LASSERT(pit >= 0, return 0);
1875 LASSERT(pit < int(pars.size()), return 0);
1876 Paragraph const & par = pars[pit];
1877 LASSERT(pos >= 0, return 0);
1878 LASSERT(pos <= par.size(), return 0);
1879 Buffer const & buffer = bv_->buffer();
1880 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1881 DocumentClass const & tclass = buffer.params().documentClass();
1882 Layout const & layout = par.layout();
1884 docstring parindent = layout.parindent;
1888 if (text_->isMainText())
1889 l_margin += bv_->leftMargin();
1891 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1892 tclass.leftmargin());
1894 if (par.getDepth() != 0) {
1895 // find the next level paragraph
1896 pit_type newpar = text_->outerHook(pit);
1897 if (newpar != pit_type(pars.size())) {
1898 if (pars[newpar].layout().isEnvironment()) {
1899 l_margin = leftMargin(max_width, newpar);
1900 // Remove the parindent that has been added
1901 // if the paragraph was empty.
1902 if (pars[newpar].empty()) {
1903 docstring pi = pars[newpar].layout().parindent;
1904 l_margin -= theFontMetrics(
1905 buffer.params().getFont()).signedWidth(pi);
1908 if (tclass.isDefaultLayout(par.layout())
1909 || tclass.isPlainLayout(par.layout())) {
1910 if (pars[newpar].params().noindent())
1913 parindent = pars[newpar].layout().parindent;
1918 // This happens after sections or environments in standard classes.
1919 // We have to check the previous layout at same depth.
1920 if (tclass.isDefaultLayout(par.layout()) && pit > 0
1921 && pars[pit - 1].getDepth() >= par.getDepth()) {
1922 pit_type prev = text_->depthHook(pit, par.getDepth());
1923 if (pars[prev < pit ? prev : pit - 1].layout().nextnoindent)
1927 FontInfo const labelfont = text_->labelFont(par);
1928 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1930 switch (layout.margintype) {
1931 case MARGIN_DYNAMIC:
1932 if (!layout.leftmargin.empty()) {
1933 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1936 if (!par.labelString().empty()) {
1937 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1938 l_margin += labelfont_metrics.width(par.labelString());
1939 l_margin += labelfont_metrics.width(layout.labelsep);
1943 case MARGIN_MANUAL: {
1944 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1945 // The width of an empty par, even with manual label, should be 0
1946 if (!par.empty() && pos >= par.beginOfBody()) {
1947 if (!par.getLabelWidthString().empty()) {
1948 docstring labstr = par.getLabelWidthString();
1949 l_margin += labelfont_metrics.width(labstr);
1950 l_margin += labelfont_metrics.width(layout.labelsep);
1956 case MARGIN_STATIC: {
1957 l_margin += theFontMetrics(buffer.params().getFont()).
1958 signedWidth(layout.leftmargin) * 4 / (par.getDepth() + 4);
1962 case MARGIN_FIRST_DYNAMIC:
1963 if (layout.labeltype == LABEL_MANUAL) {
1964 // if we are at position 0, we are never in the body
1965 if (pos > 0 && pos >= par.beginOfBody())
1966 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1968 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1970 // Special case to fix problems with
1972 || (layout.labeltype == LABEL_STATIC
1973 && layout.latextype == LATEX_ENVIRONMENT
1974 && !text_->isFirstInSequence(pit))) {
1975 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1976 } else if (!layout.labelIsAbove()) {
1977 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1978 l_margin += labelfont_metrics.width(layout.labelsep);
1979 l_margin += labelfont_metrics.width(par.labelString());
1983 case MARGIN_RIGHT_ADDRESS_BOX: {
1985 // The left margin depends on the widest row in this paragraph.
1986 // This code is wrong because it depends on the rows, but at the
1987 // same time this function is used in redoParagraph to construct
1989 ParagraphMetrics const & pm = par_metrics_[pit];
1990 RowList::const_iterator rit = pm.rows().begin();
1991 RowList::const_iterator end = pm.rows().end();
1992 int minfill = max_width;
1993 for ( ; rit != end; ++rit)
1994 if (rit->fill() < minfill)
1995 minfill = rit->fill();
1996 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(layout.leftmargin);
1997 l_margin += minfill;
1999 // also wrong, but much shorter.
2000 l_margin += max_width / 2;
2005 if (!par.params().leftIndent().zero())
2006 l_margin += par.params().leftIndent().inPixels(max_width);
2010 if (par.params().align() == LYX_ALIGN_LAYOUT)
2011 align = layout.align;
2013 align = par.params().align();
2015 // set the correct parindent
2017 && (layout.labeltype == LABEL_NO_LABEL
2018 || layout.labeltype == LABEL_ABOVE
2019 || layout.labeltype == LABEL_CENTERED
2020 || (layout.labeltype == LABEL_STATIC
2021 && layout.latextype == LATEX_ENVIRONMENT
2022 && !text_->isFirstInSequence(pit)))
2023 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
2024 && !par.params().noindent()
2025 // in some insets, paragraphs are never indented
2026 && !text_->inset().neverIndent()
2027 // display style insets are always centered, omit indentation
2030 && par.getInset(pos)->display())
2031 && (!(tclass.isDefaultLayout(par.layout())
2032 || tclass.isPlainLayout(par.layout()))
2033 || buffer.params().paragraph_separation
2034 == BufferParams::ParagraphIndentSeparation)
2037 // use the parindent of the layout when the default indentation is
2038 // used otherwise use the indentation set in the document settings
2039 if (buffer.params().getIndentation().asLyXCommand() == "default")
2040 l_margin += theFontMetrics(
2041 buffer.params().getFont()).signedWidth(parindent);
2043 l_margin += buffer.params().getIndentation().inPixels(*bv_);
2050 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
2052 ParagraphMetrics const & pm = par_metrics_[pit];
2054 return pm.singleWidth(pos, displayFont(pit, pos));
2058 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
2060 if (par_metrics_.empty())
2066 ParMetricsCache::iterator it = par_metrics_.begin();
2067 ParMetricsCache::iterator const pm_end = par_metrics_.end();
2068 y -= it->second.ascent();
2069 for (; it != pm_end; ++it) {
2070 ParagraphMetrics const & pmi = it->second;
2072 pit_type const pit = it->first;
2073 // Save the paragraph position in the cache.
2074 it->second.setPosition(y);
2075 drawParagraph(pi, pit, x, y);
2081 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
2083 BufferParams const & bparams = bv_->buffer().params();
2084 ParagraphMetrics const & pm = par_metrics_[pit];
2085 if (pm.rows().empty())
2089 bool const original_drawing_state = pi.pain.isDrawingEnabled();
2090 int const ww = bv_->workHeight();
2091 size_t const nrows = pm.rows().size();
2093 Cursor const & cur = bv_->cursor();
2094 DocIterator sel_beg = cur.selectionBegin();
2095 DocIterator sel_end = cur.selectionEnd();
2096 bool selection = cur.selection()
2097 // This is our text.
2098 && cur.text() == text_
2099 // if the anchor is outside, this is not our selection
2100 && cur.normalAnchor().text() == text_
2101 && pit >= sel_beg.pit() && pit <= sel_end.pit();
2103 // We store the begin and end pos of the selection relative to this par
2104 DocIterator sel_beg_par = cur.selectionBegin();
2105 DocIterator sel_end_par = cur.selectionEnd();
2107 // We care only about visible selection.
2109 if (pit != sel_beg.pit()) {
2110 sel_beg_par.pit() = pit;
2111 sel_beg_par.pos() = 0;
2113 if (pit != sel_end.pit()) {
2114 sel_end_par.pit() = pit;
2115 sel_end_par.pos() = sel_end_par.lastpos();
2119 for (size_t i = 0; i != nrows; ++i) {
2121 Row const & row = pm.rows()[i];
2125 bool const inside = (y + row.descent() >= 0
2126 && y - row.ascent() < ww);
2127 // It is not needed to draw on screen if we are not inside.
2128 pi.pain.setDrawingEnabled(inside && original_drawing_state);
2129 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
2132 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2134 row.setSelection(-1, -1);
2136 // The row knows nothing about the paragraph, so we have to check
2137 // whether this row is the first or last and update the margins.
2138 if (row.selection()) {
2139 if (row.sel_beg == 0)
2140 row.begin_margin_sel = sel_beg.pit() < pit;
2141 if (row.sel_end == sel_end_par.lastpos())
2142 row.end_margin_sel = sel_end.pit() > pit;
2145 // Row signature; has row changed since last paint?
2146 row.setCrc(pm.computeRowSignature(row, bparams));
2147 bool row_has_changed = row.changed();
2149 // Take this opportunity to spellcheck the row contents.
2150 if (row_has_changed && lyxrc.spellcheck_continuously) {
2151 text_->getPar(pit).spellCheck();
2154 // Don't paint the row if a full repaint has not been requested
2155 // and if it has not changed.
2156 if (!pi.full_repaint && !row_has_changed) {
2157 // Paint only the insets if the text itself is
2159 rp.paintOnlyInsets();
2164 // Clear background of this row if paragraph background was not
2165 // already cleared because of a full repaint.
2166 if (!pi.full_repaint && row_has_changed) {
2167 pi.pain.fillRectangle(x, y - row.ascent(),
2168 width(), row.height(), pi.background_color);
2171 // Instrumentation for testing row cache (see also
2173 if (lyxerr.debugging(Debug::PAINTING) && inside
2174 && (row.selection() || pi.full_repaint || row_has_changed)) {
2175 string const foreword = text_->isMainText() ?
2176 "main text redraw " : "inset text redraw: ";
2177 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
2178 << " row_selection=" << row.selection()
2179 << " full_repaint=" << pi.full_repaint
2180 << " row_has_changed=" << row_has_changed);
2183 // Backup full_repaint status and force full repaint
2184 // for inner insets as the Row has been cleared out.
2185 bool tmp = pi.full_repaint;
2186 pi.full_repaint = true;
2188 rp.paintSelection();
2191 rp.paintChangeBar();
2192 bool const is_rtl = text_->isRTL(text_->getPar(pit));
2193 if (i == 0 && !is_rtl)
2195 if (i == nrows - 1 && is_rtl)
2198 if (i == nrows - 1 && !is_rtl)
2200 if (i == 0 && is_rtl)
2204 // Restore full_repaint status.
2205 pi.full_repaint = tmp;
2207 // Re-enable screen drawing for future use of the painter.
2208 pi.pain.setDrawingEnabled(original_drawing_state);
2210 //LYXERR(Debug::PAINTING, ".");
2214 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2215 Dimension & dim) const
2217 Cursor const & bvcur = cur.bv().cursor();
2219 // get word in front of cursor
2220 docstring word = text_->previousWord(bvcur.top());
2221 DocIterator wordStart = bvcur;
2222 wordStart.pos() -= word.length();
2224 // get position on screen of the word start and end
2225 //FIXME: Is it necessary to explicitly set this to false?
2226 wordStart.boundary(false);
2227 Point lxy = cur.bv().getPos(wordStart);
2228 Point rxy = cur.bv().getPos(bvcur);
2230 // calculate dimensions of the word
2232 row.pos(wordStart.pos());
2233 row.endpos(bvcur.pos());
2234 setRowHeight(row, bvcur.pit(), false);
2235 dim = row.dimension();
2236 dim.wid = abs(rxy.x_ - lxy.x_);
2238 // calculate position of word
2240 x = min(rxy.x_, lxy.x_);
2242 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2243 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2246 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2248 // ParagraphMetrics const & pm = par_metrics_[pit];
2249 // Row const & r = pm.rows()[row];
2255 int defaultRowHeight()
2257 return int(theFontMetrics(sane_font).maxHeight() * 1.2);