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