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