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