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