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