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