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