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