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