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