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(outerFont(pit, pars).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 pit_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);
949 w += pm.singleWidth(i, *fi);
951 // add inline completion width
952 if (inlineCompletionLPos == i) {
953 docstring const & completion = bv_->inlineCompletion();
954 if (completion.length() > 0)
955 w += theFontMetrics(*fi).width(completion);
960 if (body_pos > 0 && body_pos >= end) {
961 FontMetrics const & fm = theFontMetrics(
962 text_->labelFont(par));
963 w += fm.width(par.layout().labelsep);
964 if (end > 0 && par.isLineSeparator(end - 1))
965 w -= singleWidth(pit, end - 1);
966 w = max(w, label_end);
969 return w + right_margin;
973 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
974 pos_type const end, bool topBottomSpace) const
976 Paragraph const & par = text_->getPar(pit);
977 // get the maximum ascent and the maximum descent
978 double layoutasc = 0;
979 double layoutdesc = 0;
980 double const dh = defaultRowHeight();
982 // ok, let us initialize the maxasc and maxdesc value.
983 // Only the fontsize count. The other properties
984 // are taken from the layoutfont. Nicer on the screen :)
985 Layout const & layout = par.layout();
987 // as max get the first character of this row then it can
988 // increase but not decrease the height. Just some point to
989 // start with so we don't have to do the assignment below too
991 Buffer const & buffer = bv_->buffer();
992 Font font = displayFont(pit, first);
993 FontSize const tmpsize = font.fontInfo().size();
994 font.fontInfo() = text_->layoutFont(pit);
995 FontSize const size = font.fontInfo().size();
996 font.fontInfo().setSize(tmpsize);
998 FontInfo labelfont = text_->labelFont(par);
1000 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1001 FontMetrics const & fontmetrics = theFontMetrics(font);
1003 // these are minimum values
1004 double const spacing_val = layout.spacing.getValue()
1005 * text_->spacing(par);
1006 //lyxerr << "spacing_val = " << spacing_val << endl;
1007 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
1008 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
1010 // insets may be taller
1011 ParagraphMetrics const & pm = par_metrics_[pit];
1012 InsetList::const_iterator ii = par.insetList().begin();
1013 InsetList::const_iterator iend = par.insetList().end();
1014 for ( ; ii != iend; ++ii) {
1015 if (ii->pos >= first && ii->pos < end) {
1016 Dimension const & dim = pm.insetDimension(ii->inset);
1017 maxasc = max(maxasc, dim.ascent());
1018 maxdesc = max(maxdesc, dim.descent());
1022 // Check if any custom fonts are larger (Asger)
1023 // This is not completely correct, but we can live with the small,
1024 // cosmetic error for now.
1028 par.highestFontInRange(first, end, size);
1029 if (maxsize > font.fontInfo().size()) {
1030 // use standard paragraph font with the maximal size
1031 FontInfo maxfont = font.fontInfo();
1032 maxfont.setSize(maxsize);
1033 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
1034 maxasc = max(maxasc, maxfontmetrics.maxAscent());
1035 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
1038 // This is nicer with box insets:
1042 ParagraphList const & pars = text_->paragraphs();
1043 Inset const & inset = text_->inset();
1045 // is it a top line?
1046 if (first == 0 && topBottomSpace) {
1047 BufferParams const & bufparams = buffer.params();
1048 // some parskips VERY EASY IMPLEMENTATION
1049 if (bufparams.paragraph_separation
1050 == BufferParams::ParagraphSkipSeparation
1051 && inset.lyxCode() != ERT_CODE
1052 && inset.lyxCode() != LISTINGS_CODE
1054 && ((layout.isParagraph() && par.getDepth() == 0)
1055 || (pars[pit - 1].layout().isParagraph()
1056 && pars[pit - 1].getDepth() == 0)))
1058 maxasc += bufparams.getDefSkip().inPixels(*bv_);
1061 if (par.params().startOfAppendix())
1062 maxasc += int(3 * dh);
1064 // This is special code for the chapter, since the label of this
1065 // layout is printed in an extra row
1066 if (layout.counter == "chapter"
1067 && !par.params().labelString().empty()) {
1068 labeladdon = int(labelfont_metrics.maxHeight()
1069 * layout.spacing.getValue()
1070 * text_->spacing(par));
1073 // special code for the top label
1074 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1075 || layout.labeltype == LABEL_BIBLIO
1076 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1077 && isFirstInSequence(pit, pars)
1078 && !par.labelString().empty())
1081 labelfont_metrics.maxHeight()
1082 * layout.spacing.getValue()
1083 * text_->spacing(par)
1084 + (layout.topsep + layout.labelbottomsep) * dh);
1087 // Add the layout spaces, for example before and after
1088 // a section, or between the items of a itemize or enumerate
1091 pit_type prev = depthHook(pit, pars, par.getDepth());
1092 Paragraph const & prevpar = pars[prev];
1094 && prevpar.layout() == layout
1095 && prevpar.getDepth() == par.getDepth()
1096 && prevpar.getLabelWidthString()
1097 == par.getLabelWidthString()) {
1098 layoutasc = layout.itemsep * dh;
1099 } else if (pit != 0 || first != 0) {
1100 if (layout.topsep > 0)
1101 layoutasc = layout.topsep * dh;
1104 prev = outerHook(pit, pars);
1105 if (prev != pit_type(pars.size())) {
1106 maxasc += int(pars[prev].layout().parsep * dh);
1107 } else if (pit != 0) {
1108 Paragraph const & prevpar = pars[pit - 1];
1109 if (prevpar.getDepth() != 0 ||
1110 prevpar.layout() == layout) {
1111 maxasc += int(layout.parsep * dh);
1116 // is it a bottom line?
1117 if (end >= par.size() && topBottomSpace) {
1118 // add the layout spaces, for example before and after
1119 // a section, or between the items of a itemize or enumerate
1121 pit_type nextpit = pit + 1;
1122 if (nextpit != pit_type(pars.size())) {
1123 pit_type cpit = pit;
1127 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1128 usual = pars[cpit].layout().bottomsep * dh;
1129 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1130 if (pars[cpit].layout() != pars[nextpit].layout()
1131 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1133 unusual = pars[cpit].layout().bottomsep * dh;
1135 layoutdesc = max(unusual, usual);
1136 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1137 if (pars[cpit].layout() != pars[nextpit].layout()
1138 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1139 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1144 // incalculate the layout spaces
1145 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1146 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1148 // FIXME: the correct way is to do the following is to move the
1149 // following code in another method specially tailored for the
1150 // main Text. The following test is thus bogus.
1151 // Top and bottom margin of the document (only at top-level)
1152 if (main_text_ && topBottomSpace) {
1153 if (pit == 0 && first == 0)
1155 if (pit + 1 == pit_type(pars.size()) &&
1156 end == par.size() &&
1157 !(end > 0 && par.isNewline(end - 1)))
1161 return Dimension(0, maxasc + labeladdon, maxdesc);
1165 // x is an absolute screen coord
1166 // returns the column near the specified x-coordinate of the row
1167 // x is set to the real beginning of this column
1168 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1169 Row const & row, int & x, bool & boundary) const
1171 Buffer const & buffer = bv_->buffer();
1173 /// For the main Text, it is possible that this pit is not
1174 /// yet in the CoordCache when moving cursor up.
1175 /// x Paragraph coordinate is always 0 for main text anyway.
1176 int const xo = origin_.x_;
1178 Paragraph const & par = text_->getPar(pit);
1180 bidi.computeTables(par, buffer, row);
1182 pos_type vc = row.pos();
1183 pos_type end = row.endpos();
1185 Layout const & layout = par.layout();
1187 bool left_side = false;
1189 pos_type body_pos = par.beginOfBody();
1191 double tmpx = row.x;
1192 double last_tmpx = tmpx;
1195 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1198 // check for empty row
1204 while (vc < end && tmpx <= x) {
1205 c = bidi.vis2log(vc);
1207 if (body_pos > 0 && c == body_pos - 1) {
1208 FontMetrics const & fm = theFontMetrics(
1209 text_->labelFont(par));
1210 tmpx += row.label_hfill + fm.width(layout.labelsep);
1211 if (par.isLineSeparator(body_pos - 1))
1212 tmpx -= singleWidth(pit, body_pos - 1);
1215 tmpx += singleWidth(pit, c);
1216 if (par.isSeparator(c) && c >= body_pos)
1217 tmpx += row.separator;
1221 if ((tmpx + last_tmpx) / 2 > x) {
1226 LASSERT(vc <= end, /**/); // This shouldn't happen.
1229 // This (rtl_support test) is not needed, but gives
1230 // some speedup if rtl_support == false
1231 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1233 // If lastrow is false, we don't need to compute
1234 // the value of rtl.
1235 bool const rtl = lastrow ? text_->isRTL(par) : false;
1237 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1238 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1239 if (!par.isNewline(end - 1))
1241 } else if (vc == row.pos()) {
1242 c = bidi.vis2log(vc);
1243 if (bidi.level(c) % 2 == 1)
1246 c = bidi.vis2log(vc - 1);
1247 bool const rtl = (bidi.level(c) % 2 == 1);
1248 if (left_side == rtl) {
1250 boundary = isRTLBoundary(pit, c);
1254 // I believe this code is not needed anymore (Jug 20050717)
1256 // The following code is necessary because the cursor position past
1257 // the last char in a row is logically equivalent to that before
1258 // the first char in the next row. That's why insets causing row
1259 // divisions -- Newline and display-style insets -- must be treated
1260 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1261 // Newline inset, air gap below:
1262 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1263 if (bidi.level(end -1) % 2 == 0)
1264 tmpx -= singleWidth(pit, end - 1);
1266 tmpx += singleWidth(pit, end - 1);
1270 // Air gap above display inset:
1271 if (row.pos() < end && c >= end && end < par.size()
1272 && par.isInset(end) && par.getInset(end)->display()) {
1275 // Air gap below display inset:
1276 if (row.pos() < end && c >= end && par.isInset(end - 1)
1277 && par.getInset(end - 1)->display()) {
1283 pos_type const col = c - row.pos();
1285 if (!c || end == par.size())
1288 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1293 return min(col, end - 1 - row.pos());
1297 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1299 // We play safe and use parMetrics(pit) to make sure the
1300 // ParagraphMetrics will be redone and OK to use if needed.
1301 // Otherwise we would use an empty ParagraphMetrics in
1302 // upDownInText() while in selection mode.
1303 ParagraphMetrics const & pm = parMetrics(pit);
1305 LASSERT(row < int(pm.rows().size()), /**/);
1307 Row const & r = pm.rows()[row];
1308 return r.pos() + getColumnNearX(pit, r, x, bound);
1312 void TextMetrics::newParMetricsDown()
1314 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1315 pit_type const pit = last.first + 1;
1316 if (pit == int(text_->paragraphs().size()))
1319 // do it and update its position.
1321 par_metrics_[pit].setPosition(last.second.position()
1322 + last.second.descent() + par_metrics_[pit].ascent());
1326 void TextMetrics::newParMetricsUp()
1328 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1329 if (first.first == 0)
1332 pit_type const pit = first.first - 1;
1333 // do it and update its position.
1335 par_metrics_[pit].setPosition(first.second.position()
1336 - first.second.ascent() - par_metrics_[pit].descent());
1339 // y is screen coordinate
1340 pit_type TextMetrics::getPitNearY(int y)
1342 LASSERT(!text_->paragraphs().empty(), return -1);
1343 LASSERT(!par_metrics_.empty(), return -1);
1344 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1346 // look for highest numbered paragraph with y coordinate less than given y
1349 ParMetricsCache::const_iterator it = par_metrics_.begin();
1350 ParMetricsCache::const_iterator et = par_metrics_.end();
1351 ParMetricsCache::const_iterator last = et; last--;
1353 ParagraphMetrics const & pm = it->second;
1355 if (y < it->second.position() - int(pm.ascent())) {
1356 // We are looking for a position that is before the first paragraph in
1357 // the cache (which is in priciple off-screen, that is before the
1360 // We are already at the first paragraph in the inset.
1362 // OK, this is the paragraph we are looking for.
1363 pit = it->first - 1;
1368 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1370 if (y >= last->second.position() + int(pm_last.descent())) {
1371 // We are looking for a position that is after the last paragraph in
1372 // the cache (which is in priciple off-screen), that is before the
1374 pit = last->first + 1;
1375 if (pit == int(text_->paragraphs().size()))
1376 // We are already at the last paragraph in the inset.
1378 // OK, this is the paragraph we are looking for.
1379 newParMetricsDown();
1383 for (; it != et; ++it) {
1384 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1385 << " y: " << it->second.position());
1387 ParagraphMetrics const & pm = par_metrics_[it->first];
1389 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1391 yy = it->second.position();
1395 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1401 Row const & TextMetrics::getPitAndRowNearY(int y, pit_type & pit,
1402 bool assert_in_view, bool up)
1404 ParagraphMetrics const & pm = par_metrics_[pit];
1406 int yy = pm.position() - pm.ascent();
1407 LASSERT(!pm.rows().empty(), /**/);
1408 RowList::const_iterator rit = pm.rows().begin();
1409 RowList::const_iterator rlast = pm.rows().end();
1411 for (; rit != rlast; yy += rit->height(), ++rit)
1412 if (yy + rit->height() > y)
1415 if (assert_in_view && yy + rit->height() != y) {
1417 if (rit != pm.rows().begin())
1419 else if (pit != 0) {
1422 ParagraphMetrics const & pm2 = par_metrics_[pit];
1423 rit = pm2.rows().end();
1429 else if (pit != int(par_metrics_.size())) {
1431 newParMetricsDown();
1432 ParagraphMetrics const & pm2 = par_metrics_[pit];
1433 rit = pm2.rows().begin();
1441 // x,y are absolute screen coordinates
1442 // sets cursor recursively descending into nested editable insets
1443 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1444 bool assert_in_view, bool up)
1446 if (lyxerr.debugging(Debug::WORKAREA)) {
1447 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1448 cur.bv().coordCache().dump();
1450 pit_type pit = getPitNearY(y);
1451 LASSERT(pit != -1, return 0);
1453 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1456 int xx = x; // is modified by getColumnNearX
1457 pos_type const pos = row.pos()
1458 + getColumnNearX(pit, row, xx, bound);
1461 cur.boundary(bound);
1464 // try to descend into nested insets
1465 Inset * inset = checkInsetHit(x, y);
1466 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1468 // Either we deconst editXY or better we move current_font
1469 // and real_current_font to Cursor
1470 // FIXME: what is needed now that current_font and real_current_font
1472 cur.setCurrentFont();
1476 ParagraphList const & pars = text_->paragraphs();
1477 Inset const * insetBefore = pos ? pars[pit].getInset(pos - 1) : 0;
1478 //Inset * insetBehind = pars[pit].getInset(pos);
1480 // This should be just before or just behind the
1481 // cursor position set above.
1482 LASSERT((pos != 0 && inset == insetBefore)
1483 || inset == pars[pit].getInset(pos), /**/);
1485 // Make sure the cursor points to the position before
1487 if (inset == insetBefore) {
1489 cur.boundary(false);
1492 // Try to descend recursively inside the inset.
1493 inset = inset->editXY(cur, x, y);
1495 if (cur.top().text() == text_)
1496 cur.setCurrentFont();
1501 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1503 LASSERT(text_ == cur.text(), /**/);
1504 pit_type pit = getPitNearY(y);
1505 LASSERT(pit != -1, return);
1507 ParagraphMetrics const & pm = par_metrics_[pit];
1509 int yy = pm.position() - pm.ascent();
1510 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1511 " pit: " << pit << " yy: " << yy);
1514 LASSERT(pm.rows().size(), /**/);
1515 for (; r < int(pm.rows().size()) - 1; ++r) {
1516 Row const & row = pm.rows()[r];
1517 if (int(yy + row.height()) > y)
1522 Row const & row = pm.rows()[r];
1524 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1528 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1530 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1532 text_->setCursor(cur, pit, pos, true, bound);
1533 // remember new position.
1538 //takes screen x,y coordinates
1539 Inset * TextMetrics::checkInsetHit(int x, int y)
1541 pit_type pit = getPitNearY(y);
1542 LASSERT(pit != -1, return 0);
1544 Paragraph const & par = text_->paragraphs()[pit];
1545 ParagraphMetrics const & pm = par_metrics_[pit];
1547 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1549 InsetList::const_iterator iit = par.insetList().begin();
1550 InsetList::const_iterator iend = par.insetList().end();
1551 for (; iit != iend; ++iit) {
1552 Inset * inset = iit->inset;
1554 LYXERR(Debug::DEBUG, "examining inset " << inset);
1556 if (!bv_->coordCache().getInsets().has(inset)) {
1557 LYXERR(Debug::DEBUG, "inset has no cached position");
1561 Dimension const & dim = pm.insetDimension(inset);
1562 Point p = bv_->coordCache().getInsets().xy(inset);
1564 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1565 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1568 && x <= p.x_ + dim.wid
1569 && y >= p.y_ - dim.asc
1570 && y <= p.y_ + dim.des) {
1571 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1576 LYXERR(Debug::DEBUG, "No inset hit. ");
1581 int TextMetrics::cursorX(CursorSlice const & sl,
1582 bool boundary) const
1584 LASSERT(sl.text() == text_, /**/);
1585 pit_type const pit = sl.pit();
1586 Paragraph const & par = text_->paragraphs()[pit];
1587 ParagraphMetrics const & pm = par_metrics_[pit];
1588 if (pm.rows().empty())
1591 pos_type ppos = sl.pos();
1592 // Correct position in front of big insets
1593 bool const boundary_correction = ppos != 0 && boundary;
1594 if (boundary_correction)
1597 Row const & row = pm.getRow(sl.pos(), boundary);
1599 pos_type cursor_vpos = 0;
1601 Buffer const & buffer = bv_->buffer();
1604 bidi.computeTables(par, buffer, row);
1606 pos_type const row_pos = row.pos();
1607 pos_type const end = row.endpos();
1608 // Spaces at logical line breaks in bidi text must be skipped during
1609 // cursor positioning. However, they may appear visually in the middle
1610 // of a row; they must be skipped, wherever they are...
1611 // * logically "abc_[HEBREW_\nHEBREW]"
1612 // * visually "abc_[_WERBEH\nWERBEH]"
1613 pos_type skipped_sep_vpos = -1;
1616 cursor_vpos = row_pos;
1617 else if (ppos >= end)
1618 cursor_vpos = text_->isRTL(par) ? row_pos : end;
1619 else if (ppos > row_pos && ppos >= end)
1620 // Place cursor after char at (logical) position pos - 1
1621 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1622 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1624 // Place cursor before char at (logical) position ppos
1625 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1626 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1628 pos_type body_pos = par.beginOfBody();
1630 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1633 // check for possible inline completion in this row
1634 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1635 pos_type inlineCompletionVPos = -1;
1636 if (inlineCompletionPos.inTexted()
1637 && inlineCompletionPos.text() == text_
1638 && inlineCompletionPos.pit() == pit
1639 && inlineCompletionPos.pos() - 1 >= row_pos
1640 && inlineCompletionPos.pos() - 1 < end) {
1641 // draw logically behind the previous character
1642 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1645 // Use font span to speed things up, see below
1649 // If the last logical character is a separator, skip it, unless
1650 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1651 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1652 skipped_sep_vpos = bidi.log2vis(end - 1);
1654 // Inline completion RTL special case row_pos == cursor_pos:
1655 // "__|b" => cursor_pos is right of __
1656 if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1657 font = displayFont(pit, row_pos + 1);
1658 docstring const & completion = bv_->inlineCompletion();
1659 if (font.isRightToLeft() && completion.length() > 0)
1660 x += theFontMetrics(font.fontInfo()).width(completion);
1663 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1664 // Skip the separator which is at the logical end of the row
1665 if (vpos == skipped_sep_vpos)
1667 pos_type pos = bidi.vis2log(vpos);
1668 if (body_pos > 0 && pos == body_pos - 1) {
1669 FontMetrics const & labelfm = theFontMetrics(
1670 text_->labelFont(par));
1671 x += row.label_hfill + labelfm.width(par.layout().labelsep);
1672 if (par.isLineSeparator(body_pos - 1))
1673 x -= singleWidth(pit, body_pos - 1);
1676 // Use font span to speed things up, see above
1677 if (pos < font_span.first || pos > font_span.last) {
1678 font_span = par.fontSpan(pos);
1679 font = displayFont(pit, pos);
1682 x += pm.singleWidth(pos, font);
1684 // Inline completion RTL case:
1685 // "a__|b", __ of b => non-boundary a-pos is right of __
1686 if (vpos + 1 == inlineCompletionVPos
1687 && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1688 font = displayFont(pit, vpos + 1);
1689 docstring const & completion = bv_->inlineCompletion();
1690 if (font.isRightToLeft() && completion.length() > 0)
1691 x += theFontMetrics(font.fontInfo()).width(completion);
1694 // Inline completion LTR case:
1695 // "b|__a", __ of b => non-boundary a-pos is in front of __
1696 if (vpos == inlineCompletionVPos
1697 && (vpos + 1 < cursor_vpos || boundary_correction)) {
1698 font = displayFont(pit, vpos);
1699 docstring const & completion = bv_->inlineCompletion();
1700 if (!font.isRightToLeft() && completion.length() > 0)
1701 x += theFontMetrics(font.fontInfo()).width(completion);
1704 if (par.isSeparator(pos) && pos >= body_pos)
1708 // see correction above
1709 if (boundary_correction) {
1710 if (isRTL(sl, boundary))
1711 x -= singleWidth(pit, ppos);
1713 x += singleWidth(pit, ppos);
1720 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1722 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1723 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1724 if (pm.rows().empty())
1728 h -= par_metrics_[0].rows()[0].ascent();
1729 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1730 h += par_metrics_[pit].height();
1733 if (pos && boundary)
1735 size_t const rend = pm.pos2row(pos);
1736 for (size_t rit = 0; rit != rend; ++rit)
1737 h += pm.rows()[rit].height();
1738 h += pm.rows()[rend].ascent();
1743 // the cursor set functions have a special mechanism. When they
1744 // realize you left an empty paragraph, they will delete it.
1746 bool TextMetrics::cursorHome(Cursor & cur)
1748 LASSERT(text_ == cur.text(), /**/);
1749 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1750 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1751 return text_->setCursor(cur, cur.pit(), row.pos());
1755 bool TextMetrics::cursorEnd(Cursor & cur)
1757 LASSERT(text_ == cur.text(), /**/);
1758 // if not on the last row of the par, put the cursor before
1759 // the final space exept if I have a spanning inset or one string
1760 // is so long that we force a break.
1761 pos_type end = cur.textRow().endpos();
1763 // empty text, end-1 is no valid position
1765 bool boundary = false;
1766 if (end != cur.lastpos()) {
1767 if (!cur.paragraph().isLineSeparator(end-1)
1768 && !cur.paragraph().isNewline(end-1))
1773 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1777 void TextMetrics::deleteLineForward(Cursor & cur)
1779 LASSERT(text_ == cur.text(), /**/);
1780 if (cur.lastpos() == 0) {
1781 // Paragraph is empty, so we just go forward
1782 text_->cursorForward(cur);
1785 cur.setSelection(true); // to avoid deletion
1788 // What is this test for ??? (JMarc)
1789 if (!cur.selection())
1790 text_->deleteWordForward(cur);
1792 cap::cutSelection(cur, true, false);
1793 cur.checkBufferStructure();
1798 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1800 ParagraphList const & pars = text_->paragraphs();
1801 return row.endpos() >= pars[pit].size()
1802 && pit + 1 == pit_type(pars.size());
1806 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1808 return row.pos() == 0 && pit == 0;
1812 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1814 LASSERT(pit >= 0, /**/);
1815 LASSERT(pit < int(text_->paragraphs().size()), /**/);
1816 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1820 int TextMetrics::leftMargin(int max_width,
1821 pit_type const pit, pos_type const pos) const
1823 ParagraphList const & pars = text_->paragraphs();
1825 LASSERT(pit >= 0, /**/);
1826 LASSERT(pit < int(pars.size()), /**/);
1827 Paragraph const & par = pars[pit];
1828 LASSERT(pos >= 0, /**/);
1829 LASSERT(pos <= par.size(), /**/);
1830 Buffer const & buffer = bv_->buffer();
1831 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1832 DocumentClass const & tclass = buffer.params().documentClass();
1833 Layout const & layout = par.layout();
1835 docstring parindent = layout.parindent;
1839 if (text_->isMainText())
1840 l_margin += bv_->leftMargin();
1842 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1843 tclass.leftmargin());
1845 if (par.getDepth() != 0) {
1846 // find the next level paragraph
1847 pit_type newpar = outerHook(pit, pars);
1848 if (newpar != pit_type(pars.size())) {
1849 if (pars[newpar].layout().isEnvironment()) {
1850 l_margin = leftMargin(max_width, newpar);
1852 if (tclass.isDefaultLayout(par.layout())
1853 || tclass.isPlainLayout(par.layout())) {
1854 if (pars[newpar].params().noindent())
1857 parindent = pars[newpar].layout().parindent;
1862 // This happens after sections in standard classes. The 1.3.x
1863 // code compared depths too, but it does not seem necessary
1865 if (tclass.isDefaultLayout(par.layout())
1866 && pit > 0 && pars[pit - 1].layout().nextnoindent)
1869 FontInfo const labelfont = text_->labelFont(par);
1870 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1872 switch (layout.margintype) {
1873 case MARGIN_DYNAMIC:
1874 if (!layout.leftmargin.empty()) {
1875 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1878 if (!par.labelString().empty()) {
1879 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1880 l_margin += labelfont_metrics.width(par.labelString());
1881 l_margin += labelfont_metrics.width(layout.labelsep);
1885 case MARGIN_MANUAL: {
1886 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1887 // The width of an empty par, even with manual label, should be 0
1888 if (!par.empty() && pos >= par.beginOfBody()) {
1889 if (!par.getLabelWidthString().empty()) {
1890 docstring labstr = par.getLabelWidthString();
1891 l_margin += labelfont_metrics.width(labstr);
1892 l_margin += labelfont_metrics.width(layout.labelsep);
1898 case MARGIN_STATIC: {
1899 l_margin += theFontMetrics(buffer.params().getFont()).
1900 signedWidth(layout.leftmargin) * 4 / (par.getDepth() + 4);
1904 case MARGIN_FIRST_DYNAMIC:
1905 if (layout.labeltype == LABEL_MANUAL) {
1906 // if we are at position 0, we are never in the body
1907 if (pos > 0 && pos >= par.beginOfBody())
1908 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1910 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1912 // Special case to fix problems with
1914 || (layout.labeltype == LABEL_STATIC
1915 && layout.latextype == LATEX_ENVIRONMENT
1916 && !isFirstInSequence(pit, pars))) {
1917 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1918 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
1919 && layout.labeltype != LABEL_BIBLIO
1920 && layout.labeltype !=
1921 LABEL_CENTERED_TOP_ENVIRONMENT) {
1922 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1923 l_margin += labelfont_metrics.width(layout.labelsep);
1924 l_margin += labelfont_metrics.width(par.labelString());
1928 case MARGIN_RIGHT_ADDRESS_BOX: {
1930 // ok, a terrible hack. The left margin depends on the widest
1931 // row in this paragraph.
1932 RowList::iterator rit = par.rows().begin();
1933 RowList::iterator end = par.rows().end();
1934 // FIXME: This is wrong.
1935 int minfill = max_width;
1936 for ( ; rit != end; ++rit)
1937 if (rit->fill() < minfill)
1938 minfill = rit->fill();
1939 l_margin += theFontMetrics(params.getFont()).signedWidth(layout.leftmargin);
1940 l_margin += minfill;
1942 // also wrong, but much shorter.
1943 l_margin += max_width / 2;
1948 if (!par.params().leftIndent().zero())
1949 l_margin += par.params().leftIndent().inPixels(max_width);
1953 if (par.params().align() == LYX_ALIGN_LAYOUT)
1954 align = layout.align;
1956 align = par.params().align();
1958 // set the correct parindent
1960 && (layout.labeltype == LABEL_NO_LABEL
1961 || layout.labeltype == LABEL_TOP_ENVIRONMENT
1962 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1963 || (layout.labeltype == LABEL_STATIC
1964 && layout.latextype == LATEX_ENVIRONMENT
1965 && !isFirstInSequence(pit, pars)))
1966 && align == LYX_ALIGN_BLOCK
1967 && !par.params().noindent()
1968 // in some insets, paragraphs are never indented
1969 && !text_->inset().neverIndent()
1970 // display style insets are always centered, omit indentation
1973 && par.getInset(pos)->display())
1974 && (!(tclass.isDefaultLayout(par.layout())
1975 || tclass.isPlainLayout(par.layout()))
1976 || buffer.params().paragraph_separation == BufferParams::ParagraphIndentSeparation)
1979 // use the parindent of the layout when the default indentation is used
1980 // otherwise use the indentation set in the document settings
1981 if (buffer.params().getIndentation().asLyXCommand() == "default")
1982 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1985 l_margin += buffer.params().getIndentation().inPixels(*bv_);
1992 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1994 ParagraphMetrics const & pm = par_metrics_[pit];
1996 return pm.singleWidth(pos, displayFont(pit, pos));
2000 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
2002 if (par_metrics_.empty())
2008 ParMetricsCache::iterator it = par_metrics_.begin();
2009 ParMetricsCache::iterator const pm_end = par_metrics_.end();
2010 y -= it->second.ascent();
2011 for (; it != pm_end; ++it) {
2012 ParagraphMetrics const & pmi = it->second;
2014 pit_type const pit = it->first;
2015 // Save the paragraph position in the cache.
2016 it->second.setPosition(y);
2017 drawParagraph(pi, pit, x, y);
2023 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
2025 BufferParams const & bparams = bv_->buffer().params();
2026 ParagraphMetrics const & pm = par_metrics_[pit];
2027 if (pm.rows().empty())
2031 bool const original_drawing_state = pi.pain.isDrawingEnabled();
2032 int const ww = bv_->workHeight();
2033 size_t const nrows = pm.rows().size();
2035 Cursor const & cur = bv_->cursor();
2036 DocIterator sel_beg = cur.selectionBegin();
2037 DocIterator sel_end = cur.selectionEnd();
2038 bool selection = cur.selection()
2039 // This is our text.
2040 && cur.text() == text_
2041 // if the anchor is outside, this is not our selection
2042 && cur.anchor().text() == text_
2043 && pit >= sel_beg.pit() && pit <= sel_end.pit();
2045 // We store the begin and end pos of the selection relative to this par
2046 DocIterator sel_beg_par = cur.selectionBegin();
2047 DocIterator sel_end_par = cur.selectionEnd();
2049 // We care only about visible selection.
2051 if (pit != sel_beg.pit()) {
2052 sel_beg_par.pit() = pit;
2053 sel_beg_par.pos() = 0;
2055 if (pit != sel_end.pit()) {
2056 sel_end_par.pit() = pit;
2057 sel_end_par.pos() = sel_end_par.lastpos();
2061 for (size_t i = 0; i != nrows; ++i) {
2063 Row const & row = pm.rows()[i];
2067 bool const inside = (y + row.descent() >= 0
2068 && y - row.ascent() < ww);
2069 // It is not needed to draw on screen if we are not inside.
2070 pi.pain.setDrawingEnabled(inside && original_drawing_state);
2071 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
2074 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2076 row.setSelection(-1, -1);
2078 // The row knows nothing about the paragraph, so we have to check
2079 // whether this row is the first or last and update the margins.
2080 if (row.selection()) {
2081 if (row.sel_beg == 0)
2082 row.begin_margin_sel = sel_beg.pit() < pit;
2083 if (row.sel_end == sel_end_par.lastpos())
2084 row.end_margin_sel = sel_end.pit() > pit;
2087 // Row signature; has row changed since last paint?
2088 row.setCrc(pm.computeRowSignature(row, bparams));
2089 bool row_has_changed = row.changed();
2091 // Don't paint the row if a full repaint has not been requested
2092 // and if it has not changed.
2093 if (!pi.full_repaint && !row_has_changed) {
2094 // Paint only the insets if the text itself is
2096 rp.paintOnlyInsets();
2101 // Clear background of this row if paragraph background was not
2102 // already cleared because of a full repaint.
2103 if (!pi.full_repaint && row_has_changed) {
2104 pi.pain.fillRectangle(x, y - row.ascent(),
2105 width(), row.height(), pi.background_color);
2108 if (row.selection())
2109 drawRowSelection(pi, x, row, cur, pit);
2111 // Instrumentation for testing row cache (see also
2113 if (lyxerr.debugging(Debug::PAINTING) && inside
2114 && (row.selection() || pi.full_repaint || row_has_changed)) {
2115 string const foreword = text_->isMainText() ?
2116 "main text redraw " : "inset text redraw: ";
2117 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
2118 << " row_selection=" << row.selection()
2119 << " full_repaint=" << pi.full_repaint
2120 << " row_has_changed=" << row_has_changed);
2123 // Backup full_repaint status and force full repaint
2124 // for inner insets as the Row has been cleared out.
2125 bool tmp = pi.full_repaint;
2126 pi.full_repaint = true;
2129 rp.paintChangeBar();
2136 // Restore full_repaint status.
2137 pi.full_repaint = tmp;
2139 // Re-enable screen drawing for future use of the painter.
2140 pi.pain.setDrawingEnabled(original_drawing_state);
2142 //LYXERR(Debug::PAINTING, ".");
2146 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2147 Cursor const & curs, pit_type pit) const
2149 DocIterator beg = curs.selectionBegin();
2151 beg.pos() = row.sel_beg;
2153 DocIterator end = curs.selectionEnd();
2155 end.pos() = row.sel_end;
2157 bool const begin_boundary = beg.pos() >= row.endpos();
2158 bool const end_boundary = row.sel_end == row.endpos();
2160 DocIterator cur = beg;
2161 cur.boundary(begin_boundary);
2162 int x1 = cursorX(beg.top(), begin_boundary);
2163 int x2 = cursorX(end.top(), end_boundary);
2164 int const y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2165 int const y2 = y1 + row.height();
2167 int const rm = text_->isMainText() ? bv_->rightMargin() : 0;
2168 int const lm = text_->isMainText() ? bv_->leftMargin() : 0;
2171 if (row.begin_margin_sel) {
2172 if (text_->isRTL(beg.paragraph())) {
2173 pi.pain.fillRectangle(x + x1, y1, width() - rm - x1, y2 - y1,
2176 pi.pain.fillRectangle(x + lm, y1, x1 - lm, y2 - y1,
2181 if (row.end_margin_sel) {
2182 if (text_->isRTL(beg.paragraph())) {
2183 pi.pain.fillRectangle(x + lm, y1, x2 - lm, y2 - y1,
2186 pi.pain.fillRectangle(x + x2, y1, width() - rm - x2, y2 - y1,
2191 // if we are on a boundary from the beginning, it's probably
2192 // a RTL boundary and we jump to the other side directly as this
2193 // segement is 0-size and confuses the logic below
2195 cur.boundary(false);
2197 // go through row and draw from RTL boundary to RTL boundary
2199 bool drawNow = false;
2201 // simplified cursorForward code below which does not
2202 // descend into insets and which does not go into the
2203 // next line. Compare the logic with the original cursorForward
2205 // if left of boundary -> just jump to right side, but
2206 // for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2207 if (cur.boundary()) {
2208 cur.boundary(false);
2209 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2210 // in front of RTL boundary -> Stay on this side of the boundary
2211 // because: ab|cDDEEFFghi -> abc|DDEEFFghi
2220 if (cur.pos() == row.endpos())
2225 // the previous segment was just drawn, now the next starts
2226 x1 = cursorX(cur.top(), cur.boundary());
2229 if (!(cur < end) || drawNow) {
2230 x2 = cursorX(cur.top(), cur.boundary());
2231 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2234 // reset x1, so it is set again next round (which will be on the
2235 // right side of a boundary or at the selection end)
2242 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2243 Dimension & dim) const
2245 Cursor const & bvcur = cur.bv().cursor();
2247 // get word in front of cursor
2248 docstring word = text_->previousWord(bvcur.top());
2249 DocIterator wordStart = bvcur;
2250 wordStart.pos() -= word.length();
2252 // get position on screen of the word start and end
2253 Point lxy = cur.bv().getPos(wordStart, false);
2254 Point rxy = cur.bv().getPos(bvcur, bvcur.boundary());
2256 // calculate dimensions of the word
2257 dim = rowHeight(bvcur.pit(), wordStart.pos(), bvcur.pos(), false);
2258 dim.wid = abs(rxy.x_ - lxy.x_);
2260 // calculate position of word
2262 x = min(rxy.x_, lxy.x_);
2264 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2265 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2268 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2270 // ParagraphMetrics const & pm = par_metrics_[pit];
2271 // Row const & r = pm.rows()[row];
2277 int defaultRowHeight()
2279 return int(theFontMetrics(sane_font).maxHeight() * 1.2);