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