]> git.lyx.org Git - features.git/blob - src/TextMetrics.cpp
Re-implement the wide() hack in a clean way (at metrics level): an InsetText will...
[features.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 "VSpace.h"
40
41 #include "frontends/FontMetrics.h"
42 #include "frontends/Painter.h"
43
44 #include <boost/current_function.hpp>
45
46 using std::max;
47 using std::min;
48 using std::endl;
49
50 namespace lyx {
51
52 using frontend::FontMetrics;
53
54 namespace {
55
56 int numberOfSeparators(Paragraph const & par, Row const & row)
57 {
58         pos_type const first = max(row.pos(), par.beginOfBody());
59         pos_type const last = row.endpos() - 1;
60         int n = 0;
61         for (pos_type p = first; p < last; ++p) {
62                 if (par.isSeparator(p))
63                         ++n;
64         }
65         return n;
66 }
67
68
69 int numberOfLabelHfills(Paragraph const & par, Row const & row)
70 {
71         pos_type last = row.endpos() - 1;
72         pos_type first = row.pos();
73
74         // hfill *DO* count at the beginning of paragraphs!
75         if (first) {
76                 while (first < last && par.isHfill(first))
77                         ++first;
78         }
79
80         last = min(last, par.beginOfBody());
81         int n = 0;
82         for (pos_type p = first; p < last; ++p) {
83                 if (par.isHfill(p))
84                         ++n;
85         }
86         return n;
87 }
88
89
90 int numberOfHfills(Paragraph const & par, Row const & row)
91 {
92         pos_type const last = row.endpos();
93         pos_type first = row.pos();
94
95         // hfill *DO* count at the beginning of paragraphs!
96         if (first) {
97                 while (first < last && par.isHfill(first))
98                         ++first;
99         }
100
101         first = max(first, par.beginOfBody());
102
103         int n = 0;
104         for (pos_type p = first; p < last; ++p) {
105                 if (par.isHfill(p))
106                         ++n;
107         }
108         return n;
109 }
110
111 } // namespace anon
112
113 TextMetrics::TextMetrics(BufferView * bv, Text * text)
114         : bv_(bv), text_(text)
115 {
116         BOOST_ASSERT(bv_);
117         max_width_ = bv_->workWidth();
118         dim_.wid = max_width_;
119         dim_.asc = 10;
120         dim_.des = 10;
121
122         //text_->updateLabels(bv->buffer());
123 }
124
125
126 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
127 {
128         return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
129 }
130
131
132 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit,
133                 bool redo)
134 {
135         ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
136         if (pmc_it == par_metrics_.end()) {
137                 pmc_it = par_metrics_.insert(
138                         std::make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
139         }
140         if (pmc_it->second.rows().empty() && redo) {
141                 redoParagraph(pit);
142         }
143         return pmc_it->second;
144 }
145
146
147 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim)
148 {
149         BOOST_ASSERT(mi.base.textwidth);
150         max_width_ = mi.base.textwidth;
151         // backup old dimension.
152         Dimension const old_dim = dim_;
153         // reset dimension.
154         dim_ = Dimension();
155         size_t npar = text_->paragraphs().size();
156         if (npar > 1)
157                 // If there is more than one row, expand the text to 
158                 // the full allowable width.
159                 dim_.wid = max_width_;
160
161         //lyxerr << "Text::metrics: width: " << mi.base.textwidth
162         //      << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
163
164         bool changed = false;
165         unsigned int h = 0;
166         for (pit_type pit = 0; pit != npar; ++pit) {
167                 changed |= redoParagraph(pit);
168                 ParagraphMetrics const & pm = par_metrics_[pit];
169                 h += pm.height();
170                 if (dim_.wid < pm.width())
171                         dim_.wid = pm.width();
172         }
173
174         dim_.asc = par_metrics_[0].ascent();
175         dim_.des = h - dim_.asc;
176         //lyxerr << "dim_.wid " << dim_.wid << endl;
177         //lyxerr << "dim_.asc " << dim_.asc << endl;
178         //lyxerr << "dim_.des " << dim_.des << endl;
179
180         changed |= dim_ != old_dim;
181         dim = dim_;
182         return changed;
183 }
184
185
186 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
187 {
188         return main_text_? pm.rightMargin(bv_->buffer()) : 0;
189 }
190
191
192 int TextMetrics::rightMargin(pit_type const pit) const
193 {
194         return main_text_? par_metrics_[pit].rightMargin(bv_->buffer()) : 0;
195 }
196
197
198 bool TextMetrics::redoParagraph(pit_type const pit)
199 {
200         Paragraph & par = text_->getPar(pit);
201         // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
202         // redoParagraph() recursively inside parMetrics.
203         Dimension old_dim = parMetrics(pit, false).dim();
204         ParagraphMetrics & pm = par_metrics_[pit];
205         pm.reset(par);
206
207         Buffer & buffer = bv_->buffer();
208         BufferParams const & bparams = buffer.params();
209         main_text_ = (text_ == &buffer.text());
210         bool changed = false;
211
212         // FIXME This check ought to be done somewhere else. It is the reason
213         // why text_ is not     const. But then, where else to do it?
214         // Well, how can you end up with either (a) a biblio environment that
215         // has no InsetBibitem or (b) a biblio environment with more than one
216         // InsetBibitem? I think the answer is: when paragraphs are merged;
217         // when layout is set; when material is pasted.
218         int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
219         if (moveCursor > 0)
220                 const_cast<Cursor &>(bv_->cursor()).posRight();
221         else if (moveCursor < 0) {
222                 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
223                 if (cursor.pos() >= -moveCursor)
224                         cursor.posLeft();
225         }
226
227         // Optimisation: this is used in the next two loops
228         // so better to calculate that once here.
229         int const right_margin = rightMargin(pm);
230
231         // redo insets
232         // FIXME: We should always use getFont(), see documentation of
233         // noFontChange() in Inset.h.
234         Font const bufferfont = buffer.params().getFont();
235         InsetList::const_iterator ii = par.insetlist.begin();
236         InsetList::const_iterator iend = par.insetlist.end();
237         for (; ii != iend; ++ii) {
238                 Dimension old_dim = ii->inset->dimension();
239                 Dimension dim;
240                 int const w = max_width_ - text_->leftMargin(buffer, max_width_, pit, ii->pos)
241                         - right_margin;
242                 Font const & font = ii->inset->noFontChange() ?
243                         bufferfont : text_->getFont(buffer, par, ii->pos);
244                 MetricsInfo mi(bv_, font, w);
245                 changed |= ii->inset->metrics(mi, dim);
246                 changed |= (old_dim != dim);
247         }
248
249         par.setBeginOfBody();
250         pos_type first = 0;
251         size_t row_index = 0;
252         // maximum pixel width of a row
253         int width = max_width_ - right_margin; // - leftMargin(buffer, max_width_, pit, row);
254         do {
255                 Dimension dim;
256                 pos_type end = rowBreakPoint(width, pit, first);
257                 if (row_index || end < par.size())
258                         // If there is more than one row, expand the text to 
259                         // the full allowable width. This setting here is needed
260                         // for the computeRowMetrics below().
261                         dim_.wid = max_width_;
262
263                 dim.wid = rowWidth(right_margin, pit, first, end);
264                 boost::tie(dim.asc, dim.des) = rowHeight(pit, first, end);
265                 if (row_index == pm.rows().size())
266                         pm.rows().push_back(Row());
267                 Row & row = pm.rows()[row_index];
268                 row.setChanged(false);
269                 row.pos(first);
270                 row.endpos(end);
271                 row.setDimension(dim);
272                 computeRowMetrics(pit, row);
273                 pm.computeRowSignature(row, bparams);
274                 first = end;
275                 ++row_index;
276
277                 pm.dim().wid = std::max(pm.dim().wid, dim.wid);
278                 pm.dim().des += dim.height();
279         } while (first < par.size());
280
281         if (row_index < pm.rows().size())
282                 pm.rows().resize(row_index);
283
284         // Make sure that if a par ends in newline, there is one more row
285         // under it
286         if (first > 0 && par.isNewline(first - 1)) {
287                 Dimension dim;
288                 dim.wid = rowWidth(right_margin, pit, first, first);
289                 boost::tie(dim.asc, dim.des) = rowHeight(pit, first, first);
290                 if (row_index == pm.rows().size())
291                         pm.rows().push_back(Row());
292                 Row & row = pm.rows()[row_index];
293                 row.setChanged(false);
294                 row.pos(first);
295                 row.endpos(first);
296                 row.setDimension(dim);
297                 computeRowMetrics(pit, row);
298                 pm.computeRowSignature(row, bparams);
299                 pm.dim().des += dim.height();
300         }
301
302         pm.dim().asc += pm.rows()[0].ascent();
303         pm.dim().des -= pm.rows()[0].ascent();
304
305         changed |= old_dim.height() != pm.dim().height();
306
307         return changed;
308 }
309
310
311 void TextMetrics::computeRowMetrics(pit_type const pit,
312                 Row & row) const
313 {
314         Buffer & buffer = bv_->buffer();
315         Paragraph const & par = text_->getPar(pit);
316
317         double w = dim_.wid - row.width();
318         BOOST_ASSERT(w >= 0);
319         //lyxerr << "\ndim_.wid " << dim_.wid << endl;
320         //lyxerr << "row.width() " << row.width() << endl;
321         //lyxerr << "w " << w << endl;
322
323         bool const is_rtl = text_->isRTL(buffer, par);
324         if (is_rtl)
325                 row.x = rightMargin(pit);
326         else
327                 row.x = text_->leftMargin(buffer, max_width_, pit, row.pos());
328
329         // is there a manual margin with a manual label
330         LayoutPtr const & layout = par.layout();
331
332         if (layout->margintype == MARGIN_MANUAL
333             && layout->labeltype == LABEL_MANUAL) {
334                 /// We might have real hfills in the label part
335                 int nlh = numberOfLabelHfills(par, row);
336
337                 // A manual label par (e.g. List) has an auto-hfill
338                 // between the label text and the body of the
339                 // paragraph too.
340                 // But we don't want to do this auto hfill if the par
341                 // is empty.
342                 if (!par.empty())
343                         ++nlh;
344
345                 if (nlh && !par.getLabelWidthString().empty())
346                         row.label_hfill = labelFill(pit, row) / double(nlh);
347         }
348
349         // are there any hfills in the row?
350         int const nh = numberOfHfills(par, row);
351
352         if (nh) {
353                 if (w > 0)
354                         row.hfill = w / nh;
355         // we don't have to look at the alignment if it is ALIGN_LEFT and
356         // if the row is already larger then the permitted width as then
357         // we force the LEFT_ALIGN'edness!
358         } else if (int(row.width()) < max_width_) {
359                 // is it block, flushleft or flushright?
360                 // set x how you need it
361                 int align;
362                 if (par.params().align() == LYX_ALIGN_LAYOUT)
363                         align = layout->align;
364                 else
365                         align = par.params().align();
366
367                 // Display-style insets should always be on a centred row
368                 // The test on par.size() is to catch zero-size pars, which
369                 // would trigger the assert in Paragraph::getInset().
370                 //inset = par.size() ? par.getInset(row.pos()) : 0;
371                 if (row.pos() < par.size()
372                     && par.isInset(row.pos()))
373                 {
374                     switch(par.getInset(row.pos())->display()) {
375                         case Inset::AlignLeft:
376                                 align = LYX_ALIGN_BLOCK;
377                                 break;
378                         case Inset::AlignCenter:
379                                 align = LYX_ALIGN_CENTER;
380                                 break;
381                         case Inset::Inline:
382                         case Inset::AlignRight:
383                                 // unchanged (use align)
384                                 break;
385                     }
386                 }
387
388                 switch (align) {
389                 case LYX_ALIGN_BLOCK: {
390                         int const ns = numberOfSeparators(par, row);
391                         bool disp_inset = false;
392                         if (row.endpos() < par.size()) {
393                                 Inset const * in = par.getInset(row.endpos());
394                                 if (in)
395                                         disp_inset = in->display();
396                         }
397                         // If we have separators, this is not the last row of a
398                         // par, does not end in newline, and is not row above a
399                         // display inset... then stretch it
400                         if (ns
401                             && row.endpos() < par.size()
402                             && !par.isNewline(row.endpos() - 1)
403                             && !disp_inset
404                                 ) {
405                                 row.separator = w / ns;
406                                 //lyxerr << "row.separator " << row.separator << endl;
407                                 //lyxerr << "ns " << ns << endl;
408                         } else if (is_rtl) {
409                                 row.x += w;
410                         }
411                         break;
412                 }
413                 case LYX_ALIGN_RIGHT:
414                         row.x += w;
415                         break;
416                 case LYX_ALIGN_CENTER:
417                         row.x += w / 2;
418                         break;
419                 }
420         }
421
422         if (is_rtl) {
423                 pos_type body_pos = par.beginOfBody();
424                 pos_type end = row.endpos();
425
426                 if (body_pos > 0
427                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
428                 {
429                         row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
430                                 width(layout->labelsep);
431                         if (body_pos <= end)
432                                 row.x += row.label_hfill;
433                 }
434         }
435 }
436
437
438 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
439 {
440         Buffer & buffer = bv_->buffer();
441         Paragraph const & par = text_->getPar(pit);
442
443         pos_type last = par.beginOfBody();
444         BOOST_ASSERT(last > 0);
445
446         // -1 because a label ends with a space that is in the label
447         --last;
448
449         // a separator at this end does not count
450         if (par.isLineSeparator(last))
451                 --last;
452
453         int w = 0;
454         for (pos_type i = row.pos(); i <= last; ++i)
455                 w += singleWidth(pit, i);
456
457         docstring const & label = par.params().labelWidthString();
458         if (label.empty())
459                 return 0;
460
461         FontMetrics const & fm
462                 = theFontMetrics(text_->getLabelFont(buffer, par));
463
464         return max(0, fm.width(label) - w);
465 }
466
467
468 namespace {
469
470 // this needs special handling - only newlines count as a break point
471 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
472 {
473         pos_type const end = par.size();
474
475         for (; i < end; ++i)
476                 if (par.isNewline(i))
477                         return i + 1;
478
479         return end;
480 }
481
482 };
483
484
485 int TextMetrics::labelEnd(pit_type const pit) const
486 {
487         // labelEnd is only needed if the layout fills a flushleft label.
488         if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
489                 return 0;
490         // return the beginning of the body
491         return text_->leftMargin(bv_->buffer(), max_width_, pit);
492 }
493
494
495 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
496                 pit_type pos) const
497 {
498         Buffer & buffer = bv_->buffer();
499         ParagraphMetrics const & pm = par_metrics_[pit];
500         Paragraph const & par = text_->getPar(pit);
501         pos_type const end = par.size();
502         if (pos == end || width < 0)
503                 return end;
504
505         LayoutPtr const & layout = par.layout();
506
507         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
508                 return addressBreakPoint(pos, par);
509
510         pos_type const body_pos = par.beginOfBody();
511
512
513         // Now we iterate through until we reach the right margin
514         // or the end of the par, then choose the possible break
515         // nearest that.
516
517         int label_end = labelEnd(pit);
518         int const left = text_->leftMargin(buffer, max_width_, pit, pos);
519         int x = left;
520
521         // pixel width since last breakpoint
522         int chunkwidth = 0;
523
524         FontIterator fi = FontIterator(buffer, *text_, par, pos);
525         pos_type point = end;
526         pos_type i = pos;
527         for ( ; i < end; ++i, ++fi) {
528                 int thiswidth = pm.singleWidth(i, *fi);
529
530                 // add the auto-hfill from label end to the body
531                 if (body_pos && i == body_pos) {
532                         FontMetrics const & fm = theFontMetrics(
533                                 text_->getLabelFont(buffer, par));
534                         int add = fm.width(layout->labelsep);
535                         if (par.isLineSeparator(i - 1))
536                                 add -= singleWidth(pit, i - 1);
537
538                         add = std::max(add, label_end - x);
539                         thiswidth += add;
540                 }
541
542                 x += thiswidth;
543                 chunkwidth += thiswidth;
544
545                 // break before a character that will fall off
546                 // the right of the row
547                 if (x >= width) {
548                         // if no break before, break here
549                         if (point == end || chunkwidth >= width - left) {
550                                 if (i > pos)
551                                         point = i;
552                                 else
553                                         point = i + 1;
554
555                         }
556                         // exit on last registered breakpoint:
557                         break;
558                 }
559
560                 if (par.isNewline(i)) {
561                         point = i + 1;
562                         break;
563                 }
564                 // Break before...
565                 if (i + 1 < end) {
566                         if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
567                                 point = i + 1;
568                                 break;
569                         }
570                         // ...and after.
571                         if (par.isInset(i) && par.getInset(i)->display()) {
572                                 point = i + 1;
573                                 break;
574                         }
575                 }
576
577                 if (!par.isInset(i) || par.getInset(i)->isChar()) {
578                         // some insets are line separators too
579                         if (par.isLineSeparator(i)) {
580                                 // register breakpoint:
581                                 point = i + 1;
582                                 chunkwidth = 0;
583                         }
584                 }
585         }
586
587         // maybe found one, but the par is short enough.
588         if (i == end && x < width)
589                 point = end;
590
591         // manual labels cannot be broken in LaTeX. But we
592         // want to make our on-screen rendering of footnotes
593         // etc. still break
594         if (body_pos && point < body_pos)
595                 point = body_pos;
596
597         return point;
598 }
599
600
601 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
602                 pos_type const first, pos_type const end) const
603 {
604         Buffer & buffer = bv_->buffer();
605         // get the pure distance
606         ParagraphMetrics const & pm = par_metrics_[pit];
607         Paragraph const & par = text_->getPar(pit);
608         int w = text_->leftMargin(buffer, max_width_, pit, first);
609         int label_end = labelEnd(pit);
610
611         pos_type const body_pos = par.beginOfBody();
612         pos_type i = first;
613
614         if (i < end) {
615                 FontIterator fi = FontIterator(buffer, *text_, par, i);
616                 for ( ; i < end; ++i, ++fi) {
617                         if (body_pos > 0 && i == body_pos) {
618                                 FontMetrics const & fm = theFontMetrics(
619                                         text_->getLabelFont(buffer, par));
620                                 w += fm.width(par.layout()->labelsep);
621                                 if (par.isLineSeparator(i - 1))
622                                         w -= singleWidth(pit, i - 1);
623                                 w = max(w, label_end);
624                         }
625                         w += pm.singleWidth(i, *fi);
626                 }
627         }
628
629         if (body_pos > 0 && body_pos >= end) {
630                 FontMetrics const & fm = theFontMetrics(
631                         text_->getLabelFont(buffer, par));
632                 w += fm.width(par.layout()->labelsep);
633                 if (end > 0 && par.isLineSeparator(end - 1))
634                         w -= singleWidth(pit, end - 1);
635                 w = max(w, label_end);
636         }
637
638         return w + right_margin;
639 }
640
641
642 boost::tuple<int, int> TextMetrics::rowHeight(pit_type const pit, pos_type const first,
643                 pos_type const end) const
644 {
645         Paragraph const & par = text_->getPar(pit);
646         // get the maximum ascent and the maximum descent
647         double layoutasc = 0;
648         double layoutdesc = 0;
649         double const dh = defaultRowHeight();
650
651         // ok, let us initialize the maxasc and maxdesc value.
652         // Only the fontsize count. The other properties
653         // are taken from the layoutfont. Nicer on the screen :)
654         LayoutPtr const & layout = par.layout();
655
656         // as max get the first character of this row then it can
657         // increase but not decrease the height. Just some point to
658         // start with so we don't have to do the assignment below too
659         // often.
660         Buffer const & buffer = bv_->buffer();
661         Font font = text_->getFont(buffer, par, first);
662         Font::FONT_SIZE const tmpsize = font.size();
663         font = text_->getLayoutFont(buffer, pit);
664         Font::FONT_SIZE const size = font.size();
665         font.setSize(tmpsize);
666
667         Font labelfont = text_->getLabelFont(buffer, par);
668
669         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
670         FontMetrics const & fontmetrics = theFontMetrics(font);
671
672         // these are minimum values
673         double const spacing_val = layout->spacing.getValue()
674                 * text_->spacing(buffer, par);
675         //lyxerr << "spacing_val = " << spacing_val << endl;
676         int maxasc  = int(fontmetrics.maxAscent()  * spacing_val);
677         int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
678
679         // insets may be taller
680         InsetList::const_iterator ii = par.insetlist.begin();
681         InsetList::const_iterator iend = par.insetlist.end();
682         for ( ; ii != iend; ++ii) {
683                 if (ii->pos >= first && ii->pos < end) {
684                         maxasc  = max(maxasc,  ii->inset->ascent());
685                         maxdesc = max(maxdesc, ii->inset->descent());
686                 }
687         }
688
689         // Check if any custom fonts are larger (Asger)
690         // This is not completely correct, but we can live with the small,
691         // cosmetic error for now.
692         int labeladdon = 0;
693
694         Font::FONT_SIZE maxsize =
695                 par.highestFontInRange(first, end, size);
696         if (maxsize > font.size()) {
697                 // use standard paragraph font with the maximal size
698                 Font maxfont = font;
699                 maxfont.setSize(maxsize);
700                 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
701                 maxasc  = max(maxasc,  maxfontmetrics.maxAscent());
702                 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
703         }
704
705         // This is nicer with box insets:
706         ++maxasc;
707         ++maxdesc;
708
709         ParagraphList const & pars = text_->paragraphs();
710
711         // is it a top line?
712         if (first == 0) {
713                 BufferParams const & bufparams = buffer.params();
714                 // some parskips VERY EASY IMPLEMENTATION
715                 if (bufparams.paragraph_separation
716                     == BufferParams::PARSEP_SKIP
717                         && par.ownerCode() != Inset::ERT_CODE
718                         && par.ownerCode() != Inset::LISTINGS_CODE
719                         && pit > 0
720                         && ((layout->isParagraph() && par.getDepth() == 0)
721                             || (pars[pit - 1].layout()->isParagraph()
722                                 && pars[pit - 1].getDepth() == 0)))
723                 {
724                                 maxasc += bufparams.getDefSkip().inPixels(*bv_);
725                 }
726
727                 if (par.params().startOfAppendix())
728                         maxasc += int(3 * dh);
729
730                 // This is special code for the chapter, since the label of this
731                 // layout is printed in an extra row
732                 if (layout->counter == "chapter"
733                     && !par.params().labelString().empty()) {
734                         labeladdon = int(labelfont_metrics.maxHeight()
735                                      * layout->spacing.getValue()
736                                      * text_->spacing(buffer, par));
737                 }
738
739                 // special code for the top label
740                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
741                      || layout->labeltype == LABEL_BIBLIO
742                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
743                     && isFirstInSequence(pit, pars)
744                     && !par.getLabelstring().empty())
745                 {
746                         labeladdon = int(
747                                   labelfont_metrics.maxHeight()
748                                         * layout->spacing.getValue()
749                                         * text_->spacing(buffer, par)
750                                 + (layout->topsep + layout->labelbottomsep) * dh);
751                 }
752
753                 // Add the layout spaces, for example before and after
754                 // a section, or between the items of a itemize or enumerate
755                 // environment.
756
757                 pit_type prev = depthHook(pit, pars, par.getDepth());
758                 Paragraph const & prevpar = pars[prev];
759                 if (prev != pit
760                     && prevpar.layout() == layout
761                     && prevpar.getDepth() == par.getDepth()
762                     && prevpar.getLabelWidthString()
763                                         == par.getLabelWidthString()) {
764                         layoutasc = layout->itemsep * dh;
765                 } else if (pit != 0 || first != 0) {
766                         if (layout->topsep > 0)
767                                 layoutasc = layout->topsep * dh;
768                 }
769
770                 prev = outerHook(pit, pars);
771                 if (prev != pit_type(pars.size())) {
772                         maxasc += int(pars[prev].layout()->parsep * dh);
773                 } else if (pit != 0) {
774                         Paragraph const & prevpar = pars[pit - 1];
775                         if (prevpar.getDepth() != 0 ||
776                                         prevpar.layout() == layout) {
777                                 maxasc += int(layout->parsep * dh);
778                         }
779                 }
780         }
781
782         // is it a bottom line?
783         if (end >= par.size()) {
784                 // add the layout spaces, for example before and after
785                 // a section, or between the items of a itemize or enumerate
786                 // environment
787                 pit_type nextpit = pit + 1;
788                 if (nextpit != pit_type(pars.size())) {
789                         pit_type cpit = pit;
790                         double usual = 0;
791                         double unusual = 0;
792
793                         if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
794                                 usual = pars[cpit].layout()->bottomsep * dh;
795                                 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
796                                 if (pars[cpit].layout() != pars[nextpit].layout()
797                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
798                                 {
799                                         unusual = pars[cpit].layout()->bottomsep * dh;
800                                 }
801                                 layoutdesc = max(unusual, usual);
802                         } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
803                                 if (pars[cpit].layout() != pars[nextpit].layout()
804                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
805                                         layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
806                         }
807                 }
808         }
809
810         // incalculate the layout spaces
811         maxasc  += int(layoutasc  * 2 / (2 + pars[pit].getDepth()));
812         maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
813
814         // FIXME: the correct way is to do the following is to move the
815         // following code in another method specially tailored for the
816         // main Text. The following test is thus bogus.
817         // Top and bottom margin of the document (only at top-level)
818         if (main_text_) {
819                 if (pit == 0 && first == 0)
820                         maxasc += 20;
821                 if (pit + 1 == pit_type(pars.size()) &&
822                     end == par.size() &&
823                                 !(end > 0 && par.isNewline(end - 1)))
824                         maxdesc += 20;
825         }
826
827         return boost::make_tuple(maxasc + labeladdon, maxdesc);
828 }
829
830
831 // x is an absolute screen coord
832 // returns the column near the specified x-coordinate of the row
833 // x is set to the real beginning of this column
834 pos_type TextMetrics::getColumnNearX(pit_type const pit,
835                 Row const & row, int & x, bool & boundary) const
836 {
837         Buffer const & buffer = bv_->buffer();
838
839         /// For the main Text, it is possible that this pit is not
840         /// yet in the CoordCache when moving cursor up.
841         /// x Paragraph coordinate is always 0 for main text anyway.
842         int const xo = main_text_? 0 : bv_->coordCache().get(text_, pit).x_;
843         x -= xo;
844         Paragraph const & par = text_->getPar(pit);
845         ParagraphMetrics const & pm = par_metrics_[pit];
846         Bidi bidi;
847         bidi.computeTables(par, buffer, row);
848
849         pos_type vc = row.pos();
850         pos_type end = row.endpos();
851         pos_type c = 0;
852         LayoutPtr const & layout = par.layout();
853
854         bool left_side = false;
855
856         pos_type body_pos = par.beginOfBody();
857
858         double tmpx = row.x;
859         double last_tmpx = tmpx;
860
861         if (body_pos > 0 &&
862             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
863                 body_pos = 0;
864
865         // check for empty row
866         if (vc == end) {
867                 x = int(tmpx) + xo;
868                 return 0;
869         }
870
871         while (vc < end && tmpx <= x) {
872                 c = bidi.vis2log(vc);
873                 last_tmpx = tmpx;
874                 if (body_pos > 0 && c == body_pos - 1) {
875                         FontMetrics const & fm = theFontMetrics(
876                                 text_->getLabelFont(buffer, par));
877                         tmpx += row.label_hfill + fm.width(layout->labelsep);
878                         if (par.isLineSeparator(body_pos - 1))
879                                 tmpx -= singleWidth(pit, body_pos - 1);
880                 }
881
882                 if (pm.hfillExpansion(row, c)) {
883                         tmpx += singleWidth(pit, c);
884                         if (c >= body_pos)
885                                 tmpx += row.hfill;
886                         else
887                                 tmpx += row.label_hfill;
888                 } else if (par.isSeparator(c)) {
889                         tmpx += singleWidth(pit, c);
890                         if (c >= body_pos)
891                                 tmpx += row.separator;
892                 } else {
893                         tmpx += singleWidth(pit, c);
894                 }
895                 ++vc;
896         }
897
898         if ((tmpx + last_tmpx) / 2 > x) {
899                 tmpx = last_tmpx;
900                 left_side = true;
901         }
902
903         BOOST_ASSERT(vc <= end);  // This shouldn't happen.
904
905         boundary = false;
906         // This (rtl_support test) is not needed, but gives
907         // some speedup if rtl_support == false
908         bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
909
910         // If lastrow is false, we don't need to compute
911         // the value of rtl.
912         bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
913         if (lastrow &&
914             ((rtl  &&  left_side && vc == row.pos() && x < tmpx - 5) ||
915              (!rtl && !left_side && vc == end  && x > tmpx + 5)))
916                 c = end;
917         else if (vc == row.pos()) {
918                 c = bidi.vis2log(vc);
919                 if (bidi.level(c) % 2 == 1)
920                         ++c;
921         } else {
922                 c = bidi.vis2log(vc - 1);
923                 bool const rtl = (bidi.level(c) % 2 == 1);
924                 if (left_side == rtl) {
925                         ++c;
926                         boundary = text_->isRTLBoundary(buffer, par, c);
927                 }
928         }
929
930 // I believe this code is not needed anymore (Jug 20050717)
931 #if 0
932         // The following code is necessary because the cursor position past
933         // the last char in a row is logically equivalent to that before
934         // the first char in the next row. That's why insets causing row
935         // divisions -- Newline and display-style insets -- must be treated
936         // specially, so cursor up/down doesn't get stuck in an air gap -- MV
937         // Newline inset, air gap below:
938         if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
939                 if (bidi.level(end -1) % 2 == 0)
940                         tmpx -= singleWidth(pit, end - 1);
941                 else
942                         tmpx += singleWidth(pit, end - 1);
943                 c = end - 1;
944         }
945
946         // Air gap above display inset:
947         if (row.pos() < end && c >= end && end < par.size()
948             && par.isInset(end) && par.getInset(end)->display()) {
949                 c = end - 1;
950         }
951         // Air gap below display inset:
952         if (row.pos() < end && c >= end && par.isInset(end - 1)
953             && par.getInset(end - 1)->display()) {
954                 c = end - 1;
955         }
956 #endif
957
958         x = int(tmpx) + xo;
959         pos_type const col = c - row.pos();
960
961         if (!c || end == par.size())
962                 return col;
963
964         if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
965                 boundary = true;
966                 return col;
967         }
968
969         return min(col, end - 1 - row.pos());
970 }
971
972
973 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
974 {
975         ParagraphMetrics const & pm = par_metrics_[pit];
976         BOOST_ASSERT(!pm.rows().empty());
977         BOOST_ASSERT(row < int(pm.rows().size()));
978         bool bound = false;
979         Row const & r = pm.rows()[row];
980         return r.pos() + getColumnNearX(pit, r, x, bound);
981 }
982
983
984 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
985 {
986         Buffer const & buffer = bv_->buffer();
987         ParagraphMetrics const & pm = par_metrics_[pit];
988
989         return pm.singleWidth(pos, text_->getFont(buffer, text_->getPar(pit), pos));
990 }
991
992
993 // only used for inset right now. should also be used for main text
994 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
995 {
996         if (par_metrics_.empty())
997                 return;
998
999         ParMetricsCache::const_iterator it = par_metrics_.begin();
1000         ParMetricsCache::const_iterator const end = par_metrics_.end();
1001         y -= it->second.ascent();
1002         for (; it != end; ++it) {
1003                 ParagraphMetrics const & pmi = it->second;
1004                 y += pmi.ascent();
1005                 drawParagraph(pi, it->first, x, y);
1006                 y += pmi.descent();
1007         }
1008 }
1009
1010
1011 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1012 {
1013 //      lyxerr << "  paintPar: pit: " << pit << " at y: " << y << endl;
1014         int const ww = bv_->workHeight();
1015
1016         bv_->coordCache().parPos()[text_][pit] = Point(x, y);
1017
1018         ParagraphMetrics const & pm = par_metrics_[pit];
1019         if (pm.rows().empty())
1020                 return;
1021
1022         RowList::const_iterator const rb = pm.rows().begin();
1023         RowList::const_iterator const re = pm.rows().end();
1024
1025         Bidi bidi;
1026
1027         y -= rb->ascent();
1028         for (RowList::const_iterator rit = rb; rit != re; ++rit) {
1029                 y += rit->ascent();
1030
1031                 bool const inside = (y + rit->descent() >= 0
1032                         && y - rit->ascent() < ww);
1033                 // it is not needed to draw on screen if we are not inside.
1034                 pi.pain.setDrawingEnabled(inside);
1035                 RowPainter rp(pi, *text_, pit, *rit, bidi, x, y);
1036
1037                 // Row signature; has row changed since last paint?
1038                 bool row_has_changed = rit->changed();
1039                 
1040                 if (!pi.full_repaint && !row_has_changed) {
1041                         // Paint the only the insets if the text itself is
1042                         // unchanged.
1043                         rp.paintOnlyInsets();
1044                         y += rit->descent();
1045                         continue;
1046                 }
1047
1048                 // Paint the row if a full repaint has been requested or it has
1049                 // changed.
1050                 // Clear background of this row
1051                 // (if paragraph background was not cleared)
1052                 if (!pi.full_repaint && row_has_changed) {
1053                         pi.pain.fillRectangle(x, y - rit->ascent(),
1054                         width(), rit->height(),
1055                         text_->backgroundColor());
1056                 }
1057
1058                 // Instrumentation for testing row cache (see also
1059                 // 12 lines lower):
1060                 if (lyxerr.debugging(Debug::PAINTING)) {
1061                         if (text_->isMainText(bv_->buffer()))
1062                                 LYXERR(Debug::PAINTING) << "\n{" <<
1063                                 pi.full_repaint << row_has_changed << "}";
1064                         else
1065                                 LYXERR(Debug::PAINTING) << "[" <<
1066                                 pi.full_repaint << row_has_changed << "]";
1067                 }
1068
1069                 // Backup full_repaint status and force full repaint
1070                 // for inner insets as the Row has been cleared out.
1071                 bool tmp = pi.full_repaint;
1072                 pi.full_repaint = true;
1073                 rp.paintAppendix();
1074                 rp.paintDepthBar();
1075                 rp.paintChangeBar();
1076                 if (rit == rb)
1077                         rp.paintFirst();
1078                 rp.paintText();
1079                 if (rit + 1 == re)
1080                         rp.paintLast();
1081                 y += rit->descent();
1082                 // Restore full_repaint status.
1083                 pi.full_repaint = tmp;
1084         }
1085         // Re-enable screen drawing for future use of the painter.
1086         pi.pain.setDrawingEnabled(true);
1087
1088         //LYXERR(Debug::PAINTING) << "." << endl;
1089 }
1090
1091
1092 // only used for inset right now. should also be used for main text
1093 void TextMetrics::drawSelection(PainterInfo & pi, int x, int) const
1094 {
1095         Cursor & cur = bv_->cursor();
1096         if (!cur.selection())
1097                 return;
1098         if (!ptr_cmp(cur.text(), text_))
1099                 return;
1100
1101         LYXERR(Debug::DEBUG)
1102                 << BOOST_CURRENT_FUNCTION
1103                 << "draw selection at " << x
1104                 << endl;
1105
1106         DocIterator beg = cur.selectionBegin();
1107         DocIterator end = cur.selectionEnd();
1108
1109         // the selection doesn't touch the visible screen?
1110         if (bv_funcs::status(bv_, beg) == bv_funcs::CUR_BELOW
1111             || bv_funcs::status(bv_, end) == bv_funcs::CUR_ABOVE)
1112                 return;
1113
1114         ParagraphMetrics const & pm1 = par_metrics_[beg.pit()];
1115         ParagraphMetrics const & pm2 = par_metrics_[end.pit()];
1116         Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
1117         Row const & row2 = pm2.getRow(end.pos(), end.boundary());
1118
1119         // clip above
1120         int middleTop;
1121         bool const clipAbove = 
1122                 (bv_funcs::status(bv_, beg) == bv_funcs::CUR_ABOVE);
1123         if (clipAbove)
1124                 middleTop = 0;
1125         else
1126                 middleTop = bv_funcs::getPos(*bv_, beg, beg.boundary()).y_ + row1.descent();
1127         
1128         // clip below
1129         int middleBottom;
1130         bool const clipBelow = 
1131                 (bv_funcs::status(bv_, end) == bv_funcs::CUR_BELOW);
1132         if (clipBelow)
1133                 middleBottom = bv_->workHeight();
1134         else
1135                 middleBottom = bv_funcs::getPos(*bv_, end, end.boundary()).y_ - row2.ascent();
1136
1137         // start and end in the same line?
1138         if (!(clipAbove || clipBelow) && &row1 == &row2)
1139                 // then only draw this row's selection
1140                 drawRowSelection(pi, x, row1, beg, end, false, false);
1141         else {
1142                 if (!clipAbove) {
1143                         // get row end
1144                         DocIterator begRowEnd = beg;
1145                         begRowEnd.pos() = row1.endpos();
1146                         begRowEnd.boundary(true);
1147                         
1148                         // draw upper rectangle
1149                         drawRowSelection(pi, x, row1, beg, begRowEnd, false, true);
1150                 }
1151                         
1152                 if (middleTop < middleBottom) {
1153                         // draw middle rectangle
1154                         pi.pain.fillRectangle(x, middleTop, width(), middleBottom - middleTop,
1155                                 Color::selection);
1156                 }
1157
1158                 if (!clipBelow) {
1159                         // get row begin
1160                         DocIterator endRowBeg = end;
1161                         endRowBeg.pos() = row2.pos();
1162                         endRowBeg.boundary(false);
1163                         
1164                         // draw low rectangle
1165                         drawRowSelection(pi, x, row2, endRowBeg, end, true, false);
1166                 }
1167         }
1168 }
1169
1170
1171 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
1172                 DocIterator const & beg, DocIterator const & end,
1173                 bool drawOnBegMargin, bool drawOnEndMargin) const
1174 {
1175         Buffer & buffer = bv_->buffer();
1176         DocIterator cur = beg;
1177         int x1 = text_->cursorX(*bv_, beg.top(), beg.boundary());
1178         int x2 = text_->cursorX(*bv_, end.top(), end.boundary());
1179         int y1 = bv_funcs::getPos(*bv_, cur, cur.boundary()).y_ - row.ascent();
1180         int y2 = y1 + row.height();
1181         
1182         // draw the margins
1183         if (drawOnBegMargin) {
1184                 if (text_->isRTL(buffer, beg.paragraph()))
1185                         pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color::selection);
1186                 else
1187                         pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color::selection);
1188         }
1189         
1190         if (drawOnEndMargin) {
1191                 if (text_->isRTL(buffer, beg.paragraph()))
1192                         pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color::selection);
1193                 else
1194                         pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color::selection);
1195         }
1196         
1197         // if we are on a boundary from the beginning, it's probably
1198         // a RTL boundary and we jump to the other side directly as this
1199         // segement is 0-size and confuses the logic below
1200         if (cur.boundary())
1201                 cur.boundary(false);
1202         
1203         // go through row and draw from RTL boundary to RTL boundary
1204         while (cur < end) {
1205                 bool drawNow = false;
1206                 
1207                 // simplified cursorRight code below which does not
1208                 // descend into insets and which does not go into the
1209                 // next line. Compare the logic with the original cursorRight
1210                 
1211                 // if left of boundary -> just jump to right side
1212                 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
1213                 if (cur.boundary()) {
1214                         cur.boundary(false);
1215                 }       else if (text_->isRTLBoundary(buffer, cur.paragraph(), cur.pos() + 1)) {
1216                         // in front of RTL boundary -> Stay on this side of the boundary because:
1217                         //   ab|cDDEEFFghi -> abc|DDEEFFghi
1218                         ++cur.pos();
1219                         cur.boundary(true);
1220                         drawNow = true;
1221                 } else {
1222                         // move right
1223                         ++cur.pos();
1224                         
1225                         // line end?
1226                         if (cur.pos() == row.endpos())
1227                                 cur.boundary(true);
1228                 }
1229                         
1230                 if (x1 == -1) {
1231                         // the previous segment was just drawn, now the next starts
1232                         x1 = text_->cursorX(*bv_, cur.top(), cur.boundary());
1233                 }
1234                 
1235                 if (!(cur < end) || drawNow) {
1236                         x2 = text_->cursorX(*bv_, cur.top(), cur.boundary());
1237                         pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
1238                                 Color::selection);
1239                         
1240                         // reset x1, so it is set again next round (which will be on the 
1241                         // right side of a boundary or at the selection end)
1242                         x1 = -1;
1243                 }
1244         }
1245 }
1246
1247 //int Text::pos2x(pit_type pit, pos_type pos) const
1248 //{
1249 //      ParagraphMetrics const & pm = par_metrics_[pit];
1250 //      Row const & r = pm.rows()[row];
1251 //      int x = 0;
1252 //      pos -= r.pos();
1253 //}
1254
1255
1256 int defaultRowHeight()
1257 {
1258         return int(theFontMetrics(Font(Font::ALL_SANE)).maxHeight() *  1.2);
1259 }
1260
1261 } // namespace lyx