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