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