]> git.lyx.org Git - lyx.git/blob - src/TextMetrics.cpp
716e1fd77ba30cc4821b6fca09fe1fedc9c89a18
[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 = par_metrics_[pit];
158                 h += pm.height();
159                 if (w < pm.width())
160                         w = pm.width();
161         }
162
163         dim.wid = w;
164         dim.asc = par_metrics_[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         // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
189         // redoParagraph() recursively inside parMetrics.
190         Dimension old_dim = parMetrics(pit, false).dim();
191         ParagraphMetrics & pm = par_metrics_[pit];
192         pm.reset(par);
193
194         Buffer & buffer = bv_->buffer();
195         main_text_ = (text_ == &buffer.text());
196         bool changed = false;
197
198         // FIXME This check ought to be done somewhere else. It is the reason
199         // why text_ is not     const. But then, where else to do it?
200         // Well, how can you end up with either (a) a biblio environment that
201         // has no InsetBibitem or (b) a biblio environment with more than one
202         // InsetBibitem? I think the answer is: when paragraphs are merged;
203         // when layout is set; when material is pasted.
204         int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
205         if (moveCursor > 0)
206                 const_cast<Cursor &>(bv_->cursor()).posRight();
207         else if (moveCursor < 0) {
208                 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
209                 if (cursor.pos() >= -moveCursor)
210                         cursor.posLeft();
211         }
212
213         // Optimisation: this is used in the next two loops
214         // so better to calculate that once here.
215         int const right_margin = rightMargin(pm);
216
217         // redo insets
218         // FIXME: We should always use getFont(), see documentation of
219         // noFontChange() in Inset.h.
220         Font const bufferfont = buffer.params().getFont();
221         InsetList::const_iterator ii = par.insetlist.begin();
222         InsetList::const_iterator iend = par.insetlist.end();
223         for (; ii != iend; ++ii) {
224                 Dimension dim;
225                 int const w = max_width_ - text_->leftMargin(buffer, max_width_, pit, ii->pos)
226                         - right_margin;
227                 Font const & font = ii->inset->noFontChange() ?
228                         bufferfont : text_->getFont(buffer, par, ii->pos);
229                 MetricsInfo mi(bv_, font, w);
230                 changed |= ii->inset->metrics(mi, dim);
231         }
232
233         par.setBeginOfBody();
234         pos_type z = 0;
235         // maximum pixel width of a row
236         int width = max_width_ - right_margin; // - leftMargin(buffer, max_width_, pit, row);
237         do {
238                 Row row(z);
239                 rowBreakPoint(width, pit, row);
240                 setRowWidth(right_margin, pit, row);
241                 setHeightOfRow(pit, row);
242                 pm.rows().push_back(row);
243                 pm.dim().wid = std::max(pm.dim().wid, row.width());
244                 pm.dim().des += row.height();
245                 z = row.endpos();
246         } while (z < par.size());
247
248         // Make sure that if a par ends in newline, there is one more row
249         // under it
250         if (z > 0 && par.isNewline(z - 1)) {
251                 Row row(z);
252                 row.endpos(z);
253                 setRowWidth(right_margin, pit, row);
254                 setHeightOfRow(pit, row);
255                 pm.rows().push_back(row);
256                 pm.dim().des += row.height();
257         }
258
259         pm.dim().asc += pm.rows()[0].ascent();
260         pm.dim().des -= pm.rows()[0].ascent();
261
262         changed |= old_dim.height() != pm.dim().height();
263
264         // Update the row change statuses. The painter will need that info
265         // in order to know which row has to be repainted.
266         pm.updateRowChangeStatus();
267
268         return changed;
269 }
270
271 RowMetrics TextMetrics::computeRowMetrics(pit_type const pit,
272                 Row const & row) const
273 {
274         RowMetrics result;
275         Buffer & buffer = bv_->buffer();
276         Paragraph const & par = text_->getPar(pit);
277
278         double w = dim_.wid - row.width();
279
280         bool const is_rtl = text_->isRTL(buffer, par);
281         if (is_rtl)
282                 result.x = rightMargin(pit);
283         else
284                 result.x = text_->leftMargin(buffer, max_width_, pit, row.pos());
285
286         // is there a manual margin with a manual label
287         LayoutPtr const & layout = par.layout();
288
289         if (layout->margintype == MARGIN_MANUAL
290             && layout->labeltype == LABEL_MANUAL) {
291                 /// We might have real hfills in the label part
292                 int nlh = numberOfLabelHfills(par, row);
293
294                 // A manual label par (e.g. List) has an auto-hfill
295                 // between the label text and the body of the
296                 // paragraph too.
297                 // But we don't want to do this auto hfill if the par
298                 // is empty.
299                 if (!par.empty())
300                         ++nlh;
301
302                 if (nlh && !par.getLabelWidthString().empty())
303                         result.label_hfill = labelFill(pit, row) / double(nlh);
304         }
305
306         // are there any hfills in the row?
307         int const nh = numberOfHfills(par, row);
308
309         if (nh) {
310                 if (w > 0)
311                         result.hfill = w / nh;
312         // we don't have to look at the alignment if it is ALIGN_LEFT and
313         // if the row is already larger then the permitted width as then
314         // we force the LEFT_ALIGN'edness!
315         } else if (int(row.width()) < max_width_) {
316                 // is it block, flushleft or flushright?
317                 // set x how you need it
318                 int align;
319                 if (par.params().align() == LYX_ALIGN_LAYOUT)
320                         align = layout->align;
321                 else
322                         align = par.params().align();
323
324                 // Display-style insets should always be on a centred row
325                 // The test on par.size() is to catch zero-size pars, which
326                 // would trigger the assert in Paragraph::getInset().
327                 //inset = par.size() ? par.getInset(row.pos()) : 0;
328                 if (row.pos() < par.size()
329                     && par.isInset(row.pos()))
330                 {
331                     switch(par.getInset(row.pos())->display()) {
332                         case Inset::AlignLeft:
333                                 align = LYX_ALIGN_BLOCK;
334                                 break;
335                         case Inset::AlignCenter:
336                                 align = LYX_ALIGN_CENTER;
337                                 break;
338                         case Inset::Inline:
339                         case Inset::AlignRight:
340                                 // unchanged (use align)
341                                 break;
342                     }
343                 }
344
345                 switch (align) {
346                 case LYX_ALIGN_BLOCK: {
347                         int const ns = numberOfSeparators(par, row);
348                         bool disp_inset = false;
349                         if (row.endpos() < par.size()) {
350                                 Inset const * in = par.getInset(row.endpos());
351                                 if (in)
352                                         disp_inset = in->display();
353                         }
354                         // If we have separators, this is not the last row of a
355                         // par, does not end in newline, and is not row above a
356                         // display inset... then stretch it
357                         if (ns
358                             && row.endpos() < par.size()
359                             && !par.isNewline(row.endpos() - 1)
360                             && !disp_inset
361                                 ) {
362                                 result.separator = w / ns;
363                         } else if (is_rtl) {
364                                 result.x += w;
365                         }
366                         break;
367                 }
368                 case LYX_ALIGN_RIGHT:
369                         result.x += w;
370                         break;
371                 case LYX_ALIGN_CENTER:
372                         result.x += w / 2;
373                         break;
374                 }
375         }
376
377         if (is_rtl) {
378                 pos_type body_pos = par.beginOfBody();
379                 pos_type end = row.endpos();
380
381                 if (body_pos > 0
382                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
383                 {
384                         result.x += theFontMetrics(text_->getLabelFont(buffer, par)).
385                                 width(layout->labelsep);
386                         if (body_pos <= end)
387                                 result.x += result.label_hfill;
388                 }
389         }
390
391         return result;
392 }
393
394
395 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
396 {
397         Buffer & buffer = bv_->buffer();
398         Paragraph const & par = text_->getPar(pit);
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 += singleWidth(pit, 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         ParagraphMetrics const & pm = par_metrics_[pit];
457         Paragraph const & par = text_->getPar(pit);
458         pos_type const end = par.size();
459         pos_type const pos = row.pos();
460         if (pos == end) {
461                 row.endpos(end);
462                 return;
463         }
464
465         if (width < 0) {
466                 row.endpos(end);
467                 return;
468         }
469
470         LayoutPtr const & layout = par.layout();
471
472         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
473                 row.endpos(addressBreakPoint(pos, par));
474                 return;
475         }
476
477         pos_type const body_pos = par.beginOfBody();
478
479
480         // Now we iterate through until we reach the right margin
481         // or the end of the par, then choose the possible break
482         // nearest that.
483
484         int label_end = labelEnd(pit);
485         int const left = text_->leftMargin(buffer, max_width_, pit, pos);
486         int x = left;
487
488         // pixel width since last breakpoint
489         int chunkwidth = 0;
490
491         FontIterator fi = FontIterator(buffer, *text_, par, pos);
492         pos_type point = end;
493         pos_type i = pos;
494         for ( ; i < end; ++i, ++fi) {
495                 int thiswidth = pm.singleWidth(i, *fi);
496
497                 // add the auto-hfill from label end to the body
498                 if (body_pos && i == body_pos) {
499                         FontMetrics const & fm = theFontMetrics(
500                                 text_->getLabelFont(buffer, par));
501                         int add = fm.width(layout->labelsep);
502                         if (par.isLineSeparator(i - 1))
503                                 add -= singleWidth(pit, 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         ParagraphMetrics const & pm = par_metrics_[pit];
575         Paragraph const & par = text_->getPar(pit);
576         int w = text_->leftMargin(buffer, max_width_, pit, row.pos());
577         int label_end = labelEnd(pit);
578
579         pos_type const body_pos = par.beginOfBody();
580         pos_type i = row.pos();
581
582         if (i < end) {
583                 FontIterator fi = FontIterator(buffer, *text_, par, i);
584                 for ( ; i < end; ++i, ++fi) {
585                         if (body_pos > 0 && i == body_pos) {
586                                 FontMetrics const & fm = theFontMetrics(
587                                         text_->getLabelFont(buffer, par));
588                                 w += fm.width(par.layout()->labelsep);
589                                 if (par.isLineSeparator(i - 1))
590                                         w -= singleWidth(pit, i - 1);
591                                 w = max(w, label_end);
592                         }
593                         w += pm.singleWidth(i, *fi);
594                 }
595         }
596
597         if (body_pos > 0 && body_pos >= end) {
598                 FontMetrics const & fm = theFontMetrics(
599                         text_->getLabelFont(buffer, par));
600                 w += fm.width(par.layout()->labelsep);
601                 if (end > 0 && par.isLineSeparator(end - 1))
602                         w -= singleWidth(pit, 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         LayoutPtr 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 maxfont = font;
668                 maxfont.setSize(maxsize);
669                 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
670                 maxasc  = max(maxasc,  maxfontmetrics.maxAscent());
671                 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
672         }
673
674         // This is nicer with box insets:
675         ++maxasc;
676         ++maxdesc;
677
678         row.ascent(maxasc);
679         ParagraphList const & pars = text_->paragraphs();
680
681         // is it a top line?
682         if (row.pos() == 0) {
683                 BufferParams const & bufparams = buffer.params();
684                 // some parskips VERY EASY IMPLEMENTATION
685                 if (bufparams.paragraph_separation
686                     == BufferParams::PARSEP_SKIP
687                         && par.ownerCode() != Inset::ERT_CODE
688                         && par.ownerCode() != Inset::LISTINGS_CODE
689                         && pit > 0
690                         && ((layout->isParagraph() && par.getDepth() == 0)
691                             || (pars[pit - 1].layout()->isParagraph()
692                                 && pars[pit - 1].getDepth() == 0)))
693                 {
694                                 maxasc += bufparams.getDefSkip().inPixels(*bv_);
695                 }
696
697                 if (par.params().startOfAppendix())
698                         maxasc += int(3 * dh);
699
700                 // This is special code for the chapter, since the label of this
701                 // layout is printed in an extra row
702                 if (layout->counter == "chapter"
703                     && !par.params().labelString().empty()) {
704                         labeladdon = int(labelfont_metrics.maxHeight()
705                                      * layout->spacing.getValue()
706                                      * text_->spacing(buffer, par));
707                 }
708
709                 // special code for the top label
710                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
711                      || layout->labeltype == LABEL_BIBLIO
712                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
713                     && isFirstInSequence(pit, pars)
714                     && !par.getLabelstring().empty())
715                 {
716                         labeladdon = int(
717                                   labelfont_metrics.maxHeight()
718                                         * layout->spacing.getValue()
719                                         * text_->spacing(buffer, par)
720                                 + (layout->topsep + layout->labelbottomsep) * dh);
721                 }
722
723                 // Add the layout spaces, for example before and after
724                 // a section, or between the items of a itemize or enumerate
725                 // environment.
726
727                 pit_type prev = depthHook(pit, pars, par.getDepth());
728                 Paragraph const & prevpar = pars[prev];
729                 if (prev != pit
730                     && prevpar.layout() == layout
731                     && prevpar.getDepth() == par.getDepth()
732                     && prevpar.getLabelWidthString()
733                                         == par.getLabelWidthString()) {
734                         layoutasc = layout->itemsep * dh;
735                 } else if (pit != 0 || row.pos() != 0) {
736                         if (layout->topsep > 0)
737                                 layoutasc = layout->topsep * dh;
738                 }
739
740                 prev = outerHook(pit, pars);
741                 if (prev != pit_type(pars.size())) {
742                         maxasc += int(pars[prev].layout()->parsep * dh);
743                 } else if (pit != 0) {
744                         Paragraph const & prevpar = pars[pit - 1];
745                         if (prevpar.getDepth() != 0 ||
746                                         prevpar.layout() == layout) {
747                                 maxasc += int(layout->parsep * dh);
748                         }
749                 }
750         }
751
752         // is it a bottom line?
753         if (row.endpos() >= par.size()) {
754                 // add the layout spaces, for example before and after
755                 // a section, or between the items of a itemize or enumerate
756                 // environment
757                 pit_type nextpit = pit + 1;
758                 if (nextpit != pit_type(pars.size())) {
759                         pit_type cpit = pit;
760                         double usual = 0;
761                         double unusual = 0;
762
763                         if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
764                                 usual = pars[cpit].layout()->bottomsep * dh;
765                                 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
766                                 if (pars[cpit].layout() != pars[nextpit].layout()
767                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
768                                 {
769                                         unusual = pars[cpit].layout()->bottomsep * dh;
770                                 }
771                                 layoutdesc = max(unusual, usual);
772                         } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
773                                 if (pars[cpit].layout() != pars[nextpit].layout()
774                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
775                                         layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
776                         }
777                 }
778         }
779
780         // incalculate the layout spaces
781         maxasc  += int(layoutasc  * 2 / (2 + pars[pit].getDepth()));
782         maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
783
784         // FIXME: the correct way is to do the following is to move the
785         // following code in another method specially tailored for the
786         // main Text. The following test is thus bogus.
787         // Top and bottom margin of the document (only at top-level)
788         if (main_text_) {
789                 if (pit == 0 && row.pos() == 0)
790                         maxasc += 20;
791                 if (pit + 1 == pit_type(pars.size()) &&
792                     row.endpos() == par.size() &&
793                                 !(row.endpos() > 0 && par.isNewline(row.endpos() - 1)))
794                         maxdesc += 20;
795         }
796
797         row.ascent(maxasc + labeladdon);
798         row.descent(maxdesc);
799 }
800
801
802 // x is an absolute screen coord
803 // returns the column near the specified x-coordinate of the row
804 // x is set to the real beginning of this column
805 pos_type TextMetrics::getColumnNearX(pit_type const pit,
806                 Row const & row, int & x, bool & boundary) const
807 {
808         Buffer const & buffer = bv_->buffer();
809
810         /// For the main Text, it is possible that this pit is not
811         /// yet in the CoordCache when moving cursor up.
812         /// x Paragraph coordinate is always 0 for main text anyway.
813         int const xo = main_text_? 0 : bv_->coordCache().get(text_, pit).x_;
814         x -= xo;
815         RowMetrics const r = computeRowMetrics(pit, row);
816         Paragraph const & par = text_->getPar(pit);
817         Bidi bidi;
818         bidi.computeTables(par, buffer, row);
819
820         pos_type vc = row.pos();
821         pos_type end = row.endpos();
822         pos_type c = 0;
823         LayoutPtr const & layout = par.layout();
824
825         bool left_side = false;
826
827         pos_type body_pos = par.beginOfBody();
828
829         double tmpx = r.x;
830         double last_tmpx = tmpx;
831
832         if (body_pos > 0 &&
833             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
834                 body_pos = 0;
835
836         // check for empty row
837         if (vc == end) {
838                 x = int(tmpx) + xo;
839                 return 0;
840         }
841
842         while (vc < end && tmpx <= x) {
843                 c = bidi.vis2log(vc);
844                 last_tmpx = tmpx;
845                 if (body_pos > 0 && c == body_pos - 1) {
846                         FontMetrics const & fm = theFontMetrics(
847                                 text_->getLabelFont(buffer, par));
848                         tmpx += r.label_hfill + fm.width(layout->labelsep);
849                         if (par.isLineSeparator(body_pos - 1))
850                                 tmpx -= singleWidth(pit, body_pos - 1);
851                 }
852
853                 if (par.hfillExpansion(row, c)) {
854                         tmpx += singleWidth(pit, c);
855                         if (c >= body_pos)
856                                 tmpx += r.hfill;
857                         else
858                                 tmpx += r.label_hfill;
859                 } else if (par.isSeparator(c)) {
860                         tmpx += singleWidth(pit, c);
861                         if (c >= body_pos)
862                                 tmpx += r.separator;
863                 } else {
864                         tmpx += singleWidth(pit, c);
865                 }
866                 ++vc;
867         }
868
869         if ((tmpx + last_tmpx) / 2 > x) {
870                 tmpx = last_tmpx;
871                 left_side = true;
872         }
873
874         BOOST_ASSERT(vc <= end);  // This shouldn't happen.
875
876         boundary = false;
877         // This (rtl_support test) is not needed, but gives
878         // some speedup if rtl_support == false
879         bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
880
881         // If lastrow is false, we don't need to compute
882         // the value of rtl.
883         bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
884         if (lastrow &&
885             ((rtl  &&  left_side && vc == row.pos() && x < tmpx - 5) ||
886              (!rtl && !left_side && vc == end  && x > tmpx + 5)))
887                 c = end;
888         else if (vc == row.pos()) {
889                 c = bidi.vis2log(vc);
890                 if (bidi.level(c) % 2 == 1)
891                         ++c;
892         } else {
893                 c = bidi.vis2log(vc - 1);
894                 bool const rtl = (bidi.level(c) % 2 == 1);
895                 if (left_side == rtl) {
896                         ++c;
897                         boundary = text_->isRTLBoundary(buffer, par, c);
898                 }
899         }
900
901 // I believe this code is not needed anymore (Jug 20050717)
902 #if 0
903         // The following code is necessary because the cursor position past
904         // the last char in a row is logically equivalent to that before
905         // the first char in the next row. That's why insets causing row
906         // divisions -- Newline and display-style insets -- must be treated
907         // specially, so cursor up/down doesn't get stuck in an air gap -- MV
908         // Newline inset, air gap below:
909         if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
910                 if (bidi.level(end -1) % 2 == 0)
911                         tmpx -= singleWidth(pit, end - 1);
912                 else
913                         tmpx += singleWidth(pit, end - 1);
914                 c = end - 1;
915         }
916
917         // Air gap above display inset:
918         if (row.pos() < end && c >= end && end < par.size()
919             && par.isInset(end) && par.getInset(end)->display()) {
920                 c = end - 1;
921         }
922         // Air gap below display inset:
923         if (row.pos() < end && c >= end && par.isInset(end - 1)
924             && par.getInset(end - 1)->display()) {
925                 c = end - 1;
926         }
927 #endif
928
929         x = int(tmpx) + xo;
930         pos_type const col = c - row.pos();
931
932         if (!c || end == par.size())
933                 return col;
934
935         if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
936                 boundary = true;
937                 return col;
938         }
939
940         return min(col, end - 1 - row.pos());
941 }
942
943
944 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
945 {
946         ParagraphMetrics const & pm = par_metrics_[pit];
947         BOOST_ASSERT(!pm.rows().empty());
948         BOOST_ASSERT(row < int(pm.rows().size()));
949         bool bound = false;
950         Row const & r = pm.rows()[row];
951         return r.pos() + getColumnNearX(pit, r, x, bound);
952 }
953
954
955 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
956 {
957         Buffer const & buffer = bv_->buffer();
958         ParagraphMetrics const & pm = par_metrics_[pit];
959
960         return pm.singleWidth(pos, text_->getFont(buffer, text_->getPar(pit), pos));
961 }
962
963
964 //int Text::pos2x(pit_type pit, pos_type pos) const
965 //{
966 //      ParagraphMetrics const & pm = par_metrics_[pit];
967 //      Row const & r = pm.rows()[row];
968 //      int x = 0;
969 //      pos -= r.pos();
970 //}
971
972
973 int defaultRowHeight()
974 {
975         return int(theFontMetrics(Font(Font::ALL_SANE)).maxHeight() *  1.2);
976 }
977
978 } // namespace lyx