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