]> git.lyx.org Git - features.git/blob - src/TextMetrics.cpp
Move Color::color enum to ColorCode.h
[features.git] / src / TextMetrics.cpp
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.
5  *
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
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "TextMetrics.h"
21
22 #include "Bidi.h"
23 #include "Buffer.h"
24 #include "buffer_funcs.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "CutAndPaste.h"
28 #include "debug.h"
29 #include "FontIterator.h"
30 #include "FuncRequest.h"
31 #include "InsetList.h"
32 #include "Layout.h"
33 #include "Length.h"
34 #include "LyXRC.h"
35 #include "MetricsInfo.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.h"
39 #include "rowpainter.h"
40 #include "Text.h"
41 #include "VSpace.h"
42
43 #include "frontends/FontMetrics.h"
44 #include "frontends/Painter.h"
45
46 #include <boost/current_function.hpp>
47
48 using std::make_pair;
49 using std::max;
50 using std::min;
51 using std::endl;
52 using std::pair;
53
54 namespace lyx {
55
56 using frontend::FontMetrics;
57
58 namespace {
59
60 int numberOfSeparators(Paragraph const & par, Row const & row)
61 {
62         pos_type const first = max(row.pos(), par.beginOfBody());
63         pos_type const last = row.endpos() - 1;
64         int n = 0;
65         for (pos_type p = first; p < last; ++p) {
66                 if (par.isSeparator(p))
67                         ++n;
68         }
69         return n;
70 }
71
72
73 int numberOfLabelHfills(Paragraph const & par, Row const & row)
74 {
75         pos_type last = row.endpos() - 1;
76         pos_type first = row.pos();
77
78         // hfill *DO* count at the beginning of paragraphs!
79         if (first) {
80                 while (first < last && par.isHfill(first))
81                         ++first;
82         }
83
84         last = min(last, par.beginOfBody());
85         int n = 0;
86         for (pos_type p = first; p < last; ++p) {
87                 if (par.isHfill(p))
88                         ++n;
89         }
90         return n;
91 }
92
93
94 int numberOfHfills(Paragraph const & par, Row const & row)
95 {
96         pos_type const last = row.endpos();
97         pos_type first = row.pos();
98
99         // hfill *DO* count at the beginning of paragraphs!
100         if (first) {
101                 while (first < last && par.isHfill(first))
102                         ++first;
103         }
104
105         first = max(first, par.beginOfBody());
106
107         int n = 0;
108         for (pos_type p = first; p < last; ++p) {
109                 if (par.isHfill(p))
110                         ++n;
111         }
112         return n;
113 }
114
115 } // namespace anon
116
117 TextMetrics::TextMetrics(BufferView * bv, Text * text)
118         : bv_(bv), text_(text)
119 {
120         BOOST_ASSERT(bv_);
121         max_width_ = bv_->workWidth();
122         dim_.wid = max_width_;
123         dim_.asc = 10;
124         dim_.des = 10;
125
126         //text_->updateLabels(bv->buffer());
127 }
128
129
130 bool TextMetrics::has(pit_type pit) const
131 {
132         return par_metrics_.find(pit) != par_metrics_.end();
133 }
134
135
136 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
137 {
138         return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
139 }
140
141
142
143 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
144 {
145         ParMetricsCache::const_iterator it = par_metrics_.begin();
146         return make_pair(it->first, &it->second);
147 }
148
149
150 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
151 {
152         ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
153         return make_pair(it->first, &it->second);
154 }
155
156
157 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit,
158                 bool redo)
159 {
160         ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
161         if (pmc_it == par_metrics_.end()) {
162                 pmc_it = par_metrics_.insert(
163                         make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
164         }
165         if (pmc_it->second.rows().empty() && redo) {
166                 redoParagraph(pit);
167         }
168         return pmc_it->second;
169 }
170
171
172 int TextMetrics::parPosition(pit_type pit) const
173 {
174         if (pit < par_metrics_.begin()->first)
175                 return -1000000;
176         else if (pit > par_metrics_.rbegin()->first)
177                 return +1000000;
178
179         return par_metrics_[pit].position();
180 }
181
182
183 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
184 {
185         BOOST_ASSERT(mi.base.textwidth);
186         max_width_ = mi.base.textwidth;
187         // backup old dimension.
188         Dimension const old_dim = dim_;
189         // reset dimension.
190         dim_ = Dimension();
191         dim_.wid = min_width;
192         pit_type const npar = text_->paragraphs().size();
193         if (npar > 1)
194                 // If there is more than one row, expand the text to 
195                 // the full allowable width.
196                 dim_.wid = max_width_;
197
198         //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
199         //      << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
200
201         bool changed = false;
202         unsigned int h = 0;
203         for (pit_type pit = 0; pit != npar; ++pit) {
204                 changed |= redoParagraph(pit);
205                 ParagraphMetrics const & pm = par_metrics_[pit];
206                 h += pm.height();
207                 if (dim_.wid < pm.width())
208                         dim_.wid = pm.width();
209         }
210
211         dim_.asc = par_metrics_[0].ascent();
212         dim_.des = h - dim_.asc;
213         //lyxerr << "dim_.wid " << dim_.wid << endl;
214         //lyxerr << "dim_.asc " << dim_.asc << endl;
215         //lyxerr << "dim_.des " << dim_.des << endl;
216
217         changed |= dim_ != old_dim;
218         dim = dim_;
219         return changed;
220 }
221
222
223 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
224 {
225         return main_text_? pm.rightMargin(bv_->buffer()) : 0;
226 }
227
228
229 int TextMetrics::rightMargin(pit_type const pit) const
230 {
231         return main_text_? par_metrics_[pit].rightMargin(bv_->buffer()) : 0;
232 }
233
234
235 void TextMetrics::applyOuterFont(Font & font) const
236 {
237         Font lf(font_);
238         lf.reduce(bv_->buffer().params().getFont());
239         lf.realize(font);
240         lf.setLanguage(font.language());
241         font = lf;
242 }
243
244
245 Font TextMetrics::getDisplayFont(pit_type pit, pos_type pos) const
246 {
247         BOOST_ASSERT(pos >= 0);
248
249         ParagraphList const & pars = text_->paragraphs();
250         Paragraph const & par = pars[pit];
251         LayoutPtr const & layout = par.layout();
252         Buffer const & buffer = bv_->buffer();
253         // FIXME: broken?
254         BufferParams const & params = buffer.params();
255         pos_type const body_pos = par.beginOfBody();
256
257         // We specialize the 95% common case:
258         if (!par.getDepth()) {
259                 Font f = par.getFontSettings(params, pos);
260                 if (!text_->isMainText(buffer))
261                         applyOuterFont(f);
262                 bool lab = layout->labeltype == LABEL_MANUAL && pos < body_pos;
263
264                 Font const & lf = lab ? layout->labelfont : layout->font;
265                 Font rlf = lab ? layout->reslabelfont : layout->resfont;
266                 
267                 // In case the default family has been customized
268                 if (lf.family() == Font::INHERIT_FAMILY)
269                         rlf.setFamily(params.getFont().family());
270                 return f.realize(rlf);
271         }
272
273         // The uncommon case need not be optimized as much
274         Font const & layoutfont = pos < body_pos ? 
275                 layout->labelfont : layout->font;
276
277         Font font = par.getFontSettings(params, pos);
278         font.realize(layoutfont);
279
280         if (!text_->isMainText(buffer))
281                 applyOuterFont(font);
282
283         // Realize against environment font information
284         // NOTE: the cast to pit_type should be removed when pit_type
285         // changes to a unsigned integer.
286         if (pit < pit_type(pars.size()))
287                 font.realize(outerFont(pit, pars));
288
289         // Realize with the fonts of lesser depth.
290         font.realize(params.getFont());
291
292         return font;
293 }
294
295
296 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
297 {
298         if (!lyxrc.rtl_support || !sl.text())
299                 return false;
300
301         int correction = 0;
302         if (boundary && sl.pos() > 0)
303                 correction = -1;
304                 
305         return getDisplayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
306 }
307
308
309 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
310 {
311         if (!lyxrc.rtl_support)
312                 return false;
313
314         // no RTL boundary at line start
315         if (pos == 0)
316                 return false;
317
318         Paragraph const & par = text_->getPar(pit);
319
320         bool left = getDisplayFont(pit, pos - 1).isVisibleRightToLeft();
321         bool right;
322         if (pos == par.size())
323                 right = par.isRTL(bv_->buffer().params());
324         else
325                 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
326         return left != right;
327 }
328
329
330 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
331                 Font const & font) const
332 {
333         if (!lyxrc.rtl_support)
334                 return false;
335
336         Paragraph const & par = text_->getPar(pit);
337         bool left = font.isVisibleRightToLeft();
338         bool right;
339         if (pos == par.size())
340                 right = par.isRTL(bv_->buffer().params());
341         else
342                 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
343         return left != right;
344 }
345
346
347 bool TextMetrics::redoParagraph(pit_type const pit)
348 {
349         Paragraph & par = text_->getPar(pit);
350         // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
351         // redoParagraph() recursively inside parMetrics.
352         Dimension old_dim = parMetrics(pit, false).dim();
353         ParagraphMetrics & pm = par_metrics_[pit];
354         pm.reset(par);
355
356         Buffer & buffer = bv_->buffer();
357         BufferParams const & bparams = buffer.params();
358         main_text_ = (text_ == &buffer.text());
359         bool changed = false;
360
361         // FIXME This check ought to be done somewhere else. It is the reason
362         // why text_ is not     const. But then, where else to do it?
363         // Well, how can you end up with either (a) a biblio environment that
364         // has no InsetBibitem or (b) a biblio environment with more than one
365         // InsetBibitem? I think the answer is: when paragraphs are merged;
366         // when layout is set; when material is pasted.
367         int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
368         if (moveCursor > 0)
369                 const_cast<Cursor &>(bv_->cursor()).posRight();
370         else if (moveCursor < 0) {
371                 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
372                 if (cursor.pos() >= -moveCursor)
373                         cursor.posLeft();
374         }
375
376         // Optimisation: this is used in the next two loops
377         // so better to calculate that once here.
378         int const right_margin = rightMargin(pm);
379
380         // redo insets
381         // FIXME: We should always use getFont(), see documentation of
382         // noFontChange() in Inset.h.
383         Font const bufferfont = buffer.params().getFont();
384         InsetList::const_iterator ii = par.insetList().begin();
385         InsetList::const_iterator iend = par.insetList().end();
386         for (; ii != iend; ++ii) {
387                 Dimension dim;
388                 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
389                         - right_margin;
390                 Font const & font = ii->inset->noFontChange() ?
391                         bufferfont : getDisplayFont(pit, ii->pos);
392                 MetricsInfo mi(bv_, font, w);
393                 ii->inset->metrics(mi, dim);
394                 Dimension const old_dim = pm.insetDimension(ii->inset);
395                 pm.setInsetDimension(ii->inset, dim);
396                 changed |= (old_dim != dim);
397         }
398
399         Cursor const & cur = bv_->cursor();
400         DocIterator sel_beg = cur.selectionBegin();
401         DocIterator sel_end = cur.selectionEnd();
402         bool selection = cur.selection()
403                 // This is out text.
404                 && cur.text() == text_
405                 // if the anchor is outside, this is not our selection 
406                 && cur.anchor().text() == text_
407                 && pit >= sel_beg.pit() && pit <= sel_end.pit();
408
409         // We care only about visible selection.
410         if (selection) {
411                 if (pit != sel_beg.pit()) {
412                         sel_beg.pit() = pit;
413                         sel_beg.pos() = 0;
414                 }
415                 if (pit != sel_end.pit()) {
416                         sel_end.pit() = pit;
417                         sel_end.pos() = sel_end.lastpos();
418                 }
419         }
420
421         par.setBeginOfBody();
422         pos_type first = 0;
423         size_t row_index = 0;
424         // maximum pixel width of a row
425         int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
426         do {
427                 Dimension dim;
428                 pos_type end = rowBreakPoint(width, pit, first);
429                 if (row_index || end < par.size())
430                         // If there is more than one row, expand the text to 
431                         // the full allowable width. This setting here is needed
432                         // for the computeRowMetrics() below.
433                         dim_.wid = max_width_;
434
435                 dim.wid = rowWidth(right_margin, pit, first, end);
436                 boost::tie(dim.asc, dim.des) = rowHeight(pit, first, end);
437                 if (row_index == pm.rows().size())
438                         pm.rows().push_back(Row());
439                 Row & row = pm.rows()[row_index];
440                 row.setChanged(false);
441                 row.pos(first);
442                 row.endpos(end);
443                 if (selection)
444                         row.setSelection(sel_beg.pos(), sel_end.pos());
445                 else
446                         row.setSelection(-1, -1);
447                 row.setDimension(dim);
448                 int const max_row_width = max(dim_.wid, dim.wid);
449                 computeRowMetrics(pit, row, max_row_width);
450                 pm.computeRowSignature(row, bparams);
451                 first = end;
452                 ++row_index;
453
454                 pm.dim().wid = std::max(pm.dim().wid, dim.wid);
455                 pm.dim().des += dim.height();
456         } while (first < par.size());
457
458         if (row_index < pm.rows().size())
459                 pm.rows().resize(row_index);
460
461         // Make sure that if a par ends in newline, there is one more row
462         // under it
463         if (first > 0 && par.isNewline(first - 1)) {
464                 Dimension dim;
465                 dim.wid = rowWidth(right_margin, pit, first, first);
466                 boost::tie(dim.asc, dim.des) = rowHeight(pit, first, first);
467                 if (row_index == pm.rows().size())
468                         pm.rows().push_back(Row());
469                 Row & row = pm.rows()[row_index];
470                 row.setChanged(false);
471                 row.pos(first);
472                 row.endpos(first);
473                 row.setDimension(dim);
474                 int const max_row_width = max(dim_.wid, dim.wid);
475                 computeRowMetrics(pit, row, max_row_width);
476                 pm.computeRowSignature(row, bparams);
477                 pm.dim().des += dim.height();
478         }
479
480         pm.dim().asc += pm.rows()[0].ascent();
481         pm.dim().des -= pm.rows()[0].ascent();
482
483         changed |= old_dim.height() != pm.dim().height();
484
485         return changed;
486 }
487
488
489 void TextMetrics::computeRowMetrics(pit_type const pit,
490                 Row & row, int width) const
491 {
492
493         row.label_hfill = 0;
494         row.hfill = 0;
495         row.separator = 0;
496
497         Buffer & buffer = bv_->buffer();
498         Paragraph const & par = text_->getPar(pit);
499
500         double w = width - row.width();
501         // FIXME: put back this assertion when the crash on new doc is solved.
502         //BOOST_ASSERT(w >= 0);
503
504         //lyxerr << "\ndim_.wid " << dim_.wid << endl;
505         //lyxerr << "row.width() " << row.width() << endl;
506         //lyxerr << "w " << w << endl;
507
508         bool const is_rtl = text_->isRTL(buffer, par);
509         if (is_rtl)
510                 row.x = rightMargin(pit);
511         else
512                 row.x = leftMargin(max_width_, pit, row.pos());
513
514         // is there a manual margin with a manual label
515         LayoutPtr const & layout = par.layout();
516
517         if (layout->margintype == MARGIN_MANUAL
518             && layout->labeltype == LABEL_MANUAL) {
519                 /// We might have real hfills in the label part
520                 int nlh = numberOfLabelHfills(par, row);
521
522                 // A manual label par (e.g. List) has an auto-hfill
523                 // between the label text and the body of the
524                 // paragraph too.
525                 // But we don't want to do this auto hfill if the par
526                 // is empty.
527                 if (!par.empty())
528                         ++nlh;
529
530                 if (nlh && !par.getLabelWidthString().empty())
531                         row.label_hfill = labelFill(pit, row) / double(nlh);
532         }
533
534         // are there any hfills in the row?
535         int const nh = numberOfHfills(par, row);
536
537         if (nh) {
538                 if (w > 0)
539                         row.hfill = w / nh;
540         // we don't have to look at the alignment if it is ALIGN_LEFT and
541         // if the row is already larger then the permitted width as then
542         // we force the LEFT_ALIGN'edness!
543         } else if (int(row.width()) < max_width_) {
544                 // is it block, flushleft or flushright?
545                 // set x how you need it
546                 int align;
547                 if (par.params().align() == LYX_ALIGN_LAYOUT)
548                         align = layout->align;
549                 else
550                         align = par.params().align();
551
552                 // Display-style insets should always be on a centred row
553                 // The test on par.size() is to catch zero-size pars, which
554                 // would trigger the assert in Paragraph::getInset().
555                 //inset = par.size() ? par.getInset(row.pos()) : 0;
556                 if (row.pos() < par.size()
557                     && par.isInset(row.pos()))
558                 {
559                     switch(par.getInset(row.pos())->display()) {
560                         case Inset::AlignLeft:
561                                 align = LYX_ALIGN_BLOCK;
562                                 break;
563                         case Inset::AlignCenter:
564                                 align = LYX_ALIGN_CENTER;
565                                 break;
566                         case Inset::Inline:
567                         case Inset::AlignRight:
568                                 // unchanged (use align)
569                                 break;
570                     }
571                 }
572
573                 switch (align) {
574                 case LYX_ALIGN_BLOCK: {
575                         int const ns = numberOfSeparators(par, row);
576                         bool disp_inset = false;
577                         if (row.endpos() < par.size()) {
578                                 Inset const * in = par.getInset(row.endpos());
579                                 if (in)
580                                         disp_inset = in->display();
581                         }
582                         // If we have separators, this is not the last row of a
583                         // par, does not end in newline, and is not row above a
584                         // display inset... then stretch it
585                         if (ns
586                             && row.endpos() < par.size()
587                             && !par.isNewline(row.endpos() - 1)
588                             && !disp_inset
589                                 ) {
590                                 row.separator = w / ns;
591                                 //lyxerr << "row.separator " << row.separator << endl;
592                                 //lyxerr << "ns " << ns << endl;
593                         } else if (is_rtl) {
594                                 row.x += w;
595                         }
596                         break;
597                 }
598                 case LYX_ALIGN_RIGHT:
599                         row.x += w;
600                         break;
601                 case LYX_ALIGN_CENTER:
602                         row.x += w / 2;
603                         break;
604                 }
605         }
606
607         if (is_rtl) {
608                 pos_type body_pos = par.beginOfBody();
609                 pos_type end = row.endpos();
610
611                 if (body_pos > 0
612                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
613                 {
614                         row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
615                                 width(layout->labelsep);
616                         if (body_pos <= end)
617                                 row.x += row.label_hfill;
618                 }
619         }
620 }
621
622
623 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
624 {
625         Buffer & buffer = bv_->buffer();
626         Paragraph const & par = text_->getPar(pit);
627
628         pos_type last = par.beginOfBody();
629         BOOST_ASSERT(last > 0);
630
631         // -1 because a label ends with a space that is in the label
632         --last;
633
634         // a separator at this end does not count
635         if (par.isLineSeparator(last))
636                 --last;
637
638         int w = 0;
639         for (pos_type i = row.pos(); i <= last; ++i)
640                 w += singleWidth(pit, i);
641
642         docstring const & label = par.params().labelWidthString();
643         if (label.empty())
644                 return 0;
645
646         FontMetrics const & fm
647                 = theFontMetrics(text_->getLabelFont(buffer, par));
648
649         return max(0, fm.width(label) - w);
650 }
651
652
653 namespace {
654
655 // this needs special handling - only newlines count as a break point
656 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
657 {
658         pos_type const end = par.size();
659
660         for (; i < end; ++i)
661                 if (par.isNewline(i))
662                         return i + 1;
663
664         return end;
665 }
666
667 };
668
669
670 int TextMetrics::labelEnd(pit_type const pit) const
671 {
672         // labelEnd is only needed if the layout fills a flushleft label.
673         if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
674                 return 0;
675         // return the beginning of the body
676         return leftMargin(max_width_, pit);
677 }
678
679
680 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
681                 pit_type pos) const
682 {
683         Buffer & buffer = bv_->buffer();
684         ParagraphMetrics const & pm = par_metrics_[pit];
685         Paragraph const & par = text_->getPar(pit);
686         pos_type const end = par.size();
687         if (pos == end || width < 0)
688                 return end;
689
690         LayoutPtr const & layout = par.layout();
691
692         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
693                 return addressBreakPoint(pos, par);
694
695         pos_type const body_pos = par.beginOfBody();
696
697
698         // Now we iterate through until we reach the right margin
699         // or the end of the par, then choose the possible break
700         // nearest that.
701
702         int label_end = labelEnd(pit);
703         int const left = leftMargin(max_width_, pit, pos);
704         int x = left;
705
706         // pixel width since last breakpoint
707         int chunkwidth = 0;
708
709         FontIterator fi = FontIterator(*this, par, pit, pos);
710         pos_type point = end;
711         pos_type i = pos;
712         for ( ; i < end; ++i, ++fi) {
713                 int thiswidth = pm.singleWidth(i, *fi);
714
715                 // add the auto-hfill from label end to the body
716                 if (body_pos && i == body_pos) {
717                         FontMetrics const & fm = theFontMetrics(
718                                 text_->getLabelFont(buffer, par));
719                         int add = fm.width(layout->labelsep);
720                         if (par.isLineSeparator(i - 1))
721                                 add -= singleWidth(pit, i - 1);
722
723                         add = std::max(add, label_end - x);
724                         thiswidth += add;
725                 }
726
727                 x += thiswidth;
728                 chunkwidth += thiswidth;
729
730                 // break before a character that will fall off
731                 // the right of the row
732                 if (x >= width) {
733                         // if no break before, break here
734                         if (point == end || chunkwidth >= width - left) {
735                                 if (i > pos)
736                                         point = i;
737                                 else
738                                         point = i + 1;
739
740                         }
741                         // exit on last registered breakpoint:
742                         break;
743                 }
744
745                 if (par.isNewline(i)) {
746                         point = i + 1;
747                         break;
748                 }
749                 // Break before...
750                 if (i + 1 < end) {
751                         if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
752                                 point = i + 1;
753                                 break;
754                         }
755                         // ...and after.
756                         if (par.isInset(i) && par.getInset(i)->display()) {
757                                 point = i + 1;
758                                 break;
759                         }
760                 }
761
762                 if (!par.isInset(i) || par.getInset(i)->isChar()) {
763                         // some insets are line separators too
764                         if (par.isLineSeparator(i)) {
765                                 // register breakpoint:
766                                 point = i + 1;
767                                 chunkwidth = 0;
768                         }
769                 }
770         }
771
772         // maybe found one, but the par is short enough.
773         if (i == end && x < width)
774                 point = end;
775
776         // manual labels cannot be broken in LaTeX. But we
777         // want to make our on-screen rendering of footnotes
778         // etc. still break
779         if (body_pos && point < body_pos)
780                 point = body_pos;
781
782         return point;
783 }
784
785
786 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
787                 pos_type const first, pos_type const end) const
788 {
789         Buffer & buffer = bv_->buffer();
790         // get the pure distance
791         ParagraphMetrics const & pm = par_metrics_[pit];
792         Paragraph const & par = text_->getPar(pit);
793         int w = leftMargin(max_width_, pit, first);
794         int label_end = labelEnd(pit);
795
796         pos_type const body_pos = par.beginOfBody();
797         pos_type i = first;
798
799         if (i < end) {
800                 FontIterator fi = FontIterator(*this, par, pit, i);
801                 for ( ; i < end; ++i, ++fi) {
802                         if (body_pos > 0 && i == body_pos) {
803                                 FontMetrics const & fm = theFontMetrics(
804                                         text_->getLabelFont(buffer, par));
805                                 w += fm.width(par.layout()->labelsep);
806                                 if (par.isLineSeparator(i - 1))
807                                         w -= singleWidth(pit, i - 1);
808                                 w = max(w, label_end);
809                         }
810                         w += pm.singleWidth(i, *fi);
811                 }
812         }
813
814         if (body_pos > 0 && body_pos >= end) {
815                 FontMetrics const & fm = theFontMetrics(
816                         text_->getLabelFont(buffer, par));
817                 w += fm.width(par.layout()->labelsep);
818                 if (end > 0 && par.isLineSeparator(end - 1))
819                         w -= singleWidth(pit, end - 1);
820                 w = max(w, label_end);
821         }
822
823         return w + right_margin;
824 }
825
826
827 boost::tuple<int, int> TextMetrics::rowHeight(pit_type const pit, pos_type const first,
828                 pos_type const end) const
829 {
830         Paragraph const & par = text_->getPar(pit);
831         // get the maximum ascent and the maximum descent
832         double layoutasc = 0;
833         double layoutdesc = 0;
834         double const dh = defaultRowHeight();
835
836         // ok, let us initialize the maxasc and maxdesc value.
837         // Only the fontsize count. The other properties
838         // are taken from the layoutfont. Nicer on the screen :)
839         LayoutPtr const & layout = par.layout();
840
841         // as max get the first character of this row then it can
842         // increase but not decrease the height. Just some point to
843         // start with so we don't have to do the assignment below too
844         // often.
845         Buffer const & buffer = bv_->buffer();
846         Font font = getDisplayFont(pit, first);
847         Font::FONT_SIZE const tmpsize = font.size();
848         font = text_->getLayoutFont(buffer, pit);
849         Font::FONT_SIZE const size = font.size();
850         font.setSize(tmpsize);
851
852         Font labelfont = text_->getLabelFont(buffer, par);
853
854         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
855         FontMetrics const & fontmetrics = theFontMetrics(font);
856
857         // these are minimum values
858         double const spacing_val = layout->spacing.getValue()
859                 * text_->spacing(buffer, par);
860         //lyxerr << "spacing_val = " << spacing_val << endl;
861         int maxasc  = int(fontmetrics.maxAscent()  * spacing_val);
862         int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
863
864         // insets may be taller
865         ParagraphMetrics const & pm = par_metrics_[pit];
866         InsetList::const_iterator ii = par.insetList().begin();
867         InsetList::const_iterator iend = par.insetList().end();
868         for ( ; ii != iend; ++ii) {
869                 Dimension const & dim = pm.insetDimension(ii->inset);
870                 if (ii->pos >= first && ii->pos < end) {
871                         maxasc  = max(maxasc,  dim.ascent());
872                         maxdesc = max(maxdesc, dim.descent());
873                 }
874         }
875
876         // Check if any custom fonts are larger (Asger)
877         // This is not completely correct, but we can live with the small,
878         // cosmetic error for now.
879         int labeladdon = 0;
880
881         Font::FONT_SIZE maxsize =
882                 par.highestFontInRange(first, end, size);
883         if (maxsize > font.size()) {
884                 // use standard paragraph font with the maximal size
885                 Font maxfont = font;
886                 maxfont.setSize(maxsize);
887                 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
888                 maxasc  = max(maxasc,  maxfontmetrics.maxAscent());
889                 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
890         }
891
892         // This is nicer with box insets:
893         ++maxasc;
894         ++maxdesc;
895
896         ParagraphList const & pars = text_->paragraphs();
897
898         // is it a top line?
899         if (first == 0) {
900                 BufferParams const & bufparams = buffer.params();
901                 // some parskips VERY EASY IMPLEMENTATION
902                 if (bufparams.paragraph_separation
903                     == BufferParams::PARSEP_SKIP
904                         && par.ownerCode() != ERT_CODE
905                         && par.ownerCode() != LISTINGS_CODE
906                         && pit > 0
907                         && ((layout->isParagraph() && par.getDepth() == 0)
908                             || (pars[pit - 1].layout()->isParagraph()
909                                 && pars[pit - 1].getDepth() == 0)))
910                 {
911                                 maxasc += bufparams.getDefSkip().inPixels(*bv_);
912                 }
913
914                 if (par.params().startOfAppendix())
915                         maxasc += int(3 * dh);
916
917                 // This is special code for the chapter, since the label of this
918                 // layout is printed in an extra row
919                 if (layout->counter == "chapter"
920                     && !par.params().labelString().empty()) {
921                         labeladdon = int(labelfont_metrics.maxHeight()
922                                      * layout->spacing.getValue()
923                                      * text_->spacing(buffer, par));
924                 }
925
926                 // special code for the top label
927                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
928                      || layout->labeltype == LABEL_BIBLIO
929                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
930                     && isFirstInSequence(pit, pars)
931                     && !par.getLabelstring().empty())
932                 {
933                         labeladdon = int(
934                                   labelfont_metrics.maxHeight()
935                                         * layout->spacing.getValue()
936                                         * text_->spacing(buffer, par)
937                                 + (layout->topsep + layout->labelbottomsep) * dh);
938                 }
939
940                 // Add the layout spaces, for example before and after
941                 // a section, or between the items of a itemize or enumerate
942                 // environment.
943
944                 pit_type prev = depthHook(pit, pars, par.getDepth());
945                 Paragraph const & prevpar = pars[prev];
946                 if (prev != pit
947                     && prevpar.layout() == layout
948                     && prevpar.getDepth() == par.getDepth()
949                     && prevpar.getLabelWidthString()
950                                         == par.getLabelWidthString()) {
951                         layoutasc = layout->itemsep * dh;
952                 } else if (pit != 0 || first != 0) {
953                         if (layout->topsep > 0)
954                                 layoutasc = layout->topsep * dh;
955                 }
956
957                 prev = outerHook(pit, pars);
958                 if (prev != pit_type(pars.size())) {
959                         maxasc += int(pars[prev].layout()->parsep * dh);
960                 } else if (pit != 0) {
961                         Paragraph const & prevpar = pars[pit - 1];
962                         if (prevpar.getDepth() != 0 ||
963                                         prevpar.layout() == layout) {
964                                 maxasc += int(layout->parsep * dh);
965                         }
966                 }
967         }
968
969         // is it a bottom line?
970         if (end >= par.size()) {
971                 // add the layout spaces, for example before and after
972                 // a section, or between the items of a itemize or enumerate
973                 // environment
974                 pit_type nextpit = pit + 1;
975                 if (nextpit != pit_type(pars.size())) {
976                         pit_type cpit = pit;
977                         double usual = 0;
978                         double unusual = 0;
979
980                         if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
981                                 usual = pars[cpit].layout()->bottomsep * dh;
982                                 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
983                                 if (pars[cpit].layout() != pars[nextpit].layout()
984                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
985                                 {
986                                         unusual = pars[cpit].layout()->bottomsep * dh;
987                                 }
988                                 layoutdesc = max(unusual, usual);
989                         } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
990                                 if (pars[cpit].layout() != pars[nextpit].layout()
991                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
992                                         layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
993                         }
994                 }
995         }
996
997         // incalculate the layout spaces
998         maxasc  += int(layoutasc  * 2 / (2 + pars[pit].getDepth()));
999         maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1000
1001         // FIXME: the correct way is to do the following is to move the
1002         // following code in another method specially tailored for the
1003         // main Text. The following test is thus bogus.
1004         // Top and bottom margin of the document (only at top-level)
1005         if (main_text_) {
1006                 if (pit == 0 && first == 0)
1007                         maxasc += 20;
1008                 if (pit + 1 == pit_type(pars.size()) &&
1009                     end == par.size() &&
1010                                 !(end > 0 && par.isNewline(end - 1)))
1011                         maxdesc += 20;
1012         }
1013
1014         return boost::make_tuple(maxasc + labeladdon, maxdesc);
1015 }
1016
1017
1018 // x is an absolute screen coord
1019 // returns the column near the specified x-coordinate of the row
1020 // x is set to the real beginning of this column
1021 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1022                 Row const & row, int & x, bool & boundary) const
1023 {
1024         Buffer const & buffer = bv_->buffer();
1025
1026         /// For the main Text, it is possible that this pit is not
1027         /// yet in the CoordCache when moving cursor up.
1028         /// x Paragraph coordinate is always 0 for main text anyway.
1029         int const xo = origin_.x_;
1030         x -= xo;
1031         Paragraph const & par = text_->getPar(pit);
1032         ParagraphMetrics const & pm = par_metrics_[pit];
1033         Bidi bidi;
1034         bidi.computeTables(par, buffer, row);
1035
1036         pos_type vc = row.pos();
1037         pos_type end = row.endpos();
1038         pos_type c = 0;
1039         LayoutPtr const & layout = par.layout();
1040
1041         bool left_side = false;
1042
1043         pos_type body_pos = par.beginOfBody();
1044
1045         double tmpx = row.x;
1046         double last_tmpx = tmpx;
1047
1048         if (body_pos > 0 &&
1049             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1050                 body_pos = 0;
1051
1052         // check for empty row
1053         if (vc == end) {
1054                 x = int(tmpx) + xo;
1055                 return 0;
1056         }
1057
1058         while (vc < end && tmpx <= x) {
1059                 c = bidi.vis2log(vc);
1060                 last_tmpx = tmpx;
1061                 if (body_pos > 0 && c == body_pos - 1) {
1062                         FontMetrics const & fm = theFontMetrics(
1063                                 text_->getLabelFont(buffer, par));
1064                         tmpx += row.label_hfill + fm.width(layout->labelsep);
1065                         if (par.isLineSeparator(body_pos - 1))
1066                                 tmpx -= singleWidth(pit, body_pos - 1);
1067                 }
1068
1069                 if (pm.hfillExpansion(row, c)) {
1070                         tmpx += singleWidth(pit, c);
1071                         if (c >= body_pos)
1072                                 tmpx += row.hfill;
1073                         else
1074                                 tmpx += row.label_hfill;
1075                 } else if (par.isSeparator(c)) {
1076                         tmpx += singleWidth(pit, c);
1077                         if (c >= body_pos)
1078                                 tmpx += row.separator;
1079                 } else {
1080                         tmpx += singleWidth(pit, c);
1081                 }
1082                 ++vc;
1083         }
1084
1085         if ((tmpx + last_tmpx) / 2 > x) {
1086                 tmpx = last_tmpx;
1087                 left_side = true;
1088         }
1089
1090         BOOST_ASSERT(vc <= end);  // This shouldn't happen.
1091
1092         boundary = false;
1093         // This (rtl_support test) is not needed, but gives
1094         // some speedup if rtl_support == false
1095         bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1096
1097         // If lastrow is false, we don't need to compute
1098         // the value of rtl.
1099         bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1100         if (lastrow &&
1101             ((rtl  &&  left_side && vc == row.pos() && x < tmpx - 5) ||
1102              (!rtl && !left_side && vc == end  && x > tmpx + 5)))
1103                 c = end;
1104         else if (vc == row.pos()) {
1105                 c = bidi.vis2log(vc);
1106                 if (bidi.level(c) % 2 == 1)
1107                         ++c;
1108         } else {
1109                 c = bidi.vis2log(vc - 1);
1110                 bool const rtl = (bidi.level(c) % 2 == 1);
1111                 if (left_side == rtl) {
1112                         ++c;
1113                         boundary = isRTLBoundary(pit, c);
1114                 }
1115         }
1116
1117 // I believe this code is not needed anymore (Jug 20050717)
1118 #if 0
1119         // The following code is necessary because the cursor position past
1120         // the last char in a row is logically equivalent to that before
1121         // the first char in the next row. That's why insets causing row
1122         // divisions -- Newline and display-style insets -- must be treated
1123         // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1124         // Newline inset, air gap below:
1125         if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1126                 if (bidi.level(end -1) % 2 == 0)
1127                         tmpx -= singleWidth(pit, end - 1);
1128                 else
1129                         tmpx += singleWidth(pit, end - 1);
1130                 c = end - 1;
1131         }
1132
1133         // Air gap above display inset:
1134         if (row.pos() < end && c >= end && end < par.size()
1135             && par.isInset(end) && par.getInset(end)->display()) {
1136                 c = end - 1;
1137         }
1138         // Air gap below display inset:
1139         if (row.pos() < end && c >= end && par.isInset(end - 1)
1140             && par.getInset(end - 1)->display()) {
1141                 c = end - 1;
1142         }
1143 #endif
1144
1145         x = int(tmpx) + xo;
1146         pos_type const col = c - row.pos();
1147
1148         if (!c || end == par.size())
1149                 return col;
1150
1151         if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1152                 boundary = true;
1153                 return col;
1154         }
1155
1156         return min(col, end - 1 - row.pos());
1157 }
1158
1159
1160 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1161 {
1162         // We play safe and use parMetrics(pit) to make sure the
1163         // ParagraphMetrics will be redone and OK to use if needed.
1164         // Otherwise we would use an empty ParagraphMetrics in
1165         // upDownInText() while in selection mode.
1166         ParagraphMetrics const & pm = parMetrics(pit);
1167
1168         BOOST_ASSERT(row < int(pm.rows().size()));
1169         bool bound = false;
1170         Row const & r = pm.rows()[row];
1171         return r.pos() + getColumnNearX(pit, r, x, bound);
1172 }
1173
1174
1175 void TextMetrics::newParMetricsDown()
1176 {
1177         pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1178         pit_type const pit = last.first + 1;
1179         if (pit == int(text_->paragraphs().size()))
1180                 return;
1181
1182         // do it and update its position.
1183         redoParagraph(pit);
1184         par_metrics_[pit].setPosition(last.second.position()
1185                 + last.second.descent());
1186 }
1187
1188
1189 void TextMetrics::newParMetricsUp()
1190 {
1191         pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1192         if (first.first == 0)
1193                 return;
1194
1195         pit_type const pit = first.first - 1;
1196         // do it and update its position.
1197         redoParagraph(pit);
1198         par_metrics_[pit].setPosition(first.second.position()
1199                 - first.second.ascent());
1200 }
1201
1202 // y is screen coordinate
1203 pit_type TextMetrics::getPitNearY(int y)
1204 {
1205         BOOST_ASSERT(!text_->paragraphs().empty());
1206         LYXERR(Debug::DEBUG)
1207                 << BOOST_CURRENT_FUNCTION
1208                 << ": y: " << y << " cache size: " << par_metrics_.size()
1209                 << endl;
1210
1211         // look for highest numbered paragraph with y coordinate less than given y
1212         pit_type pit = 0;
1213         int yy = -1;
1214         ParMetricsCache::const_iterator it = par_metrics_.begin();
1215         ParMetricsCache::const_iterator et = par_metrics_.end();
1216         ParMetricsCache::const_iterator last = et; last--;
1217
1218         ParagraphMetrics const & pm = it->second;
1219
1220         // If we are off-screen (before the visible part)
1221         if (y < 0
1222                 // and even before the first paragraph in the cache.
1223                 && y < it->second.position() - int(pm.ascent())) {
1224                 //  and we are not at the first paragraph in the inset.
1225                 if (it->first == 0)
1226                         return 0;
1227                 // then this is the paragraph we are looking for.
1228                 pit = it->first - 1;
1229                 // rebreak it and update the CoordCache.
1230                 redoParagraph(pit);
1231                 par_metrics_[pit].setPosition(it->second.position() - pm.descent());
1232                 return pit;
1233         }
1234
1235         ParagraphMetrics const & pm_last = par_metrics_[last->first];
1236
1237         // If we are off-screen (after the visible part)
1238         if (y > bv_->workHeight()
1239                 // and even after the first paragraph in the cache.
1240                 && y >= last->second.position() + int(pm_last.descent())) {
1241                 pit = last->first + 1;
1242                 //  and we are not at the last paragraph in the inset.
1243                 if (pit == int(text_->paragraphs().size()))
1244                         return last->first;
1245                 // then this is the paragraph we are looking for.
1246                 // rebreak it and update the CoordCache.
1247                 redoParagraph(pit);
1248                 par_metrics_[pit].setPosition(last->second.position() + pm_last.ascent());
1249                 return pit;
1250         }
1251
1252         for (; it != et; ++it) {
1253                 LYXERR(Debug::DEBUG)
1254                         << BOOST_CURRENT_FUNCTION
1255                         << "  examining: pit: " << it->first
1256                         << " y: " << it->second.position()
1257                         << endl;
1258
1259                 ParagraphMetrics const & pm = par_metrics_[it->first];
1260
1261                 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1262                         pit = it->first;
1263                         yy = it->second.position();
1264                 }
1265         }
1266
1267         LYXERR(Debug::DEBUG)
1268                 << BOOST_CURRENT_FUNCTION
1269                 << ": found best y: " << yy << " for pit: " << pit
1270                 << endl;
1271
1272         return pit;
1273 }
1274
1275
1276 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1277 {
1278         ParagraphMetrics const & pm = par_metrics_[pit];
1279
1280         int yy = pm.position() - pm.ascent();
1281         BOOST_ASSERT(!pm.rows().empty());
1282         RowList::const_iterator rit = pm.rows().begin();
1283         RowList::const_iterator rlast = pm.rows().end();
1284         --rlast;
1285         for (; rit != rlast; yy += rit->height(), ++rit)
1286                 if (yy + rit->height() > y)
1287                         break;
1288         return *rit;
1289 }
1290
1291
1292 // x,y are absolute screen coordinates
1293 // sets cursor recursively descending into nested editable insets
1294 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1295 {
1296         if (lyxerr.debugging(Debug::WORKAREA)) {
1297                 lyxerr << "TextMetrics::editXY(cur, " << x << ", " << y << ")" << std::endl;
1298                 cur.bv().coordCache().dump();
1299         }
1300         pit_type pit = getPitNearY(y);
1301         BOOST_ASSERT(pit != -1);
1302
1303         Row const & row = getRowNearY(y, pit);
1304         bool bound = false;
1305
1306         int xx = x; // is modified by getColumnNearX
1307         pos_type const pos = row.pos()
1308                 + getColumnNearX(pit, row, xx, bound);
1309         cur.pit() = pit;
1310         cur.pos() = pos;
1311         cur.boundary(bound);
1312         cur.setTargetX(x);
1313
1314         // try to descend into nested insets
1315         Inset * inset = checkInsetHit(x, y);
1316         //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1317         if (!inset) {
1318                 // Either we deconst editXY or better we move current_font
1319                 // and real_current_font to Cursor
1320                 // FIXME: what is needed now that current_font and real_current_font
1321                 // are transferred?
1322                 cur.setCurrentFont();
1323                 return 0;
1324         }
1325
1326         ParagraphList const & pars = text_->paragraphs();
1327         Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1328         //Inset * insetBehind = pars[pit].getInset(pos);
1329
1330         // This should be just before or just behind the
1331         // cursor position set above.
1332         BOOST_ASSERT((pos != 0 && inset == insetBefore)
1333                 || inset == pars[pit].getInset(pos));
1334
1335         // Make sure the cursor points to the position before
1336         // this inset.
1337         if (inset == insetBefore) {
1338                 --cur.pos();
1339                 cur.boundary(false);
1340         }
1341
1342         // Try to descend recursively inside the inset.
1343         inset = inset->editXY(cur, x, y);
1344
1345         if (cur.top().text() == text_)
1346                 cur.setCurrentFont();
1347         return inset;
1348 }
1349
1350
1351 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1352 {
1353         BOOST_ASSERT(text_ == cur.text());
1354         pit_type pit = getPitNearY(y);
1355
1356         ParagraphMetrics const & pm = par_metrics_[pit];
1357
1358         int yy = pm.position() - pm.ascent();
1359         LYXERR(Debug::DEBUG)
1360                 << BOOST_CURRENT_FUNCTION
1361                 << ": x: " << x
1362                 << " y: " << y
1363                 << " pit: " << pit
1364                 << " yy: " << yy << endl;
1365
1366         int r = 0;
1367         BOOST_ASSERT(pm.rows().size());
1368         for (; r < int(pm.rows().size()) - 1; ++r) {
1369                 Row const & row = pm.rows()[r];
1370                 if (int(yy + row.height()) > y)
1371                         break;
1372                 yy += row.height();
1373         }
1374
1375         Row const & row = pm.rows()[r];
1376
1377         LYXERR(Debug::DEBUG)
1378                 << BOOST_CURRENT_FUNCTION
1379                 << ": row " << r
1380                 << " from pos: " << row.pos()
1381                 << endl;
1382
1383         bool bound = false;
1384         int xx = x;
1385         pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1386
1387         LYXERR(Debug::DEBUG)
1388                 << BOOST_CURRENT_FUNCTION
1389                 << ": setting cursor pit: " << pit
1390                 << " pos: " << pos
1391                 << endl;
1392
1393         text_->setCursor(cur, pit, pos, true, bound);
1394         // remember new position.
1395         cur.setTargetX();
1396 }
1397
1398
1399 //takes screen x,y coordinates
1400 Inset * TextMetrics::checkInsetHit(int x, int y)
1401 {
1402         pit_type pit = getPitNearY(y);
1403         BOOST_ASSERT(pit != -1);
1404
1405         Paragraph const & par = text_->paragraphs()[pit];
1406         ParagraphMetrics const & pm = par_metrics_[pit];
1407
1408         LYXERR(Debug::DEBUG)
1409                 << BOOST_CURRENT_FUNCTION
1410                 << ": x: " << x
1411                 << " y: " << y
1412                 << "  pit: " << pit
1413                 << endl;
1414         InsetList::const_iterator iit = par.insetList().begin();
1415         InsetList::const_iterator iend = par.insetList().end();
1416         for (; iit != iend; ++iit) {
1417                 Inset * inset = iit->inset;
1418
1419                 LYXERR(Debug::DEBUG)
1420                         << BOOST_CURRENT_FUNCTION
1421                         << ": examining inset " << inset << endl;
1422
1423                 if (!bv_->coordCache().getInsets().has(inset)) {
1424                         LYXERR(Debug::DEBUG)
1425                                 << BOOST_CURRENT_FUNCTION
1426                                 << ": inset has no cached position" << endl;
1427                         return 0;
1428                 }
1429
1430                 Dimension const & dim = pm.insetDimension(inset);
1431                 Point p = bv_->coordCache().getInsets().xy(inset);
1432
1433                 LYXERR(Debug::DEBUG)
1434                         << BOOST_CURRENT_FUNCTION
1435                         << ": xo: " << p.x_ << "..." << p.x_ + dim.wid
1436                         << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des
1437                         << endl;
1438
1439                 if (x >= p.x_
1440                         && x <= p.x_ + dim.wid
1441                         && y >= p.y_ - dim.asc
1442                         && y <= p.y_ + dim.des) {
1443                         LYXERR(Debug::DEBUG)
1444                                 << BOOST_CURRENT_FUNCTION
1445                                 << ": Hit inset: " << inset << endl;
1446                         return inset;
1447                 }
1448         }
1449
1450         LYXERR(Debug::DEBUG)
1451                 << BOOST_CURRENT_FUNCTION
1452                 << ": No inset hit. " << endl;
1453         return 0;
1454 }
1455
1456
1457 int TextMetrics::cursorX(CursorSlice const & sl,
1458                 bool boundary) const
1459 {
1460         BOOST_ASSERT(sl.text() == text_);
1461         pit_type const pit = sl.pit();
1462         Paragraph const & par = text_->paragraphs()[pit];
1463         ParagraphMetrics const & pm = par_metrics_[pit];
1464         if (pm.rows().empty())
1465                 return 0;
1466
1467         pos_type ppos = sl.pos();
1468         // Correct position in front of big insets
1469         bool const boundary_correction = ppos != 0 && boundary;
1470         if (boundary_correction)
1471                 --ppos;
1472
1473         Row const & row = pm.getRow(sl.pos(), boundary);
1474
1475         pos_type cursor_vpos = 0;
1476
1477         Buffer const & buffer = bv_->buffer();
1478         double x = row.x;
1479         Bidi bidi;
1480         bidi.computeTables(par, buffer, row);
1481
1482         pos_type const row_pos  = row.pos();
1483         pos_type const end      = row.endpos();
1484         // Spaces at logical line breaks in bidi text must be skipped during 
1485         // cursor positioning. However, they may appear visually in the middle
1486         // of a row; they must be skipped, wherever they are...
1487         // * logically "abc_[HEBREW_\nHEBREW]"
1488         // * visually "abc_[_WERBEH\nWERBEH]"
1489         pos_type skipped_sep_vpos = -1;
1490
1491         if (end <= row_pos)
1492                 cursor_vpos = row_pos;
1493         else if (ppos >= end)
1494                 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1495         else if (ppos > row_pos && ppos >= end)
1496                 // Place cursor after char at (logical) position pos - 1
1497                 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1498                         ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1499         else
1500                 // Place cursor before char at (logical) position ppos
1501                 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1502                         ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1503
1504         pos_type body_pos = par.beginOfBody();
1505         if (body_pos > 0 &&
1506             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1507                 body_pos = 0;
1508
1509         // Use font span to speed things up, see below
1510         FontSpan font_span;
1511         Font font;
1512
1513         // If the last logical character is a separator, skip it, unless
1514         // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1515         if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1516                 skipped_sep_vpos = bidi.log2vis(end - 1);
1517         
1518         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1519                 // Skip the separator which is at the logical end of the row
1520                 if (vpos == skipped_sep_vpos)
1521                         continue;
1522                 pos_type pos = bidi.vis2log(vpos);
1523                 if (body_pos > 0 && pos == body_pos - 1) {
1524                         FontMetrics const & labelfm = theFontMetrics(
1525                                 text_->getLabelFont(buffer, par));
1526                         x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1527                         if (par.isLineSeparator(body_pos - 1))
1528                                 x -= singleWidth(pit, body_pos - 1);
1529                 }
1530
1531                 // Use font span to speed things up, see above
1532                 if (pos < font_span.first || pos > font_span.last) {
1533                         font_span = par.fontSpan(pos);
1534                         font = getDisplayFont(pit, pos);
1535                 }
1536
1537                 x += pm.singleWidth(pos, font);
1538
1539                 if (pm.hfillExpansion(row, pos))
1540                         x += (pos >= body_pos) ? row.hfill : row.label_hfill;
1541                 else if (par.isSeparator(pos) && pos >= body_pos)
1542                         x += row.separator;
1543         }
1544
1545         // see correction above
1546         if (boundary_correction) {
1547                 if (isRTL(sl, boundary))
1548                         x -= singleWidth(pit, ppos);
1549                 else
1550                         x += singleWidth(pit, ppos);
1551         }
1552
1553         return int(x);
1554 }
1555
1556
1557 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1558 {
1559         //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << std::endl;
1560         ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1561         if (pm.rows().empty())
1562                 return 0;
1563
1564         int h = 0;
1565         h -= par_metrics_[0].rows()[0].ascent();
1566         for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1567                 h += par_metrics_[pit].height();
1568         }
1569         int pos = sl.pos();
1570         if (pos && boundary)
1571                 --pos;
1572         size_t const rend = pm.pos2row(pos);
1573         for (size_t rit = 0; rit != rend; ++rit)
1574                 h += pm.rows()[rit].height();
1575         h += pm.rows()[rend].ascent();
1576         return h;
1577 }
1578
1579
1580 void TextMetrics::cursorPrevious(Cursor & cur)
1581 {
1582         pos_type cpos = cur.pos();
1583         pit_type cpar = cur.pit();
1584
1585         int x = cur.x_target();
1586         setCursorFromCoordinates(cur, x, 0);
1587         cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1588
1589         if (cpar == cur.pit() && cpos == cur.pos())
1590                 // we have a row which is taller than the workarea. The
1591                 // simplest solution is to move to the previous row instead.
1592                 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1593
1594         cur.finishUndo();
1595         cur.updateFlags(Update::Force | Update::FitCursor);
1596 }
1597
1598
1599 void TextMetrics::cursorNext(Cursor & cur)
1600 {
1601         pos_type cpos = cur.pos();
1602         pit_type cpar = cur.pit();
1603
1604         int x = cur.x_target();
1605         setCursorFromCoordinates(cur, x, cur.bv().workHeight() - 1);
1606         cur.dispatch(FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1607
1608         if (cpar == cur.pit() && cpos == cur.pos())
1609                 // we have a row which is taller than the workarea. The
1610                 // simplest solution is to move to the next row instead.
1611                 cur.dispatch(
1612                         FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1613
1614         cur.finishUndo();
1615         cur.updateFlags(Update::Force | Update::FitCursor);
1616 }
1617
1618
1619 // the cursor set functions have a special mechanism. When they
1620 // realize you left an empty paragraph, they will delete it.
1621
1622 bool TextMetrics::cursorHome(Cursor & cur)
1623 {
1624         BOOST_ASSERT(text_ == cur.text());
1625         ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1626         Row const & row = pm.getRow(cur.pos(),cur.boundary());
1627         return text_->setCursor(cur, cur.pit(), row.pos());
1628 }
1629
1630
1631 bool TextMetrics::cursorEnd(Cursor & cur)
1632 {
1633         BOOST_ASSERT(text_ == cur.text());
1634         // if not on the last row of the par, put the cursor before
1635         // the final space exept if I have a spanning inset or one string
1636         // is so long that we force a break.
1637         pos_type end = cur.textRow().endpos();
1638         if (end == 0)
1639                 // empty text, end-1 is no valid position
1640                 return false;
1641         bool boundary = false;
1642         if (end != cur.lastpos()) {
1643                 if (!cur.paragraph().isLineSeparator(end-1)
1644                     && !cur.paragraph().isNewline(end-1))
1645                         boundary = true;
1646                 else
1647                         --end;
1648         }
1649         return text_->setCursor(cur, cur.pit(), end, true, boundary);
1650 }
1651
1652
1653 void TextMetrics::deleteLineForward(Cursor & cur)
1654 {
1655         BOOST_ASSERT(text_ == cur.text());
1656         if (cur.lastpos() == 0) {
1657                 // Paragraph is empty, so we just go forward
1658                 text_->cursorForward(cur);
1659         } else {
1660                 cur.resetAnchor();
1661                 cur.selection() = true; // to avoid deletion
1662                 cursorEnd(cur);
1663                 cur.setSelection();
1664                 // What is this test for ??? (JMarc)
1665                 if (!cur.selection())
1666                         text_->deleteWordForward(cur);
1667                 else
1668                         cap::cutSelection(cur, true, false);
1669                 checkBufferStructure(cur.buffer(), cur);
1670         }
1671 }
1672
1673
1674 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1675 {
1676         ParagraphList const & pars = text_->paragraphs();
1677         return row.endpos() >= pars[pit].size()
1678                 && pit + 1 == pit_type(pars.size());
1679 }
1680
1681
1682 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1683 {
1684         return row.pos() == 0 && pit == 0;
1685 }
1686
1687
1688 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1689 {
1690         BOOST_ASSERT(pit >= 0);
1691         BOOST_ASSERT(pit < int(text_->paragraphs().size()));
1692         return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1693 }
1694
1695
1696 int TextMetrics::leftMargin(int max_width,
1697                 pit_type const pit, pos_type const pos) const
1698 {
1699         ParagraphList const & pars = text_->paragraphs();
1700
1701         BOOST_ASSERT(pit >= 0);
1702         BOOST_ASSERT(pit < int(pars.size()));
1703         Paragraph const & par = pars[pit];
1704         BOOST_ASSERT(pos >= 0);
1705         BOOST_ASSERT(pos <= par.size());
1706         Buffer const & buffer = bv_->buffer();
1707         //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1708         TextClass const & tclass = buffer.params().getTextClass();
1709         LayoutPtr const & layout = par.layout();
1710
1711         docstring parindent = layout->parindent;
1712
1713         int l_margin = 0;
1714
1715         if (text_->isMainText(buffer))
1716                 l_margin += changebarMargin();
1717
1718         l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1719                 tclass.leftmargin());
1720
1721         if (par.getDepth() != 0) {
1722                 // find the next level paragraph
1723                 pit_type newpar = outerHook(pit, pars);
1724                 if (newpar != pit_type(pars.size())) {
1725                         if (pars[newpar].layout()->isEnvironment()) {
1726                                 l_margin = leftMargin(max_width, newpar);
1727                         }
1728                         if (par.layout() == tclass.defaultLayout()) {
1729                                 if (pars[newpar].params().noindent())
1730                                         parindent.erase();
1731                                 else
1732                                         parindent = pars[newpar].layout()->parindent;
1733                         }
1734                 }
1735         }
1736
1737         // This happens after sections in standard classes. The 1.3.x
1738         // code compared depths too, but it does not seem necessary
1739         // (JMarc)
1740         if (par.layout() == tclass.defaultLayout()
1741             && pit > 0 && pars[pit - 1].layout()->nextnoindent)
1742                 parindent.erase();
1743
1744         Font const labelfont = text_->getLabelFont(buffer, par);
1745         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1746
1747         switch (layout->margintype) {
1748         case MARGIN_DYNAMIC:
1749                 if (!layout->leftmargin.empty()) {
1750                         l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1751                                 layout->leftmargin);
1752                 }
1753                 if (!par.getLabelstring().empty()) {
1754                         l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1755                         l_margin += labelfont_metrics.width(par.getLabelstring());
1756                         l_margin += labelfont_metrics.width(layout->labelsep);
1757                 }
1758                 break;
1759
1760         case MARGIN_MANUAL: {
1761                 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1762                 // The width of an empty par, even with manual label, should be 0
1763                 if (!par.empty() && pos >= par.beginOfBody()) {
1764                         if (!par.getLabelWidthString().empty()) {
1765                                 docstring labstr = par.getLabelWidthString();
1766                                 l_margin += labelfont_metrics.width(labstr);
1767                                 l_margin += labelfont_metrics.width(layout->labelsep);
1768                         }
1769                 }
1770                 break;
1771         }
1772
1773         case MARGIN_STATIC: {
1774                 l_margin += theFontMetrics(buffer.params().getFont()).
1775                         signedWidth(layout->leftmargin) * 4     / (par.getDepth() + 4);
1776                 break;
1777         }
1778
1779         case MARGIN_FIRST_DYNAMIC:
1780                 if (layout->labeltype == LABEL_MANUAL) {
1781                         if (pos >= par.beginOfBody()) {
1782                                 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1783                         } else {
1784                                 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1785                         }
1786                 } else if (pos != 0
1787                            // Special case to fix problems with
1788                            // theorems (JMarc)
1789                            || (layout->labeltype == LABEL_STATIC
1790                                && layout->latextype == LATEX_ENVIRONMENT
1791                                && !isFirstInSequence(pit, pars))) {
1792                         l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1793                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
1794                            && layout->labeltype != LABEL_BIBLIO
1795                            && layout->labeltype !=
1796                            LABEL_CENTERED_TOP_ENVIRONMENT) {
1797                         l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1798                         l_margin += labelfont_metrics.width(layout->labelsep);
1799                         l_margin += labelfont_metrics.width(par.getLabelstring());
1800                 }
1801                 break;
1802
1803         case MARGIN_RIGHT_ADDRESS_BOX: {
1804 #if 0
1805                 // ok, a terrible hack. The left margin depends on the widest
1806                 // row in this paragraph.
1807                 RowList::iterator rit = par.rows().begin();
1808                 RowList::iterator end = par.rows().end();
1809                 // FIXME: This is wrong.
1810                 int minfill = max_width;
1811                 for ( ; rit != end; ++rit)
1812                         if (rit->fill() < minfill)
1813                                 minfill = rit->fill();
1814                 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
1815                 l_margin += minfill;
1816 #endif
1817                 // also wrong, but much shorter.
1818                 l_margin += max_width / 2;
1819                 break;
1820         }
1821         }
1822
1823         if (!par.params().leftIndent().zero())
1824                 l_margin += par.params().leftIndent().inPixels(max_width);
1825
1826         LyXAlignment align;
1827
1828         if (par.params().align() == LYX_ALIGN_LAYOUT)
1829                 align = layout->align;
1830         else
1831                 align = par.params().align();
1832
1833         // set the correct parindent
1834         if (pos == 0
1835             && (layout->labeltype == LABEL_NO_LABEL
1836                || layout->labeltype == LABEL_TOP_ENVIRONMENT
1837                || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1838                || (layout->labeltype == LABEL_STATIC
1839                    && layout->latextype == LATEX_ENVIRONMENT
1840                    && !isFirstInSequence(pit, pars)))
1841             && align == LYX_ALIGN_BLOCK
1842             && !par.params().noindent()
1843             // in some insets, paragraphs are never indented
1844             && !(par.inInset() && par.inInset()->neverIndent(buffer))
1845             // display style insets are always centered, omit indentation
1846             && !(!par.empty()
1847                     && par.isInset(pos)
1848                     && par.getInset(pos)->display())
1849             && (par.layout() != tclass.defaultLayout()
1850                 || buffer.params().paragraph_separation ==
1851                    BufferParams::PARSEP_INDENT))
1852         {
1853                 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1854                         parindent);
1855         }
1856
1857         return l_margin;
1858 }
1859
1860
1861 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1862 {
1863         ParagraphMetrics const & pm = par_metrics_[pit];
1864
1865         return pm.singleWidth(pos, getDisplayFont(pit, pos));
1866 }
1867
1868
1869 // only used for inset right now. should also be used for main text
1870 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1871 {
1872         if (par_metrics_.empty())
1873                 return;
1874
1875         origin_.x_ = x;
1876         origin_.y_ = y;
1877
1878         ParMetricsCache::iterator it = par_metrics_.begin();
1879         ParMetricsCache::iterator const pm_end = par_metrics_.end();
1880         y -= it->second.ascent();
1881         for (; it != pm_end; ++it) {
1882                 ParagraphMetrics const & pmi = it->second;
1883                 y += pmi.ascent();
1884                 pit_type const pit = it->first;
1885                 // Save the paragraph position in the cache.
1886                 it->second.setPosition(y);
1887                 drawParagraph(pi, pit, x, y);
1888                 y += pmi.descent();
1889         }
1890 }
1891
1892
1893 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1894 {
1895 //      lyxerr << "  paintPar: pit: " << pit << " at y: " << y << endl;
1896         int const ww = bv_->workHeight();
1897
1898         ParagraphMetrics const & pm = par_metrics_[pit];
1899         if (pm.rows().empty())
1900                 return;
1901
1902         RowList::const_iterator const rb = pm.rows().begin();
1903         RowList::const_iterator const re = pm.rows().end();
1904
1905         Bidi bidi;
1906
1907         y -= rb->ascent();
1908         for (RowList::const_iterator rit = rb; rit != re; ++rit) {
1909                 y += rit->ascent();
1910
1911                 bool const inside = (y + rit->descent() >= 0
1912                         && y - rit->ascent() < ww);
1913                 // it is not needed to draw on screen if we are not inside.
1914                 pi.pain.setDrawingEnabled(inside);
1915                 RowPainter rp(pi, *text_, pit, *rit, bidi, x, y);
1916
1917                 // Row signature; has row changed since last paint?
1918                 bool row_has_changed = rit->changed();
1919                 
1920                 bool row_selection = rit->sel_beg != -1 && rit->sel_end != -1;
1921
1922                 if (!row_selection && !pi.full_repaint && !row_has_changed) {
1923                         // Paint the only the insets if the text itself is
1924                         // unchanged.
1925                         rp.paintOnlyInsets();
1926                         y += rit->descent();
1927                         continue;
1928                 }
1929
1930                 // Paint the row if a full repaint has been requested or it has
1931                 // changed.
1932                 // Clear background of this row
1933                 // (if paragraph background was not cleared)
1934                 if (row_selection || (!pi.full_repaint && row_has_changed)) {
1935                         pi.pain.fillRectangle(x, y - rit->ascent(),
1936                                 width(), rit->height(),
1937                                 ColorCode(ColorCode(pi.background_color)));
1938                 }
1939                 if (row_selection) {
1940                         DocIterator beg = bv_->cursor().selectionBegin();
1941                         DocIterator end = bv_->cursor().selectionEnd();
1942                         beg.pit() = pit;
1943                         beg.pos() = rit->sel_beg;
1944                         if (pit == end.pit()) {
1945                                 end.pos() = rit->sel_end;
1946                         } else {
1947                                 end.pit() = pit + 1;
1948                                 end.pos() = 0;
1949                         }
1950                         drawSelection(pi, beg, end, x);
1951                 }
1952
1953                 // Instrumentation for testing row cache (see also
1954                 // 12 lines lower):
1955                 if (lyxerr.debugging(Debug::PAINTING)) {
1956                         if (text_->isMainText(bv_->buffer()))
1957                                 LYXERR(Debug::PAINTING) << "\n{" << inside <<
1958                                 pi.full_repaint << row_has_changed << "}";
1959                         else
1960                                 LYXERR(Debug::PAINTING) << "[" << inside <<
1961                                 pi.full_repaint << row_has_changed << "]";
1962                 }
1963
1964                 // Backup full_repaint status and force full repaint
1965                 // for inner insets as the Row has been cleared out.
1966                 bool tmp = pi.full_repaint;
1967                 pi.full_repaint = true;
1968                 rp.paintAppendix();
1969                 rp.paintDepthBar();
1970                 rp.paintChangeBar();
1971                 if (rit == rb)
1972                         rp.paintFirst();
1973                 rp.paintText();
1974                 if (rit + 1 == re)
1975                         rp.paintLast();
1976                 y += rit->descent();
1977                 // Restore full_repaint status.
1978                 pi.full_repaint = tmp;
1979         }
1980         // Re-enable screen drawing for future use of the painter.
1981         pi.pain.setDrawingEnabled(true);
1982
1983         //LYXERR(Debug::PAINTING) << "." << endl;
1984 }
1985
1986
1987 // FIXME: only take care of one row!
1988 void TextMetrics::drawSelection(PainterInfo & pi,
1989         DocIterator const & beg, DocIterator const & end, int x) const
1990 {
1991         ParagraphMetrics const & pm1 = parMetrics(beg.pit());
1992         ParagraphMetrics const & pm2 = parMetrics(end.pit());
1993         Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
1994         Row const & row2 = pm2.getRow(end.pos(), end.boundary());
1995
1996         // clip above
1997         int middleTop;
1998         bool const clipAbove = (bv_->cursorStatus(beg) == CUR_ABOVE);
1999         if (clipAbove)
2000                 middleTop = 0;
2001         else
2002                 middleTop = bv_->getPos(beg, beg.boundary()).y_ + row1.descent();
2003         
2004         // clip below
2005         int middleBottom;
2006         bool const clipBelow = (bv_->cursorStatus(end) == CUR_BELOW);
2007         if (clipBelow)
2008                 middleBottom = bv_->workHeight();
2009         else
2010                 middleBottom = bv_->getPos(end, end.boundary()).y_ - row2.ascent();
2011
2012         // start and end in the same line?
2013         if (!clipAbove && !clipBelow && &row1 == &row2)
2014                 // then only draw this row's selection
2015                 drawRowSelection(pi, x, row1, beg, end, false, false);
2016         else {
2017                 if (!clipAbove) {
2018                         // get row end
2019                         DocIterator begRowEnd = beg;
2020                         begRowEnd.pos() = row1.endpos();
2021                         begRowEnd.boundary(true);
2022                         
2023                         // draw upper rectangle
2024                         drawRowSelection(pi, x, row1, beg, begRowEnd, false, true);
2025                 }
2026                         
2027                 if (middleTop < middleBottom) {
2028                         // draw middle rectangle
2029                         pi.pain.fillRectangle(x, middleTop, width(), middleBottom - middleTop,
2030                                 Color_selection);
2031                 }
2032
2033                 if (!clipBelow) {
2034                         // get row begin
2035                         DocIterator endRowBeg = end;
2036                         endRowBeg.pos() = row2.pos();
2037                         endRowBeg.boundary(false);
2038                         
2039                         // draw low rectangle
2040                         drawRowSelection(pi, x, row2, endRowBeg, end, true, false);
2041                 }
2042         }
2043 }
2044
2045
2046 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2047                 DocIterator const & beg, DocIterator const & end,
2048                 bool drawOnBegMargin, bool drawOnEndMargin) const
2049 {
2050         Buffer & buffer = bv_->buffer();
2051         DocIterator cur = beg;
2052         int x1 = cursorX(beg.top(), beg.boundary());
2053         int x2 = cursorX(end.top(), end.boundary());
2054         int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2055         int y2 = y1 + row.height();
2056         
2057         // draw the margins
2058         if (drawOnBegMargin) {
2059                 if (text_->isRTL(buffer, beg.paragraph()))
2060                         pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color_selection);
2061                 else
2062                         pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color_selection);
2063         }
2064         
2065         if (drawOnEndMargin) {
2066                 if (text_->isRTL(buffer, beg.paragraph()))
2067                         pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color_selection);
2068                 else
2069                         pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color_selection);
2070         }
2071         
2072         // if we are on a boundary from the beginning, it's probably
2073         // a RTL boundary and we jump to the other side directly as this
2074         // segement is 0-size and confuses the logic below
2075         if (cur.boundary())
2076                 cur.boundary(false);
2077         
2078         // go through row and draw from RTL boundary to RTL boundary
2079         while (cur < end) {
2080                 bool drawNow = false;
2081                 
2082                 // simplified cursorForward code below which does not
2083                 // descend into insets and which does not go into the
2084                 // next line. Compare the logic with the original cursorForward
2085                 
2086                 // if left of boundary -> just jump to right side
2087                 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2088                 if (cur.boundary()) {
2089                         cur.boundary(false);
2090                 }       else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2091                         // in front of RTL boundary -> Stay on this side of the boundary because:
2092                         //   ab|cDDEEFFghi -> abc|DDEEFFghi
2093                         ++cur.pos();
2094                         cur.boundary(true);
2095                         drawNow = true;
2096                 } else {
2097                         // move right
2098                         ++cur.pos();
2099                         
2100                         // line end?
2101                         if (cur.pos() == row.endpos())
2102                                 cur.boundary(true);
2103                 }
2104                         
2105                 if (x1 == -1) {
2106                         // the previous segment was just drawn, now the next starts
2107                         x1 = cursorX(cur.top(), cur.boundary());
2108                 }
2109                 
2110                 if (!(cur < end) || drawNow) {
2111                         x2 = cursorX(cur.top(), cur.boundary());
2112                         pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2113                                 Color_selection);
2114                         
2115                         // reset x1, so it is set again next round (which will be on the 
2116                         // right side of a boundary or at the selection end)
2117                         x1 = -1;
2118                 }
2119         }
2120 }
2121
2122 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2123 //{
2124 //      ParagraphMetrics const & pm = par_metrics_[pit];
2125 //      Row const & r = pm.rows()[row];
2126 //      int x = 0;
2127 //      pos -= r.pos();
2128 //}
2129
2130
2131 int defaultRowHeight()
2132 {
2133         return int(theFontMetrics(Font(Font::ALL_SANE)).maxHeight() *  1.2);
2134 }
2135
2136 } // namespace lyx