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