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