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