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