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 "FontIterator.h"
31 #include "FuncRequest.h"
32 #include "InsetList.h"
36 #include "MetricsInfo.h"
37 #include "paragraph_funcs.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
40 #include "rowpainter.h"
42 #include "TextClass.h"
45 #include "mathed/MacroTable.h"
46 #include "mathed/MathMacroTemplate.h"
48 #include "frontends/FontMetrics.h"
49 #include "frontends/Painter.h"
51 #include "support/debug.h"
53 #include <boost/assert.hpp>
60 using frontend::FontMetrics;
62 static int numberOfSeparators(Paragraph const & par, Row const & row)
64 pos_type const first = max(row.pos(), par.beginOfBody());
65 pos_type const last = row.endpos() - 1;
67 for (pos_type p = first; p < last; ++p) {
68 if (par.isSeparator(p))
75 static int numberOfLabelHfills(Paragraph const & par, Row const & row)
77 pos_type last = row.endpos() - 1;
78 pos_type first = row.pos();
80 // hfill *DO* count at the beginning of paragraphs!
82 while (first < last && par.isHfill(first))
86 last = min(last, par.beginOfBody());
88 for (pos_type p = first; p < last; ++p) {
96 static int numberOfHfills(Paragraph const & par, Row const & row)
98 pos_type const last = row.endpos();
99 pos_type first = row.pos();
101 // hfill *DO* count at the beginning of paragraphs!
103 while (first < last && par.isHfill(first))
107 first = max(first, par.beginOfBody());
110 for (pos_type p = first; p < last; ++p) {
118 /////////////////////////////////////////////////////////////////////
122 /////////////////////////////////////////////////////////////////////
125 TextMetrics::TextMetrics(BufferView * bv, Text * text)
126 : bv_(bv), text_(text)
129 max_width_ = bv_->workWidth();
130 dim_.wid = max_width_;
134 //text_->updateLabels(bv->buffer());
138 bool TextMetrics::contains(pit_type pit) const
140 return par_metrics_.find(pit) != par_metrics_.end();
144 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
146 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
151 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
153 ParMetricsCache::const_iterator it = par_metrics_.begin();
154 return make_pair(it->first, &it->second);
158 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
160 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
161 return make_pair(it->first, &it->second);
165 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
167 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
168 if (pmc_it == par_metrics_.end()) {
169 pmc_it = par_metrics_.insert(
170 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
172 if (pmc_it->second.rows().empty() && redo)
174 return pmc_it->second;
178 int TextMetrics::parPosition(pit_type pit) const
180 if (pit < par_metrics_.begin()->first)
182 if (pit > par_metrics_.rbegin()->first)
185 return par_metrics_[pit].position();
189 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
191 BOOST_ASSERT(mi.base.textwidth);
192 max_width_ = mi.base.textwidth;
193 // backup old dimension.
194 Dimension const old_dim = dim_;
197 dim_.wid = min_width;
198 pit_type const npar = text_->paragraphs().size();
200 // If there is more than one row, expand the text to
201 // the full allowable width.
202 dim_.wid = max_width_;
204 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
205 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
207 bool changed = false;
209 for (pit_type pit = 0; pit != npar; ++pit) {
210 changed |= redoParagraph(pit);
211 ParagraphMetrics const & pm = par_metrics_[pit];
213 if (dim_.wid < pm.width())
214 dim_.wid = pm.width();
217 dim_.asc = par_metrics_[0].ascent();
218 dim_.des = h - dim_.asc;
219 //lyxerr << "dim_.wid " << dim_.wid << endl;
220 //lyxerr << "dim_.asc " << dim_.asc << endl;
221 //lyxerr << "dim_.des " << dim_.des << endl;
223 changed |= dim_ != old_dim;
229 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
231 return main_text_? pm.rightMargin(*bv_) : 0;
235 int TextMetrics::rightMargin(pit_type const pit) const
237 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
241 void TextMetrics::applyOuterFont(Font & font) const
244 lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
245 lf.fontInfo().realize(font.fontInfo());
246 lf.setLanguage(font.language());
251 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
253 BOOST_ASSERT(pos >= 0);
255 ParagraphList const & pars = text_->paragraphs();
256 Paragraph const & par = pars[pit];
257 Layout const & layout = par.layout();
258 Buffer const & buffer = bv_->buffer();
260 BufferParams const & params = buffer.params();
261 pos_type const body_pos = par.beginOfBody();
263 // We specialize the 95% common case:
264 if (!par.getDepth()) {
265 Font f = par.getFontSettings(params, pos);
266 if (!text_->isMainText(buffer))
268 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
270 FontInfo const & lf = lab ? layout.labelfont : layout.font;
271 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
273 // In case the default family has been customized
274 if (lf.family() == INHERIT_FAMILY)
275 rlf.setFamily(params.getFont().fontInfo().family());
276 f.fontInfo().realize(rlf);
280 // The uncommon case need not be optimized as much
281 FontInfo const & layoutfont = pos < body_pos ?
282 layout.labelfont : layout.font;
284 Font font = par.getFontSettings(params, pos);
285 font.fontInfo().realize(layoutfont);
287 if (!text_->isMainText(buffer))
288 applyOuterFont(font);
290 // Realize against environment font information
291 // NOTE: the cast to pit_type should be removed when pit_type
292 // changes to a unsigned integer.
293 if (pit < pit_type(pars.size()))
294 font.fontInfo().realize(outerFont(pit, pars).fontInfo());
296 // Realize with the fonts of lesser depth.
297 font.fontInfo().realize(params.getFont().fontInfo());
303 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
305 if (!lyxrc.rtl_support || !sl.text())
309 if (boundary && sl.pos() > 0)
312 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
316 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
318 if (!lyxrc.rtl_support)
321 // no RTL boundary at line start
325 Paragraph const & par = text_->getPar(pit);
327 bool left = displayFont(pit, pos - 1).isVisibleRightToLeft();
329 if (pos == par.size())
330 right = par.isRTL(bv_->buffer().params());
332 right = displayFont(pit, pos).isVisibleRightToLeft();
333 return left != right;
337 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
338 Font const & font) const
340 if (!lyxrc.rtl_support)
343 Paragraph const & par = text_->getPar(pit);
344 bool left = font.isVisibleRightToLeft();
346 if (pos == par.size())
347 right = par.isRTL(bv_->buffer().params());
349 right = displayFont(pit, pos).isVisibleRightToLeft();
350 return left != right;
354 bool TextMetrics::redoParagraph(pit_type const pit)
356 Paragraph & par = text_->getPar(pit);
357 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
358 // redoParagraph() recursively inside parMetrics.
359 Dimension old_dim = parMetrics(pit, false).dim();
360 ParagraphMetrics & pm = par_metrics_[pit];
363 Buffer & buffer = bv_->buffer();
364 main_text_ = (text_ == &buffer.text());
365 bool changed = false;
367 // FIXME: This check ought to be done somewhere else. It is the reason
368 // why text_ is not const. But then, where else to do it?
369 // Well, how can you end up with either (a) a biblio environment that
370 // has no InsetBibitem or (b) a biblio environment with more than one
371 // InsetBibitem? I think the answer is: when paragraphs are merged;
372 // when layout is set; when material is pasted.
373 int const moveCursor = par.checkBiblio(buffer);
375 const_cast<Cursor &>(bv_->cursor()).posForward();
376 else if (moveCursor < 0) {
377 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
378 if (cursor.pos() >= -moveCursor)
379 cursor.posBackward();
382 // Optimisation: this is used in the next two loops
383 // so better to calculate that once here.
384 int const right_margin = rightMargin(pm);
386 // iterator pointing to paragraph to resolve macros
387 DocIterator parPos = text_->macrocontextPosition();
391 LYXERR(Debug::INFO, "MacroContext not initialised!"
392 << " Going through the buffer again and hope"
393 << " the context is better then.");
394 updateLabels(bv_->buffer());
395 parPos = text_->macrocontextPosition();
396 BOOST_ASSERT(!parPos.empty());
401 // FIXME: We should always use getFont(), see documentation of
402 // noFontChange() in Inset.h.
403 Font const bufferfont = buffer.params().getFont();
404 InsetList::const_iterator ii = par.insetList().begin();
405 InsetList::const_iterator iend = par.insetList().end();
406 for (; ii != iend; ++ii) {
407 // position already initialized?
408 if (!parPos.empty()) {
409 parPos.pos() = ii->pos;
411 // A macro template would normally not be visible
412 // by itself. But the tex macro semantics allow
413 // recursion, so we artifically take the context
414 // after the macro template to simulate this.
415 if (ii->inset->lyxCode() == MATHMACRO_CODE)
419 // do the metric calculation
421 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
423 Font const & font = ii->inset->noFontChange() ?
424 bufferfont : displayFont(pit, ii->pos);
425 MacroContext mc(buffer, parPos);
426 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
427 ii->inset->metrics(mi, dim);
428 Dimension const old_dim = pm.insetDimension(ii->inset);
429 pm.setInsetDimension(ii->inset, dim);
430 changed |= (old_dim != dim);
433 par.setBeginOfBody();
435 size_t row_index = 0;
436 // maximum pixel width of a row
437 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
440 pos_type end = rowBreakPoint(width, pit, first);
441 if (row_index || end < par.size())
442 // If there is more than one row, expand the text to
443 // the full allowable width. This setting here is needed
444 // for the computeRowMetrics() below.
445 dim_.wid = max_width_;
447 dim = rowHeight(pit, first, end);
448 dim.wid = rowWidth(right_margin, pit, first, end);
449 if (row_index == pm.rows().size())
450 pm.rows().push_back(Row());
451 Row & row = pm.rows()[row_index];
452 row.setChanged(false);
455 row.setDimension(dim);
456 int const max_row_width = max(dim_.wid, dim.wid);
457 computeRowMetrics(pit, row, max_row_width);
461 pm.dim().wid = max(pm.dim().wid, dim.wid);
462 pm.dim().des += dim.height();
463 } while (first < par.size());
465 if (row_index < pm.rows().size())
466 pm.rows().resize(row_index);
468 // Make sure that if a par ends in newline, there is one more row
470 if (first > 0 && par.isNewline(first - 1)) {
471 Dimension dim = rowHeight(pit, first, first);
472 dim.wid = rowWidth(right_margin, pit, first, first);
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);
482 pm.dim().des += dim.height();
485 pm.dim().asc += pm.rows()[0].ascent();
486 pm.dim().des -= pm.rows()[0].ascent();
488 changed |= old_dim.height() != pm.dim().height();
494 void TextMetrics::computeRowMetrics(pit_type const pit,
495 Row & row, int width) const
500 Buffer & buffer = bv_->buffer();
501 Paragraph const & par = text_->getPar(pit);
503 double w = width - row.width();
504 // FIXME: put back this assertion when the crash on new doc is solved.
505 //BOOST_ASSERT(w >= 0);
507 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
508 //lyxerr << "row.width() " << row.width() << endl;
509 //lyxerr << "w " << w << endl;
511 bool const is_rtl = text_->isRTL(buffer, par);
513 row.x = rightMargin(pit);
515 row.x = leftMargin(max_width_, pit, row.pos());
517 // is there a manual margin with a manual label
518 Layout const & layout = par.layout();
520 if (layout.margintype == MARGIN_MANUAL
521 && layout.labeltype == LABEL_MANUAL) {
522 /// We might have real hfills in the label part
523 int nlh = numberOfLabelHfills(par, row);
525 // A manual label par (e.g. List) has an auto-hfill
526 // between the label text and the body of the
528 // But we don't want to do this auto hfill if the par
533 if (nlh && !par.getLabelWidthString().empty())
534 row.label_hfill = labelFill(pit, row) / double(nlh);
538 // are there any hfills in the row?
539 if (int const nh = numberOfHfills(par, row)) {
541 hfill = w / double(nh);
542 // we don't have to look at the alignment if it is ALIGN_LEFT and
543 // if the row is already larger then the permitted width as then
544 // we force the LEFT_ALIGN'edness!
545 } else if (int(row.width()) < max_width_) {
546 // is it block, flushleft or flushright?
547 // set x how you need it
549 if (par.params().align() == LYX_ALIGN_LAYOUT)
550 align = layout.align;
552 align = par.params().align();
554 // Display-style insets should always be on a centred row
555 if (Inset const * inset = par.getInset(row.pos())) {
556 switch (inset->display()) {
557 case Inset::AlignLeft:
558 align = LYX_ALIGN_BLOCK;
560 case Inset::AlignCenter:
561 align = LYX_ALIGN_CENTER;
564 case Inset::AlignRight:
565 // unchanged (use align)
571 case LYX_ALIGN_BLOCK: {
572 int const ns = numberOfSeparators(par, row);
573 bool disp_inset = false;
574 if (row.endpos() < par.size()) {
575 Inset const * in = par.getInset(row.endpos());
577 disp_inset = in->display();
579 // If we have separators, this is not the last row of a
580 // par, does not end in newline, and is not row above a
581 // display inset... then stretch it
583 && row.endpos() < par.size()
584 && !par.isNewline(row.endpos() - 1)
587 row.separator = w / ns;
588 //lyxerr << "row.separator " << row.separator << endl;
589 //lyxerr << "ns " << ns << endl;
595 case LYX_ALIGN_RIGHT:
598 case LYX_ALIGN_CENTER:
605 pos_type body_pos = par.beginOfBody();
606 pos_type end = row.endpos();
609 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
611 row.x += theFontMetrics(text_->labelFont(buffer, par)).
612 width(layout.labelsep);
614 row.x += row.label_hfill;
618 pos_type const endpos = row.endpos();
619 pos_type body_pos = par.beginOfBody();
621 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
624 ParagraphMetrics & pm = par_metrics_[pit];
625 InsetList::const_iterator ii = par.insetList().begin();
626 InsetList::const_iterator iend = par.insetList().end();
627 for ( ; ii != iend; ++ii) {
628 if (ii->pos >= endpos || ii->pos < row.pos()
629 || ii->inset->lyxCode() != HFILL_CODE)
631 Dimension dim = row.dimension();
632 if (pm.hfillExpansion(row, ii->pos))
633 dim.wid = int(ii->pos >= body_pos ?
634 max(hfill, 5.0) : row.label_hfill);
637 // Cache the inset dimension.
638 bv_->coordCache().insets().add(ii->inset, dim);
639 pm.setInsetDimension(ii->inset, dim);
644 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
646 Buffer & buffer = bv_->buffer();
647 Paragraph const & par = text_->getPar(pit);
649 pos_type last = par.beginOfBody();
650 BOOST_ASSERT(last > 0);
652 // -1 because a label ends with a space that is in the label
655 // a separator at this end does not count
656 if (par.isLineSeparator(last))
660 for (pos_type i = row.pos(); i <= last; ++i)
661 w += singleWidth(pit, i);
663 docstring const & label = par.params().labelWidthString();
667 FontMetrics const & fm
668 = theFontMetrics(text_->labelFont(buffer, par));
670 return max(0, fm.width(label) - w);
674 // this needs special handling - only newlines count as a break point
675 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
677 pos_type const end = par.size();
680 if (par.isNewline(i))
687 int TextMetrics::labelEnd(pit_type const pit) const
689 // labelEnd is only needed if the layout fills a flushleft label.
690 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
692 // return the beginning of the body
693 return leftMargin(max_width_, pit);
697 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
700 Buffer & buffer = bv_->buffer();
701 ParagraphMetrics const & pm = par_metrics_[pit];
702 Paragraph const & par = text_->getPar(pit);
703 pos_type const end = par.size();
704 if (pos == end || width < 0)
707 Layout const & layout = par.layout();
709 if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX)
710 return addressBreakPoint(pos, par);
712 pos_type const body_pos = par.beginOfBody();
714 // check for possible inline completion
715 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
716 pos_type inlineCompletionLPos = -1;
717 if (inlineCompletionPos.inTexted()
718 && inlineCompletionPos.text() == text_
719 && inlineCompletionPos.pit() == pit) {
720 // draw logically behind the previous character
721 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
724 // Now we iterate through until we reach the right margin
725 // or the end of the par, then choose the possible break
728 int label_end = labelEnd(pit);
729 int const left = leftMargin(max_width_, pit, pos);
732 // pixel width since last breakpoint
735 FontIterator fi = FontIterator(*this, par, pit, pos);
736 pos_type point = end;
738 for ( ; i < end; ++i, ++fi) {
739 int thiswidth = pm.singleWidth(i, *fi);
741 // add inline completion width
742 if (inlineCompletionLPos == i) {
743 docstring const & completion = bv_->inlineCompletion();
744 if (completion.length() > 0)
745 thiswidth += theFontMetrics(*fi).width(completion);
748 // add the auto-hfill from label end to the body
749 if (body_pos && i == body_pos) {
750 FontMetrics const & fm = theFontMetrics(
751 text_->labelFont(buffer, par));
752 int add = fm.width(layout.labelsep);
753 if (par.isLineSeparator(i - 1))
754 add -= singleWidth(pit, i - 1);
756 add = max(add, label_end - x);
761 chunkwidth += thiswidth;
763 // break before a character that will fall off
764 // the right of the row
766 // if no break before, break here
767 if (point == end || chunkwidth >= width - left) {
773 // exit on last registered breakpoint:
777 if (par.isNewline(i)) {
781 Inset const * inset = 0;
784 if ((inset = par.getInset(i + 1)) && inset->display()) {
789 if ((inset = par.getInset(i)) && inset->display()) {
795 inset = par.getInset(i);
796 if (!inset || inset->isChar()) {
797 // some insets are line separators too
798 if (par.isLineSeparator(i)) {
799 // register breakpoint:
806 // maybe found one, but the par is short enough.
807 if (i == end && x < width)
810 // manual labels cannot be broken in LaTeX. But we
811 // want to make our on-screen rendering of footnotes
813 if (body_pos && point < body_pos)
820 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
821 pos_type const first, pos_type const end) const
823 Buffer & buffer = bv_->buffer();
824 // get the pure distance
825 ParagraphMetrics const & pm = par_metrics_[pit];
826 Paragraph const & par = text_->getPar(pit);
827 int w = leftMargin(max_width_, pit, first);
828 int label_end = labelEnd(pit);
830 // check for possible inline completion
831 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
832 pos_type inlineCompletionLPos = -1;
833 if (inlineCompletionPos.inTexted()
834 && inlineCompletionPos.text() == text_
835 && inlineCompletionPos.pit() == pit) {
836 // draw logically behind the previous character
837 inlineCompletionLPos = inlineCompletionPos.pos() - 1;
840 pos_type const body_pos = par.beginOfBody();
844 FontIterator fi = FontIterator(*this, par, pit, i);
845 for ( ; i < end; ++i, ++fi) {
846 if (body_pos > 0 && i == body_pos) {
847 FontMetrics const & fm = theFontMetrics(
848 text_->labelFont(buffer, par));
849 w += fm.width(par.layout().labelsep);
850 if (par.isLineSeparator(i - 1))
851 w -= singleWidth(pit, i - 1);
852 w = max(w, label_end);
854 w += pm.singleWidth(i, *fi);
856 // add inline completion width
857 if (inlineCompletionLPos == i) {
858 docstring const & completion = bv_->inlineCompletion();
859 if (completion.length() > 0)
860 w += theFontMetrics(*fi).width(completion);
865 if (body_pos > 0 && body_pos >= end) {
866 FontMetrics const & fm = theFontMetrics(
867 text_->labelFont(buffer, par));
868 w += fm.width(par.layout().labelsep);
869 if (end > 0 && par.isLineSeparator(end - 1))
870 w -= singleWidth(pit, end - 1);
871 w = max(w, label_end);
874 return w + right_margin;
878 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
879 pos_type const end, bool topBottomSpace) const
881 Paragraph const & par = text_->getPar(pit);
882 // get the maximum ascent and the maximum descent
883 double layoutasc = 0;
884 double layoutdesc = 0;
885 double const dh = defaultRowHeight();
887 // ok, let us initialize the maxasc and maxdesc value.
888 // Only the fontsize count. The other properties
889 // are taken from the layoutfont. Nicer on the screen :)
890 Layout const & layout = par.layout();
892 // as max get the first character of this row then it can
893 // increase but not decrease the height. Just some point to
894 // start with so we don't have to do the assignment below too
896 Buffer const & buffer = bv_->buffer();
897 Font font = displayFont(pit, first);
898 FontSize const tmpsize = font.fontInfo().size();
899 font.fontInfo() = text_->layoutFont(buffer, pit);
900 FontSize const size = font.fontInfo().size();
901 font.fontInfo().setSize(tmpsize);
903 FontInfo labelfont = text_->labelFont(buffer, par);
905 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
906 FontMetrics const & fontmetrics = theFontMetrics(font);
908 // these are minimum values
909 double const spacing_val = layout.spacing.getValue()
910 * text_->spacing(buffer, par);
911 //lyxerr << "spacing_val = " << spacing_val << endl;
912 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
913 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
915 // insets may be taller
916 ParagraphMetrics const & pm = par_metrics_[pit];
917 InsetList::const_iterator ii = par.insetList().begin();
918 InsetList::const_iterator iend = par.insetList().end();
919 for ( ; ii != iend; ++ii) {
920 Dimension const & dim = pm.insetDimension(ii->inset);
921 if (ii->pos >= first && ii->pos < end) {
922 maxasc = max(maxasc, dim.ascent());
923 maxdesc = max(maxdesc, dim.descent());
927 // Check if any custom fonts are larger (Asger)
928 // This is not completely correct, but we can live with the small,
929 // cosmetic error for now.
933 par.highestFontInRange(first, end, size);
934 if (maxsize > font.fontInfo().size()) {
935 // use standard paragraph font with the maximal size
936 FontInfo maxfont = font.fontInfo();
937 maxfont.setSize(maxsize);
938 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
939 maxasc = max(maxasc, maxfontmetrics.maxAscent());
940 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
943 // This is nicer with box insets:
947 ParagraphList const & pars = text_->paragraphs();
950 if (first == 0 && topBottomSpace) {
951 BufferParams const & bufparams = buffer.params();
952 // some parskips VERY EASY IMPLEMENTATION
953 if (bufparams.paragraph_separation
954 == BufferParams::ParagraphSkipSeparation
955 && par.ownerCode() != ERT_CODE
956 && par.ownerCode() != LISTINGS_CODE
958 && ((layout.isParagraph() && par.getDepth() == 0)
959 || (pars[pit - 1].layout().isParagraph()
960 && pars[pit - 1].getDepth() == 0)))
962 maxasc += bufparams.getDefSkip().inPixels(*bv_);
965 if (par.params().startOfAppendix())
966 maxasc += int(3 * dh);
968 // This is special code for the chapter, since the label of this
969 // layout is printed in an extra row
970 if (layout.counter == "chapter"
971 && !par.params().labelString().empty()) {
972 labeladdon = int(labelfont_metrics.maxHeight()
973 * layout.spacing.getValue()
974 * text_->spacing(buffer, par));
977 // special code for the top label
978 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
979 || layout.labeltype == LABEL_BIBLIO
980 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
981 && isFirstInSequence(pit, pars)
982 && !par.labelString().empty())
985 labelfont_metrics.maxHeight()
986 * layout.spacing.getValue()
987 * text_->spacing(buffer, par)
988 + (layout.topsep + layout.labelbottomsep) * dh);
991 // Add the layout spaces, for example before and after
992 // a section, or between the items of a itemize or enumerate
995 pit_type prev = depthHook(pit, pars, par.getDepth());
996 Paragraph const & prevpar = pars[prev];
998 && prevpar.layout() == layout
999 && prevpar.getDepth() == par.getDepth()
1000 && prevpar.getLabelWidthString()
1001 == par.getLabelWidthString()) {
1002 layoutasc = layout.itemsep * dh;
1003 } else if (pit != 0 || first != 0) {
1004 if (layout.topsep > 0)
1005 layoutasc = layout.topsep * dh;
1008 prev = outerHook(pit, pars);
1009 if (prev != pit_type(pars.size())) {
1010 maxasc += int(pars[prev].layout().parsep * dh);
1011 } else if (pit != 0) {
1012 Paragraph const & prevpar = pars[pit - 1];
1013 if (prevpar.getDepth() != 0 ||
1014 prevpar.layout() == layout) {
1015 maxasc += int(layout.parsep * dh);
1020 // is it a bottom line?
1021 if (end >= par.size() && topBottomSpace) {
1022 // add the layout spaces, for example before and after
1023 // a section, or between the items of a itemize or enumerate
1025 pit_type nextpit = pit + 1;
1026 if (nextpit != pit_type(pars.size())) {
1027 pit_type cpit = pit;
1031 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1032 usual = pars[cpit].layout().bottomsep * dh;
1033 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1034 if (pars[cpit].layout() != pars[nextpit].layout()
1035 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1037 unusual = pars[cpit].layout().bottomsep * dh;
1039 layoutdesc = max(unusual, usual);
1040 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1041 if (pars[cpit].layout() != pars[nextpit].layout()
1042 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1043 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1048 // incalculate the layout spaces
1049 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1050 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1052 // FIXME: the correct way is to do the following is to move the
1053 // following code in another method specially tailored for the
1054 // main Text. The following test is thus bogus.
1055 // Top and bottom margin of the document (only at top-level)
1056 if (main_text_ && topBottomSpace) {
1057 if (pit == 0 && first == 0)
1059 if (pit + 1 == pit_type(pars.size()) &&
1060 end == par.size() &&
1061 !(end > 0 && par.isNewline(end - 1)))
1065 return Dimension(0, maxasc + labeladdon, maxdesc);
1069 // x is an absolute screen coord
1070 // returns the column near the specified x-coordinate of the row
1071 // x is set to the real beginning of this column
1072 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1073 Row const & row, int & x, bool & boundary) const
1075 Buffer const & buffer = bv_->buffer();
1077 /// For the main Text, it is possible that this pit is not
1078 /// yet in the CoordCache when moving cursor up.
1079 /// x Paragraph coordinate is always 0 for main text anyway.
1080 int const xo = origin_.x_;
1082 Paragraph const & par = text_->getPar(pit);
1084 bidi.computeTables(par, buffer, row);
1086 pos_type vc = row.pos();
1087 pos_type end = row.endpos();
1089 Layout const & layout = par.layout();
1091 bool left_side = false;
1093 pos_type body_pos = par.beginOfBody();
1095 double tmpx = row.x;
1096 double last_tmpx = tmpx;
1099 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1102 // check for empty row
1108 while (vc < end && tmpx <= x) {
1109 c = bidi.vis2log(vc);
1111 if (body_pos > 0 && c == body_pos - 1) {
1112 FontMetrics const & fm = theFontMetrics(
1113 text_->labelFont(buffer, par));
1114 tmpx += row.label_hfill + fm.width(layout.labelsep);
1115 if (par.isLineSeparator(body_pos - 1))
1116 tmpx -= singleWidth(pit, body_pos - 1);
1119 tmpx += singleWidth(pit, c);
1120 if (par.isSeparator(c) && c >= body_pos)
1121 tmpx += row.separator;
1125 if ((tmpx + last_tmpx) / 2 > x) {
1130 BOOST_ASSERT(vc <= end); // This shouldn't happen.
1133 // This (rtl_support test) is not needed, but gives
1134 // some speedup if rtl_support == false
1135 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1137 // If lastrow is false, we don't need to compute
1138 // the value of rtl.
1139 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1141 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1142 (!rtl && !left_side && vc == end && x > tmpx + 5))) {
1143 if (!par.isNewline(end - 1))
1145 } else if (vc == row.pos()) {
1146 c = bidi.vis2log(vc);
1147 if (bidi.level(c) % 2 == 1)
1150 c = bidi.vis2log(vc - 1);
1151 bool const rtl = (bidi.level(c) % 2 == 1);
1152 if (left_side == rtl) {
1154 boundary = isRTLBoundary(pit, c);
1158 // I believe this code is not needed anymore (Jug 20050717)
1160 // The following code is necessary because the cursor position past
1161 // the last char in a row is logically equivalent to that before
1162 // the first char in the next row. That's why insets causing row
1163 // divisions -- Newline and display-style insets -- must be treated
1164 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1165 // Newline inset, air gap below:
1166 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1167 if (bidi.level(end -1) % 2 == 0)
1168 tmpx -= singleWidth(pit, end - 1);
1170 tmpx += singleWidth(pit, end - 1);
1174 // Air gap above display inset:
1175 if (row.pos() < end && c >= end && end < par.size()
1176 && par.isInset(end) && par.getInset(end)->display()) {
1179 // Air gap below display inset:
1180 if (row.pos() < end && c >= end && par.isInset(end - 1)
1181 && par.getInset(end - 1)->display()) {
1187 pos_type const col = c - row.pos();
1189 if (!c || end == par.size())
1192 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1197 return min(col, end - 1 - row.pos());
1201 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1203 // We play safe and use parMetrics(pit) to make sure the
1204 // ParagraphMetrics will be redone and OK to use if needed.
1205 // Otherwise we would use an empty ParagraphMetrics in
1206 // upDownInText() while in selection mode.
1207 ParagraphMetrics const & pm = parMetrics(pit);
1209 BOOST_ASSERT(row < int(pm.rows().size()));
1211 Row const & r = pm.rows()[row];
1212 return r.pos() + getColumnNearX(pit, r, x, bound);
1216 void TextMetrics::newParMetricsDown()
1218 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1219 pit_type const pit = last.first + 1;
1220 if (pit == int(text_->paragraphs().size()))
1223 // do it and update its position.
1225 par_metrics_[pit].setPosition(last.second.position()
1226 + last.second.descent() + par_metrics_[pit].ascent());
1230 void TextMetrics::newParMetricsUp()
1232 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1233 if (first.first == 0)
1236 pit_type const pit = first.first - 1;
1237 // do it and update its position.
1239 par_metrics_[pit].setPosition(first.second.position()
1240 - first.second.ascent() - par_metrics_[pit].descent());
1243 // y is screen coordinate
1244 pit_type TextMetrics::getPitNearY(int y)
1246 BOOST_ASSERT(!text_->paragraphs().empty());
1247 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1249 // look for highest numbered paragraph with y coordinate less than given y
1252 ParMetricsCache::const_iterator it = par_metrics_.begin();
1253 ParMetricsCache::const_iterator et = par_metrics_.end();
1254 ParMetricsCache::const_iterator last = et; last--;
1256 ParagraphMetrics const & pm = it->second;
1258 if (y < it->second.position() - int(pm.ascent())) {
1259 // We are looking for a position that is before the first paragraph in
1260 // the cache (which is in priciple off-screen, that is before the
1263 // We are already at the first paragraph in the inset.
1265 // OK, this is the paragraph we are looking for.
1266 pit = it->first - 1;
1271 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1273 if (y >= last->second.position() + int(pm_last.descent())) {
1274 // We are looking for a position that is after the last paragraph in
1275 // the cache (which is in priciple off-screen, that is before the
1277 pit = last->first + 1;
1278 if (pit == int(text_->paragraphs().size()))
1279 // We are already at the last paragraph in the inset.
1281 // OK, this is the paragraph we are looking for.
1282 newParMetricsDown();
1286 for (; it != et; ++it) {
1287 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1288 << " y: " << it->second.position());
1290 ParagraphMetrics const & pm = par_metrics_[it->first];
1292 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1294 yy = it->second.position();
1298 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1304 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1306 ParagraphMetrics const & pm = par_metrics_[pit];
1308 int yy = pm.position() - pm.ascent();
1309 BOOST_ASSERT(!pm.rows().empty());
1310 RowList::const_iterator rit = pm.rows().begin();
1311 RowList::const_iterator rlast = pm.rows().end();
1313 for (; rit != rlast; yy += rit->height(), ++rit)
1314 if (yy + rit->height() > y)
1320 // x,y are absolute screen coordinates
1321 // sets cursor recursively descending into nested editable insets
1322 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1324 if (lyxerr.debugging(Debug::WORKAREA)) {
1325 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1326 cur.bv().coordCache().dump();
1328 pit_type pit = getPitNearY(y);
1329 BOOST_ASSERT(pit != -1);
1331 Row const & row = getRowNearY(y, pit);
1334 int xx = x; // is modified by getColumnNearX
1335 pos_type const pos = row.pos()
1336 + getColumnNearX(pit, row, xx, bound);
1339 cur.boundary(bound);
1342 // try to descend into nested insets
1343 Inset * inset = checkInsetHit(x, y);
1344 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1346 // Either we deconst editXY or better we move current_font
1347 // and real_current_font to Cursor
1348 // FIXME: what is needed now that current_font and real_current_font
1350 cur.setCurrentFont();
1354 ParagraphList const & pars = text_->paragraphs();
1355 Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1356 //Inset * insetBehind = pars[pit].getInset(pos);
1358 // This should be just before or just behind the
1359 // cursor position set above.
1360 BOOST_ASSERT((pos != 0 && inset == insetBefore)
1361 || inset == pars[pit].getInset(pos));
1363 // Make sure the cursor points to the position before
1365 if (inset == insetBefore) {
1367 cur.boundary(false);
1370 // Try to descend recursively inside the inset.
1371 inset = inset->editXY(cur, x, y);
1373 if (cur.top().text() == text_)
1374 cur.setCurrentFont();
1379 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1381 BOOST_ASSERT(text_ == cur.text());
1382 pit_type pit = getPitNearY(y);
1384 ParagraphMetrics const & pm = par_metrics_[pit];
1386 int yy = pm.position() - pm.ascent();
1387 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1388 " pit: " << pit << " yy: " << yy);
1391 BOOST_ASSERT(pm.rows().size());
1392 for (; r < int(pm.rows().size()) - 1; ++r) {
1393 Row const & row = pm.rows()[r];
1394 if (int(yy + row.height()) > y)
1399 Row const & row = pm.rows()[r];
1401 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1405 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1407 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1409 text_->setCursor(cur, pit, pos, true, bound);
1410 // remember new position.
1415 //takes screen x,y coordinates
1416 Inset * TextMetrics::checkInsetHit(int x, int y)
1418 pit_type pit = getPitNearY(y);
1419 BOOST_ASSERT(pit != -1);
1421 Paragraph const & par = text_->paragraphs()[pit];
1422 ParagraphMetrics const & pm = par_metrics_[pit];
1424 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1426 InsetList::const_iterator iit = par.insetList().begin();
1427 InsetList::const_iterator iend = par.insetList().end();
1428 for (; iit != iend; ++iit) {
1429 Inset * inset = iit->inset;
1431 LYXERR(Debug::DEBUG, "examining inset " << inset);
1433 if (!bv_->coordCache().getInsets().has(inset)) {
1434 LYXERR(Debug::DEBUG, "inset has no cached position");
1438 Dimension const & dim = pm.insetDimension(inset);
1439 Point p = bv_->coordCache().getInsets().xy(inset);
1441 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1442 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1445 && x <= p.x_ + dim.wid
1446 && y >= p.y_ - dim.asc
1447 && y <= p.y_ + dim.des) {
1448 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1453 LYXERR(Debug::DEBUG, "No inset hit. ");
1458 int TextMetrics::cursorX(CursorSlice const & sl,
1459 bool boundary) const
1461 BOOST_ASSERT(sl.text() == text_);
1462 pit_type const pit = sl.pit();
1463 Paragraph const & par = text_->paragraphs()[pit];
1464 ParagraphMetrics const & pm = par_metrics_[pit];
1465 if (pm.rows().empty())
1468 pos_type ppos = sl.pos();
1469 // Correct position in front of big insets
1470 bool const boundary_correction = ppos != 0 && boundary;
1471 if (boundary_correction)
1474 Row const & row = pm.getRow(sl.pos(), boundary);
1476 pos_type cursor_vpos = 0;
1478 Buffer const & buffer = bv_->buffer();
1481 bidi.computeTables(par, buffer, row);
1483 pos_type const row_pos = row.pos();
1484 pos_type const end = row.endpos();
1485 // Spaces at logical line breaks in bidi text must be skipped during
1486 // cursor positioning. However, they may appear visually in the middle
1487 // of a row; they must be skipped, wherever they are...
1488 // * logically "abc_[HEBREW_\nHEBREW]"
1489 // * visually "abc_[_WERBEH\nWERBEH]"
1490 pos_type skipped_sep_vpos = -1;
1493 cursor_vpos = row_pos;
1494 else if (ppos >= end)
1495 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1496 else if (ppos > row_pos && ppos >= end)
1497 // Place cursor after char at (logical) position pos - 1
1498 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1499 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1501 // Place cursor before char at (logical) position ppos
1502 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1503 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1505 pos_type body_pos = par.beginOfBody();
1507 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1510 // check for possible inline completion in this row
1511 DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1512 pos_type inlineCompletionVPos = -1;
1513 if (inlineCompletionPos.inTexted()
1514 && inlineCompletionPos.text() == text_
1515 && inlineCompletionPos.pit() == pit
1516 && inlineCompletionPos.pos() - 1 >= row_pos
1517 && inlineCompletionPos.pos() - 1 < end) {
1518 // draw logically behind the previous character
1519 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1522 // Use font span to speed things up, see below
1526 // If the last logical character is a separator, skip it, unless
1527 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1528 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1529 skipped_sep_vpos = bidi.log2vis(end - 1);
1531 // Inline completion RTL special case row_pos == cursor_pos:
1532 // "__|b" => cursor_pos is right of __
1533 if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1534 font = displayFont(pit, row_pos + 1);
1535 docstring const & completion = bv_->inlineCompletion();
1536 if (font.isRightToLeft() && completion.length() > 0)
1537 x += theFontMetrics(font.fontInfo()).width(completion);
1540 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1541 // Skip the separator which is at the logical end of the row
1542 if (vpos == skipped_sep_vpos)
1544 pos_type pos = bidi.vis2log(vpos);
1545 if (body_pos > 0 && pos == body_pos - 1) {
1546 FontMetrics const & labelfm = theFontMetrics(
1547 text_->labelFont(buffer, par));
1548 x += row.label_hfill + labelfm.width(par.layout().labelsep);
1549 if (par.isLineSeparator(body_pos - 1))
1550 x -= singleWidth(pit, body_pos - 1);
1553 // Use font span to speed things up, see above
1554 if (pos < font_span.first || pos > font_span.last) {
1555 font_span = par.fontSpan(pos);
1556 font = displayFont(pit, pos);
1559 x += pm.singleWidth(pos, font);
1561 // Inline completion RTL case:
1562 // "a__|b", __ of b => non-boundary a-pos is right of __
1563 if (vpos + 1 == inlineCompletionVPos
1564 && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1565 font = displayFont(pit, vpos + 1);
1566 docstring const & completion = bv_->inlineCompletion();
1567 if (font.isRightToLeft() && completion.length() > 0)
1568 x += theFontMetrics(font.fontInfo()).width(completion);
1571 // Inline completion LTR case:
1572 // "b|__a", __ of b => non-boundary a-pos is in front of __
1573 if (vpos == inlineCompletionVPos
1574 && (vpos + 1 < cursor_vpos || boundary_correction)) {
1575 font = displayFont(pit, vpos);
1576 docstring const & completion = bv_->inlineCompletion();
1577 if (!font.isRightToLeft() && completion.length() > 0)
1578 x += theFontMetrics(font.fontInfo()).width(completion);
1581 if (par.isSeparator(pos) && pos >= body_pos)
1585 // see correction above
1586 if (boundary_correction) {
1587 if (isRTL(sl, boundary))
1588 x -= singleWidth(pit, ppos);
1590 x += singleWidth(pit, ppos);
1597 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1599 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1600 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1601 if (pm.rows().empty())
1605 h -= par_metrics_[0].rows()[0].ascent();
1606 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1607 h += par_metrics_[pit].height();
1610 if (pos && boundary)
1612 size_t const rend = pm.pos2row(pos);
1613 for (size_t rit = 0; rit != rend; ++rit)
1614 h += pm.rows()[rit].height();
1615 h += pm.rows()[rend].ascent();
1620 // the cursor set functions have a special mechanism. When they
1621 // realize you left an empty paragraph, they will delete it.
1623 bool TextMetrics::cursorHome(Cursor & cur)
1625 BOOST_ASSERT(text_ == cur.text());
1626 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1627 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1628 return text_->setCursor(cur, cur.pit(), row.pos());
1632 bool TextMetrics::cursorEnd(Cursor & cur)
1634 BOOST_ASSERT(text_ == cur.text());
1635 // if not on the last row of the par, put the cursor before
1636 // the final space exept if I have a spanning inset or one string
1637 // is so long that we force a break.
1638 pos_type end = cur.textRow().endpos();
1640 // empty text, end-1 is no valid position
1642 bool boundary = false;
1643 if (end != cur.lastpos()) {
1644 if (!cur.paragraph().isLineSeparator(end-1)
1645 && !cur.paragraph().isNewline(end-1))
1650 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1654 void TextMetrics::deleteLineForward(Cursor & cur)
1656 BOOST_ASSERT(text_ == cur.text());
1657 if (cur.lastpos() == 0) {
1658 // Paragraph is empty, so we just go forward
1659 text_->cursorForward(cur);
1662 cur.selection() = true; // to avoid deletion
1665 // What is this test for ??? (JMarc)
1666 if (!cur.selection())
1667 text_->deleteWordForward(cur);
1669 cap::cutSelection(cur, true, false);
1670 cur.checkBufferStructure();
1675 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1677 ParagraphList const & pars = text_->paragraphs();
1678 return row.endpos() >= pars[pit].size()
1679 && pit + 1 == pit_type(pars.size());
1683 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1685 return row.pos() == 0 && pit == 0;
1689 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1691 BOOST_ASSERT(pit >= 0);
1692 BOOST_ASSERT(pit < int(text_->paragraphs().size()));
1693 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1697 int TextMetrics::leftMargin(int max_width,
1698 pit_type const pit, pos_type const pos) const
1700 ParagraphList const & pars = text_->paragraphs();
1702 BOOST_ASSERT(pit >= 0);
1703 BOOST_ASSERT(pit < int(pars.size()));
1704 Paragraph const & par = pars[pit];
1705 BOOST_ASSERT(pos >= 0);
1706 BOOST_ASSERT(pos <= par.size());
1707 Buffer const & buffer = bv_->buffer();
1708 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1709 DocumentClass const & tclass = buffer.params().documentClass();
1710 Layout const & layout = par.layout();
1712 docstring parindent = layout.parindent;
1716 if (text_->isMainText(buffer))
1717 l_margin += bv_->leftMargin();
1719 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1720 tclass.leftmargin());
1722 if (par.getDepth() != 0) {
1723 // find the next level paragraph
1724 pit_type newpar = outerHook(pit, pars);
1725 if (newpar != pit_type(pars.size())) {
1726 if (pars[newpar].layout().isEnvironment()) {
1727 l_margin = leftMargin(max_width, newpar);
1729 if (tclass.isDefaultLayout(par.layout())
1730 || tclass.isEmptyLayout(par.layout())) {
1731 if (pars[newpar].params().noindent())
1734 parindent = pars[newpar].layout().parindent;
1739 // This happens after sections in standard classes. The 1.3.x
1740 // code compared depths too, but it does not seem necessary
1742 if (tclass.isDefaultLayout(par.layout())
1743 && pit > 0 && pars[pit - 1].layout().nextnoindent)
1746 FontInfo const labelfont = text_->labelFont(buffer, par);
1747 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1749 switch (layout.margintype) {
1750 case MARGIN_DYNAMIC:
1751 if (!layout.leftmargin.empty()) {
1752 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1755 if (!par.labelString().empty()) {
1756 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1757 l_margin += labelfont_metrics.width(par.labelString());
1758 l_margin += labelfont_metrics.width(layout.labelsep);
1762 case MARGIN_MANUAL: {
1763 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1764 // The width of an empty par, even with manual label, should be 0
1765 if (!par.empty() && pos >= par.beginOfBody()) {
1766 if (!par.getLabelWidthString().empty()) {
1767 docstring labstr = par.getLabelWidthString();
1768 l_margin += labelfont_metrics.width(labstr);
1769 l_margin += labelfont_metrics.width(layout.labelsep);
1775 case MARGIN_STATIC: {
1776 l_margin += theFontMetrics(buffer.params().getFont()).
1777 signedWidth(layout.leftmargin) * 4 / (par.getDepth() + 4);
1781 case MARGIN_FIRST_DYNAMIC:
1782 if (layout.labeltype == LABEL_MANUAL) {
1783 if (pos >= par.beginOfBody()) {
1784 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1786 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1789 // Special case to fix problems with
1791 || (layout.labeltype == LABEL_STATIC
1792 && layout.latextype == LATEX_ENVIRONMENT
1793 && !isFirstInSequence(pit, pars))) {
1794 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1795 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
1796 && layout.labeltype != LABEL_BIBLIO
1797 && layout.labeltype !=
1798 LABEL_CENTERED_TOP_ENVIRONMENT) {
1799 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1800 l_margin += labelfont_metrics.width(layout.labelsep);
1801 l_margin += labelfont_metrics.width(par.labelString());
1805 case MARGIN_RIGHT_ADDRESS_BOX: {
1807 // ok, a terrible hack. The left margin depends on the widest
1808 // row in this paragraph.
1809 RowList::iterator rit = par.rows().begin();
1810 RowList::iterator end = par.rows().end();
1811 // FIXME: This is wrong.
1812 int minfill = max_width;
1813 for ( ; rit != end; ++rit)
1814 if (rit->fill() < minfill)
1815 minfill = rit->fill();
1816 l_margin += theFontMetrics(params.getFont()).signedWidth(layout.leftmargin);
1817 l_margin += minfill;
1819 // also wrong, but much shorter.
1820 l_margin += max_width / 2;
1825 if (!par.params().leftIndent().zero())
1826 l_margin += par.params().leftIndent().inPixels(max_width);
1830 if (par.params().align() == LYX_ALIGN_LAYOUT)
1831 align = layout.align;
1833 align = par.params().align();
1835 // set the correct parindent
1837 && (layout.labeltype == LABEL_NO_LABEL
1838 || layout.labeltype == LABEL_TOP_ENVIRONMENT
1839 || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1840 || (layout.labeltype == LABEL_STATIC
1841 && layout.latextype == LATEX_ENVIRONMENT
1842 && !isFirstInSequence(pit, pars)))
1843 && align == LYX_ALIGN_BLOCK
1844 && !par.params().noindent()
1845 // in some insets, paragraphs are never indented
1846 && !(par.inInset() && par.inInset()->neverIndent())
1847 // display style insets are always centered, omit indentation
1850 && par.getInset(pos)->display())
1851 && ((tclass.isDefaultLayout(par.layout())
1852 || tclass.isEmptyLayout(par.layout()))
1853 || buffer.params().paragraph_separation == BufferParams::ParagraphIndentSeparation)
1856 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1864 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1866 ParagraphMetrics const & pm = par_metrics_[pit];
1868 return pm.singleWidth(pos, displayFont(pit, pos));
1872 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1874 if (par_metrics_.empty())
1880 ParMetricsCache::iterator it = par_metrics_.begin();
1881 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1882 y -= it->second.ascent();
1883 for (; it != pm_end; ++it) {
1884 ParagraphMetrics const & pmi = it->second;
1886 pit_type const pit = it->first;
1887 // Save the paragraph position in the cache.
1888 it->second.setPosition(y);
1889 drawParagraph(pi, pit, x, y);
1895 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1897 BufferParams const & bparams = bv_->buffer().params();
1898 ParagraphMetrics const & pm = par_metrics_[pit];
1899 if (pm.rows().empty())
1903 bool const original_drawing_state = pi.pain.isDrawingEnabled();
1904 int const ww = bv_->workHeight();
1905 size_t const nrows = pm.rows().size();
1907 Cursor const & cur = bv_->cursor();
1908 DocIterator sel_beg = cur.selectionBegin();
1909 DocIterator sel_end = cur.selectionEnd();
1910 bool selection = cur.selection()
1911 // This is our text.
1912 && cur.text() == text_
1913 // if the anchor is outside, this is not our selection
1914 && cur.anchor().text() == text_
1915 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1917 // We care only about visible selection.
1919 if (pit != sel_beg.pit()) {
1920 sel_beg.pit() = pit;
1923 if (pit != sel_end.pit()) {
1924 sel_end.pit() = pit;
1925 sel_end.pos() = sel_end.lastpos();
1929 for (size_t i = 0; i != nrows; ++i) {
1931 Row const & row = pm.rows()[i];
1935 bool const inside = (y + row.descent() >= 0
1936 && y - row.ascent() < ww);
1937 // It is not needed to draw on screen if we are not inside.
1938 pi.pain.setDrawingEnabled(inside && original_drawing_state);
1939 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
1942 row.setSelection(sel_beg.pos(), sel_end.pos());
1944 row.setSelection(-1, -1);
1946 // Row signature; has row changed since last paint?
1947 row.setCrc(pm.computeRowSignature(row, bparams));
1948 bool row_has_changed = row.changed();
1950 // Don't paint the row if a full repaint has not been requested
1951 // and if it has not changed.
1952 if (!pi.full_repaint && !row_has_changed) {
1953 // Paint only the insets if the text itself is
1955 rp.paintOnlyInsets();
1960 // Clear background of this row if paragraph background was not
1961 // already cleared because of a full repaint.
1962 if (!pi.full_repaint && row_has_changed) {
1963 pi.pain.fillRectangle(x, y - row.ascent(),
1964 width(), row.height(), pi.background_color);
1967 bool row_selection = row.sel_beg != -1 && row.sel_end != -1;
1968 if (row_selection) {
1969 DocIterator beg = bv_->cursor().selectionBegin();
1970 DocIterator end = bv_->cursor().selectionEnd();
1971 bool const beg_margin = beg.pit() < pit && i == 0;
1972 bool const end_margin = end.pit() > pit && i == nrows - 1;
1974 beg.pos() = row.sel_beg;
1976 end.pos() = row.sel_end;
1977 drawRowSelection(pi, x, row, beg, end, beg_margin, end_margin);
1980 // Instrumentation for testing row cache (see also
1982 if (lyxerr.debugging(Debug::PAINTING) && inside
1983 && (row_selection || pi.full_repaint || row_has_changed)) {
1984 string const foreword = text_->isMainText(bv_->buffer()) ?
1985 "main text redraw " : "inset text redraw: ";
1986 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
1987 << " row_selection=" << row_selection
1988 << " full_repaint=" << pi.full_repaint
1989 << " row_has_changed=" << row_has_changed);
1992 // Backup full_repaint status and force full repaint
1993 // for inner insets as the Row has been cleared out.
1994 bool tmp = pi.full_repaint;
1995 pi.full_repaint = true;
1998 rp.paintChangeBar();
2005 // Restore full_repaint status.
2006 pi.full_repaint = tmp;
2008 // Re-enable screen drawing for future use of the painter.
2009 pi.pain.setDrawingEnabled(original_drawing_state);
2011 //LYXERR(Debug::PAINTING, ".");
2015 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2016 DocIterator const & beg, DocIterator const & end,
2017 bool drawOnBegMargin, bool drawOnEndMargin) const
2019 Buffer & buffer = bv_->buffer();
2020 DocIterator cur = beg;
2021 int x1 = cursorX(beg.top(), beg.boundary());
2022 int x2 = cursorX(end.top(), end.boundary());
2023 int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2024 int y2 = y1 + row.height();
2027 if (drawOnBegMargin) {
2028 if (text_->isRTL(buffer, beg.paragraph()))
2029 pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color_selection);
2031 pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color_selection);
2034 if (drawOnEndMargin) {
2035 if (text_->isRTL(buffer, beg.paragraph()))
2036 pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color_selection);
2038 pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color_selection);
2041 // if we are on a boundary from the beginning, it's probably
2042 // a RTL boundary and we jump to the other side directly as this
2043 // segement is 0-size and confuses the logic below
2045 cur.boundary(false);
2047 // go through row and draw from RTL boundary to RTL boundary
2049 bool drawNow = false;
2051 // simplified cursorForward code below which does not
2052 // descend into insets and which does not go into the
2053 // next line. Compare the logic with the original cursorForward
2055 // if left of boundary -> just jump to right side
2056 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2057 if (cur.boundary()) {
2058 cur.boundary(false);
2059 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2060 // in front of RTL boundary -> Stay on this side of the boundary because:
2061 // ab|cDDEEFFghi -> abc|DDEEFFghi
2070 if (cur.pos() == row.endpos())
2075 // the previous segment was just drawn, now the next starts
2076 x1 = cursorX(cur.top(), cur.boundary());
2079 if (!(cur < end) || drawNow) {
2080 x2 = cursorX(cur.top(), cur.boundary());
2081 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2084 // reset x1, so it is set again next round (which will be on the
2085 // right side of a boundary or at the selection end)
2091 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2093 // ParagraphMetrics const & pm = par_metrics_[pit];
2094 // Row const & r = pm.rows()[row];
2100 int defaultRowHeight()
2102 return int(theFontMetrics(sane_font).maxHeight() * 1.2);