scramble email addresses
[lyx.git] / src / TextMetrics.cpp
blob39fddf750290c3d1b46bfe48dc17b45282bbb96a
1 /**
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
9 * \author John Levon
10 * \author André Pönitz
11 * \author Dekel Tsur
12 * \author Jürgen Vigna
13 * \author Abdelrazak Younes
15 * Full author contact details are available in file CREDITS.
18 #include <config.h>
20 #include "TextMetrics.h"
22 #include "Bidi.h"
23 #include "Buffer.h"
24 #include "buffer_funcs.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "Color.h"
28 #include "CutAndPaste.h"
29 #include "debug.h"
30 #include "FontIterator.h"
31 #include "FuncRequest.h"
32 #include "InsetList.h"
33 #include "Layout.h"
34 #include "Length.h"
35 #include "LyXRC.h"
36 #include "MetricsInfo.h"
37 #include "paragraph_funcs.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
40 #include "rowpainter.h"
41 #include "Text.h"
42 #include "VSpace.h"
44 #include "frontends/FontMetrics.h"
45 #include "frontends/Painter.h"
47 #include <boost/current_function.hpp>
49 using std::make_pair;
50 using std::max;
51 using std::min;
52 using std::endl;
53 using std::pair;
55 namespace lyx {
57 using frontend::FontMetrics;
59 namespace {
61 int numberOfSeparators(Paragraph const & par, Row const & row)
63 pos_type const first = max(row.pos(), par.beginOfBody());
64 pos_type const last = row.endpos() - 1;
65 int n = 0;
66 for (pos_type p = first; p < last; ++p) {
67 if (par.isSeparator(p))
68 ++n;
70 return n;
74 int numberOfLabelHfills(Paragraph const & par, Row const & row)
76 pos_type last = row.endpos() - 1;
77 pos_type first = row.pos();
79 // hfill *DO* count at the beginning of paragraphs!
80 if (first) {
81 while (first < last && par.isHfill(first))
82 ++first;
85 last = min(last, par.beginOfBody());
86 int n = 0;
87 for (pos_type p = first; p < last; ++p) {
88 if (par.isHfill(p))
89 ++n;
91 return n;
95 int numberOfHfills(Paragraph const & par, Row const & row)
97 pos_type const last = row.endpos();
98 pos_type first = row.pos();
100 // hfill *DO* count at the beginning of paragraphs!
101 if (first) {
102 while (first < last && par.isHfill(first))
103 ++first;
106 first = max(first, par.beginOfBody());
108 int n = 0;
109 for (pos_type p = first; p < last; ++p) {
110 if (par.isHfill(p))
111 ++n;
113 return n;
116 } // namespace anon
118 TextMetrics::TextMetrics(BufferView * bv, Text * text)
119 : bv_(bv), text_(text)
121 BOOST_ASSERT(bv_);
122 max_width_ = bv_->workWidth();
123 dim_.wid = max_width_;
124 dim_.asc = 10;
125 dim_.des = 10;
127 //text_->updateLabels(bv->buffer());
131 bool TextMetrics::has(pit_type pit) const
133 return par_metrics_.find(pit) != par_metrics_.end();
137 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
139 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
144 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
146 ParMetricsCache::const_iterator it = par_metrics_.begin();
147 return make_pair(it->first, &it->second);
151 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
153 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
154 return make_pair(it->first, &it->second);
158 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit,
159 bool redo)
161 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
162 if (pmc_it == par_metrics_.end()) {
163 pmc_it = par_metrics_.insert(
164 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
166 if (pmc_it->second.rows().empty() && redo) {
167 redoParagraph(pit);
169 return pmc_it->second;
173 int TextMetrics::parPosition(pit_type pit) const
175 if (pit < par_metrics_.begin()->first)
176 return -1000000;
177 else if (pit > par_metrics_.rbegin()->first)
178 return +1000000;
180 return par_metrics_[pit].position();
184 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
186 BOOST_ASSERT(mi.base.textwidth);
187 max_width_ = mi.base.textwidth;
188 // backup old dimension.
189 Dimension const old_dim = dim_;
190 // reset dimension.
191 dim_ = Dimension();
192 dim_.wid = min_width;
193 pit_type const npar = text_->paragraphs().size();
194 if (npar > 1)
195 // If there is more than one row, expand the text to
196 // the full allowable width.
197 dim_.wid = max_width_;
199 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
200 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
202 bool changed = false;
203 unsigned int h = 0;
204 for (pit_type pit = 0; pit != npar; ++pit) {
205 changed |= redoParagraph(pit);
206 ParagraphMetrics const & pm = par_metrics_[pit];
207 h += pm.height();
208 if (dim_.wid < pm.width())
209 dim_.wid = pm.width();
212 dim_.asc = par_metrics_[0].ascent();
213 dim_.des = h - dim_.asc;
214 //lyxerr << "dim_.wid " << dim_.wid << endl;
215 //lyxerr << "dim_.asc " << dim_.asc << endl;
216 //lyxerr << "dim_.des " << dim_.des << endl;
218 changed |= dim_ != old_dim;
219 dim = dim_;
220 return changed;
224 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
226 return main_text_? pm.rightMargin(bv_->buffer()) : 0;
230 int TextMetrics::rightMargin(pit_type const pit) const
232 return main_text_? par_metrics_[pit].rightMargin(bv_->buffer()) : 0;
236 void TextMetrics::applyOuterFont(Font & font) const
238 Font lf(font_);
239 lf.reduce(bv_->buffer().params().getFont());
240 lf.realize(font);
241 lf.setLanguage(font.language());
242 font = lf;
246 Font TextMetrics::getDisplayFont(pit_type pit, pos_type pos) const
248 BOOST_ASSERT(pos >= 0);
250 ParagraphList const & pars = text_->paragraphs();
251 Paragraph const & par = pars[pit];
252 LayoutPtr const & layout = par.layout();
253 Buffer const & buffer = bv_->buffer();
254 // FIXME: broken?
255 BufferParams const & params = buffer.params();
256 pos_type const body_pos = par.beginOfBody();
258 // We specialize the 95% common case:
259 if (!par.getDepth()) {
260 Font f = par.getFontSettings(params, pos);
261 if (!text_->isMainText(buffer))
262 applyOuterFont(f);
263 bool lab = layout->labeltype == LABEL_MANUAL && pos < body_pos;
265 Font const & lf = lab ? layout->labelfont : layout->font;
266 Font rlf = lab ? layout->reslabelfont : layout->resfont;
268 // In case the default family has been customized
269 if (lf.family() == Font::INHERIT_FAMILY)
270 rlf.setFamily(params.getFont().family());
271 return f.realize(rlf);
274 // The uncommon case need not be optimized as much
275 Font const & layoutfont = pos < body_pos ?
276 layout->labelfont : layout->font;
278 Font font = par.getFontSettings(params, pos);
279 font.realize(layoutfont);
281 if (!text_->isMainText(buffer))
282 applyOuterFont(font);
284 // Realize against environment font information
285 // NOTE: the cast to pit_type should be removed when pit_type
286 // changes to a unsigned integer.
287 if (pit < pit_type(pars.size()))
288 font.realize(outerFont(pit, pars));
290 // Realize with the fonts of lesser depth.
291 font.realize(params.getFont());
293 return font;
297 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
299 if (!lyxrc.rtl_support || !sl.text())
300 return false;
302 int correction = 0;
303 if (boundary && sl.pos() > 0)
304 correction = -1;
306 return getDisplayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
310 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
312 if (!lyxrc.rtl_support)
313 return false;
315 // no RTL boundary at line start
316 if (pos == 0)
317 return false;
319 Paragraph const & par = text_->getPar(pit);
321 bool left = getDisplayFont(pit, pos - 1).isVisibleRightToLeft();
322 bool right;
323 if (pos == par.size())
324 right = par.isRTL(bv_->buffer().params());
325 else
326 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
327 return left != right;
331 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
332 Font const & font) const
334 if (!lyxrc.rtl_support)
335 return false;
337 Paragraph const & par = text_->getPar(pit);
338 bool left = font.isVisibleRightToLeft();
339 bool right;
340 if (pos == par.size())
341 right = par.isRTL(bv_->buffer().params());
342 else
343 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
344 return left != right;
348 bool TextMetrics::redoParagraph(pit_type const pit)
350 Paragraph & par = text_->getPar(pit);
351 // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
352 // redoParagraph() recursively inside parMetrics.
353 Dimension old_dim = parMetrics(pit, false).dim();
354 ParagraphMetrics & pm = par_metrics_[pit];
355 pm.reset(par);
357 Buffer & buffer = bv_->buffer();
358 BufferParams const & bparams = buffer.params();
359 main_text_ = (text_ == &buffer.text());
360 bool changed = false;
362 // FIXME This check ought to be done somewhere else. It is the reason
363 // why text_ is not const. But then, where else to do it?
364 // Well, how can you end up with either (a) a biblio environment that
365 // has no InsetBibitem or (b) a biblio environment with more than one
366 // InsetBibitem? I think the answer is: when paragraphs are merged;
367 // when layout is set; when material is pasted.
368 int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
369 if (moveCursor > 0)
370 const_cast<Cursor &>(bv_->cursor()).posRight();
371 else if (moveCursor < 0) {
372 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
373 if (cursor.pos() >= -moveCursor)
374 cursor.posLeft();
377 // Optimisation: this is used in the next two loops
378 // so better to calculate that once here.
379 int const right_margin = rightMargin(pm);
381 // redo insets
382 // FIXME: We should always use getFont(), see documentation of
383 // noFontChange() in Inset.h.
384 Font const bufferfont = buffer.params().getFont();
385 InsetList::const_iterator ii = par.insetList().begin();
386 InsetList::const_iterator iend = par.insetList().end();
387 for (; ii != iend; ++ii) {
388 Dimension dim;
389 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
390 - right_margin;
391 Font const & font = ii->inset->noFontChange() ?
392 bufferfont : getDisplayFont(pit, ii->pos);
393 MetricsInfo mi(bv_, font, w);
394 ii->inset->metrics(mi, dim);
395 Dimension const old_dim = pm.insetDimension(ii->inset);
396 pm.setInsetDimension(ii->inset, dim);
397 changed |= (old_dim != dim);
400 Cursor const & cur = bv_->cursor();
401 DocIterator sel_beg = cur.selectionBegin();
402 DocIterator sel_end = cur.selectionEnd();
403 bool selection = cur.selection()
404 // This is out text.
405 && cur.text() == text_
406 // if the anchor is outside, this is not our selection
407 && cur.anchor().text() == text_
408 && pit >= sel_beg.pit() && pit <= sel_end.pit();
410 // We care only about visible selection.
411 if (selection) {
412 if (pit != sel_beg.pit()) {
413 sel_beg.pit() = pit;
414 sel_beg.pos() = 0;
416 if (pit != sel_end.pit()) {
417 sel_end.pit() = pit;
418 sel_end.pos() = sel_end.lastpos();
422 par.setBeginOfBody();
423 pos_type first = 0;
424 size_t row_index = 0;
425 // maximum pixel width of a row
426 int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
427 do {
428 Dimension dim;
429 pos_type end = rowBreakPoint(width, pit, first);
430 if (row_index || end < par.size())
431 // If there is more than one row, expand the text to
432 // the full allowable width. This setting here is needed
433 // for the computeRowMetrics() below.
434 dim_.wid = max_width_;
436 dim.wid = rowWidth(right_margin, pit, first, end);
437 boost::tie(dim.asc, dim.des) = rowHeight(pit, first, end);
438 if (row_index == pm.rows().size())
439 pm.rows().push_back(Row());
440 Row & row = pm.rows()[row_index];
441 row.setChanged(false);
442 row.pos(first);
443 row.endpos(end);
444 if (selection)
445 row.setSelection(sel_beg.pos(), sel_end.pos());
446 else
447 row.setSelection(-1, -1);
448 row.setDimension(dim);
449 int const max_row_width = max(dim_.wid, dim.wid);
450 computeRowMetrics(pit, row, max_row_width);
451 pm.computeRowSignature(row, bparams);
452 first = end;
453 ++row_index;
455 pm.dim().wid = std::max(pm.dim().wid, dim.wid);
456 pm.dim().des += dim.height();
457 } while (first < par.size());
459 if (row_index < pm.rows().size())
460 pm.rows().resize(row_index);
462 // Make sure that if a par ends in newline, there is one more row
463 // under it
464 if (first > 0 && par.isNewline(first - 1)) {
465 Dimension dim;
466 dim.wid = rowWidth(right_margin, pit, first, first);
467 boost::tie(dim.asc, dim.des) = rowHeight(pit, first, first);
468 if (row_index == pm.rows().size())
469 pm.rows().push_back(Row());
470 Row & row = pm.rows()[row_index];
471 row.setChanged(false);
472 row.pos(first);
473 row.endpos(first);
474 row.setDimension(dim);
475 int const max_row_width = max(dim_.wid, dim.wid);
476 computeRowMetrics(pit, row, max_row_width);
477 pm.computeRowSignature(row, bparams);
478 pm.dim().des += dim.height();
481 pm.dim().asc += pm.rows()[0].ascent();
482 pm.dim().des -= pm.rows()[0].ascent();
484 changed |= old_dim.height() != pm.dim().height();
486 return changed;
490 void TextMetrics::computeRowMetrics(pit_type const pit,
491 Row & row, int width) const
494 row.label_hfill = 0;
495 row.hfill = 0;
496 row.separator = 0;
498 Buffer & buffer = bv_->buffer();
499 Paragraph const & par = text_->getPar(pit);
501 double w = width - row.width();
502 // FIXME: put back this assertion when the crash on new doc is solved.
503 //BOOST_ASSERT(w >= 0);
505 //lyxerr << "\ndim_.wid " << dim_.wid << endl;
506 //lyxerr << "row.width() " << row.width() << endl;
507 //lyxerr << "w " << w << endl;
509 bool const is_rtl = text_->isRTL(buffer, par);
510 if (is_rtl)
511 row.x = rightMargin(pit);
512 else
513 row.x = leftMargin(max_width_, pit, row.pos());
515 // is there a manual margin with a manual label
516 LayoutPtr const & layout = par.layout();
518 if (layout->margintype == MARGIN_MANUAL
519 && layout->labeltype == LABEL_MANUAL) {
520 /// We might have real hfills in the label part
521 int nlh = numberOfLabelHfills(par, row);
523 // A manual label par (e.g. List) has an auto-hfill
524 // between the label text and the body of the
525 // paragraph too.
526 // But we don't want to do this auto hfill if the par
527 // is empty.
528 if (!par.empty())
529 ++nlh;
531 if (nlh && !par.getLabelWidthString().empty())
532 row.label_hfill = labelFill(pit, row) / double(nlh);
535 // are there any hfills in the row?
536 int const nh = numberOfHfills(par, row);
538 if (nh) {
539 if (w > 0)
540 row.hfill = w / nh;
541 // we don't have to look at the alignment if it is ALIGN_LEFT and
542 // if the row is already larger then the permitted width as then
543 // we force the LEFT_ALIGN'edness!
544 } else if (int(row.width()) < max_width_) {
545 // is it block, flushleft or flushright?
546 // set x how you need it
547 int align;
548 if (par.params().align() == LYX_ALIGN_LAYOUT)
549 align = layout->align;
550 else
551 align = par.params().align();
553 // Display-style insets should always be on a centred row
554 // The test on par.size() is to catch zero-size pars, which
555 // would trigger the assert in Paragraph::getInset().
556 //inset = par.size() ? par.getInset(row.pos()) : 0;
557 if (row.pos() < par.size()
558 && par.isInset(row.pos()))
560 switch(par.getInset(row.pos())->display()) {
561 case Inset::AlignLeft:
562 align = LYX_ALIGN_BLOCK;
563 break;
564 case Inset::AlignCenter:
565 align = LYX_ALIGN_CENTER;
566 break;
567 case Inset::Inline:
568 case Inset::AlignRight:
569 // unchanged (use align)
570 break;
574 switch (align) {
575 case LYX_ALIGN_BLOCK: {
576 int const ns = numberOfSeparators(par, row);
577 bool disp_inset = false;
578 if (row.endpos() < par.size()) {
579 Inset const * in = par.getInset(row.endpos());
580 if (in)
581 disp_inset = in->display();
583 // If we have separators, this is not the last row of a
584 // par, does not end in newline, and is not row above a
585 // display inset... then stretch it
586 if (ns
587 && row.endpos() < par.size()
588 && !par.isNewline(row.endpos() - 1)
589 && !disp_inset
591 row.separator = w / ns;
592 //lyxerr << "row.separator " << row.separator << endl;
593 //lyxerr << "ns " << ns << endl;
594 } else if (is_rtl) {
595 row.x += w;
597 break;
599 case LYX_ALIGN_RIGHT:
600 row.x += w;
601 break;
602 case LYX_ALIGN_CENTER:
603 row.x += w / 2;
604 break;
608 if (is_rtl) {
609 pos_type body_pos = par.beginOfBody();
610 pos_type end = row.endpos();
612 if (body_pos > 0
613 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
615 row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
616 width(layout->labelsep);
617 if (body_pos <= end)
618 row.x += row.label_hfill;
624 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
626 Buffer & buffer = bv_->buffer();
627 Paragraph const & par = text_->getPar(pit);
629 pos_type last = par.beginOfBody();
630 BOOST_ASSERT(last > 0);
632 // -1 because a label ends with a space that is in the label
633 --last;
635 // a separator at this end does not count
636 if (par.isLineSeparator(last))
637 --last;
639 int w = 0;
640 for (pos_type i = row.pos(); i <= last; ++i)
641 w += singleWidth(pit, i);
643 docstring const & label = par.params().labelWidthString();
644 if (label.empty())
645 return 0;
647 FontMetrics const & fm
648 = theFontMetrics(text_->getLabelFont(buffer, par));
650 return max(0, fm.width(label) - w);
654 namespace {
656 // this needs special handling - only newlines count as a break point
657 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
659 pos_type const end = par.size();
661 for (; i < end; ++i)
662 if (par.isNewline(i))
663 return i + 1;
665 return end;
671 int TextMetrics::labelEnd(pit_type const pit) const
673 // labelEnd is only needed if the layout fills a flushleft label.
674 if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
675 return 0;
676 // return the beginning of the body
677 return leftMargin(max_width_, pit);
681 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
682 pit_type pos) const
684 Buffer & buffer = bv_->buffer();
685 ParagraphMetrics const & pm = par_metrics_[pit];
686 Paragraph const & par = text_->getPar(pit);
687 pos_type const end = par.size();
688 if (pos == end || width < 0)
689 return end;
691 LayoutPtr const & layout = par.layout();
693 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
694 return addressBreakPoint(pos, par);
696 pos_type const body_pos = par.beginOfBody();
699 // Now we iterate through until we reach the right margin
700 // or the end of the par, then choose the possible break
701 // nearest that.
703 int label_end = labelEnd(pit);
704 int const left = leftMargin(max_width_, pit, pos);
705 int x = left;
707 // pixel width since last breakpoint
708 int chunkwidth = 0;
710 FontIterator fi = FontIterator(*this, par, pit, pos);
711 pos_type point = end;
712 pos_type i = pos;
713 for ( ; i < end; ++i, ++fi) {
714 int thiswidth = pm.singleWidth(i, *fi);
716 // add the auto-hfill from label end to the body
717 if (body_pos && i == body_pos) {
718 FontMetrics const & fm = theFontMetrics(
719 text_->getLabelFont(buffer, par));
720 int add = fm.width(layout->labelsep);
721 if (par.isLineSeparator(i - 1))
722 add -= singleWidth(pit, i - 1);
724 add = std::max(add, label_end - x);
725 thiswidth += add;
728 x += thiswidth;
729 chunkwidth += thiswidth;
731 // break before a character that will fall off
732 // the right of the row
733 if (x >= width) {
734 // if no break before, break here
735 if (point == end || chunkwidth >= width - left) {
736 if (i > pos)
737 point = i;
738 else
739 point = i + 1;
742 // exit on last registered breakpoint:
743 break;
746 if (par.isNewline(i)) {
747 point = i + 1;
748 break;
750 // Break before...
751 if (i + 1 < end) {
752 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
753 point = i + 1;
754 break;
756 // ...and after.
757 if (par.isInset(i) && par.getInset(i)->display()) {
758 point = i + 1;
759 break;
763 if (!par.isInset(i) || par.getInset(i)->isChar()) {
764 // some insets are line separators too
765 if (par.isLineSeparator(i)) {
766 // register breakpoint:
767 point = i + 1;
768 chunkwidth = 0;
773 // maybe found one, but the par is short enough.
774 if (i == end && x < width)
775 point = end;
777 // manual labels cannot be broken in LaTeX. But we
778 // want to make our on-screen rendering of footnotes
779 // etc. still break
780 if (body_pos && point < body_pos)
781 point = body_pos;
783 return point;
787 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
788 pos_type const first, pos_type const end) const
790 Buffer & buffer = bv_->buffer();
791 // get the pure distance
792 ParagraphMetrics const & pm = par_metrics_[pit];
793 Paragraph const & par = text_->getPar(pit);
794 int w = leftMargin(max_width_, pit, first);
795 int label_end = labelEnd(pit);
797 pos_type const body_pos = par.beginOfBody();
798 pos_type i = first;
800 if (i < end) {
801 FontIterator fi = FontIterator(*this, par, pit, i);
802 for ( ; i < end; ++i, ++fi) {
803 if (body_pos > 0 && i == body_pos) {
804 FontMetrics const & fm = theFontMetrics(
805 text_->getLabelFont(buffer, par));
806 w += fm.width(par.layout()->labelsep);
807 if (par.isLineSeparator(i - 1))
808 w -= singleWidth(pit, i - 1);
809 w = max(w, label_end);
811 w += pm.singleWidth(i, *fi);
815 if (body_pos > 0 && body_pos >= end) {
816 FontMetrics const & fm = theFontMetrics(
817 text_->getLabelFont(buffer, par));
818 w += fm.width(par.layout()->labelsep);
819 if (end > 0 && par.isLineSeparator(end - 1))
820 w -= singleWidth(pit, end - 1);
821 w = max(w, label_end);
824 return w + right_margin;
828 boost::tuple<int, int> TextMetrics::rowHeight(pit_type const pit, pos_type const first,
829 pos_type const end) const
831 Paragraph const & par = text_->getPar(pit);
832 // get the maximum ascent and the maximum descent
833 double layoutasc = 0;
834 double layoutdesc = 0;
835 double const dh = defaultRowHeight();
837 // ok, let us initialize the maxasc and maxdesc value.
838 // Only the fontsize count. The other properties
839 // are taken from the layoutfont. Nicer on the screen :)
840 LayoutPtr const & layout = par.layout();
842 // as max get the first character of this row then it can
843 // increase but not decrease the height. Just some point to
844 // start with so we don't have to do the assignment below too
845 // often.
846 Buffer const & buffer = bv_->buffer();
847 Font font = getDisplayFont(pit, first);
848 Font::FONT_SIZE const tmpsize = font.size();
849 font = text_->getLayoutFont(buffer, pit);
850 Font::FONT_SIZE const size = font.size();
851 font.setSize(tmpsize);
853 Font labelfont = text_->getLabelFont(buffer, par);
855 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
856 FontMetrics const & fontmetrics = theFontMetrics(font);
858 // these are minimum values
859 double const spacing_val = layout->spacing.getValue()
860 * text_->spacing(buffer, par);
861 //lyxerr << "spacing_val = " << spacing_val << endl;
862 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
863 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
865 // insets may be taller
866 ParagraphMetrics const & pm = par_metrics_[pit];
867 InsetList::const_iterator ii = par.insetList().begin();
868 InsetList::const_iterator iend = par.insetList().end();
869 for ( ; ii != iend; ++ii) {
870 Dimension const & dim = pm.insetDimension(ii->inset);
871 if (ii->pos >= first && ii->pos < end) {
872 maxasc = max(maxasc, dim.ascent());
873 maxdesc = max(maxdesc, dim.descent());
877 // Check if any custom fonts are larger (Asger)
878 // This is not completely correct, but we can live with the small,
879 // cosmetic error for now.
880 int labeladdon = 0;
882 Font::FONT_SIZE maxsize =
883 par.highestFontInRange(first, end, size);
884 if (maxsize > font.size()) {
885 // use standard paragraph font with the maximal size
886 Font maxfont = font;
887 maxfont.setSize(maxsize);
888 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
889 maxasc = max(maxasc, maxfontmetrics.maxAscent());
890 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
893 // This is nicer with box insets:
894 ++maxasc;
895 ++maxdesc;
897 ParagraphList const & pars = text_->paragraphs();
899 // is it a top line?
900 if (first == 0) {
901 BufferParams const & bufparams = buffer.params();
902 // some parskips VERY EASY IMPLEMENTATION
903 if (bufparams.paragraph_separation
904 == BufferParams::PARSEP_SKIP
905 && par.ownerCode() != ERT_CODE
906 && par.ownerCode() != LISTINGS_CODE
907 && pit > 0
908 && ((layout->isParagraph() && par.getDepth() == 0)
909 || (pars[pit - 1].layout()->isParagraph()
910 && pars[pit - 1].getDepth() == 0)))
912 maxasc += bufparams.getDefSkip().inPixels(*bv_);
915 if (par.params().startOfAppendix())
916 maxasc += int(3 * dh);
918 // This is special code for the chapter, since the label of this
919 // layout is printed in an extra row
920 if (layout->counter == "chapter"
921 && !par.params().labelString().empty()) {
922 labeladdon = int(labelfont_metrics.maxHeight()
923 * layout->spacing.getValue()
924 * text_->spacing(buffer, par));
927 // special code for the top label
928 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
929 || layout->labeltype == LABEL_BIBLIO
930 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
931 && isFirstInSequence(pit, pars)
932 && !par.getLabelstring().empty())
934 labeladdon = int(
935 labelfont_metrics.maxHeight()
936 * layout->spacing.getValue()
937 * text_->spacing(buffer, par)
938 + (layout->topsep + layout->labelbottomsep) * dh);
941 // Add the layout spaces, for example before and after
942 // a section, or between the items of a itemize or enumerate
943 // environment.
945 pit_type prev = depthHook(pit, pars, par.getDepth());
946 Paragraph const & prevpar = pars[prev];
947 if (prev != pit
948 && prevpar.layout() == layout
949 && prevpar.getDepth() == par.getDepth()
950 && prevpar.getLabelWidthString()
951 == par.getLabelWidthString()) {
952 layoutasc = layout->itemsep * dh;
953 } else if (pit != 0 || first != 0) {
954 if (layout->topsep > 0)
955 layoutasc = layout->topsep * dh;
958 prev = outerHook(pit, pars);
959 if (prev != pit_type(pars.size())) {
960 maxasc += int(pars[prev].layout()->parsep * dh);
961 } else if (pit != 0) {
962 Paragraph const & prevpar = pars[pit - 1];
963 if (prevpar.getDepth() != 0 ||
964 prevpar.layout() == layout) {
965 maxasc += int(layout->parsep * dh);
970 // is it a bottom line?
971 if (end >= par.size()) {
972 // add the layout spaces, for example before and after
973 // a section, or between the items of a itemize or enumerate
974 // environment
975 pit_type nextpit = pit + 1;
976 if (nextpit != pit_type(pars.size())) {
977 pit_type cpit = pit;
978 double usual = 0;
979 double unusual = 0;
981 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
982 usual = pars[cpit].layout()->bottomsep * dh;
983 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
984 if (pars[cpit].layout() != pars[nextpit].layout()
985 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
987 unusual = pars[cpit].layout()->bottomsep * dh;
989 layoutdesc = max(unusual, usual);
990 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
991 if (pars[cpit].layout() != pars[nextpit].layout()
992 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
993 layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
998 // incalculate the layout spaces
999 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1000 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1002 // FIXME: the correct way is to do the following is to move the
1003 // following code in another method specially tailored for the
1004 // main Text. The following test is thus bogus.
1005 // Top and bottom margin of the document (only at top-level)
1006 if (main_text_) {
1007 if (pit == 0 && first == 0)
1008 maxasc += 20;
1009 if (pit + 1 == pit_type(pars.size()) &&
1010 end == par.size() &&
1011 !(end > 0 && par.isNewline(end - 1)))
1012 maxdesc += 20;
1015 return boost::make_tuple(maxasc + labeladdon, maxdesc);
1019 // x is an absolute screen coord
1020 // returns the column near the specified x-coordinate of the row
1021 // x is set to the real beginning of this column
1022 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1023 Row const & row, int & x, bool & boundary) const
1025 Buffer const & buffer = bv_->buffer();
1027 /// For the main Text, it is possible that this pit is not
1028 /// yet in the CoordCache when moving cursor up.
1029 /// x Paragraph coordinate is always 0 for main text anyway.
1030 int const xo = origin_.x_;
1031 x -= xo;
1032 Paragraph const & par = text_->getPar(pit);
1033 ParagraphMetrics const & pm = par_metrics_[pit];
1034 Bidi bidi;
1035 bidi.computeTables(par, buffer, row);
1037 pos_type vc = row.pos();
1038 pos_type end = row.endpos();
1039 pos_type c = 0;
1040 LayoutPtr const & layout = par.layout();
1042 bool left_side = false;
1044 pos_type body_pos = par.beginOfBody();
1046 double tmpx = row.x;
1047 double last_tmpx = tmpx;
1049 if (body_pos > 0 &&
1050 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1051 body_pos = 0;
1053 // check for empty row
1054 if (vc == end) {
1055 x = int(tmpx) + xo;
1056 return 0;
1059 while (vc < end && tmpx <= x) {
1060 c = bidi.vis2log(vc);
1061 last_tmpx = tmpx;
1062 if (body_pos > 0 && c == body_pos - 1) {
1063 FontMetrics const & fm = theFontMetrics(
1064 text_->getLabelFont(buffer, par));
1065 tmpx += row.label_hfill + fm.width(layout->labelsep);
1066 if (par.isLineSeparator(body_pos - 1))
1067 tmpx -= singleWidth(pit, body_pos - 1);
1070 if (pm.hfillExpansion(row, c)) {
1071 tmpx += singleWidth(pit, c);
1072 if (c >= body_pos)
1073 tmpx += row.hfill;
1074 else
1075 tmpx += row.label_hfill;
1076 } else if (par.isSeparator(c)) {
1077 tmpx += singleWidth(pit, c);
1078 if (c >= body_pos)
1079 tmpx += row.separator;
1080 } else {
1081 tmpx += singleWidth(pit, c);
1083 ++vc;
1086 if ((tmpx + last_tmpx) / 2 > x) {
1087 tmpx = last_tmpx;
1088 left_side = true;
1091 BOOST_ASSERT(vc <= end); // This shouldn't happen.
1093 boundary = false;
1094 // This (rtl_support test) is not needed, but gives
1095 // some speedup if rtl_support == false
1096 bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1098 // If lastrow is false, we don't need to compute
1099 // the value of rtl.
1100 bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1101 if (lastrow &&
1102 ((rtl && left_side && vc == row.pos() && x < tmpx - 5) ||
1103 (!rtl && !left_side && vc == end && x > tmpx + 5)))
1104 c = end;
1105 else if (vc == row.pos()) {
1106 c = bidi.vis2log(vc);
1107 if (bidi.level(c) % 2 == 1)
1108 ++c;
1109 } else {
1110 c = bidi.vis2log(vc - 1);
1111 bool const rtl = (bidi.level(c) % 2 == 1);
1112 if (left_side == rtl) {
1113 ++c;
1114 boundary = isRTLBoundary(pit, c);
1118 // I believe this code is not needed anymore (Jug 20050717)
1119 #if 0
1120 // The following code is necessary because the cursor position past
1121 // the last char in a row is logically equivalent to that before
1122 // the first char in the next row. That's why insets causing row
1123 // divisions -- Newline and display-style insets -- must be treated
1124 // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1125 // Newline inset, air gap below:
1126 if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1127 if (bidi.level(end -1) % 2 == 0)
1128 tmpx -= singleWidth(pit, end - 1);
1129 else
1130 tmpx += singleWidth(pit, end - 1);
1131 c = end - 1;
1134 // Air gap above display inset:
1135 if (row.pos() < end && c >= end && end < par.size()
1136 && par.isInset(end) && par.getInset(end)->display()) {
1137 c = end - 1;
1139 // Air gap below display inset:
1140 if (row.pos() < end && c >= end && par.isInset(end - 1)
1141 && par.getInset(end - 1)->display()) {
1142 c = end - 1;
1144 #endif
1146 x = int(tmpx) + xo;
1147 pos_type const col = c - row.pos();
1149 if (!c || end == par.size())
1150 return col;
1152 if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1153 boundary = true;
1154 return col;
1157 return min(col, end - 1 - row.pos());
1161 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1163 // We play safe and use parMetrics(pit) to make sure the
1164 // ParagraphMetrics will be redone and OK to use if needed.
1165 // Otherwise we would use an empty ParagraphMetrics in
1166 // upDownInText() while in selection mode.
1167 ParagraphMetrics const & pm = parMetrics(pit);
1169 BOOST_ASSERT(row < int(pm.rows().size()));
1170 bool bound = false;
1171 Row const & r = pm.rows()[row];
1172 return r.pos() + getColumnNearX(pit, r, x, bound);
1176 void TextMetrics::newParMetricsDown()
1178 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1179 pit_type const pit = last.first + 1;
1180 if (pit == int(text_->paragraphs().size()))
1181 return;
1183 // do it and update its position.
1184 redoParagraph(pit);
1185 par_metrics_[pit].setPosition(last.second.position()
1186 + last.second.descent());
1190 void TextMetrics::newParMetricsUp()
1192 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1193 if (first.first == 0)
1194 return;
1196 pit_type const pit = first.first - 1;
1197 // do it and update its position.
1198 redoParagraph(pit);
1199 par_metrics_[pit].setPosition(first.second.position()
1200 - first.second.ascent());
1203 // y is screen coordinate
1204 pit_type TextMetrics::getPitNearY(int y)
1206 BOOST_ASSERT(!text_->paragraphs().empty());
1207 LYXERR(Debug::DEBUG)
1208 << BOOST_CURRENT_FUNCTION
1209 << ": y: " << y << " cache size: " << par_metrics_.size()
1210 << endl;
1212 // look for highest numbered paragraph with y coordinate less than given y
1213 pit_type pit = 0;
1214 int yy = -1;
1215 ParMetricsCache::const_iterator it = par_metrics_.begin();
1216 ParMetricsCache::const_iterator et = par_metrics_.end();
1217 ParMetricsCache::const_iterator last = et; last--;
1219 ParagraphMetrics const & pm = it->second;
1221 // If we are off-screen (before the visible part)
1222 if (y < 0
1223 // and even before the first paragraph in the cache.
1224 && y < it->second.position() - int(pm.ascent())) {
1225 // and we are not at the first paragraph in the inset.
1226 if (it->first == 0)
1227 return 0;
1228 // then this is the paragraph we are looking for.
1229 pit = it->first - 1;
1230 // rebreak it and update the CoordCache.
1231 redoParagraph(pit);
1232 par_metrics_[pit].setPosition(it->second.position() - pm.descent());
1233 return pit;
1236 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1238 // If we are off-screen (after the visible part)
1239 if (y > bv_->workHeight()
1240 // and even after the first paragraph in the cache.
1241 && y >= last->second.position() + int(pm_last.descent())) {
1242 pit = last->first + 1;
1243 // and we are not at the last paragraph in the inset.
1244 if (pit == int(text_->paragraphs().size()))
1245 return last->first;
1246 // then this is the paragraph we are looking for.
1247 // rebreak it and update the CoordCache.
1248 redoParagraph(pit);
1249 par_metrics_[pit].setPosition(last->second.position() + pm_last.ascent());
1250 return pit;
1253 for (; it != et; ++it) {
1254 LYXERR(Debug::DEBUG)
1255 << BOOST_CURRENT_FUNCTION
1256 << " examining: pit: " << it->first
1257 << " y: " << it->second.position()
1258 << endl;
1260 ParagraphMetrics const & pm = par_metrics_[it->first];
1262 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1263 pit = it->first;
1264 yy = it->second.position();
1268 LYXERR(Debug::DEBUG)
1269 << BOOST_CURRENT_FUNCTION
1270 << ": found best y: " << yy << " for pit: " << pit
1271 << endl;
1273 return pit;
1277 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1279 ParagraphMetrics const & pm = par_metrics_[pit];
1281 int yy = pm.position() - pm.ascent();
1282 BOOST_ASSERT(!pm.rows().empty());
1283 RowList::const_iterator rit = pm.rows().begin();
1284 RowList::const_iterator rlast = pm.rows().end();
1285 --rlast;
1286 for (; rit != rlast; yy += rit->height(), ++rit)
1287 if (yy + rit->height() > y)
1288 break;
1289 return *rit;
1293 // x,y are absolute screen coordinates
1294 // sets cursor recursively descending into nested editable insets
1295 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1297 if (lyxerr.debugging(Debug::WORKAREA)) {
1298 lyxerr << "TextMetrics::editXY(cur, " << x << ", " << y << ")" << std::endl;
1299 cur.bv().coordCache().dump();
1301 pit_type pit = getPitNearY(y);
1302 BOOST_ASSERT(pit != -1);
1304 Row const & row = getRowNearY(y, pit);
1305 bool bound = false;
1307 int xx = x; // is modified by getColumnNearX
1308 pos_type const pos = row.pos()
1309 + getColumnNearX(pit, row, xx, bound);
1310 cur.pit() = pit;
1311 cur.pos() = pos;
1312 cur.boundary(bound);
1313 cur.setTargetX(x);
1315 // try to descend into nested insets
1316 Inset * inset = checkInsetHit(x, y);
1317 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1318 if (!inset) {
1319 // Either we deconst editXY or better we move current_font
1320 // and real_current_font to Cursor
1321 // FIXME: what is needed now that current_font and real_current_font
1322 // are transferred?
1323 cur.setCurrentFont();
1324 return 0;
1327 ParagraphList const & pars = text_->paragraphs();
1328 Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1329 //Inset * insetBehind = pars[pit].getInset(pos);
1331 // This should be just before or just behind the
1332 // cursor position set above.
1333 BOOST_ASSERT((pos != 0 && inset == insetBefore)
1334 || inset == pars[pit].getInset(pos));
1336 // Make sure the cursor points to the position before
1337 // this inset.
1338 if (inset == insetBefore) {
1339 --cur.pos();
1340 cur.boundary(false);
1343 // Try to descend recursively inside the inset.
1344 inset = inset->editXY(cur, x, y);
1346 if (cur.top().text() == text_)
1347 cur.setCurrentFont();
1348 return inset;
1352 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1354 BOOST_ASSERT(text_ == cur.text());
1355 pit_type pit = getPitNearY(y);
1357 ParagraphMetrics const & pm = par_metrics_[pit];
1359 int yy = pm.position() - pm.ascent();
1360 LYXERR(Debug::DEBUG)
1361 << BOOST_CURRENT_FUNCTION
1362 << ": x: " << x
1363 << " y: " << y
1364 << " pit: " << pit
1365 << " yy: " << yy << endl;
1367 int r = 0;
1368 BOOST_ASSERT(pm.rows().size());
1369 for (; r < int(pm.rows().size()) - 1; ++r) {
1370 Row const & row = pm.rows()[r];
1371 if (int(yy + row.height()) > y)
1372 break;
1373 yy += row.height();
1376 Row const & row = pm.rows()[r];
1378 LYXERR(Debug::DEBUG)
1379 << BOOST_CURRENT_FUNCTION
1380 << ": row " << r
1381 << " from pos: " << row.pos()
1382 << endl;
1384 bool bound = false;
1385 int xx = x;
1386 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1388 LYXERR(Debug::DEBUG)
1389 << BOOST_CURRENT_FUNCTION
1390 << ": setting cursor pit: " << pit
1391 << " pos: " << pos
1392 << endl;
1394 text_->setCursor(cur, pit, pos, true, bound);
1395 // remember new position.
1396 cur.setTargetX();
1400 //takes screen x,y coordinates
1401 Inset * TextMetrics::checkInsetHit(int x, int y)
1403 pit_type pit = getPitNearY(y);
1404 BOOST_ASSERT(pit != -1);
1406 Paragraph const & par = text_->paragraphs()[pit];
1407 ParagraphMetrics const & pm = par_metrics_[pit];
1409 LYXERR(Debug::DEBUG)
1410 << BOOST_CURRENT_FUNCTION
1411 << ": x: " << x
1412 << " y: " << y
1413 << " pit: " << pit
1414 << endl;
1415 InsetList::const_iterator iit = par.insetList().begin();
1416 InsetList::const_iterator iend = par.insetList().end();
1417 for (; iit != iend; ++iit) {
1418 Inset * inset = iit->inset;
1420 LYXERR(Debug::DEBUG)
1421 << BOOST_CURRENT_FUNCTION
1422 << ": examining inset " << inset << endl;
1424 if (!bv_->coordCache().getInsets().has(inset)) {
1425 LYXERR(Debug::DEBUG)
1426 << BOOST_CURRENT_FUNCTION
1427 << ": inset has no cached position" << endl;
1428 return 0;
1431 Dimension const & dim = pm.insetDimension(inset);
1432 Point p = bv_->coordCache().getInsets().xy(inset);
1434 LYXERR(Debug::DEBUG)
1435 << BOOST_CURRENT_FUNCTION
1436 << ": xo: " << p.x_ << "..." << p.x_ + dim.wid
1437 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des
1438 << endl;
1440 if (x >= p.x_
1441 && x <= p.x_ + dim.wid
1442 && y >= p.y_ - dim.asc
1443 && y <= p.y_ + dim.des) {
1444 LYXERR(Debug::DEBUG)
1445 << BOOST_CURRENT_FUNCTION
1446 << ": Hit inset: " << inset << endl;
1447 return inset;
1451 LYXERR(Debug::DEBUG)
1452 << BOOST_CURRENT_FUNCTION
1453 << ": No inset hit. " << endl;
1454 return 0;
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())
1466 return 0;
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)
1472 --ppos;
1474 Row const & row = pm.getRow(sl.pos(), boundary);
1476 pos_type cursor_vpos = 0;
1478 Buffer const & buffer = bv_->buffer();
1479 double x = row.x;
1480 Bidi bidi;
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;
1492 if (end <= row_pos)
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);
1500 else
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();
1506 if (body_pos > 0 &&
1507 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1508 body_pos = 0;
1510 // Use font span to speed things up, see below
1511 FontSpan font_span;
1512 Font font;
1514 // If the last logical character is a separator, skip it, unless
1515 // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1516 if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1517 skipped_sep_vpos = bidi.log2vis(end - 1);
1519 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1520 // Skip the separator which is at the logical end of the row
1521 if (vpos == skipped_sep_vpos)
1522 continue;
1523 pos_type pos = bidi.vis2log(vpos);
1524 if (body_pos > 0 && pos == body_pos - 1) {
1525 FontMetrics const & labelfm = theFontMetrics(
1526 text_->getLabelFont(buffer, par));
1527 x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1528 if (par.isLineSeparator(body_pos - 1))
1529 x -= singleWidth(pit, body_pos - 1);
1532 // Use font span to speed things up, see above
1533 if (pos < font_span.first || pos > font_span.last) {
1534 font_span = par.fontSpan(pos);
1535 font = getDisplayFont(pit, pos);
1538 x += pm.singleWidth(pos, font);
1540 if (pm.hfillExpansion(row, pos))
1541 x += (pos >= body_pos) ? row.hfill : row.label_hfill;
1542 else if (par.isSeparator(pos) && pos >= body_pos)
1543 x += row.separator;
1546 // see correction above
1547 if (boundary_correction) {
1548 if (isRTL(sl, boundary))
1549 x -= singleWidth(pit, ppos);
1550 else
1551 x += singleWidth(pit, ppos);
1554 return int(x);
1558 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1560 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << std::endl;
1561 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1562 if (pm.rows().empty())
1563 return 0;
1565 int h = 0;
1566 h -= par_metrics_[0].rows()[0].ascent();
1567 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1568 h += par_metrics_[pit].height();
1570 int pos = sl.pos();
1571 if (pos && boundary)
1572 --pos;
1573 size_t const rend = pm.pos2row(pos);
1574 for (size_t rit = 0; rit != rend; ++rit)
1575 h += pm.rows()[rit].height();
1576 h += pm.rows()[rend].ascent();
1577 return h;
1581 void TextMetrics::cursorPrevious(Cursor & cur)
1583 pos_type cpos = cur.pos();
1584 pit_type cpar = cur.pit();
1586 int x = cur.x_target();
1587 setCursorFromCoordinates(cur, x, 0);
1588 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1590 if (cpar == cur.pit() && cpos == cur.pos())
1591 // we have a row which is taller than the workarea. The
1592 // simplest solution is to move to the previous row instead.
1593 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1595 cur.finishUndo();
1596 cur.updateFlags(Update::Force | Update::FitCursor);
1600 void TextMetrics::cursorNext(Cursor & cur)
1602 pos_type cpos = cur.pos();
1603 pit_type cpar = cur.pit();
1605 int x = cur.x_target();
1606 setCursorFromCoordinates(cur, x, cur.bv().workHeight() - 1);
1607 cur.dispatch(FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1609 if (cpar == cur.pit() && cpos == cur.pos())
1610 // we have a row which is taller than the workarea. The
1611 // simplest solution is to move to the next row instead.
1612 cur.dispatch(
1613 FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1615 cur.finishUndo();
1616 cur.updateFlags(Update::Force | Update::FitCursor);
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();
1639 if (end == 0)
1640 // empty text, end-1 is no valid position
1641 return false;
1642 bool boundary = false;
1643 if (end != cur.lastpos()) {
1644 if (!cur.paragraph().isLineSeparator(end-1)
1645 && !cur.paragraph().isNewline(end-1))
1646 boundary = true;
1647 else
1648 --end;
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);
1660 } else {
1661 cur.resetAnchor();
1662 cur.selection() = true; // to avoid deletion
1663 cursorEnd(cur);
1664 cur.setSelection();
1665 // What is this test for ??? (JMarc)
1666 if (!cur.selection())
1667 text_->deleteWordForward(cur);
1668 else
1669 cap::cutSelection(cur, true, false);
1670 checkBufferStructure(cur.buffer(), cur);
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 TextClass const & tclass = buffer.params().getTextClass();
1710 LayoutPtr const & layout = par.layout();
1712 docstring parindent = layout->parindent;
1714 int l_margin = 0;
1716 if (text_->isMainText(buffer))
1717 l_margin += changebarMargin();
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 (par.layout() == tclass.defaultLayout()) {
1730 if (pars[newpar].params().noindent())
1731 parindent.erase();
1732 else
1733 parindent = pars[newpar].layout()->parindent;
1738 // This happens after sections in standard classes. The 1.3.x
1739 // code compared depths too, but it does not seem necessary
1740 // (JMarc)
1741 if (par.layout() == tclass.defaultLayout()
1742 && pit > 0 && pars[pit - 1].layout()->nextnoindent)
1743 parindent.erase();
1745 Font const labelfont = text_->getLabelFont(buffer, par);
1746 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1748 switch (layout->margintype) {
1749 case MARGIN_DYNAMIC:
1750 if (!layout->leftmargin.empty()) {
1751 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1752 layout->leftmargin);
1754 if (!par.getLabelstring().empty()) {
1755 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1756 l_margin += labelfont_metrics.width(par.getLabelstring());
1757 l_margin += labelfont_metrics.width(layout->labelsep);
1759 break;
1761 case MARGIN_MANUAL: {
1762 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1763 // The width of an empty par, even with manual label, should be 0
1764 if (!par.empty() && pos >= par.beginOfBody()) {
1765 if (!par.getLabelWidthString().empty()) {
1766 docstring labstr = par.getLabelWidthString();
1767 l_margin += labelfont_metrics.width(labstr);
1768 l_margin += labelfont_metrics.width(layout->labelsep);
1771 break;
1774 case MARGIN_STATIC: {
1775 l_margin += theFontMetrics(buffer.params().getFont()).
1776 signedWidth(layout->leftmargin) * 4 / (par.getDepth() + 4);
1777 break;
1780 case MARGIN_FIRST_DYNAMIC:
1781 if (layout->labeltype == LABEL_MANUAL) {
1782 if (pos >= par.beginOfBody()) {
1783 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1784 } else {
1785 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1787 } else if (pos != 0
1788 // Special case to fix problems with
1789 // theorems (JMarc)
1790 || (layout->labeltype == LABEL_STATIC
1791 && layout->latextype == LATEX_ENVIRONMENT
1792 && !isFirstInSequence(pit, pars))) {
1793 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1794 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
1795 && layout->labeltype != LABEL_BIBLIO
1796 && layout->labeltype !=
1797 LABEL_CENTERED_TOP_ENVIRONMENT) {
1798 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1799 l_margin += labelfont_metrics.width(layout->labelsep);
1800 l_margin += labelfont_metrics.width(par.getLabelstring());
1802 break;
1804 case MARGIN_RIGHT_ADDRESS_BOX: {
1805 #if 0
1806 // ok, a terrible hack. The left margin depends on the widest
1807 // row in this paragraph.
1808 RowList::iterator rit = par.rows().begin();
1809 RowList::iterator end = par.rows().end();
1810 // FIXME: This is wrong.
1811 int minfill = max_width;
1812 for ( ; rit != end; ++rit)
1813 if (rit->fill() < minfill)
1814 minfill = rit->fill();
1815 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
1816 l_margin += minfill;
1817 #endif
1818 // also wrong, but much shorter.
1819 l_margin += max_width / 2;
1820 break;
1824 if (!par.params().leftIndent().zero())
1825 l_margin += par.params().leftIndent().inPixels(max_width);
1827 LyXAlignment align;
1829 if (par.params().align() == LYX_ALIGN_LAYOUT)
1830 align = layout->align;
1831 else
1832 align = par.params().align();
1834 // set the correct parindent
1835 if (pos == 0
1836 && (layout->labeltype == LABEL_NO_LABEL
1837 || layout->labeltype == LABEL_TOP_ENVIRONMENT
1838 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1839 || (layout->labeltype == LABEL_STATIC
1840 && layout->latextype == LATEX_ENVIRONMENT
1841 && !isFirstInSequence(pit, pars)))
1842 && align == LYX_ALIGN_BLOCK
1843 && !par.params().noindent()
1844 // in some insets, paragraphs are never indented
1845 && !(par.inInset() && par.inInset()->neverIndent(buffer))
1846 // display style insets are always centered, omit indentation
1847 && !(!par.empty()
1848 && par.isInset(pos)
1849 && par.getInset(pos)->display())
1850 && (par.layout() != tclass.defaultLayout()
1851 || buffer.params().paragraph_separation ==
1852 BufferParams::PARSEP_INDENT))
1854 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1855 parindent);
1858 return l_margin;
1862 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1864 ParagraphMetrics const & pm = par_metrics_[pit];
1866 return pm.singleWidth(pos, getDisplayFont(pit, pos));
1870 // only used for inset right now. should also be used for main text
1871 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1873 if (par_metrics_.empty())
1874 return;
1876 origin_.x_ = x;
1877 origin_.y_ = y;
1879 ParMetricsCache::iterator it = par_metrics_.begin();
1880 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1881 y -= it->second.ascent();
1882 for (; it != pm_end; ++it) {
1883 ParagraphMetrics const & pmi = it->second;
1884 y += pmi.ascent();
1885 pit_type const pit = it->first;
1886 // Save the paragraph position in the cache.
1887 it->second.setPosition(y);
1888 drawParagraph(pi, pit, x, y);
1889 y += pmi.descent();
1894 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1896 // lyxerr << " paintPar: pit: " << pit << " at y: " << y << endl;
1897 int const ww = bv_->workHeight();
1899 ParagraphMetrics const & pm = par_metrics_[pit];
1900 if (pm.rows().empty())
1901 return;
1903 RowList::const_iterator const rb = pm.rows().begin();
1904 RowList::const_iterator const re = pm.rows().end();
1906 Bidi bidi;
1908 y -= rb->ascent();
1909 for (RowList::const_iterator rit = rb; rit != re; ++rit) {
1910 y += rit->ascent();
1912 bool const inside = (y + rit->descent() >= 0
1913 && y - rit->ascent() < ww);
1914 // it is not needed to draw on screen if we are not inside.
1915 pi.pain.setDrawingEnabled(inside);
1916 RowPainter rp(pi, *text_, pit, *rit, bidi, x, y);
1918 // Row signature; has row changed since last paint?
1919 bool row_has_changed = rit->changed();
1921 bool row_selection = rit->sel_beg != -1 && rit->sel_end != -1;
1923 if (!row_selection && !pi.full_repaint && !row_has_changed) {
1924 // Paint the only the insets if the text itself is
1925 // unchanged.
1926 rp.paintOnlyInsets();
1927 y += rit->descent();
1928 continue;
1931 // Paint the row if a full repaint has been requested or it has
1932 // changed.
1933 // Clear background of this row
1934 // (if paragraph background was not cleared)
1935 if (row_selection || (!pi.full_repaint && row_has_changed)) {
1936 pi.pain.fillRectangle(x, y - rit->ascent(),
1937 width(), rit->height(),
1938 Color_color(Color::color(pi.background_color)));
1940 if (row_selection) {
1941 DocIterator beg = bv_->cursor().selectionBegin();
1942 DocIterator end = bv_->cursor().selectionEnd();
1943 beg.pit() = pit;
1944 beg.pos() = rit->sel_beg;
1945 if (pit == end.pit()) {
1946 end.pos() = rit->sel_end;
1947 } else {
1948 end.pit() = pit + 1;
1949 end.pos() = 0;
1951 drawSelection(pi, beg, end, x);
1954 // Instrumentation for testing row cache (see also
1955 // 12 lines lower):
1956 if (lyxerr.debugging(Debug::PAINTING)) {
1957 if (text_->isMainText(bv_->buffer()))
1958 LYXERR(Debug::PAINTING) << "\n{" << inside <<
1959 pi.full_repaint << row_has_changed << "}";
1960 else
1961 LYXERR(Debug::PAINTING) << "[" << inside <<
1962 pi.full_repaint << row_has_changed << "]";
1965 // Backup full_repaint status and force full repaint
1966 // for inner insets as the Row has been cleared out.
1967 bool tmp = pi.full_repaint;
1968 pi.full_repaint = true;
1969 rp.paintAppendix();
1970 rp.paintDepthBar();
1971 rp.paintChangeBar();
1972 if (rit == rb)
1973 rp.paintFirst();
1974 rp.paintText();
1975 if (rit + 1 == re)
1976 rp.paintLast();
1977 y += rit->descent();
1978 // Restore full_repaint status.
1979 pi.full_repaint = tmp;
1981 // Re-enable screen drawing for future use of the painter.
1982 pi.pain.setDrawingEnabled(true);
1984 //LYXERR(Debug::PAINTING) << "." << endl;
1988 // FIXME: only take care of one row!
1989 void TextMetrics::drawSelection(PainterInfo & pi,
1990 DocIterator const & beg, DocIterator const & end, int x) const
1992 ParagraphMetrics const & pm1 = parMetrics(beg.pit());
1993 ParagraphMetrics const & pm2 = parMetrics(end.pit());
1994 Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
1995 Row const & row2 = pm2.getRow(end.pos(), end.boundary());
1997 // clip above
1998 int middleTop;
1999 bool const clipAbove = (bv_->cursorStatus(beg) == CUR_ABOVE);
2000 if (clipAbove)
2001 middleTop = 0;
2002 else
2003 middleTop = bv_->getPos(beg, beg.boundary()).y_ + row1.descent();
2005 // clip below
2006 int middleBottom;
2007 bool const clipBelow = (bv_->cursorStatus(end) == CUR_BELOW);
2008 if (clipBelow)
2009 middleBottom = bv_->workHeight();
2010 else
2011 middleBottom = bv_->getPos(end, end.boundary()).y_ - row2.ascent();
2013 // start and end in the same line?
2014 if (!clipAbove && !clipBelow && &row1 == &row2)
2015 // then only draw this row's selection
2016 drawRowSelection(pi, x, row1, beg, end, false, false);
2017 else {
2018 if (!clipAbove) {
2019 // get row end
2020 DocIterator begRowEnd = beg;
2021 begRowEnd.pos() = row1.endpos();
2022 begRowEnd.boundary(true);
2024 // draw upper rectangle
2025 drawRowSelection(pi, x, row1, beg, begRowEnd, false, true);
2028 if (middleTop < middleBottom) {
2029 // draw middle rectangle
2030 pi.pain.fillRectangle(x, middleTop, width(), middleBottom - middleTop,
2031 Color::selection);
2034 if (!clipBelow) {
2035 // get row begin
2036 DocIterator endRowBeg = end;
2037 endRowBeg.pos() = row2.pos();
2038 endRowBeg.boundary(false);
2040 // draw low rectangle
2041 drawRowSelection(pi, x, row2, endRowBeg, end, true, false);
2047 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2048 DocIterator const & beg, DocIterator const & end,
2049 bool drawOnBegMargin, bool drawOnEndMargin) const
2051 Buffer & buffer = bv_->buffer();
2052 DocIterator cur = beg;
2053 int x1 = cursorX(beg.top(), beg.boundary());
2054 int x2 = cursorX(end.top(), end.boundary());
2055 int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2056 int y2 = y1 + row.height();
2058 // draw the margins
2059 if (drawOnBegMargin) {
2060 if (text_->isRTL(buffer, beg.paragraph()))
2061 pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color::selection);
2062 else
2063 pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color::selection);
2066 if (drawOnEndMargin) {
2067 if (text_->isRTL(buffer, beg.paragraph()))
2068 pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color::selection);
2069 else
2070 pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color::selection);
2073 // if we are on a boundary from the beginning, it's probably
2074 // a RTL boundary and we jump to the other side directly as this
2075 // segement is 0-size and confuses the logic below
2076 if (cur.boundary())
2077 cur.boundary(false);
2079 // go through row and draw from RTL boundary to RTL boundary
2080 while (cur < end) {
2081 bool drawNow = false;
2083 // simplified cursorForward code below which does not
2084 // descend into insets and which does not go into the
2085 // next line. Compare the logic with the original cursorForward
2087 // if left of boundary -> just jump to right side
2088 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2089 if (cur.boundary()) {
2090 cur.boundary(false);
2091 } else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2092 // in front of RTL boundary -> Stay on this side of the boundary because:
2093 // ab|cDDEEFFghi -> abc|DDEEFFghi
2094 ++cur.pos();
2095 cur.boundary(true);
2096 drawNow = true;
2097 } else {
2098 // move right
2099 ++cur.pos();
2101 // line end?
2102 if (cur.pos() == row.endpos())
2103 cur.boundary(true);
2106 if (x1 == -1) {
2107 // the previous segment was just drawn, now the next starts
2108 x1 = cursorX(cur.top(), cur.boundary());
2111 if (!(cur < end) || drawNow) {
2112 x2 = cursorX(cur.top(), cur.boundary());
2113 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2114 Color::selection);
2116 // reset x1, so it is set again next round (which will be on the
2117 // right side of a boundary or at the selection end)
2118 x1 = -1;
2123 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2125 // ParagraphMetrics const & pm = par_metrics_[pit];
2126 // Row const & r = pm.rows()[row];
2127 // int x = 0;
2128 // pos -= r.pos();
2132 int defaultRowHeight()
2134 return int(theFontMetrics(Font(Font::ALL_SANE)).maxHeight() * 1.2);
2137 } // namespace lyx