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