]> git.lyx.org Git - lyx.git/blob - src/TextMetrics.cpp
Fix for bug 3637, joint work of Bo Peng and myself:
[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 has nothing to do here and is the reason why text_ is not
194         // const.
195         if (par.checkBiblio(buffer.params().trackChanges))
196                 const_cast<Cursor &>(bv_->cursor()).posRight();
197
198         // Optimisation: this is used in the next two loops
199         // so better to calculate that once here.
200         int const right_margin = rightMargin(pm);
201
202         // redo insets
203         // FIXME: We should always use getFont(), see documentation of
204         // noFontChange() in Inset.h.
205         Font const bufferfont = buffer.params().getFont();
206         InsetList::const_iterator ii = par.insetlist.begin();
207         InsetList::const_iterator iend = par.insetlist.end();
208         for (; ii != iend; ++ii) {
209                 Dimension dim;
210                 int const w = max_width_ - text_->leftMargin(buffer, max_width_, pit, ii->pos)
211                         - right_margin;
212                 Font const & font = ii->inset->noFontChange() ?
213                         bufferfont : text_->getFont(buffer, par, ii->pos);
214                 MetricsInfo mi(bv_, font, w);
215                 changed |= ii->inset->metrics(mi, dim);
216         }
217
218         // rebreak the paragraph
219         pm.rows().clear();
220
221         par.setBeginOfBody();
222         pos_type z = 0;
223         // maximum pixel width of a row
224         int width = max_width_ - right_margin; // - leftMargin(buffer, max_width_, pit, row);
225         do {
226                 Row row(z);
227                 rowBreakPoint(width, pit, row);
228                 setRowWidth(right_margin, pit, row);
229                 setHeightOfRow(pit, row);
230                 pm.rows().push_back(row);
231                 pm.dim().wid = std::max(pm.dim().wid, row.width());
232                 pm.dim().des += row.height();
233                 z = row.endpos();
234         } while (z < par.size());
235
236         // Make sure that if a par ends in newline, there is one more row
237         // under it
238         // FIXME this is a dirty trick. Now the _same_ position in the
239         // paragraph occurs in _two_ different rows, and has two different
240         // display positions, leading to weird behaviour when moving up/down.
241         if (z > 0 && par.isNewline(z - 1)) {
242                 Row row(z - 1);
243                 row.endpos(z - 1);
244                 setRowWidth(right_margin, pit, row);
245                 setHeightOfRow(pit, row);
246                 pm.rows().push_back(row);
247                 pm.dim().des += row.height();
248         }
249
250         pm.dim().asc += pm.rows()[0].ascent();
251         pm.dim().des -= pm.rows()[0].ascent();
252
253         // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
254         // redoParagraph() recursively inside parMetrics.
255         Dimension old_dim = parMetrics(pit, false).dim();
256
257         changed |= old_dim.height() != pm.dim().height();
258
259         par_metrics_[pit] = pm;
260
261         // Update the row change statuses. The painter will need that info
262         // in order to know which row has to be repainted.
263         par_metrics_[pit].updateRowChangeStatus();
264
265         return changed;
266 }
267
268 RowMetrics TextMetrics::computeRowMetrics(pit_type const pit,
269                 Row const & row) const
270 {
271         RowMetrics result;
272         Buffer & buffer = *bv_->buffer();
273         Paragraph const & par = text_->getPar(pit);
274
275         double w = dim_.wid - row.width();
276
277         bool const is_rtl = text_->isRTL(buffer, par);
278         if (is_rtl)
279                 result.x = rightMargin(pit);
280         else
281                 result.x = text_->leftMargin(buffer, max_width_, pit, row.pos());
282
283         // is there a manual margin with a manual label
284         Layout_ptr const & layout = par.layout();
285
286         if (layout->margintype == MARGIN_MANUAL
287             && layout->labeltype == LABEL_MANUAL) {
288                 /// We might have real hfills in the label part
289                 int nlh = numberOfLabelHfills(par, row);
290
291                 // A manual label par (e.g. List) has an auto-hfill
292                 // between the label text and the body of the
293                 // paragraph too.
294                 // But we don't want to do this auto hfill if the par
295                 // is empty.
296                 if (!par.empty())
297                         ++nlh;
298
299                 if (nlh && !par.getLabelWidthString().empty())
300                         result.label_hfill = labelFill(par, row) / double(nlh);
301         }
302
303         // are there any hfills in the row?
304         int const nh = numberOfHfills(par, row);
305
306         if (nh) {
307                 if (w > 0)
308                         result.hfill = w / nh;
309         // we don't have to look at the alignment if it is ALIGN_LEFT and
310         // if the row is already larger then the permitted width as then
311         // we force the LEFT_ALIGN'edness!
312         } else if (int(row.width()) < max_width_) {
313                 // is it block, flushleft or flushright?
314                 // set x how you need it
315                 int align;
316                 if (par.params().align() == LYX_ALIGN_LAYOUT)
317                         align = layout->align;
318                 else
319                         align = par.params().align();
320
321                 // Display-style insets should always be on a centred row
322                 // The test on par.size() is to catch zero-size pars, which
323                 // would trigger the assert in Paragraph::getInset().
324                 //inset = par.size() ? par.getInset(row.pos()) : 0;
325                 if (!par.empty()
326                     && par.isInset(row.pos()))
327                 {
328                     switch(par.getInset(row.pos())->display()) {
329                         case Inset::AlignLeft:
330                                 align = LYX_ALIGN_BLOCK;
331                                 break;
332                         case Inset::AlignCenter:
333                                 align = LYX_ALIGN_CENTER;
334                                 break;
335                         // other types unchanged (use align)
336                         }
337                 }
338
339                 switch (align) {
340                 case LYX_ALIGN_BLOCK: {
341                         int const ns = numberOfSeparators(par, row);
342                         bool disp_inset = false;
343                         if (row.endpos() < par.size()) {
344                                 Inset const * in = par.getInset(row.endpos());
345                                 if (in)
346                                         disp_inset = in->display();
347                         }
348                         // If we have separators, this is not the last row of a
349                         // par, does not end in newline, and is not row above a
350                         // display inset... then stretch it
351                         if (ns
352                             && row.endpos() < par.size()
353                             && !par.isNewline(row.endpos() - 1)
354                             && !disp_inset
355                                 ) {
356                                 result.separator = w / ns;
357                         } else if (is_rtl) {
358                                 result.x += w;
359                         }
360                         break;
361                 }
362                 case LYX_ALIGN_RIGHT:
363                         result.x += w;
364                         break;
365                 case LYX_ALIGN_CENTER:
366                         result.x += w / 2;
367                         break;
368                 }
369         }
370
371         text_->bidi.computeTables(par, buffer, row);
372         if (is_rtl) {
373                 pos_type body_pos = par.beginOfBody();
374                 pos_type end = row.endpos();
375
376                 if (body_pos > 0
377                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
378                 {
379                         docstring const lsep = from_utf8(layout->labelsep);
380                         result.x += theFontMetrics(text_->getLabelFont(buffer, par)).width(lsep);
381                         if (body_pos <= end)
382                                 result.x += result.label_hfill;
383                 }
384         }
385
386         return result;
387 }
388
389
390 int TextMetrics::labelFill(Paragraph const & par, Row const & row) const
391 {
392         Buffer & buffer = *bv_->buffer();
393
394         pos_type last = par.beginOfBody();
395         BOOST_ASSERT(last > 0);
396
397         // -1 because a label ends with a space that is in the label
398         --last;
399
400         // a separator at this end does not count
401         if (par.isLineSeparator(last))
402                 --last;
403
404         int w = 0;
405         for (pos_type i = row.pos(); i <= last; ++i)
406                 w += text_->singleWidth(buffer, par, i);
407
408         docstring const & label = par.params().labelWidthString();
409         if (label.empty())
410                 return 0;
411
412         FontMetrics const & fm 
413                 = theFontMetrics(text_->getLabelFont(buffer, par));
414
415         return max(0, fm.width(label) - w);
416 }
417
418
419 namespace {
420
421 // this needs special handling - only newlines count as a break point
422 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
423 {
424         pos_type const end = par.size();
425
426         for (; i < end; ++i)
427                 if (par.isNewline(i))
428                         return i + 1;
429
430         return end;
431 }
432
433 };
434
435
436 int TextMetrics::labelEnd(pit_type const pit) const
437 {
438         // labelEnd is only needed if the layout fills a flushleft label.
439         if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
440                 return 0;
441         // return the beginning of the body
442         return text_->leftMargin(*bv_->buffer(), max_width_, pit);
443 }
444
445
446 void TextMetrics::rowBreakPoint(int width, pit_type const pit,
447                 Row & row) const
448 {
449         Buffer & buffer = *bv_->buffer();
450         Paragraph const & par = text_->getPar(pit);
451         pos_type const end = par.size();
452         pos_type const pos = row.pos();
453         if (pos == end) {
454                 row.endpos(end);
455                 return;
456         }
457
458         if (width < 0) {
459                 row.endpos(end);
460                 return;
461         }
462
463         Layout_ptr const & layout = par.layout();
464
465         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
466                 row.endpos(addressBreakPoint(pos, par));
467                 return;
468         }
469
470         pos_type const body_pos = par.beginOfBody();
471
472
473         // Now we iterate through until we reach the right margin
474         // or the end of the par, then choose the possible break
475         // nearest that.
476
477         int label_end = labelEnd(pit);
478         int const left = text_->leftMargin(buffer, max_width_, pit, pos);
479         int x = left;
480
481         // pixel width since last breakpoint
482         int chunkwidth = 0;
483
484         FontIterator fi = FontIterator(buffer, *text_, par, pos);
485         pos_type point = end;
486         pos_type i = pos;
487         FontMetrics const & fm = theFontMetrics(text_->getLabelFont(buffer, par));
488         for ( ; i < end; ++i, ++fi) {
489                 char_type const c = par.getChar(i);
490                 int thiswidth = text_->singleWidth(par, i, c, *fi);
491
492                 // add the auto-hfill from label end to the body
493                 if (body_pos && i == body_pos) {
494                         docstring lsep = from_utf8(layout->labelsep);
495                         int add = fm.width(lsep);
496                         if (par.isLineSeparator(i - 1))
497                                 add -= text_->singleWidth(buffer, par, i - 1);
498
499                         add = std::max(add, label_end - x);
500                         thiswidth += add;
501                 }
502
503                 x += thiswidth;
504                 chunkwidth += thiswidth;
505
506                 // break before a character that will fall off
507                 // the right of the row
508                 if (x >= width) {
509                         // if no break before, break here
510                         if (point == end || chunkwidth >= width - left) {
511                                 if (i > pos)
512                                         point = i;
513                                 else
514                                         point = i + 1;
515
516                         }
517                         // exit on last registered breakpoint:
518                         break;
519                 }
520
521                 if (par.isNewline(i)) {
522                         point = i + 1;
523                         break;
524                 }
525                 // Break before...
526                 if (i + 1 < end) {
527                         if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
528                                 point = i + 1;
529                                 break;
530                         }
531                         // ...and after.
532                         if (par.isInset(i) && par.getInset(i)->display()) {
533                                 point = i + 1;
534                                 break;
535                         }
536                 }
537
538                 if (!par.isInset(i) || par.getInset(i)->isChar()) {
539                         // some insets are line separators too
540                         if (par.isLineSeparator(i)) {
541                                 // register breakpoint:
542                                 point = i + 1;
543                                 chunkwidth = 0;
544                         }
545                 }
546         }
547
548         // maybe found one, but the par is short enough.
549         if (i == end && x < width)
550                 point = end;
551
552         // manual labels cannot be broken in LaTeX. But we
553         // want to make our on-screen rendering of footnotes
554         // etc. still break
555         if (body_pos && point < body_pos)
556                 point = body_pos;
557
558         row.endpos(point);
559 }
560
561
562 void TextMetrics::setRowWidth(int right_margin,
563                 pit_type const pit, Row & row) const
564 {
565         Buffer & buffer = *bv_->buffer();
566         // get the pure distance
567         pos_type const end = row.endpos();
568
569         Paragraph const & par = text_->getPar(pit);
570         docstring const labelsep = from_utf8(par.layout()->labelsep);
571         int w = text_->leftMargin(buffer, max_width_, pit, row.pos());
572         int label_end = labelEnd(pit);
573
574         pos_type const body_pos = par.beginOfBody();
575         pos_type i = row.pos();
576
577         FontMetrics const & fm = theFontMetrics(text_->getLabelFont(buffer, par));
578
579         if (i < end) {
580                 FontIterator fi = FontIterator(buffer, *text_, par, i);
581                 for ( ; i < end; ++i, ++fi) {
582                         if (body_pos > 0 && i == body_pos) {
583                                 w += fm.width(labelsep);
584                                 if (par.isLineSeparator(i - 1))
585                                         w -= text_->singleWidth(buffer, par, i - 1);
586                                 w = max(w, label_end);
587                         }
588                         char_type const c = par.getChar(i);
589                         w += text_->singleWidth(par, i, c, *fi);
590                 }
591         }
592
593         if (body_pos > 0 && body_pos >= end) {
594                 w += fm.width(labelsep);
595                 if (end > 0 && par.isLineSeparator(end - 1))
596                         w -= text_->singleWidth(buffer, par, end - 1);
597                 w = max(w, label_end);
598         }
599
600         row.width(w + right_margin);
601 }
602
603
604 void TextMetrics::setHeightOfRow(pit_type const pit,
605                 Row & row)
606 {
607         Paragraph const & par = text_->getPar(pit);
608         // get the maximum ascent and the maximum descent
609         double layoutasc = 0;
610         double layoutdesc = 0;
611         double const dh = defaultRowHeight();
612
613         // ok, let us initialize the maxasc and maxdesc value.
614         // Only the fontsize count. The other properties
615         // are taken from the layoutfont. Nicer on the screen :)
616         Layout_ptr const & layout = par.layout();
617
618         // as max get the first character of this row then it can
619         // increase but not decrease the height. Just some point to
620         // start with so we don't have to do the assignment below too
621         // often.
622         Buffer const & buffer = *bv_->buffer();
623         Font font = text_->getFont(buffer, par, row.pos());
624         Font::FONT_SIZE const tmpsize = font.size();
625         font = text_->getLayoutFont(buffer, pit);
626         Font::FONT_SIZE const size = font.size();
627         font.setSize(tmpsize);
628
629         Font labelfont = text_->getLabelFont(buffer, par);
630
631         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
632         FontMetrics const & fontmetrics = theFontMetrics(font);
633
634         // these are minimum values
635         double const spacing_val = layout->spacing.getValue()
636                 * text_->spacing(buffer, par);
637         //lyxerr << "spacing_val = " << spacing_val << endl;
638         int maxasc  = int(fontmetrics.maxAscent()  * spacing_val);
639         int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
640
641         // insets may be taller
642         InsetList::const_iterator ii = par.insetlist.begin();
643         InsetList::const_iterator iend = par.insetlist.end();
644         for ( ; ii != iend; ++ii) {
645                 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
646                         maxasc  = max(maxasc,  ii->inset->ascent());
647                         maxdesc = max(maxdesc, ii->inset->descent());
648                 }
649         }
650
651         // Check if any custom fonts are larger (Asger)
652         // This is not completely correct, but we can live with the small,
653         // cosmetic error for now.
654         int labeladdon = 0;
655         pos_type const pos_end = row.endpos();
656
657         Font::FONT_SIZE maxsize =
658                 par.highestFontInRange(row.pos(), pos_end, size);
659         if (maxsize > font.size()) {
660                 font.setSize(maxsize);
661                 maxasc  = max(maxasc,  fontmetrics.maxAscent());
662                 maxdesc = max(maxdesc, fontmetrics.maxDescent());
663         }
664
665         // This is nicer with box insets:
666         ++maxasc;
667         ++maxdesc;
668
669         row.ascent(maxasc);
670         ParagraphList const & pars = text_->paragraphs();
671
672         // is it a top line?
673         if (row.pos() == 0) {
674                 BufferParams const & bufparams = buffer.params();
675                 // some parskips VERY EASY IMPLEMENTATION
676                 if (bufparams.paragraph_separation
677                     == BufferParams::PARSEP_SKIP
678                         && par.ownerCode() != Inset::ERT_CODE
679                         && par.ownerCode() != Inset::LISTINGS_CODE
680                         && pit > 0
681                         && ((layout->isParagraph() && par.getDepth() == 0)
682                             || (pars[pit - 1].layout()->isParagraph()
683                                 && pars[pit - 1].getDepth() == 0)))
684                 {
685                                 maxasc += bufparams.getDefSkip().inPixels(*bv_);
686                 }
687
688                 if (par.params().startOfAppendix())
689                         maxasc += int(3 * dh);
690
691                 // This is special code for the chapter, since the label of this
692                 // layout is printed in an extra row
693                 if (layout->counter == "chapter"
694                     && !par.params().labelString().empty()) {
695                         labeladdon = int(labelfont_metrics.maxHeight()
696                                      * layout->spacing.getValue()
697                                      * text_->spacing(buffer, par));
698                 }
699
700                 // special code for the top label
701                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
702                      || layout->labeltype == LABEL_BIBLIO
703                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
704                     && isFirstInSequence(pit, pars)
705                     && !par.getLabelstring().empty())
706                 {
707                         labeladdon = int(
708                                   labelfont_metrics.maxHeight()
709                                         * layout->spacing.getValue()
710                                         * text_->spacing(buffer, par)
711                                 + (layout->topsep + layout->labelbottomsep) * dh);
712                 }
713
714                 // Add the layout spaces, for example before and after
715                 // a section, or between the items of a itemize or enumerate
716                 // environment.
717
718                 pit_type prev = depthHook(pit, pars, par.getDepth());
719                 Paragraph const & prevpar = pars[prev];
720                 if (prev != pit
721                     && prevpar.layout() == layout
722                     && prevpar.getDepth() == par.getDepth()
723                     && prevpar.getLabelWidthString()
724                                         == par.getLabelWidthString()) {
725                         layoutasc = layout->itemsep * dh;
726                 } else if (pit != 0 || row.pos() != 0) {
727                         if (layout->topsep > 0)
728                                 layoutasc = layout->topsep * dh;
729                 }
730
731                 prev = outerHook(pit, pars);
732                 if (prev != pit_type(pars.size())) {
733                         maxasc += int(pars[prev].layout()->parsep * dh);
734                 } else if (pit != 0) {
735                         Paragraph const & prevpar = pars[pit - 1];
736                         if (prevpar.getDepth() != 0 ||
737                                         prevpar.layout() == layout) {
738                                 maxasc += int(layout->parsep * dh);
739                         }
740                 }
741         }
742
743         // is it a bottom line?
744         if (row.endpos() >= par.size()) {
745                 // add the layout spaces, for example before and after
746                 // a section, or between the items of a itemize or enumerate
747                 // environment
748                 pit_type nextpit = pit + 1;
749                 if (nextpit != pit_type(pars.size())) {
750                         pit_type cpit = pit;
751                         double usual = 0;
752                         double unusual = 0;
753
754                         if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
755                                 usual = pars[cpit].layout()->bottomsep * dh;
756                                 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
757                                 if (pars[cpit].layout() != pars[nextpit].layout()
758                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
759                                 {
760                                         unusual = pars[cpit].layout()->bottomsep * dh;
761                                 }
762                                 layoutdesc = max(unusual, usual);
763                         } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
764                                 if (pars[cpit].layout() != pars[nextpit].layout()
765                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
766                                         layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
767                         }
768                 }
769         }
770
771         // incalculate the layout spaces
772         maxasc  += int(layoutasc  * 2 / (2 + pars[pit].getDepth()));
773         maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
774
775         // FIXME: the correct way is to do the following is to move the 
776         // following code in another method specially tailored for the 
777         // main Text. The following test is thus bogus.
778         // Top and bottom margin of the document (only at top-level)
779         if (main_text_) {
780                 if (pit == 0 && row.pos() == 0)
781                         maxasc += 20;
782                 if (pit + 1 == pit_type(pars.size()) &&
783                     row.endpos() == par.size())
784                         maxdesc += 20;
785         }
786
787         row.ascent(maxasc + labeladdon);
788         row.descent(maxdesc);
789 }
790
791
792 // x is an absolute screen coord
793 // returns the column near the specified x-coordinate of the row
794 // x is set to the real beginning of this column
795 pos_type TextMetrics::getColumnNearX(pit_type const pit,
796                 Row const & row, int & x, bool & boundary) const
797 {
798         Buffer const & buffer = *bv_->buffer();
799
800         /// For the main Text, it is possible that this pit is not
801         /// yet in the CoordCache when moving cursor up.
802         /// x Paragraph coordinate is always 0 for main text anyway.
803         int const xo = main_text_? 0 : bv_->coordCache().get(text_, pit).x_;
804         x -= xo;
805         RowMetrics const r = computeRowMetrics(pit, row);
806         Paragraph const & par = text_->getPar(pit);
807
808         pos_type vc = row.pos();
809         pos_type end = row.endpos();
810         pos_type c = 0;
811         Layout_ptr const & layout = par.layout();
812
813         bool left_side = false;
814
815         pos_type body_pos = par.beginOfBody();
816
817         double tmpx = r.x;
818         double last_tmpx = tmpx;
819
820         if (body_pos > 0 &&
821             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
822                 body_pos = 0;
823
824         // check for empty row
825         if (vc == end) {
826                 x = int(tmpx) + xo;
827                 return 0;
828         }
829
830         frontend::FontMetrics const & fm 
831                 = theFontMetrics(text_->getLabelFont(buffer, par));
832
833         while (vc < end && tmpx <= x) {
834                 c = text_->bidi.vis2log(vc);
835                 last_tmpx = tmpx;
836                 if (body_pos > 0 && c == body_pos - 1) {
837                         // FIXME UNICODE
838                         docstring const lsep = from_utf8(layout->labelsep);
839                         tmpx += r.label_hfill + fm.width(lsep);
840                         if (par.isLineSeparator(body_pos - 1))
841                                 tmpx -= text_->singleWidth(buffer, par, body_pos - 1);
842                 }
843
844                 if (par.hfillExpansion(row, c)) {
845                         tmpx += text_->singleWidth(buffer, par, c);
846                         if (c >= body_pos)
847                                 tmpx += r.hfill;
848                         else
849                                 tmpx += r.label_hfill;
850                 } else if (par.isSeparator(c)) {
851                         tmpx += text_->singleWidth(buffer, par, c);
852                         if (c >= body_pos)
853                                 tmpx += r.separator;
854                 } else {
855                         tmpx += text_->singleWidth(buffer, par, c);
856                 }
857                 ++vc;
858         }
859
860         if ((tmpx + last_tmpx) / 2 > x) {
861                 tmpx = last_tmpx;
862                 left_side = true;
863         }
864
865         BOOST_ASSERT(vc <= end);  // This shouldn't happen.
866
867         boundary = false;
868         // This (rtl_support test) is not needed, but gives
869         // some speedup if rtl_support == false
870         bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
871
872         // If lastrow is false, we don't need to compute
873         // the value of rtl.
874         bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
875         if (lastrow &&
876             ((rtl  &&  left_side && vc == row.pos() && x < tmpx - 5) ||
877              (!rtl && !left_side && vc == end  && x > tmpx + 5)))
878                 c = end;
879         else if (vc == row.pos()) {
880                 c = text_->bidi.vis2log(vc);
881                 if (text_->bidi.level(c) % 2 == 1)
882                         ++c;
883         } else {
884                 c = text_->bidi.vis2log(vc - 1);
885                 bool const rtl = (text_->bidi.level(c) % 2 == 1);
886                 if (left_side == rtl) {
887                         ++c;
888                         boundary = text_->bidi.isBoundary(buffer, par, c);
889                 }
890         }
891
892 // I believe this code is not needed anymore (Jug 20050717)
893 #if 0
894         // The following code is necessary because the cursor position past
895         // the last char in a row is logically equivalent to that before
896         // the first char in the next row. That's why insets causing row
897         // divisions -- Newline and display-style insets -- must be treated
898         // specially, so cursor up/down doesn't get stuck in an air gap -- MV
899         // Newline inset, air gap below:
900         if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
901                 if (text_->bidi.level(end -1) % 2 == 0)
902                         tmpx -= text_->singleWidth(buffer, par, end - 1);
903                 else
904                         tmpx += text_->singleWidth(buffer, par, end - 1);
905                 c = end - 1;
906         }
907
908         // Air gap above display inset:
909         if (row.pos() < end && c >= end && end < par.size()
910             && par.isInset(end) && par.getInset(end)->display()) {
911                 c = end - 1;
912         }
913         // Air gap below display inset:
914         if (row.pos() < end && c >= end && par.isInset(end - 1)
915             && par.getInset(end - 1)->display()) {
916                 c = end - 1;
917         }
918 #endif
919
920         x = int(tmpx) + xo;
921         pos_type const col = c - row.pos();
922
923         if (!c || end == par.size())
924                 return col;
925
926         if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
927                 boundary = true;
928                 return col;
929         }
930
931         return min(col, end - 1 - row.pos());
932 }
933
934
935 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
936 {
937         ParagraphMetrics const & pm = parMetrics(pit);
938         BOOST_ASSERT(!pm.rows().empty());
939         BOOST_ASSERT(row < int(pm.rows().size()));
940         bool bound = false;
941         Row const & r = pm.rows()[row];
942         return r.pos() + getColumnNearX(pit, r, x, bound);
943 }
944
945
946 //int Text::pos2x(pit_type pit, pos_type pos) const
947 //{
948 //      ParagraphMetrics const & pm = parMetrics(pit);
949 //      Row const & r = pm.rows()[row];
950 //      int x = 0;
951 //      pos -= r.pos();
952 //}
953
954
955 int defaultRowHeight()
956 {
957         return int(theFontMetrics(Font(Font::ALL_SANE)).maxHeight() *  1.2);
958 }
959
960 } // namespace lyx