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