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