2 * \file src/TextMetrics.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * \author Jürgen Vigna
13 * \author Abdelrazak Younes
15 * Full author contact details are available in file CREDITS.
20 #include "TextMetrics.h"
24 #include "buffer_funcs.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "CoordCache.h"
29 #include "CutAndPaste.h"
30 #include "FuncRequest.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"
44 #include "insets/InsetText.h"
46 #include "mathed/MacroTable.h"
47 #include "mathed/MathMacroTemplate.h"
49 #include "frontends/FontMetrics.h"
50 #include "frontends/Painter.h"
52 #include "support/debug.h"
54 #include "support/lassert.h"
61 using frontend::FontMetrics;
63 static int numberOfSeparators(Paragraph const & par, Row const & row)
65 pos_type const first = max(row.pos(), par.beginOfBody());
66 pos_type const last = row.endpos() - 1;
68 for (pos_type p = first; p < last; ++p) {
69 if (par.isSeparator(p))
76 static int numberOfLabelHfills(Paragraph const & par, Row const & row)
78 pos_type last = row.endpos() - 1;
79 pos_type first = row.pos();
81 // hfill *DO* count at the beginning of paragraphs!
83 while (first < last && par.isHfill(first))
87 last = min(last, par.beginOfBody());
89 for (pos_type p = first; p < last; ++p) {
97 static int numberOfHfills(Paragraph const & par, Row const & row)
99 pos_type const last = row.endpos();
100 pos_type first = row.pos();
102 // hfill *DO* count at the beginning of paragraphs!
104 while (first < last && par.isHfill(first))
108 first = max(first, par.beginOfBody());
111 for (pos_type p = first; p < last; ++p) {
119 /////////////////////////////////////////////////////////////////////
123 /////////////////////////////////////////////////////////////////////
126 TextMetrics::TextMetrics(BufferView * bv, Text * text)
127 : bv_(bv), text_(text)
130 max_width_ = bv_->workWidth();
131 dim_.wid = max_width_;
135 //text_->updateLabels(bv->buffer());
139 bool TextMetrics::contains(pit_type pit) const
141 return par_metrics_.find(pit) != par_metrics_.end();
145 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
147 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
152 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
154 ParMetricsCache::const_iterator it = par_metrics_.begin();
155 return make_pair(it->first, &it->second);
159 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
161 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
162 return make_pair(it->first, &it->second);
166 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
168 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
169 if (pmc_it == par_metrics_.end()) {
170 pmc_it = par_metrics_.insert(
171 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
173 if (pmc_it->second.rows().empty() && redo)
175 return pmc_it->second;
179 int TextMetrics::parPosition(pit_type pit) const
181 if (pit < par_metrics_.begin()->first)
183 if (pit > par_metrics_.rbegin()->first)
186 return par_metrics_[pit].position();
190 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
192 LASSERT(mi.base.textwidth > 0, /**/);
193 max_width_ = mi.base.textwidth;
194 // backup old dimension.
195 Dimension const old_dim = dim_;
198 dim_.wid = min_width;
199 pit_type const npar = text_->paragraphs().size();
201 // If there is more than one row, expand the text to
202 // the full allowable width.
203 dim_.wid = max_width_;
205 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
206 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
208 bool changed = false;
210 for (pit_type pit = 0; pit != npar; ++pit) {
211 changed |= redoParagraph(pit);
212 ParagraphMetrics const & pm = par_metrics_[pit];
214 if (dim_.wid < pm.width())
215 dim_.wid = pm.width();
218 dim_.asc = par_metrics_[0].ascent();
219 dim_.des = h - dim_.asc;
220 //lyxerr << "dim_.wid " << dim_.wid << endl;
221 //lyxerr << "dim_.asc " << dim_.asc << endl;
222 //lyxerr << "dim_.des " << dim_.des << endl;
224 changed |= dim_ != old_dim;
230 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
232 return main_text_? pm.rightMargin(*bv_) : 0;
236 int TextMetrics::rightMargin(pit_type const pit) const
238 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
242 void TextMetrics::applyOuterFont(Font & font) const
245 lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
246 lf.fontInfo().realize(font.fontInfo());
247 lf.setLanguage(font.language());
252 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
254 LASSERT(pos >= 0, /**/);
256 ParagraphList const & pars = text_->paragraphs();
257 Paragraph const & par = pars[pit];
258 Layout const & layout = par.layout();
259 Buffer const & buffer = bv_->buffer();
261 BufferParams const & params = buffer.params();
262 pos_type const body_pos = par.beginOfBody();
264 // We specialize the 95% common case:
265 if (!par.getDepth()) {
266 Font f = par.getFontSettings(params, pos);
267 if (!text_->isMainText())
269 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
271 FontInfo const & lf = lab ? layout.labelfont : layout.font;
272 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
274 // In case the default family has been customized
275 if (lf.family() == INHERIT_FAMILY)
276 rlf.setFamily(params.getFont().fontInfo().family());
277 f.fontInfo().realize(rlf);
281 // The uncommon case need not be optimized as much
282 FontInfo const & layoutfont = pos < body_pos ?
283 layout.labelfont : layout.font;
285 Font font = par.getFontSettings(params, pos);
286 font.fontInfo().realize(layoutfont);
288 if (!text_->isMainText())
289 applyOuterFont(font);
291 // Realize against environment font information
292 // NOTE: the cast to pit_type should be removed when pit_type
293 // changes to a unsigned integer.
294 if (pit < pit_type(pars.size()))
295 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
297 // Realize with the fonts of lesser depth.
298 font.fontInfo().realize(params.getFont().fontInfo());
304 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
306 if (!lyxrc.rtl_support || !sl.text())
310 if (boundary && sl.pos() > 0)
313 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
317 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
319 if (!lyxrc.rtl_support)
322 // no RTL boundary at paragraph start
326 Font const & left_font = displayFont(pit, pos - 1);
328 return isRTLBoundary(pit, pos, left_font);
332 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
333 Font const & font) const
335 if (!lyxrc.rtl_support)
338 // no RTL boundary at paragraph start
342 ParagraphMetrics & pm = par_metrics_[pit];
343 // no RTL boundary in empty paragraph
344 if (pm.rows().empty())
347 pos_type endpos = pm.getRow(pos - 1, false).endpos();
348 pos_type startpos = pm.getRow(pos, false).pos();
349 // no RTL boundary at line start:
350 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
352 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
355 Paragraph const & par = text_->getPar(pit);
356 bool left = font.isVisibleRightToLeft();
358 if (pos == par.size())
359 right = par.isRTL(bv_->buffer().params());
361 right = displayFont(pit, pos).isVisibleRightToLeft();
363 // no RTL boundary at line break:
364 // abc|\n -> move right -> abc\n (and not: abc\n|
366 if (startpos == pos && endpos == pos && endpos != par.size()
367 && (par.isNewline(pos - 1)
368 || par.isLineSeparator(pos - 1)
369 || par.isSeparator(pos - 1)))
372 return left != right;
376 bool TextMetrics::redoParagraph(pit_type const pit)
378 Paragraph & par = text_->getPar(pit);
379 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
380 // redoParagraph() recursively inside parMetrics.
381 Dimension old_dim = parMetrics(pit, false).dim();
382 ParagraphMetrics & pm = par_metrics_[pit];
385 Buffer & buffer = bv_->buffer();
386 main_text_ = (text_ == &buffer.text());
387 bool changed = false;
389 // FIXME: This check ought to be done somewhere else. It is the reason
390 // why text_ is not const. But then, where else to do it?
391 // Well, how can you end up with either (a) a biblio environment that
392 // has no InsetBibitem or (b) a biblio environment with more than one
393 // InsetBibitem? I think the answer is: when paragraphs are merged;
394 // when layout is set; when material is pasted.
395 int const moveCursor = par.checkBiblio(buffer);
397 const_cast<Cursor &>(bv_->cursor()).posForward();
398 else if (moveCursor < 0) {
399 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
400 if (cursor.pos() >= -moveCursor)
401 cursor.posBackward();
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 bv_->buffer().updateLabels();
417 parPos = text_->macrocontextPosition();
418 LASSERT(!parPos.empty(), /**/);
423 // FIXME: We should always use getFont(), see documentation of
424 // noFontChange() in Inset.h.
425 Font const bufferfont = buffer.params().getFont();
426 InsetList::const_iterator ii = par.insetList().begin();
427 InsetList::const_iterator iend = par.insetList().end();
428 for (; ii != iend; ++ii) {
429 // position already initialized?
430 if (!parPos.empty()) {
431 parPos.pos() = ii->pos;
433 // A macro template would normally not be visible
434 // by itself. But the tex macro semantics allow
435 // recursion, so we artifically take the context
436 // after the macro template to simulate this.
437 if (ii->inset->lyxCode() == MATHMACRO_CODE)
441 // do the metric calculation
443 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
445 Font const & font = ii->inset->noFontChange() ?
446 bufferfont : displayFont(pit, ii->pos);
447 MacroContext mc(buffer, parPos);
448 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
449 ii->inset->metrics(mi, dim);
450 Dimension const old_dim = pm.insetDimension(ii->inset);
451 if (old_dim != dim) {
452 pm.setInsetDimension(ii->inset, dim);
457 par.setBeginOfBody();
459 size_t row_index = 0;
460 // maximum pixel width of a row
461 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
464 pos_type end = rowBreakPoint(width, pit, first);
465 if (row_index || end < par.size())
466 // If there is more than one row, expand the text to
467 // the full allowable width. This setting here is needed
468 // for the computeRowMetrics() below.
469 dim_.wid = max_width_;
471 dim = rowHeight(pit, first, end);
472 dim.wid = rowWidth(right_margin, pit, first, end);
473 if (row_index == pm.rows().size())
474 pm.rows().push_back(Row());
475 Row & row = pm.rows()[row_index];
476 row.setChanged(false);
479 row.setDimension(dim);
480 int const max_row_width = max(dim_.wid, dim.wid);
481 computeRowMetrics(pit, row, max_row_width);
485 pm.dim().wid = max(pm.dim().wid, dim.wid);
486 pm.dim().des += dim.height();
487 } while (first < par.size());
489 if (row_index < pm.rows().size())
490 pm.rows().resize(row_index);
492 // Make sure that if a par ends in newline, there is one more row
494 if (first > 0 && par.isNewline(first - 1)) {
495 Dimension dim = rowHeight(pit, first, first);
496 dim.wid = rowWidth(right_margin, pit, first, first);
497 if (row_index == pm.rows().size())
498 pm.rows().push_back(Row());
499 Row & row = pm.rows()[row_index];
500 row.setChanged(false);
503 row.setDimension(dim);
504 int const max_row_width = max(dim_.wid, dim.wid);
505 computeRowMetrics(pit, row, max_row_width);
506 pm.dim().des += dim.height();
509 pm.dim().asc += pm.rows()[0].ascent();
510 pm.dim().des -= pm.rows()[0].ascent();
512 changed |= old_dim.height() != pm.dim().height();
518 void TextMetrics::computeRowMetrics(pit_type const pit,
519 Row & row, int width) const
524 Paragraph const & par = text_->getPar(pit);
526 double w = width - row.width();
527 // FIXME: put back this assertion when the crash on new doc is solved.
528 //LASSERT(w >= 0, /**/);
530 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
531 //lyxerr << "row.width() " << row.width() << endl;
532 //lyxerr << "w " << w << endl;
534 bool const is_rtl = text_->isRTL(par);
536 row.x = rightMargin(pit);
538 row.x = leftMargin(max_width_, pit, row.pos());
540 // is there a manual margin with a manual label
541 Layout const & layout = par.layout();
543 if (layout.margintype == MARGIN_MANUAL
544 && layout.labeltype == LABEL_MANUAL) {
545 /// We might have real hfills in the label part
546 int nlh = numberOfLabelHfills(par, row);
548 // A manual label par (e.g. List) has an auto-hfill
549 // between the label text and the body of the
551 // But we don't want to do this auto hfill if the par
556 if (nlh && !par.getLabelWidthString().empty())
557 row.label_hfill = labelFill(pit, row) / double(nlh);
561 // are there any hfills in the row?
562 if (int const nh = numberOfHfills(par, row)) {
564 hfill = w / double(nh);
565 // we don't have to look at the alignment if it is ALIGN_LEFT and
566 // if the row is already larger then the permitted width as then
567 // we force the LEFT_ALIGN'edness!
568 } else if (int(row.width()) < max_width_) {
569 // is it block, flushleft or flushright?
570 // set x how you need it
572 if (par.params().align() == LYX_ALIGN_LAYOUT)
573 align = layout.align;
575 align = par.params().align();
577 // handle alignment inside tabular cells
578 Inset const & owner = text_->inset();
579 switch (owner.contentAlignment()) {
580 case LYX_ALIGN_CENTER:
582 case LYX_ALIGN_RIGHT:
583 if (align == LYX_ALIGN_NONE
584 || align == LYX_ALIGN_BLOCK)
585 align = owner.contentAlignment();
588 // unchanged (use align)
592 // Display-style insets should always be on a centered row
593 if (Inset const * inset = par.getInset(row.pos())) {
594 switch (inset->display()) {
595 case Inset::AlignLeft:
596 align = LYX_ALIGN_BLOCK;
598 case Inset::AlignCenter:
599 align = LYX_ALIGN_CENTER;
602 // unchanged (use align)
604 case Inset::AlignRight:
605 align = LYX_ALIGN_RIGHT;
611 case LYX_ALIGN_BLOCK: {
612 int const ns = numberOfSeparators(par, row);
613 bool disp_inset = false;
614 if (row.endpos() < par.size()) {
615 Inset const * in = par.getInset(row.endpos());
617 disp_inset = in->display();
619 // If we have separators, this is not the last row of a
620 // par, does not end in newline, and is not row above a
621 // display inset... then stretch it
623 && row.endpos() < par.size()
624 && !par.isNewline(row.endpos() - 1)
627 row.separator = w / ns;
628 //lyxerr << "row.separator " << row.separator << endl;
629 //lyxerr << "ns " << ns << endl;
635 case LYX_ALIGN_RIGHT:
638 case LYX_ALIGN_CENTER:
645 pos_type body_pos = par.beginOfBody();
646 pos_type end = row.endpos();
649 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
651 row.x += theFontMetrics(text_->labelFont(par)).
652 width(layout.labelsep);
654 row.x += row.label_hfill;
658 pos_type const endpos = row.endpos();
659 pos_type body_pos = par.beginOfBody();
661 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
664 ParagraphMetrics & pm = par_metrics_[pit];
665 InsetList::const_iterator ii = par.insetList().begin();
666 InsetList::const_iterator iend = par.insetList().end();
667 for ( ; ii != iend; ++ii) {
668 if (ii->pos >= endpos || ii->pos < row.pos()
669 || (ii->inset->lyxCode() != SPACE_CODE ||
670 !ii->inset->isStretchableSpace()))
672 Dimension dim = row.dimension();
673 if (pm.hfillExpansion(row, ii->pos))
674 dim.wid = int(ii->pos >= body_pos ?
675 max(hfill, 5.0) : row.label_hfill);
678 // Cache the inset dimension.
679 bv_->coordCache().insets().add(ii->inset, dim);
680 pm.setInsetDimension(ii->inset, dim);
685 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
687 Paragraph const & par = text_->getPar(pit);
689 pos_type last = par.beginOfBody();
690 LASSERT(last > 0, /**/);
692 // -1 because a label ends with a space that is in the label
695 // a separator at this end does not count
696 if (par.isLineSeparator(last))
700 for (pos_type i = row.pos(); i <= last; ++i)
701 w += singleWidth(pit, i);
703 docstring const & label = par.params().labelWidthString();
707 FontMetrics const & fm
708 = theFontMetrics(text_->labelFont(par));
710 return max(0, fm.width(label) - w);
714 // this needs special handling - only newlines count as a break point
715 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
717 pos_type const end = par.size();
720 if (par.isNewline(i))
727 int TextMetrics::labelEnd(pit_type const pit) const
729 // labelEnd is only needed if the layout fills a flushleft label.
730 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
732 // return the beginning of the body
733 return leftMargin(max_width_, pit);
739 * Calling Text::getFont is slow. While rebreaking we scan a
740 * paragraph from left to right calling getFont for every char. This
741 * simple class address this problem by hidding an optimization trick
742 * (not mine btw -AB): the font is reused in the whole font span. The
743 * class handles transparently the "hidden" (not part of the fontlist)
744 * label font (as getFont does).
750 FontIterator(TextMetrics const & tm,
751 Paragraph const & par, pit_type pit, pos_type pos)
752 : tm_(tm), par_(par), pit_(pit), pos_(pos),
753 font_(tm.displayFont(pit, pos)),
754 endspan_(par.fontSpan(pos).last),
755 bodypos_(par.beginOfBody())
759 Font const & operator*() const { return font_; }
762 FontIterator & operator++()
765 if (pos_ > endspan_ || pos_ == bodypos_) {
766 font_ = tm_.displayFont(pit_, pos_);
767 endspan_ = par_.fontSpan(pos_).last;
773 Font * operator->() { return &font_; }
777 TextMetrics const & tm_;
779 Paragraph const & par_;
794 pos_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
797 ParagraphMetrics const & pm = par_metrics_[pit];
798 Paragraph const & par = text_->getPar(pit);
799 pos_type const end = par.size();
800 if (pos == end || width < 0)
803 Layout const & layout = par.layout();
805 if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX)
806 return addressBreakPoint(pos, par);
808 pos_type const body_pos = par.beginOfBody();
810 // check for possible inline completion
811 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
812 pos_type inlineCompletionLPos = -1;
813 if (inlineCompletionPos.inTexted()
814 && inlineCompletionPos.text() == text_
815 && inlineCompletionPos.pit() == pit) {
816 // draw logically behind the previous character
817 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
820 // Now we iterate through until we reach the right margin
821 // or the end of the par, then choose the possible break
824 int label_end = labelEnd(pit);
825 int const left = leftMargin(max_width_, pit, pos);
828 // pixel width since last breakpoint
831 FontIterator fi = FontIterator(*this, par, pit, pos);
832 pos_type point = end;
834 for ( ; i < end; ++i, ++fi) {
835 int thiswidth = pm.singleWidth(i, *fi);
837 // add inline completion width
838 if (inlineCompletionLPos == i) {
839 docstring const & completion = bv_->inlineCompletion();
840 if (completion.length() > 0)
841 thiswidth += theFontMetrics(*fi).width(completion);
844 // add the auto-hfill from label end to the body
845 if (body_pos && i == body_pos) {
846 FontMetrics const & fm = theFontMetrics(
847 text_->labelFont(par));
848 int add = fm.width(layout.labelsep);
849 if (par.isLineSeparator(i - 1))
850 add -= singleWidth(pit, i - 1);
852 add = max(add, label_end - x);
857 chunkwidth += thiswidth;
859 // break before a character that will fall off
860 // the right of the row
862 // if no break before, break here
863 if (point == end || chunkwidth >= width - left) {
869 // exit on last registered breakpoint:
873 if (par.isNewline(i)) {
877 Inset const * inset = 0;
880 if ((inset = par.getInset(i + 1)) && inset->display()) {
885 if ((inset = par.getInset(i)) && inset->display()) {
891 inset = par.getInset(i);
892 if (!inset || inset->isChar()) {
893 // some insets are line separators too
894 if (par.isLineSeparator(i)) {
895 // register breakpoint:
902 // maybe found one, but the par is short enough.
903 if (i == end && x < width)
906 // manual labels cannot be broken in LaTeX. But we
907 // want to make our on-screen rendering of footnotes
909 if (body_pos && point < body_pos)
916 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
917 pos_type const first, pos_type const end) const
919 // get the pure distance
920 ParagraphMetrics const & pm = par_metrics_[pit];
921 Paragraph const & par = text_->getPar(pit);
922 int w = leftMargin(max_width_, pit, first);
923 int label_end = labelEnd(pit);
925 // check for possible inline completion
926 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
927 pos_type inlineCompletionLPos = -1;
928 if (inlineCompletionPos.inTexted()
929 && inlineCompletionPos.text() == text_
930 && inlineCompletionPos.pit() == pit) {
931 // draw logically behind the previous character
932 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
935 pos_type const body_pos = par.beginOfBody();
939 FontIterator fi = FontIterator(*this, par, pit, i);
940 for ( ; i < end; ++i, ++fi) {
941 if (body_pos > 0 && i == body_pos) {
942 FontMetrics const & fm = theFontMetrics(
943 text_->labelFont(par));
944 w += fm.width(par.layout().labelsep);
945 if (par.isLineSeparator(i - 1))
946 w -= singleWidth(pit, i - 1);
947 w = max(w, label_end);
950 // a line separator at the end of a line (but not at the end of a
951 // paragraph) will not be drawn and should therefore not count for
953 if (!par.isLineSeparator(i) || i != end - 1 || end == par.size())
954 w += pm.singleWidth(i, *fi);
956 // add inline completion width
957 if (inlineCompletionLPos == i) {
958 docstring const & completion = bv_->inlineCompletion();
959 if (completion.length() > 0)
960 w += theFontMetrics(*fi).width(completion);
965 if (body_pos > 0 && body_pos >= end) {
966 FontMetrics const & fm = theFontMetrics(
967 text_->labelFont(par));
968 w += fm.width(par.layout().labelsep);
969 if (end > 0 && par.isLineSeparator(end - 1))
970 w -= singleWidth(pit, end - 1);
971 w = max(w, label_end);
974 return w + right_margin;
978 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
979 pos_type const end, bool topBottomSpace) const
981 Paragraph const & par = text_->getPar(pit);
982 // get the maximum ascent and the maximum descent
983 double layoutasc = 0;
984 double layoutdesc = 0;
985 double const dh = defaultRowHeight();
987 // ok, let us initialize the maxasc and maxdesc value.
988 // Only the fontsize count. The other properties
989 // are taken from the layoutfont. Nicer on the screen :)
990 Layout const & layout = par.layout();
992 // as max get the first character of this row then it can
993 // increase but not decrease the height. Just some point to
994 // start with so we don't have to do the assignment below too
996 Buffer const & buffer = bv_->buffer();
997 Font font = displayFont(pit, first);
998 FontSize const tmpsize = font.fontInfo().size();
999 font.fontInfo() = text_->layoutFont(pit);
1000 FontSize const size = font.fontInfo().size();
1001 font.fontInfo().setSize(tmpsize);
1003 FontInfo labelfont = text_->labelFont(par);
1005 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1006 FontMetrics const & fontmetrics = theFontMetrics(font);
1008 // these are minimum values
1009 double const spacing_val = layout.spacing.getValue()
1010 * text_->spacing(par);
1011 //lyxerr << "spacing_val = " << spacing_val << endl;
1012 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
1013 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
1015 // insets may be taller
1016 ParagraphMetrics const & pm = par_metrics_[pit];
1017 InsetList::const_iterator ii = par.insetList().begin();
1018 InsetList::const_iterator iend = par.insetList().end();
1019 for ( ; ii != iend; ++ii) {
1020 if (ii->pos >= first && ii->pos < end) {
1021 Dimension const & dim = pm.insetDimension(ii->inset);
1022 maxasc = max(maxasc, dim.ascent());
1023 maxdesc = max(maxdesc, dim.descent());
1027 // Check if any custom fonts are larger (Asger)
1028 // This is not completely correct, but we can live with the small,
1029 // cosmetic error for now.
1033 par.highestFontInRange(first, end, size);
1034 if (maxsize > font.fontInfo().size()) {
1035 // use standard paragraph font with the maximal size
1036 FontInfo maxfont = font.fontInfo();
1037 maxfont.setSize(maxsize);
1038 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
1039 maxasc = max(maxasc, maxfontmetrics.maxAscent());
1040 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
1043 // This is nicer with box insets:
1047 ParagraphList const & pars = text_->paragraphs();
1048 Inset const & inset = text_->inset();
1050 // is it a top line?
1051 if (first == 0 && topBottomSpace) {
1052 BufferParams const & bufparams = buffer.params();
1053 // some parskips VERY EASY IMPLEMENTATION
1054 if (bufparams.paragraph_separation
1055 == BufferParams::ParagraphSkipSeparation
1056 && inset.lyxCode() != ERT_CODE
1057 && inset.lyxCode() != LISTINGS_CODE
1059 && ((layout.isParagraph() && par.getDepth() == 0)
1060 || (pars[pit - 1].layout().isParagraph()
1061 && pars[pit - 1].getDepth() == 0)))
1063 maxasc += bufparams.getDefSkip().inPixels(*bv_);
1066 if (par.params().startOfAppendix())
1067 maxasc += int(3 * dh);
1069 // This is special code for the chapter, since the label of this
1070 // layout is printed in an extra row
1071 if (layout.counter == "chapter"
1072 && !par.params().labelString().empty()) {
1073 labeladdon = int(labelfont_metrics.maxHeight()
1074 * layout.spacing.getValue()
1075 * text_->spacing(par));
1078 // special code for the top label
1079 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1080 || layout.labeltype == LABEL_BIBLIO
1081 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1082 && text_->isFirstInSequence(pit)
1083 && !par.labelString().empty())
1086 labelfont_metrics.maxHeight()
1087 * layout.spacing.getValue()
1088 * text_->spacing(par)
1089 + (layout.topsep + layout.labelbottomsep) * dh);
1092 // Add the layout spaces, for example before and after
1093 // a section, or between the items of a itemize or enumerate
1096 pit_type prev = text_->depthHook(pit, par.getDepth());
1097 Paragraph const & prevpar = pars[prev];
1099 && prevpar.layout() == layout
1100 && prevpar.getDepth() == par.getDepth()
1101 && prevpar.getLabelWidthString()
1102 == par.getLabelWidthString()) {
1103 layoutasc = layout.itemsep * dh;
1104 } else if (pit != 0 || first != 0) {
1105 if (layout.topsep > 0)
1106 layoutasc = layout.topsep * dh;
1109 prev = text_->outerHook(pit);
1110 if (prev != pit_type(pars.size())) {
1111 maxasc += int(pars[prev].layout().parsep * dh);
1112 } else if (pit != 0) {
1113 Paragraph const & prevpar = pars[pit - 1];
1114 if (prevpar.getDepth() != 0 ||
1115 prevpar.layout() == layout) {
1116 maxasc += int(layout.parsep * dh);
1121 // is it a bottom line?
1122 if (end >= par.size() && topBottomSpace) {
1123 // add the layout spaces, for example before and after
1124 // a section, or between the items of a itemize or enumerate
1126 pit_type nextpit = pit + 1;
1127 if (nextpit != pit_type(pars.size())) {
1128 pit_type cpit = pit;
1132 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1133 usual = pars[cpit].layout().bottomsep * dh;
1134 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1135 if (pars[cpit].layout() != pars[nextpit].layout()
1136 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1138 unusual = pars[cpit].layout().bottomsep * dh;
1140 layoutdesc = max(unusual, usual);
1141 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1142 if (pars[cpit].layout() != pars[nextpit].layout()
1143 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1144 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1149 // incalculate the layout spaces
1150 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1151 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1153 // FIXME: the correct way is to do the following is to move the
1154 // following code in another method specially tailored for the
1155 // main Text. The following test is thus bogus.
1156 // Top and bottom margin of the document (only at top-level)
1157 if (main_text_ && topBottomSpace) {
1158 if (pit == 0 && first == 0)
1160 if (pit + 1 == pit_type(pars.size()) &&
1161 end == par.size() &&
1162 !(end > 0 && par.isNewline(end - 1)))
1166 return Dimension(0, maxasc + labeladdon, maxdesc);
1170 // x is an absolute screen coord
1171 // returns the column near the specified x-coordinate of the row
1172 // x is set to the real beginning of this column
1173 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1174 Row const & row, int & x, bool & boundary) const
1176 Buffer const & buffer = bv_->buffer();
1178 /// For the main Text, it is possible that this pit is not
1179 /// yet in the CoordCache when moving cursor up.
1180 /// x Paragraph coordinate is always 0 for main text anyway.
1181 int const xo = origin_.x_;
1183 Paragraph const & par = text_->getPar(pit);
1185 bidi.computeTables(par, buffer, row);
1187 pos_type vc = row.pos();
1188 pos_type end = row.endpos();
1190 Layout const & layout = par.layout();
1192 bool left_side = false;
1194 pos_type body_pos = par.beginOfBody();
1196 double tmpx = row.x;
1197 double last_tmpx = tmpx;
1200 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1203 // check for empty row
1209 while (vc < end && tmpx <= x) {
1210 c = bidi.vis2log(vc);
1212 if (body_pos > 0 && c == body_pos - 1) {
1213 FontMetrics const & fm = theFontMetrics(
1214 text_->labelFont(par));
1215 tmpx += row.label_hfill + fm.width(layout.labelsep);
1216 if (par.isLineSeparator(body_pos - 1))
1217 tmpx -= singleWidth(pit, body_pos - 1);
1220 tmpx += singleWidth(pit, c);
1221 if (par.isSeparator(c) && c >= body_pos)
1222 tmpx += row.separator;
1226 if ((tmpx + last_tmpx) / 2 > x) {
1231 LASSERT(vc <= end, /**/); // This shouldn't happen.
1234 // This (rtl_support test) is not needed, but gives
1235 // some speedup if rtl_support == false
1236 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1238 // If lastrow is false, we don't need to compute
1239 // the value of rtl.
1240 bool const rtl = lastrow ? text_->isRTL(par) : false;
1242 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1243 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1244 if (!par.isNewline(end - 1))
1246 } else if (vc == row.pos()) {
1247 c = bidi.vis2log(vc);
1248 if (bidi.level(c) % 2 == 1)
1251 c = bidi.vis2log(vc - 1);
1252 bool const rtl = (bidi.level(c) % 2 == 1);
1253 if (left_side == rtl) {
1255 boundary = isRTLBoundary(pit, c);
1259 // I believe this code is not needed anymore (Jug 20050717)
1261 // The following code is necessary because the cursor position past
1262 // the last char in a row is logically equivalent to that before
1263 // the first char in the next row. That's why insets causing row
1264 // divisions -- Newline and display-style insets -- must be treated
1265 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1266 // Newline inset, air gap below:
1267 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1268 if (bidi.level(end -1) % 2 == 0)
1269 tmpx -= singleWidth(pit, end - 1);
1271 tmpx += singleWidth(pit, end - 1);
1275 // Air gap above display inset:
1276 if (row.pos() < end && c >= end && end < par.size()
1277 && par.isInset(end) && par.getInset(end)->display()) {
1280 // Air gap below display inset:
1281 if (row.pos() < end && c >= end && par.isInset(end - 1)
1282 && par.getInset(end - 1)->display()) {
1288 pos_type const col = c - row.pos();
1290 if (!c || end == par.size())
1293 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1298 return min(col, end - 1 - row.pos());
1302 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1304 // We play safe and use parMetrics(pit) to make sure the
1305 // ParagraphMetrics will be redone and OK to use if needed.
1306 // Otherwise we would use an empty ParagraphMetrics in
1307 // upDownInText() while in selection mode.
1308 ParagraphMetrics const & pm = parMetrics(pit);
1310 LASSERT(row < int(pm.rows().size()), /**/);
1312 Row const & r = pm.rows()[row];
1313 return r.pos() + getColumnNearX(pit, r, x, bound);
1317 void TextMetrics::newParMetricsDown()
1319 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1320 pit_type const pit = last.first + 1;
1321 if (pit == int(text_->paragraphs().size()))
1324 // do it and update its position.
1326 par_metrics_[pit].setPosition(last.second.position()
1327 + last.second.descent() + par_metrics_[pit].ascent());
1331 void TextMetrics::newParMetricsUp()
1333 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1334 if (first.first == 0)
1337 pit_type const pit = first.first - 1;
1338 // do it and update its position.
1340 par_metrics_[pit].setPosition(first.second.position()
1341 - first.second.ascent() - par_metrics_[pit].descent());
1344 // y is screen coordinate
1345 pit_type TextMetrics::getPitNearY(int y)
1347 LASSERT(!text_->paragraphs().empty(), return -1);
1348 LASSERT(!par_metrics_.empty(), return -1);
1349 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1351 // look for highest numbered paragraph with y coordinate less than given y
1354 ParMetricsCache::const_iterator it = par_metrics_.begin();
1355 ParMetricsCache::const_iterator et = par_metrics_.end();
1356 ParMetricsCache::const_iterator last = et; last--;
1358 ParagraphMetrics const & pm = it->second;
1360 if (y < it->second.position() - int(pm.ascent())) {
1361 // We are looking for a position that is before the first paragraph in
1362 // the cache (which is in priciple off-screen, that is before the
1365 // We are already at the first paragraph in the inset.
1367 // OK, this is the paragraph we are looking for.
1368 pit = it->first - 1;
1373 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1375 if (y >= last->second.position() + int(pm_last.descent())) {
1376 // We are looking for a position that is after the last paragraph in
1377 // the cache (which is in priciple off-screen), that is before the
1379 pit = last->first + 1;
1380 if (pit == int(text_->paragraphs().size()))
1381 // We are already at the last paragraph in the inset.
1383 // OK, this is the paragraph we are looking for.
1384 newParMetricsDown();
1388 for (; it != et; ++it) {
1389 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1390 << " y: " << it->second.position());
1392 ParagraphMetrics const & pm = par_metrics_[it->first];
1394 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1396 yy = it->second.position();
1400 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1406 Row const & TextMetrics::getPitAndRowNearY(int y, pit_type & pit,
1407 bool assert_in_view, bool up)
1409 ParagraphMetrics const & pm = par_metrics_[pit];
1411 int yy = pm.position() - pm.ascent();
1412 LASSERT(!pm.rows().empty(), /**/);
1413 RowList::const_iterator rit = pm.rows().begin();
1414 RowList::const_iterator rlast = pm.rows().end();
1416 for (; rit != rlast; yy += rit->height(), ++rit)
1417 if (yy + rit->height() > y)
1420 if (assert_in_view && yy + rit->height() != y) {
1422 if (rit != pm.rows().begin())
1424 else if (pit != 0) {
1427 ParagraphMetrics const & pm2 = par_metrics_[pit];
1428 rit = pm2.rows().end();
1434 else if (pit != int(par_metrics_.size())) {
1436 newParMetricsDown();
1437 ParagraphMetrics const & pm2 = par_metrics_[pit];
1438 rit = pm2.rows().begin();
1446 // x,y are absolute screen coordinates
1447 // sets cursor recursively descending into nested editable insets
1448 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1449 bool assert_in_view, bool up)
1451 if (lyxerr.debugging(Debug::WORKAREA)) {
1452 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1453 cur.bv().coordCache().dump();
1455 pit_type pit = getPitNearY(y);
1456 LASSERT(pit != -1, return 0);
1458 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1461 int xx = x; // is modified by getColumnNearX
1462 pos_type const pos = row.pos()
1463 + getColumnNearX(pit, row, xx, bound);
1466 cur.boundary(bound);
1469 // try to descend into nested insets
1470 Inset * inset = checkInsetHit(x, y);
1471 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1473 // Either we deconst editXY or better we move current_font
1474 // and real_current_font to Cursor
1475 // FIXME: what is needed now that current_font and real_current_font
1477 cur.setCurrentFont();
1481 ParagraphList const & pars = text_->paragraphs();
1482 Inset const * insetBefore = pos ? pars[pit].getInset(pos - 1) : 0;
1483 //Inset * insetBehind = pars[pit].getInset(pos);
1485 // This should be just before or just behind the
1486 // cursor position set above.
1487 LASSERT((pos != 0 && inset == insetBefore)
1488 || inset == pars[pit].getInset(pos), /**/);
1490 // Make sure the cursor points to the position before
1492 if (inset == insetBefore) {
1494 cur.boundary(false);
1497 // Try to descend recursively inside the inset.
1498 inset = inset->editXY(cur, x, y);
1500 if (cur.top().text() == text_)
1501 cur.setCurrentFont();
1506 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1508 LASSERT(text_ == cur.text(), /**/);
1509 pit_type pit = getPitNearY(y);
1510 LASSERT(pit != -1, return);
1512 ParagraphMetrics const & pm = par_metrics_[pit];
1514 int yy = pm.position() - pm.ascent();
1515 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1516 " pit: " << pit << " yy: " << yy);
1519 LASSERT(pm.rows().size(), /**/);
1520 for (; r < int(pm.rows().size()) - 1; ++r) {
1521 Row const & row = pm.rows()[r];
1522 if (int(yy + row.height()) > y)
1527 Row const & row = pm.rows()[r];
1529 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1533 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1535 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1537 text_->setCursor(cur, pit, pos, true, bound);
1538 // remember new position.
1543 //takes screen x,y coordinates
1544 Inset * TextMetrics::checkInsetHit(int x, int y)
1546 pit_type pit = getPitNearY(y);
1547 LASSERT(pit != -1, return 0);
1549 Paragraph const & par = text_->paragraphs()[pit];
1550 ParagraphMetrics const & pm = par_metrics_[pit];
1552 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1554 InsetList::const_iterator iit = par.insetList().begin();
1555 InsetList::const_iterator iend = par.insetList().end();
1556 for (; iit != iend; ++iit) {
1557 Inset * inset = iit->inset;
1559 LYXERR(Debug::DEBUG, "examining inset " << inset);
1561 if (!bv_->coordCache().getInsets().has(inset)) {
1562 LYXERR(Debug::DEBUG, "inset has no cached position");
1566 Dimension const & dim = pm.insetDimension(inset);
1567 Point p = bv_->coordCache().getInsets().xy(inset);
1569 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1570 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1573 && x <= p.x_ + dim.wid
1574 && y >= p.y_ - dim.asc
1575 && y <= p.y_ + dim.des) {
1576 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1581 LYXERR(Debug::DEBUG, "No inset hit. ");
1586 int TextMetrics::cursorX(CursorSlice const & sl,
1587 bool boundary) const
1589 LASSERT(sl.text() == text_, /**/);
1590 pit_type const pit = sl.pit();
1591 Paragraph const & par = text_->paragraphs()[pit];
1592 ParagraphMetrics const & pm = par_metrics_[pit];
1593 if (pm.rows().empty())
1596 pos_type ppos = sl.pos();
1597 // Correct position in front of big insets
1598 bool const boundary_correction = ppos != 0 && boundary;
1599 if (boundary_correction)
1602 Row const & row = pm.getRow(sl.pos(), boundary);
1604 pos_type cursor_vpos = 0;
1606 Buffer const & buffer = bv_->buffer();
1609 bidi.computeTables(par, buffer, row);
1611 pos_type const row_pos = row.pos();
1612 pos_type const end = row.endpos();
1613 // Spaces at logical line breaks in bidi text must be skipped during
1614 // cursor positioning. However, they may appear visually in the middle
1615 // of a row; they must be skipped, wherever they are...
1616 // * logically "abc_[HEBREW_\nHEBREW]"
1617 // * visually "abc_[_WERBEH\nWERBEH]"
1618 pos_type skipped_sep_vpos = -1;
1621 cursor_vpos = row_pos;
1622 else if (ppos >= end)
1623 cursor_vpos = text_->isRTL(par) ? row_pos : end;
1624 else if (ppos > row_pos && ppos >= end)
1625 // Place cursor after char at (logical) position pos - 1
1626 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1627 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1629 // Place cursor before char at (logical) position ppos
1630 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1631 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1633 pos_type body_pos = par.beginOfBody();
1635 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1638 // check for possible inline completion in this row
1639 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1640 pos_type inlineCompletionVPos = -1;
1641 if (inlineCompletionPos.inTexted()
1642 && inlineCompletionPos.text() == text_
1643 && inlineCompletionPos.pit() == pit
1644 && inlineCompletionPos.pos() - 1 >= row_pos
1645 && inlineCompletionPos.pos() - 1 < end) {
1646 // draw logically behind the previous character
1647 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1650 // Use font span to speed things up, see below
1654 // If the last logical character is a separator, skip it, unless
1655 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1656 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1657 skipped_sep_vpos = bidi.log2vis(end - 1);
1659 // Inline completion RTL special case row_pos == cursor_pos:
1660 // "__|b" => cursor_pos is right of __
1661 if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1662 font = displayFont(pit, row_pos + 1);
1663 docstring const & completion = bv_->inlineCompletion();
1664 if (font.isRightToLeft() && completion.length() > 0)
1665 x += theFontMetrics(font.fontInfo()).width(completion);
1668 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1669 // Skip the separator which is at the logical end of the row
1670 if (vpos == skipped_sep_vpos)
1672 pos_type pos = bidi.vis2log(vpos);
1673 if (body_pos > 0 && pos == body_pos - 1) {
1674 FontMetrics const & labelfm = theFontMetrics(
1675 text_->labelFont(par));
1676 x += row.label_hfill + labelfm.width(par.layout().labelsep);
1677 if (par.isLineSeparator(body_pos - 1))
1678 x -= singleWidth(pit, body_pos - 1);
1681 // Use font span to speed things up, see above
1682 if (pos < font_span.first || pos > font_span.last) {
1683 font_span = par.fontSpan(pos);
1684 font = displayFont(pit, pos);
1687 x += pm.singleWidth(pos, font);
1689 // Inline completion RTL case:
1690 // "a__|b", __ of b => non-boundary a-pos is right of __
1691 if (vpos + 1 == inlineCompletionVPos
1692 && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1693 font = displayFont(pit, vpos + 1);
1694 docstring const & completion = bv_->inlineCompletion();
1695 if (font.isRightToLeft() && completion.length() > 0)
1696 x += theFontMetrics(font.fontInfo()).width(completion);
1699 // Inline completion LTR case:
1700 // "b|__a", __ of b => non-boundary a-pos is in front of __
1701 if (vpos == inlineCompletionVPos
1702 && (vpos + 1 < cursor_vpos || boundary_correction)) {
1703 font = displayFont(pit, vpos);
1704 docstring const & completion = bv_->inlineCompletion();
1705 if (!font.isRightToLeft() && completion.length() > 0)
1706 x += theFontMetrics(font.fontInfo()).width(completion);
1709 if (par.isSeparator(pos) && pos >= body_pos)
1713 // see correction above
1714 if (boundary_correction) {
1715 if (isRTL(sl, boundary))
1716 x -= singleWidth(pit, ppos);
1718 x += singleWidth(pit, ppos);
1725 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1727 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1728 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1729 if (pm.rows().empty())
1733 h -= par_metrics_[0].rows()[0].ascent();
1734 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1735 h += par_metrics_[pit].height();
1738 if (pos && boundary)
1740 size_t const rend = pm.pos2row(pos);
1741 for (size_t rit = 0; rit != rend; ++rit)
1742 h += pm.rows()[rit].height();
1743 h += pm.rows()[rend].ascent();
1748 // the cursor set functions have a special mechanism. When they
1749 // realize you left an empty paragraph, they will delete it.
1751 bool TextMetrics::cursorHome(Cursor & cur)
1753 LASSERT(text_ == cur.text(), /**/);
1754 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1755 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1756 return text_->setCursor(cur, cur.pit(), row.pos());
1760 bool TextMetrics::cursorEnd(Cursor & cur)
1762 LASSERT(text_ == cur.text(), /**/);
1763 // if not on the last row of the par, put the cursor before
1764 // the final space exept if I have a spanning inset or one string
1765 // is so long that we force a break.
1766 pos_type end = cur.textRow().endpos();
1768 // empty text, end-1 is no valid position
1770 bool boundary = false;
1771 if (end != cur.lastpos()) {
1772 if (!cur.paragraph().isLineSeparator(end-1)
1773 && !cur.paragraph().isNewline(end-1))
1778 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1782 void TextMetrics::deleteLineForward(Cursor & cur)
1784 LASSERT(text_ == cur.text(), /**/);
1785 if (cur.lastpos() == 0) {
1786 // Paragraph is empty, so we just go forward
1787 text_->cursorForward(cur);
1790 cur.setSelection(true); // to avoid deletion
1793 // What is this test for ??? (JMarc)
1794 if (!cur.selection())
1795 text_->deleteWordForward(cur);
1797 cap::cutSelection(cur, true, false);
1798 cur.checkBufferStructure();
1803 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1805 ParagraphList const & pars = text_->paragraphs();
1806 return row.endpos() >= pars[pit].size()
1807 && pit + 1 == pit_type(pars.size());
1811 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1813 return row.pos() == 0 && pit == 0;
1817 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1819 LASSERT(pit >= 0, /**/);
1820 LASSERT(pit < int(text_->paragraphs().size()), /**/);
1821 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1825 int TextMetrics::leftMargin(int max_width,
1826 pit_type const pit, pos_type const pos) const
1828 ParagraphList const & pars = text_->paragraphs();
1830 LASSERT(pit >= 0, /**/);
1831 LASSERT(pit < int(pars.size()), /**/);
1832 Paragraph const & par = pars[pit];
1833 LASSERT(pos >= 0, /**/);
1834 LASSERT(pos <= par.size(), /**/);
1835 Buffer const & buffer = bv_->buffer();
1836 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1837 DocumentClass const & tclass = buffer.params().documentClass();
1838 Layout const & layout = par.layout();
1840 docstring parindent = layout.parindent;
1844 if (text_->isMainText())
1845 l_margin += bv_->leftMargin();
1847 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1848 tclass.leftmargin());
1850 if (par.getDepth() != 0) {
1851 // find the next level paragraph
1852 pit_type newpar = text_->outerHook(pit);
1853 if (newpar != pit_type(pars.size())) {
1854 if (pars[newpar].layout().isEnvironment()) {
1855 l_margin = leftMargin(max_width, newpar);
1857 if (tclass.isDefaultLayout(par.layout())
1858 || tclass.isPlainLayout(par.layout())) {
1859 if (pars[newpar].params().noindent())
1862 parindent = pars[newpar].layout().parindent;
1867 // This happens after sections in standard classes. The 1.3.x
1868 // code compared depths too, but it does not seem necessary
1870 if (tclass.isDefaultLayout(par.layout())
1871 && pit > 0 && pars[pit - 1].layout().nextnoindent)
1874 FontInfo const labelfont = text_->labelFont(par);
1875 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1877 switch (layout.margintype) {
1878 case MARGIN_DYNAMIC:
1879 if (!layout.leftmargin.empty()) {
1880 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1883 if (!par.labelString().empty()) {
1884 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1885 l_margin += labelfont_metrics.width(par.labelString());
1886 l_margin += labelfont_metrics.width(layout.labelsep);
1890 case MARGIN_MANUAL: {
1891 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1892 // The width of an empty par, even with manual label, should be 0
1893 if (!par.empty() && pos >= par.beginOfBody()) {
1894 if (!par.getLabelWidthString().empty()) {
1895 docstring labstr = par.getLabelWidthString();
1896 l_margin += labelfont_metrics.width(labstr);
1897 l_margin += labelfont_metrics.width(layout.labelsep);
1903 case MARGIN_STATIC: {
1904 l_margin += theFontMetrics(buffer.params().getFont()).
1905 signedWidth(layout.leftmargin) * 4 / (par.getDepth() + 4);
1909 case MARGIN_FIRST_DYNAMIC:
1910 if (layout.labeltype == LABEL_MANUAL) {
1911 // if we are at position 0, we are never in the body
1912 if (pos > 0 && pos >= par.beginOfBody())
1913 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1915 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1917 // Special case to fix problems with
1919 || (layout.labeltype == LABEL_STATIC
1920 && layout.latextype == LATEX_ENVIRONMENT
1921 && !text_->isFirstInSequence(pit))) {
1922 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1923 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
1924 && layout.labeltype != LABEL_BIBLIO
1925 && layout.labeltype !=
1926 LABEL_CENTERED_TOP_ENVIRONMENT) {
1927 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1928 l_margin += labelfont_metrics.width(layout.labelsep);
1929 l_margin += labelfont_metrics.width(par.labelString());
1933 case MARGIN_RIGHT_ADDRESS_BOX: {
1935 // ok, a terrible hack. The left margin depends on the widest
1936 // row in this paragraph.
1937 RowList::iterator rit = par.rows().begin();
1938 RowList::iterator end = par.rows().end();
1939 // FIXME: This is wrong.
1940 int minfill = max_width;
1941 for ( ; rit != end; ++rit)
1942 if (rit->fill() < minfill)
1943 minfill = rit->fill();
1944 l_margin += theFontMetrics(params.getFont()).signedWidth(layout.leftmargin);
1945 l_margin += minfill;
1947 // also wrong, but much shorter.
1948 l_margin += max_width / 2;
1953 if (!par.params().leftIndent().zero())
1954 l_margin += par.params().leftIndent().inPixels(max_width);
1958 if (par.params().align() == LYX_ALIGN_LAYOUT)
1959 align = layout.align;
1961 align = par.params().align();
1963 // set the correct parindent
1965 && (layout.labeltype == LABEL_NO_LABEL
1966 || layout.labeltype == LABEL_TOP_ENVIRONMENT
1967 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1968 || (layout.labeltype == LABEL_STATIC
1969 && layout.latextype == LATEX_ENVIRONMENT
1970 && !text_->isFirstInSequence(pit)))
1971 && align == LYX_ALIGN_BLOCK
1972 && !par.params().noindent()
1973 // in some insets, paragraphs are never indented
1974 && !text_->inset().neverIndent()
1975 // display style insets are always centered, omit indentation
1978 && par.getInset(pos)->display())
1979 && (!(tclass.isDefaultLayout(par.layout())
1980 || tclass.isPlainLayout(par.layout()))
1981 || buffer.params().paragraph_separation == BufferParams::ParagraphIndentSeparation)
1984 // use the parindent of the layout when the default indentation is used
1985 // otherwise use the indentation set in the document settings
1986 if (buffer.params().getIndentation().asLyXCommand() == "default")
1987 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1990 l_margin += buffer.params().getIndentation().inPixels(*bv_);
1997 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1999 ParagraphMetrics const & pm = par_metrics_[pit];
2001 return pm.singleWidth(pos, displayFont(pit, pos));
2005 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
2007 if (par_metrics_.empty())
2013 ParMetricsCache::iterator it = par_metrics_.begin();
2014 ParMetricsCache::iterator const pm_end = par_metrics_.end();
2015 y -= it->second.ascent();
2016 for (; it != pm_end; ++it) {
2017 ParagraphMetrics const & pmi = it->second;
2019 pit_type const pit = it->first;
2020 // Save the paragraph position in the cache.
2021 it->second.setPosition(y);
2022 drawParagraph(pi, pit, x, y);
2028 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
2030 BufferParams const & bparams = bv_->buffer().params();
2031 ParagraphMetrics const & pm = par_metrics_[pit];
2032 if (pm.rows().empty())
2036 bool const original_drawing_state = pi.pain.isDrawingEnabled();
2037 int const ww = bv_->workHeight();
2038 size_t const nrows = pm.rows().size();
2040 Cursor const & cur = bv_->cursor();
2041 DocIterator sel_beg = cur.selectionBegin();
2042 DocIterator sel_end = cur.selectionEnd();
2043 bool selection = cur.selection()
2044 // This is our text.
2045 && cur.text() == text_
2046 // if the anchor is outside, this is not our selection
2047 && cur.anchor().text() == text_
2048 && pit >= sel_beg.pit() && pit <= sel_end.pit();
2050 // We store the begin and end pos of the selection relative to this par
2051 DocIterator sel_beg_par = cur.selectionBegin();
2052 DocIterator sel_end_par = cur.selectionEnd();
2054 // We care only about visible selection.
2056 if (pit != sel_beg.pit()) {
2057 sel_beg_par.pit() = pit;
2058 sel_beg_par.pos() = 0;
2060 if (pit != sel_end.pit()) {
2061 sel_end_par.pit() = pit;
2062 sel_end_par.pos() = sel_end_par.lastpos();
2066 for (size_t i = 0; i != nrows; ++i) {
2068 Row const & row = pm.rows()[i];
2072 bool const inside = (y + row.descent() >= 0
2073 && y - row.ascent() < ww);
2074 // It is not needed to draw on screen if we are not inside.
2075 pi.pain.setDrawingEnabled(inside && original_drawing_state);
2076 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
2079 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2081 row.setSelection(-1, -1);
2083 // The row knows nothing about the paragraph, so we have to check
2084 // whether this row is the first or last and update the margins.
2085 if (row.selection()) {
2086 if (row.sel_beg == 0)
2087 row.begin_margin_sel = sel_beg.pit() < pit;
2088 if (row.sel_end == sel_end_par.lastpos())
2089 row.end_margin_sel = sel_end.pit() > pit;
2092 // Row signature; has row changed since last paint?
2093 row.setCrc(pm.computeRowSignature(row, bparams));
2094 bool row_has_changed = row.changed();
2096 // Don't paint the row if a full repaint has not been requested
2097 // and if it has not changed.
2098 if (!pi.full_repaint && !row_has_changed) {
2099 // Paint only the insets if the text itself is
2101 rp.paintOnlyInsets();
2106 // Clear background of this row if paragraph background was not
2107 // already cleared because of a full repaint.
2108 if (!pi.full_repaint && row_has_changed) {
2109 pi.pain.fillRectangle(x, y - row.ascent(),
2110 width(), row.height(), pi.background_color);
2113 if (row.selection())
2114 drawRowSelection(pi, x, row, cur, pit);
2116 // Instrumentation for testing row cache (see also
2118 if (lyxerr.debugging(Debug::PAINTING) && inside
2119 && (row.selection() || pi.full_repaint || row_has_changed)) {
2120 string const foreword = text_->isMainText() ?
2121 "main text redraw " : "inset text redraw: ";
2122 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
2123 << " row_selection=" << row.selection()
2124 << " full_repaint=" << pi.full_repaint
2125 << " row_has_changed=" << row_has_changed);
2128 // Backup full_repaint status and force full repaint
2129 // for inner insets as the Row has been cleared out.
2130 bool tmp = pi.full_repaint;
2131 pi.full_repaint = true;
2134 rp.paintChangeBar();
2141 // Restore full_repaint status.
2142 pi.full_repaint = tmp;
2144 // Re-enable screen drawing for future use of the painter.
2145 pi.pain.setDrawingEnabled(original_drawing_state);
2147 //LYXERR(Debug::PAINTING, ".");
2151 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2152 Cursor const & curs, pit_type pit) const
2154 DocIterator beg = curs.selectionBegin();
2156 beg.pos() = row.sel_beg;
2158 DocIterator end = curs.selectionEnd();
2160 end.pos() = row.sel_end;
2162 bool const begin_boundary = beg.pos() >= row.endpos();
2163 bool const end_boundary = row.sel_end == row.endpos();
2165 DocIterator cur = beg;
2166 cur.boundary(begin_boundary);
2167 int x1 = cursorX(beg.top(), begin_boundary);
2168 int x2 = cursorX(end.top(), end_boundary);
2169 int const y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2170 int const y2 = y1 + row.height();
2172 int const rm = text_->isMainText() ? bv_->rightMargin() : 0;
2173 int const lm = text_->isMainText() ? bv_->leftMargin() : 0;
2176 if (row.begin_margin_sel) {
2177 if (text_->isRTL(beg.paragraph())) {
2178 pi.pain.fillRectangle(x + x1, y1, width() - rm - x1, y2 - y1,
2181 pi.pain.fillRectangle(x + lm, y1, x1 - lm, y2 - y1,
2186 if (row.end_margin_sel) {
2187 if (text_->isRTL(beg.paragraph())) {
2188 pi.pain.fillRectangle(x + lm, y1, x2 - lm, y2 - y1,
2191 pi.pain.fillRectangle(x + x2, y1, width() - rm - x2, y2 - y1,
2196 // if we are on a boundary from the beginning, it's probably
2197 // a RTL boundary and we jump to the other side directly as this
2198 // segement is 0-size and confuses the logic below
2200 cur.boundary(false);
2202 // go through row and draw from RTL boundary to RTL boundary
2204 bool drawNow = false;
2206 // simplified cursorForward code below which does not
2207 // descend into insets and which does not go into the
2208 // next line. Compare the logic with the original cursorForward
2210 // if left of boundary -> just jump to right side, but
2211 // for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2212 if (cur.boundary()) {
2213 cur.boundary(false);
2214 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2215 // in front of RTL boundary -> Stay on this side of the boundary
2216 // because: ab|cDDEEFFghi -> abc|DDEEFFghi
2225 if (cur.pos() == row.endpos())
2230 // the previous segment was just drawn, now the next starts
2231 x1 = cursorX(cur.top(), cur.boundary());
2234 if (!(cur < end) || drawNow) {
2235 x2 = cursorX(cur.top(), cur.boundary());
2236 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2239 // reset x1, so it is set again next round (which will be on the
2240 // right side of a boundary or at the selection end)
2247 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2248 Dimension & dim) const
2250 Cursor const & bvcur = cur.bv().cursor();
2252 // get word in front of cursor
2253 docstring word = text_->previousWord(bvcur.top());
2254 DocIterator wordStart = bvcur;
2255 wordStart.pos() -= word.length();
2257 // get position on screen of the word start and end
2258 Point lxy = cur.bv().getPos(wordStart, false);
2259 Point rxy = cur.bv().getPos(bvcur, bvcur.boundary());
2261 // calculate dimensions of the word
2262 dim = rowHeight(bvcur.pit(), wordStart.pos(), bvcur.pos(), false);
2263 dim.wid = abs(rxy.x_ - lxy.x_);
2265 // calculate position of word
2267 x = min(rxy.x_, lxy.x_);
2269 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2270 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2273 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2275 // ParagraphMetrics const & pm = par_metrics_[pit];
2276 // Row const & r = pm.rows()[row];
2282 int defaultRowHeight()
2284 return int(theFontMetrics(sane_font).maxHeight() * 1.2);