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