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