]> git.lyx.org Git - lyx.git/blob - src/TextMetrics.cpp
9fd56f6b6f1e209ee2b4c5fcf34a8d34a98632ce
[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         // FIXME this is a dirty trick. Now the _same_ position in the
249         // paragraph occurs in _two_ different rows, and has two different
250         // display positions, leading to weird behaviour when moving up/down.
251         if (z > 0 && par.isNewline(z - 1)) {
252                 Row row(z - 1);
253                 row.endpos(z - 1);
254                 setRowWidth(right_margin, pit, row);
255                 setHeightOfRow(pit, row);
256                 pm.rows().push_back(row);
257                 pm.dim().des += row.height();
258         }
259
260         pm.dim().asc += pm.rows()[0].ascent();
261         pm.dim().des -= pm.rows()[0].ascent();
262
263         // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
264         // redoParagraph() recursively inside parMetrics.
265         Dimension old_dim = parMetrics(pit, false).dim();
266
267         changed |= old_dim.height() != pm.dim().height();
268
269         par_metrics_[pit] = pm;
270
271         // Update the row change statuses. The painter will need that info
272         // in order to know which row has to be repainted.
273         par_metrics_[pit].updateRowChangeStatus();
274
275         return changed;
276 }
277
278 RowMetrics TextMetrics::computeRowMetrics(pit_type const pit,
279                 Row const & row) const
280 {
281         RowMetrics result;
282         Buffer & buffer = *bv_->buffer();
283         Paragraph const & par = text_->getPar(pit);
284
285         double w = dim_.wid - row.width();
286
287         bool const is_rtl = text_->isRTL(buffer, par);
288         if (is_rtl)
289                 result.x = rightMargin(pit);
290         else
291                 result.x = text_->leftMargin(buffer, max_width_, pit, row.pos());
292
293         // is there a manual margin with a manual label
294         Layout_ptr const & layout = par.layout();
295
296         if (layout->margintype == MARGIN_MANUAL
297             && layout->labeltype == LABEL_MANUAL) {
298                 /// We might have real hfills in the label part
299                 int nlh = numberOfLabelHfills(par, row);
300
301                 // A manual label par (e.g. List) has an auto-hfill
302                 // between the label text and the body of the
303                 // paragraph too.
304                 // But we don't want to do this auto hfill if the par
305                 // is empty.
306                 if (!par.empty())
307                         ++nlh;
308
309                 if (nlh && !par.getLabelWidthString().empty())
310                         result.label_hfill = labelFill(par, row) / double(nlh);
311         }
312
313         // are there any hfills in the row?
314         int const nh = numberOfHfills(par, row);
315
316         if (nh) {
317                 if (w > 0)
318                         result.hfill = w / nh;
319         // we don't have to look at the alignment if it is ALIGN_LEFT and
320         // if the row is already larger then the permitted width as then
321         // we force the LEFT_ALIGN'edness!
322         } else if (int(row.width()) < max_width_) {
323                 // is it block, flushleft or flushright?
324                 // set x how you need it
325                 int align;
326                 if (par.params().align() == LYX_ALIGN_LAYOUT)
327                         align = layout->align;
328                 else
329                         align = par.params().align();
330
331                 // Display-style insets should always be on a centred row
332                 // The test on par.size() is to catch zero-size pars, which
333                 // would trigger the assert in Paragraph::getInset().
334                 //inset = par.size() ? par.getInset(row.pos()) : 0;
335                 if (!par.empty()
336                     && par.isInset(row.pos()))
337                 {
338                     switch(par.getInset(row.pos())->display()) {
339                         case Inset::AlignLeft:
340                                 align = LYX_ALIGN_BLOCK;
341                                 break;
342                         case Inset::AlignCenter:
343                                 align = LYX_ALIGN_CENTER;
344                                 break;
345                         // other types unchanged (use align)
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                                 result.separator = w / ns;
367                         } else if (is_rtl) {
368                                 result.x += w;
369                         }
370                         break;
371                 }
372                 case LYX_ALIGN_RIGHT:
373                         result.x += w;
374                         break;
375                 case LYX_ALIGN_CENTER:
376                         result.x += w / 2;
377                         break;
378                 }
379         }
380
381         text_->bidi.computeTables(par, buffer, row);
382         if (is_rtl) {
383                 pos_type body_pos = par.beginOfBody();
384                 pos_type end = row.endpos();
385
386                 if (body_pos > 0
387                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
388                 {
389                         docstring const lsep = from_utf8(layout->labelsep);
390                         result.x += theFontMetrics(text_->getLabelFont(buffer, par)).width(lsep);
391                         if (body_pos <= end)
392                                 result.x += result.label_hfill;
393                 }
394         }
395
396         return result;
397 }
398
399
400 int TextMetrics::labelFill(Paragraph const & par, Row const & row) const
401 {
402         Buffer & buffer = *bv_->buffer();
403
404         pos_type last = par.beginOfBody();
405         BOOST_ASSERT(last > 0);
406
407         // -1 because a label ends with a space that is in the label
408         --last;
409
410         // a separator at this end does not count
411         if (par.isLineSeparator(last))
412                 --last;
413
414         int w = 0;
415         for (pos_type i = row.pos(); i <= last; ++i)
416                 w += text_->singleWidth(buffer, par, i);
417
418         docstring const & label = par.params().labelWidthString();
419         if (label.empty())
420                 return 0;
421
422         FontMetrics const & fm 
423                 = theFontMetrics(text_->getLabelFont(buffer, par));
424
425         return max(0, fm.width(label) - w);
426 }
427
428
429 namespace {
430
431 // this needs special handling - only newlines count as a break point
432 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
433 {
434         pos_type const end = par.size();
435
436         for (; i < end; ++i)
437                 if (par.isNewline(i))
438                         return i + 1;
439
440         return end;
441 }
442
443 };
444
445
446 int TextMetrics::labelEnd(pit_type const pit) const
447 {
448         // labelEnd is only needed if the layout fills a flushleft label.
449         if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
450                 return 0;
451         // return the beginning of the body
452         return text_->leftMargin(*bv_->buffer(), max_width_, pit);
453 }
454
455
456 void TextMetrics::rowBreakPoint(int width, pit_type const pit,
457                 Row & row) const
458 {
459         Buffer & buffer = *bv_->buffer();
460         Paragraph const & par = text_->getPar(pit);
461         pos_type const end = par.size();
462         pos_type const pos = row.pos();
463         if (pos == end) {
464                 row.endpos(end);
465                 return;
466         }
467
468         if (width < 0) {
469                 row.endpos(end);
470                 return;
471         }
472
473         Layout_ptr const & layout = par.layout();
474
475         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
476                 row.endpos(addressBreakPoint(pos, par));
477                 return;
478         }
479
480         pos_type const body_pos = par.beginOfBody();
481
482
483         // Now we iterate through until we reach the right margin
484         // or the end of the par, then choose the possible break
485         // nearest that.
486
487         int label_end = labelEnd(pit);
488         int const left = text_->leftMargin(buffer, max_width_, pit, pos);
489         int x = left;
490
491         // pixel width since last breakpoint
492         int chunkwidth = 0;
493
494         FontIterator fi = FontIterator(buffer, *text_, par, pos);
495         pos_type point = end;
496         pos_type i = pos;
497         FontMetrics const & fm = theFontMetrics(text_->getLabelFont(buffer, par));
498         for ( ; i < end; ++i, ++fi) {
499                 char_type const c = par.getChar(i);
500                 int thiswidth = text_->singleWidth(par, i, c, *fi);
501
502                 // add the auto-hfill from label end to the body
503                 if (body_pos && i == body_pos) {
504                         docstring lsep = from_utf8(layout->labelsep);
505                         int add = fm.width(lsep);
506                         if (par.isLineSeparator(i - 1))
507                                 add -= text_->singleWidth(buffer, par, i - 1);
508
509                         add = std::max(add, label_end - x);
510                         thiswidth += add;
511                 }
512
513                 x += thiswidth;
514                 chunkwidth += thiswidth;
515
516                 // break before a character that will fall off
517                 // the right of the row
518                 if (x >= width) {
519                         // if no break before, break here
520                         if (point == end || chunkwidth >= width - left) {
521                                 if (i > pos)
522                                         point = i;
523                                 else
524                                         point = i + 1;
525
526                         }
527                         // exit on last registered breakpoint:
528                         break;
529                 }
530
531                 if (par.isNewline(i)) {
532                         point = i + 1;
533                         break;
534                 }
535                 // Break before...
536                 if (i + 1 < end) {
537                         if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
538                                 point = i + 1;
539                                 break;
540                         }
541                         // ...and after.
542                         if (par.isInset(i) && par.getInset(i)->display()) {
543                                 point = i + 1;
544                                 break;
545                         }
546                 }
547
548                 if (!par.isInset(i) || par.getInset(i)->isChar()) {
549                         // some insets are line separators too
550                         if (par.isLineSeparator(i)) {
551                                 // register breakpoint:
552                                 point = i + 1;
553                                 chunkwidth = 0;
554                         }
555                 }
556         }
557
558         // maybe found one, but the par is short enough.
559         if (i == end && x < width)
560                 point = end;
561
562         // manual labels cannot be broken in LaTeX. But we
563         // want to make our on-screen rendering of footnotes
564         // etc. still break
565         if (body_pos && point < body_pos)
566                 point = body_pos;
567
568         row.endpos(point);
569 }
570
571
572 void TextMetrics::setRowWidth(int right_margin,
573                 pit_type const pit, Row & row) const
574 {
575         Buffer & buffer = *bv_->buffer();
576         // get the pure distance
577         pos_type const end = row.endpos();
578
579         Paragraph const & par = text_->getPar(pit);
580         docstring const labelsep = from_utf8(par.layout()->labelsep);
581         int w = text_->leftMargin(buffer, max_width_, pit, row.pos());
582         int label_end = labelEnd(pit);
583
584         pos_type const body_pos = par.beginOfBody();
585         pos_type i = row.pos();
586
587         FontMetrics const & fm = theFontMetrics(text_->getLabelFont(buffer, par));
588
589         if (i < end) {
590                 FontIterator fi = FontIterator(buffer, *text_, par, i);
591                 for ( ; i < end; ++i, ++fi) {
592                         if (body_pos > 0 && i == body_pos) {
593                                 w += fm.width(labelsep);
594                                 if (par.isLineSeparator(i - 1))
595                                         w -= text_->singleWidth(buffer, par, i - 1);
596                                 w = max(w, label_end);
597                         }
598                         char_type const c = par.getChar(i);
599                         w += text_->singleWidth(par, i, c, *fi);
600                 }
601         }
602
603         if (body_pos > 0 && body_pos >= end) {
604                 w += fm.width(labelsep);
605                 if (end > 0 && par.isLineSeparator(end - 1))
606                         w -= text_->singleWidth(buffer, par, end - 1);
607                 w = max(w, label_end);
608         }
609
610         row.width(w + right_margin);
611 }
612
613
614 void TextMetrics::setHeightOfRow(pit_type const pit,
615                 Row & row)
616 {
617         Paragraph const & par = text_->getPar(pit);
618         // get the maximum ascent and the maximum descent
619         double layoutasc = 0;
620         double layoutdesc = 0;
621         double const dh = defaultRowHeight();
622
623         // ok, let us initialize the maxasc and maxdesc value.
624         // Only the fontsize count. The other properties
625         // are taken from the layoutfont. Nicer on the screen :)
626         Layout_ptr const & layout = par.layout();
627
628         // as max get the first character of this row then it can
629         // increase but not decrease the height. Just some point to
630         // start with so we don't have to do the assignment below too
631         // often.
632         Buffer const & buffer = *bv_->buffer();
633         Font font = text_->getFont(buffer, par, row.pos());
634         Font::FONT_SIZE const tmpsize = font.size();
635         font = text_->getLayoutFont(buffer, pit);
636         Font::FONT_SIZE const size = font.size();
637         font.setSize(tmpsize);
638
639         Font labelfont = text_->getLabelFont(buffer, par);
640
641         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
642         FontMetrics const & fontmetrics = theFontMetrics(font);
643
644         // these are minimum values
645         double const spacing_val = layout->spacing.getValue()
646                 * text_->spacing(buffer, par);
647         //lyxerr << "spacing_val = " << spacing_val << endl;
648         int maxasc  = int(fontmetrics.maxAscent()  * spacing_val);
649         int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
650
651         // insets may be taller
652         InsetList::const_iterator ii = par.insetlist.begin();
653         InsetList::const_iterator iend = par.insetlist.end();
654         for ( ; ii != iend; ++ii) {
655                 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
656                         maxasc  = max(maxasc,  ii->inset->ascent());
657                         maxdesc = max(maxdesc, ii->inset->descent());
658                 }
659         }
660
661         // Check if any custom fonts are larger (Asger)
662         // This is not completely correct, but we can live with the small,
663         // cosmetic error for now.
664         int labeladdon = 0;
665         pos_type const pos_end = row.endpos();
666
667         Font::FONT_SIZE maxsize =
668                 par.highestFontInRange(row.pos(), pos_end, size);
669         if (maxsize > font.size()) {
670                 font.setSize(maxsize);
671                 maxasc  = max(maxasc,  fontmetrics.maxAscent());
672                 maxdesc = max(maxdesc, fontmetrics.maxDescent());
673         }
674
675         // This is nicer with box insets:
676         ++maxasc;
677         ++maxdesc;
678
679         row.ascent(maxasc);
680         ParagraphList const & pars = text_->paragraphs();
681
682         // is it a top line?
683         if (row.pos() == 0) {
684                 BufferParams const & bufparams = buffer.params();
685                 // some parskips VERY EASY IMPLEMENTATION
686                 if (bufparams.paragraph_separation
687                     == BufferParams::PARSEP_SKIP
688                         && par.ownerCode() != Inset::ERT_CODE
689                         && par.ownerCode() != Inset::LISTINGS_CODE
690                         && pit > 0
691                         && ((layout->isParagraph() && par.getDepth() == 0)
692                             || (pars[pit - 1].layout()->isParagraph()
693                                 && pars[pit - 1].getDepth() == 0)))
694                 {
695                                 maxasc += bufparams.getDefSkip().inPixels(*bv_);
696                 }
697
698                 if (par.params().startOfAppendix())
699                         maxasc += int(3 * dh);
700
701                 // This is special code for the chapter, since the label of this
702                 // layout is printed in an extra row
703                 if (layout->counter == "chapter"
704                     && !par.params().labelString().empty()) {
705                         labeladdon = int(labelfont_metrics.maxHeight()
706                                      * layout->spacing.getValue()
707                                      * text_->spacing(buffer, par));
708                 }
709
710                 // special code for the top label
711                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
712                      || layout->labeltype == LABEL_BIBLIO
713                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
714                     && isFirstInSequence(pit, pars)
715                     && !par.getLabelstring().empty())
716                 {
717                         labeladdon = int(
718                                   labelfont_metrics.maxHeight()
719                                         * layout->spacing.getValue()
720                                         * text_->spacing(buffer, par)
721                                 + (layout->topsep + layout->labelbottomsep) * dh);
722                 }
723
724                 // Add the layout spaces, for example before and after
725                 // a section, or between the items of a itemize or enumerate
726                 // environment.
727
728                 pit_type prev = depthHook(pit, pars, par.getDepth());
729                 Paragraph const & prevpar = pars[prev];
730                 if (prev != pit
731                     && prevpar.layout() == layout
732                     && prevpar.getDepth() == par.getDepth()
733                     && prevpar.getLabelWidthString()
734                                         == par.getLabelWidthString()) {
735                         layoutasc = layout->itemsep * dh;
736                 } else if (pit != 0 || row.pos() != 0) {
737                         if (layout->topsep > 0)
738                                 layoutasc = layout->topsep * dh;
739                 }
740
741                 prev = outerHook(pit, pars);
742                 if (prev != pit_type(pars.size())) {
743                         maxasc += int(pars[prev].layout()->parsep * dh);
744                 } else if (pit != 0) {
745                         Paragraph const & prevpar = pars[pit - 1];
746                         if (prevpar.getDepth() != 0 ||
747                                         prevpar.layout() == layout) {
748                                 maxasc += int(layout->parsep * dh);
749                         }
750                 }
751         }
752
753         // is it a bottom line?
754         if (row.endpos() >= par.size()) {
755                 // add the layout spaces, for example before and after
756                 // a section, or between the items of a itemize or enumerate
757                 // environment
758                 pit_type nextpit = pit + 1;
759                 if (nextpit != pit_type(pars.size())) {
760                         pit_type cpit = pit;
761                         double usual = 0;
762                         double unusual = 0;
763
764                         if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
765                                 usual = pars[cpit].layout()->bottomsep * dh;
766                                 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
767                                 if (pars[cpit].layout() != pars[nextpit].layout()
768                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
769                                 {
770                                         unusual = pars[cpit].layout()->bottomsep * dh;
771                                 }
772                                 layoutdesc = max(unusual, usual);
773                         } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
774                                 if (pars[cpit].layout() != pars[nextpit].layout()
775                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
776                                         layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
777                         }
778                 }
779         }
780
781         // incalculate the layout spaces
782         maxasc  += int(layoutasc  * 2 / (2 + pars[pit].getDepth()));
783         maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
784
785         // FIXME: the correct way is to do the following is to move the 
786         // following code in another method specially tailored for the 
787         // main Text. The following test is thus bogus.
788         // Top and bottom margin of the document (only at top-level)
789         if (main_text_) {
790                 if (pit == 0 && row.pos() == 0)
791                         maxasc += 20;
792                 if (pit + 1 == pit_type(pars.size()) &&
793                     row.endpos() == par.size())
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
818         pos_type vc = row.pos();
819         pos_type end = row.endpos();
820         pos_type c = 0;
821         Layout_ptr const & layout = par.layout();
822
823         bool left_side = false;
824
825         pos_type body_pos = par.beginOfBody();
826
827         double tmpx = r.x;
828         double last_tmpx = tmpx;
829
830         if (body_pos > 0 &&
831             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
832                 body_pos = 0;
833
834         // check for empty row
835         if (vc == end) {
836                 x = int(tmpx) + xo;
837                 return 0;
838         }
839
840         frontend::FontMetrics const & fm 
841                 = theFontMetrics(text_->getLabelFont(buffer, par));
842
843         while (vc < end && tmpx <= x) {
844                 c = text_->bidi.vis2log(vc);
845                 last_tmpx = tmpx;
846                 if (body_pos > 0 && c == body_pos - 1) {
847                         // FIXME UNICODE
848                         docstring const lsep = from_utf8(layout->labelsep);
849                         tmpx += r.label_hfill + fm.width(lsep);
850                         if (par.isLineSeparator(body_pos - 1))
851                                 tmpx -= text_->singleWidth(buffer, par, body_pos - 1);
852                 }
853
854                 if (par.hfillExpansion(row, c)) {
855                         tmpx += text_->singleWidth(buffer, par, c);
856                         if (c >= body_pos)
857                                 tmpx += r.hfill;
858                         else
859                                 tmpx += r.label_hfill;
860                 } else if (par.isSeparator(c)) {
861                         tmpx += text_->singleWidth(buffer, par, c);
862                         if (c >= body_pos)
863                                 tmpx += r.separator;
864                 } else {
865                         tmpx += text_->singleWidth(buffer, par, 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 = text_->bidi.vis2log(vc);
891                 if (text_->bidi.level(c) % 2 == 1)
892                         ++c;
893         } else {
894                 c = text_->bidi.vis2log(vc - 1);
895                 bool const rtl = (text_->bidi.level(c) % 2 == 1);
896                 if (left_side == rtl) {
897                         ++c;
898                         boundary = text_->bidi.isBoundary(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 (text_->bidi.level(end -1) % 2 == 0)
912                         tmpx -= text_->singleWidth(buffer, par, end - 1);
913                 else
914                         tmpx += text_->singleWidth(buffer, par, 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 = parMetrics(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 Text::pos2x(pit_type pit, pos_type pos) const
957 //{
958 //      ParagraphMetrics const & pm = parMetrics(pit);
959 //      Row const & r = pm.rows()[row];
960 //      int x = 0;
961 //      pos -= r.pos();
962 //}
963
964
965 int defaultRowHeight()
966 {
967         return int(theFontMetrics(Font(Font::ALL_SANE)).maxHeight() *  1.2);
968 }
969
970 } // namespace lyx