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