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