]> git.lyx.org Git - lyx.git/blob - src/TextMetrics.cpp
Get package things working with modules prior to UI patch.
[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 "Color.h"
26 #include "CoordCache.h"
27 #include "debug.h"
28 #include "FontIterator.h"
29 #include "FuncRequest.h"
30 #include "Length.h"
31 #include "LyXRC.h"
32 #include "MetricsInfo.h"
33 #include "paragraph_funcs.h"
34 #include "ParagraphParameters.h"
35 #include "ParIterator.h"
36 #include "rowpainter.h"
37 #include "Text.h"
38 #include "VSpace.h"
39
40 #include "frontends/FontMetrics.h"
41 #include "frontends/Painter.h"
42
43 using std::max;
44 using std::min;
45 using std::endl;
46
47 namespace lyx {
48
49 using frontend::FontMetrics;
50
51 namespace {
52
53 int numberOfSeparators(Paragraph const & par, Row const & row)
54 {
55         pos_type const first = max(row.pos(), par.beginOfBody());
56         pos_type const last = row.endpos() - 1;
57         int n = 0;
58         for (pos_type p = first; p < last; ++p) {
59                 if (par.isSeparator(p))
60                         ++n;
61         }
62         return n;
63 }
64
65
66 int numberOfLabelHfills(Paragraph const & par, Row const & row)
67 {
68         pos_type last = row.endpos() - 1;
69         pos_type first = row.pos();
70
71         // hfill *DO* count at the beginning of paragraphs!
72         if (first) {
73                 while (first < last && par.isHfill(first))
74                         ++first;
75         }
76
77         last = min(last, par.beginOfBody());
78         int n = 0;
79         for (pos_type p = first; p < last; ++p) {
80                 if (par.isHfill(p))
81                         ++n;
82         }
83         return n;
84 }
85
86
87 int numberOfHfills(Paragraph const & par, Row const & row)
88 {
89         pos_type const last = row.endpos();
90         pos_type first = row.pos();
91
92         // hfill *DO* count at the beginning of paragraphs!
93         if (first) {
94                 while (first < last && par.isHfill(first))
95                         ++first;
96         }
97
98         first = max(first, par.beginOfBody());
99
100         int n = 0;
101         for (pos_type p = first; p < last; ++p) {
102                 if (par.isHfill(p))
103                         ++n;
104         }
105         return n;
106 }
107
108 } // namespace anon
109
110 TextMetrics::TextMetrics(BufferView * bv, Text * text)
111         : bv_(bv), text_(text)
112 {
113         BOOST_ASSERT(bv_);
114         max_width_ = bv_->workWidth();
115         dim_.wid = max_width_;
116         dim_.asc = 10;
117         dim_.des = 10;
118
119         //text_->updateLabels(bv->buffer());
120 }
121
122
123 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
124 {
125         return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
126 }
127
128
129 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit,
130                 bool redo)
131 {
132         ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
133         if (pmc_it == par_metrics_.end()) {
134                 pmc_it = par_metrics_.insert(
135                         std::make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
136         }
137         if (pmc_it->second.rows().empty() && redo) {
138                 redoParagraph(pit);
139         }
140         return pmc_it->second;
141 }
142
143
144 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim)
145 {
146         BOOST_ASSERT(mi.base.textwidth);
147         max_width_ = mi.base.textwidth;
148
149         //lyxerr << "Text::metrics: width: " << mi.base.textwidth
150         //      << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
151
152         bool changed = false;
153
154         unsigned int h = 0;
155         unsigned int w = 0;
156         for (pit_type pit = 0, n = text_->paragraphs().size(); pit != n; ++pit) {
157                 changed |= redoParagraph(pit);
158                 ParagraphMetrics const & pm = par_metrics_[pit];
159                 h += pm.height();
160                 if (w < pm.width())
161                         w = pm.width();
162         }
163
164         dim.wid = w;
165         dim.asc = par_metrics_[0].ascent();
166         dim.des = h - dim.asc;
167
168         changed |= dim_ != dim;
169         dim_ = dim;
170         return changed;
171 }
172
173
174 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
175 {
176         return main_text_? pm.rightMargin(bv_->buffer()) : 0;
177 }
178
179
180 int TextMetrics::rightMargin(pit_type const pit) const
181 {
182         return main_text_? par_metrics_[pit].rightMargin(bv_->buffer()) : 0;
183 }
184
185
186 bool TextMetrics::redoParagraph(pit_type const pit)
187 {
188         Paragraph & par = text_->getPar(pit);
189         // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
190         // redoParagraph() recursively inside parMetrics.
191         Dimension old_dim = parMetrics(pit, false).dim();
192         ParagraphMetrics & pm = par_metrics_[pit];
193         pm.reset(par);
194
195         Buffer & buffer = bv_->buffer();
196         BufferParams const & bparams = buffer.params();
197         main_text_ = (text_ == &buffer.text());
198         bool changed = false;
199
200         // FIXME This check ought to be done somewhere else. It is the reason
201         // why text_ is not     const. But then, where else to do it?
202         // Well, how can you end up with either (a) a biblio environment that
203         // has no InsetBibitem or (b) a biblio environment with more than one
204         // InsetBibitem? I think the answer is: when paragraphs are merged;
205         // when layout is set; when material is pasted.
206         int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
207         if (moveCursor > 0)
208                 const_cast<Cursor &>(bv_->cursor()).posRight();
209         else if (moveCursor < 0) {
210                 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
211                 if (cursor.pos() >= -moveCursor)
212                         cursor.posLeft();
213         }
214
215         // Optimisation: this is used in the next two loops
216         // so better to calculate that once here.
217         int const right_margin = rightMargin(pm);
218
219         // redo insets
220         // FIXME: We should always use getFont(), see documentation of
221         // noFontChange() in Inset.h.
222         Font const bufferfont = buffer.params().getFont();
223         InsetList::const_iterator ii = par.insetlist.begin();
224         InsetList::const_iterator iend = par.insetlist.end();
225         for (; ii != iend; ++ii) {
226                 Dimension old_dim = ii->inset->dimension();
227                 Dimension dim;
228                 int const w = max_width_ - text_->leftMargin(buffer, max_width_, pit, ii->pos)
229                         - right_margin;
230                 Font const & font = ii->inset->noFontChange() ?
231                         bufferfont : text_->getFont(buffer, par, ii->pos);
232                 MetricsInfo mi(bv_, font, w);
233                 changed |= ii->inset->metrics(mi, dim);
234                 changed |= (old_dim != dim);
235         }
236
237         par.setBeginOfBody();
238         pos_type first = 0;
239         size_t row_index = 0;
240         // maximum pixel width of a row
241         int width = max_width_ - right_margin; // - leftMargin(buffer, max_width_, pit, row);
242         do {
243                 Dimension dim;
244                 pos_type end = rowBreakPoint(width, pit, first);
245                 dim.wid = rowWidth(right_margin, pit, first, end);
246                 boost::tie(dim.asc, dim.des) = rowHeight(pit, first, end);
247                 if (row_index == pm.rows().size())
248                         pm.rows().push_back(Row());
249                 Row & row = pm.rows()[row_index];
250                 row.pos(first);
251                 row.endpos(end);
252                 row.setDimension(dim);
253                 computeRowMetrics(pit, row);
254                 pm.computeRowSignature(row, bparams);
255                 first = end;
256                 ++row_index;
257
258                 pm.dim().wid = std::max(pm.dim().wid, dim.wid);
259                 pm.dim().des += dim.height();
260         } while (first < par.size());
261
262         if (row_index < pm.rows().size())
263                 pm.rows().resize(row_index);
264
265         // Make sure that if a par ends in newline, there is one more row
266         // under it
267         if (first > 0 && par.isNewline(first - 1)) {
268                 Dimension dim;
269                 dim.wid = rowWidth(right_margin, pit, first, first);
270                 boost::tie(dim.asc, dim.des) = rowHeight(pit, first, first);
271                 if (row_index == pm.rows().size())
272                         pm.rows().push_back(Row());
273                 Row & row = pm.rows()[row_index];
274                 row.pos(first);
275                 row.endpos(first);
276                 row.setDimension(dim);
277                 computeRowMetrics(pit, row);
278                 pm.computeRowSignature(row, bparams);
279                 pm.dim().des += dim.height();
280         }
281
282         pm.dim().asc += pm.rows()[0].ascent();
283         pm.dim().des -= pm.rows()[0].ascent();
284
285         changed |= old_dim.height() != pm.dim().height();
286
287         return changed;
288 }
289
290 void TextMetrics::computeRowMetrics(pit_type const pit,
291                 Row & row) const
292 {
293         Buffer & buffer = bv_->buffer();
294         Paragraph const & par = text_->getPar(pit);
295
296         double w = dim_.wid - row.width();
297
298         bool const is_rtl = text_->isRTL(buffer, par);
299         if (is_rtl)
300                 row.x = rightMargin(pit);
301         else
302                 row.x = text_->leftMargin(buffer, max_width_, pit, row.pos());
303
304         // is there a manual margin with a manual label
305         LayoutPtr const & layout = par.layout();
306
307         if (layout->margintype == MARGIN_MANUAL
308             && layout->labeltype == LABEL_MANUAL) {
309                 /// We might have real hfills in the label part
310                 int nlh = numberOfLabelHfills(par, row);
311
312                 // A manual label par (e.g. List) has an auto-hfill
313                 // between the label text and the body of the
314                 // paragraph too.
315                 // But we don't want to do this auto hfill if the par
316                 // is empty.
317                 if (!par.empty())
318                         ++nlh;
319
320                 if (nlh && !par.getLabelWidthString().empty())
321                         row.label_hfill = labelFill(pit, row) / double(nlh);
322         }
323
324         // are there any hfills in the row?
325         int const nh = numberOfHfills(par, row);
326
327         if (nh) {
328                 if (w > 0)
329                         row.hfill = w / nh;
330         // we don't have to look at the alignment if it is ALIGN_LEFT and
331         // if the row is already larger then the permitted width as then
332         // we force the LEFT_ALIGN'edness!
333         } else if (int(row.width()) < max_width_) {
334                 // is it block, flushleft or flushright?
335                 // set x how you need it
336                 int align;
337                 if (par.params().align() == LYX_ALIGN_LAYOUT)
338                         align = layout->align;
339                 else
340                         align = par.params().align();
341
342                 // Display-style insets should always be on a centred row
343                 // The test on par.size() is to catch zero-size pars, which
344                 // would trigger the assert in Paragraph::getInset().
345                 //inset = par.size() ? par.getInset(row.pos()) : 0;
346                 if (row.pos() < par.size()
347                     && par.isInset(row.pos()))
348                 {
349                     switch(par.getInset(row.pos())->display()) {
350                         case Inset::AlignLeft:
351                                 align = LYX_ALIGN_BLOCK;
352                                 break;
353                         case Inset::AlignCenter:
354                                 align = LYX_ALIGN_CENTER;
355                                 break;
356                         case Inset::Inline:
357                         case Inset::AlignRight:
358                                 // unchanged (use align)
359                                 break;
360                     }
361                 }
362
363                 switch (align) {
364                 case LYX_ALIGN_BLOCK: {
365                         int const ns = numberOfSeparators(par, row);
366                         bool disp_inset = false;
367                         if (row.endpos() < par.size()) {
368                                 Inset const * in = par.getInset(row.endpos());
369                                 if (in)
370                                         disp_inset = in->display();
371                         }
372                         // If we have separators, this is not the last row of a
373                         // par, does not end in newline, and is not row above a
374                         // display inset... then stretch it
375                         if (ns
376                             && row.endpos() < par.size()
377                             && !par.isNewline(row.endpos() - 1)
378                             && !disp_inset
379                                 ) {
380                                 row.separator = w / ns;
381                         } else if (is_rtl) {
382                                 row.x += w;
383                         }
384                         break;
385                 }
386                 case LYX_ALIGN_RIGHT:
387                         row.x += w;
388                         break;
389                 case LYX_ALIGN_CENTER:
390                         row.x += w / 2;
391                         break;
392                 }
393         }
394
395         if (is_rtl) {
396                 pos_type body_pos = par.beginOfBody();
397                 pos_type end = row.endpos();
398
399                 if (body_pos > 0
400                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
401                 {
402                         row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
403                                 width(layout->labelsep);
404                         if (body_pos <= end)
405                                 row.x += row.label_hfill;
406                 }
407         }
408 }
409
410
411 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
412 {
413         Buffer & buffer = bv_->buffer();
414         Paragraph const & par = text_->getPar(pit);
415
416         pos_type last = par.beginOfBody();
417         BOOST_ASSERT(last > 0);
418
419         // -1 because a label ends with a space that is in the label
420         --last;
421
422         // a separator at this end does not count
423         if (par.isLineSeparator(last))
424                 --last;
425
426         int w = 0;
427         for (pos_type i = row.pos(); i <= last; ++i)
428                 w += singleWidth(pit, i);
429
430         docstring const & label = par.params().labelWidthString();
431         if (label.empty())
432                 return 0;
433
434         FontMetrics const & fm
435                 = theFontMetrics(text_->getLabelFont(buffer, par));
436
437         return max(0, fm.width(label) - w);
438 }
439
440
441 namespace {
442
443 // this needs special handling - only newlines count as a break point
444 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
445 {
446         pos_type const end = par.size();
447
448         for (; i < end; ++i)
449                 if (par.isNewline(i))
450                         return i + 1;
451
452         return end;
453 }
454
455 };
456
457
458 int TextMetrics::labelEnd(pit_type const pit) const
459 {
460         // labelEnd is only needed if the layout fills a flushleft label.
461         if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
462                 return 0;
463         // return the beginning of the body
464         return text_->leftMargin(bv_->buffer(), max_width_, pit);
465 }
466
467
468 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
469                 pit_type pos) const
470 {
471         Buffer & buffer = bv_->buffer();
472         ParagraphMetrics const & pm = par_metrics_[pit];
473         Paragraph const & par = text_->getPar(pit);
474         pos_type const end = par.size();
475         if (pos == end || width < 0)
476                 return end;
477
478         LayoutPtr const & layout = par.layout();
479
480         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
481                 return addressBreakPoint(pos, par);
482
483         pos_type const body_pos = par.beginOfBody();
484
485
486         // Now we iterate through until we reach the right margin
487         // or the end of the par, then choose the possible break
488         // nearest that.
489
490         int label_end = labelEnd(pit);
491         int const left = text_->leftMargin(buffer, max_width_, pit, pos);
492         int x = left;
493
494         // pixel width since last breakpoint
495         int chunkwidth = 0;
496
497         FontIterator fi = FontIterator(buffer, *text_, par, pos);
498         pos_type point = end;
499         pos_type i = pos;
500         for ( ; i < end; ++i, ++fi) {
501                 int thiswidth = pm.singleWidth(i, *fi);
502
503                 // add the auto-hfill from label end to the body
504                 if (body_pos && i == body_pos) {
505                         FontMetrics const & fm = theFontMetrics(
506                                 text_->getLabelFont(buffer, par));
507                         int add = fm.width(layout->labelsep);
508                         if (par.isLineSeparator(i - 1))
509                                 add -= singleWidth(pit, i - 1);
510
511                         add = std::max(add, label_end - x);
512                         thiswidth += add;
513                 }
514
515                 x += thiswidth;
516                 chunkwidth += thiswidth;
517
518                 // break before a character that will fall off
519                 // the right of the row
520                 if (x >= width) {
521                         // if no break before, break here
522                         if (point == end || chunkwidth >= width - left) {
523                                 if (i > pos)
524                                         point = i;
525                                 else
526                                         point = i + 1;
527
528                         }
529                         // exit on last registered breakpoint:
530                         break;
531                 }
532
533                 if (par.isNewline(i)) {
534                         point = i + 1;
535                         break;
536                 }
537                 // Break before...
538                 if (i + 1 < end) {
539                         if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
540                                 point = i + 1;
541                                 break;
542                         }
543                         // ...and after.
544                         if (par.isInset(i) && par.getInset(i)->display()) {
545                                 point = i + 1;
546                                 break;
547                         }
548                 }
549
550                 if (!par.isInset(i) || par.getInset(i)->isChar()) {
551                         // some insets are line separators too
552                         if (par.isLineSeparator(i)) {
553                                 // register breakpoint:
554                                 point = i + 1;
555                                 chunkwidth = 0;
556                         }
557                 }
558         }
559
560         // maybe found one, but the par is short enough.
561         if (i == end && x < width)
562                 point = end;
563
564         // manual labels cannot be broken in LaTeX. But we
565         // want to make our on-screen rendering of footnotes
566         // etc. still break
567         if (body_pos && point < body_pos)
568                 point = body_pos;
569
570         return point;
571 }
572
573
574 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
575                 pos_type const first, pos_type const end) const
576 {
577         Buffer & buffer = bv_->buffer();
578         // get the pure distance
579         ParagraphMetrics const & pm = par_metrics_[pit];
580         Paragraph const & par = text_->getPar(pit);
581         int w = text_->leftMargin(buffer, max_width_, pit, first);
582         int label_end = labelEnd(pit);
583
584         pos_type const body_pos = par.beginOfBody();
585         pos_type i = first;
586
587         if (i < end) {
588                 FontIterator fi = FontIterator(buffer, *text_, par, i);
589                 for ( ; i < end; ++i, ++fi) {
590                         if (body_pos > 0 && i == body_pos) {
591                                 FontMetrics const & fm = theFontMetrics(
592                                         text_->getLabelFont(buffer, par));
593                                 w += fm.width(par.layout()->labelsep);
594                                 if (par.isLineSeparator(i - 1))
595                                         w -= singleWidth(pit, i - 1);
596                                 w = max(w, label_end);
597                         }
598                         w += pm.singleWidth(i, *fi);
599                 }
600         }
601
602         if (body_pos > 0 && body_pos >= end) {
603                 FontMetrics const & fm = theFontMetrics(
604                         text_->getLabelFont(buffer, par));
605                 w += fm.width(par.layout()->labelsep);
606                 if (end > 0 && par.isLineSeparator(end - 1))
607                         w -= singleWidth(pit, end - 1);
608                 w = max(w, label_end);
609         }
610
611         return w + right_margin;
612 }
613
614
615 boost::tuple<int, int> TextMetrics::rowHeight(pit_type const pit, pos_type const first,
616                 pos_type const end) const
617 {
618         Paragraph const & par = text_->getPar(pit);
619         // get the maximum ascent and the maximum descent
620         double layoutasc = 0;
621         double layoutdesc = 0;
622         double const dh = defaultRowHeight();
623
624         // ok, let us initialize the maxasc and maxdesc value.
625         // Only the fontsize count. The other properties
626         // are taken from the layoutfont. Nicer on the screen :)
627         LayoutPtr const & layout = par.layout();
628
629         // as max get the first character of this row then it can
630         // increase but not decrease the height. Just some point to
631         // start with so we don't have to do the assignment below too
632         // often.
633         Buffer const & buffer = bv_->buffer();
634         Font font = text_->getFont(buffer, par, first);
635         Font::FONT_SIZE const tmpsize = font.size();
636         font = text_->getLayoutFont(buffer, pit);
637         Font::FONT_SIZE const size = font.size();
638         font.setSize(tmpsize);
639
640         Font labelfont = text_->getLabelFont(buffer, par);
641
642         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
643         FontMetrics const & fontmetrics = theFontMetrics(font);
644
645         // these are minimum values
646         double const spacing_val = layout->spacing.getValue()
647                 * text_->spacing(buffer, par);
648         //lyxerr << "spacing_val = " << spacing_val << endl;
649         int maxasc  = int(fontmetrics.maxAscent()  * spacing_val);
650         int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
651
652         // insets may be taller
653         InsetList::const_iterator ii = par.insetlist.begin();
654         InsetList::const_iterator iend = par.insetlist.end();
655         for ( ; ii != iend; ++ii) {
656                 if (ii->pos >= first && ii->pos < end) {
657                         maxasc  = max(maxasc,  ii->inset->ascent());
658                         maxdesc = max(maxdesc, ii->inset->descent());
659                 }
660         }
661
662         // Check if any custom fonts are larger (Asger)
663         // This is not completely correct, but we can live with the small,
664         // cosmetic error for now.
665         int labeladdon = 0;
666
667         Font::FONT_SIZE maxsize =
668                 par.highestFontInRange(first, end, size);
669         if (maxsize > font.size()) {
670                 // use standard paragraph font with the maximal size
671                 Font maxfont = font;
672                 maxfont.setSize(maxsize);
673                 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
674                 maxasc  = max(maxasc,  maxfontmetrics.maxAscent());
675                 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
676         }
677
678         // This is nicer with box insets:
679         ++maxasc;
680         ++maxdesc;
681
682         ParagraphList const & pars = text_->paragraphs();
683
684         // is it a top line?
685         if (first == 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 || first != 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 (end >= 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 && first == 0)
793                         maxasc += 20;
794                 if (pit + 1 == pit_type(pars.size()) &&
795                     end == par.size() &&
796                                 !(end > 0 && par.isNewline(end - 1)))
797                         maxdesc += 20;
798         }
799
800         return boost::make_tuple(maxasc + labeladdon, maxdesc);
801 }
802
803
804 // x is an absolute screen coord
805 // returns the column near the specified x-coordinate of the row
806 // x is set to the real beginning of this column
807 pos_type TextMetrics::getColumnNearX(pit_type const pit,
808                 Row const & row, int & x, bool & boundary) const
809 {
810         Buffer const & buffer = bv_->buffer();
811
812         /// For the main Text, it is possible that this pit is not
813         /// yet in the CoordCache when moving cursor up.
814         /// x Paragraph coordinate is always 0 for main text anyway.
815         int const xo = main_text_? 0 : bv_->coordCache().get(text_, pit).x_;
816         x -= xo;
817         Paragraph const & par = text_->getPar(pit);
818         Bidi bidi;
819         bidi.computeTables(par, buffer, row);
820
821         pos_type vc = row.pos();
822         pos_type end = row.endpos();
823         pos_type c = 0;
824         LayoutPtr const & layout = par.layout();
825
826         bool left_side = false;
827
828         pos_type body_pos = par.beginOfBody();
829
830         double tmpx = row.x;
831         double last_tmpx = tmpx;
832
833         if (body_pos > 0 &&
834             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
835                 body_pos = 0;
836
837         // check for empty row
838         if (vc == end) {
839                 x = int(tmpx) + xo;
840                 return 0;
841         }
842
843         while (vc < end && tmpx <= x) {
844                 c = bidi.vis2log(vc);
845                 last_tmpx = tmpx;
846                 if (body_pos > 0 && c == body_pos - 1) {
847                         FontMetrics const & fm = theFontMetrics(
848                                 text_->getLabelFont(buffer, par));
849                         tmpx += row.label_hfill + fm.width(layout->labelsep);
850                         if (par.isLineSeparator(body_pos - 1))
851                                 tmpx -= singleWidth(pit, body_pos - 1);
852                 }
853
854                 if (par.hfillExpansion(row, c)) {
855                         tmpx += singleWidth(pit, c);
856                         if (c >= body_pos)
857                                 tmpx += row.hfill;
858                         else
859                                 tmpx += row.label_hfill;
860                 } else if (par.isSeparator(c)) {
861                         tmpx += singleWidth(pit, c);
862                         if (c >= body_pos)
863                                 tmpx += row.separator;
864                 } else {
865                         tmpx += singleWidth(pit, c);
866                 }
867                 ++vc;
868         }
869
870         if ((tmpx + last_tmpx) / 2 > x) {
871                 tmpx = last_tmpx;
872                 left_side = true;
873         }
874
875         BOOST_ASSERT(vc <= end);  // This shouldn't happen.
876
877         boundary = false;
878         // This (rtl_support test) is not needed, but gives
879         // some speedup if rtl_support == false
880         bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
881
882         // If lastrow is false, we don't need to compute
883         // the value of rtl.
884         bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
885         if (lastrow &&
886             ((rtl  &&  left_side && vc == row.pos() && x < tmpx - 5) ||
887              (!rtl && !left_side && vc == end  && x > tmpx + 5)))
888                 c = end;
889         else if (vc == row.pos()) {
890                 c = bidi.vis2log(vc);
891                 if (bidi.level(c) % 2 == 1)
892                         ++c;
893         } else {
894                 c = bidi.vis2log(vc - 1);
895                 bool const rtl = (bidi.level(c) % 2 == 1);
896                 if (left_side == rtl) {
897                         ++c;
898                         boundary = text_->isRTLBoundary(buffer, par, c);
899                 }
900         }
901
902 // I believe this code is not needed anymore (Jug 20050717)
903 #if 0
904         // The following code is necessary because the cursor position past
905         // the last char in a row is logically equivalent to that before
906         // the first char in the next row. That's why insets causing row
907         // divisions -- Newline and display-style insets -- must be treated
908         // specially, so cursor up/down doesn't get stuck in an air gap -- MV
909         // Newline inset, air gap below:
910         if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
911                 if (bidi.level(end -1) % 2 == 0)
912                         tmpx -= singleWidth(pit, end - 1);
913                 else
914                         tmpx += singleWidth(pit, end - 1);
915                 c = end - 1;
916         }
917
918         // Air gap above display inset:
919         if (row.pos() < end && c >= end && end < par.size()
920             && par.isInset(end) && par.getInset(end)->display()) {
921                 c = end - 1;
922         }
923         // Air gap below display inset:
924         if (row.pos() < end && c >= end && par.isInset(end - 1)
925             && par.getInset(end - 1)->display()) {
926                 c = end - 1;
927         }
928 #endif
929
930         x = int(tmpx) + xo;
931         pos_type const col = c - row.pos();
932
933         if (!c || end == par.size())
934                 return col;
935
936         if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
937                 boundary = true;
938                 return col;
939         }
940
941         return min(col, end - 1 - row.pos());
942 }
943
944
945 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
946 {
947         ParagraphMetrics const & pm = par_metrics_[pit];
948         BOOST_ASSERT(!pm.rows().empty());
949         BOOST_ASSERT(row < int(pm.rows().size()));
950         bool bound = false;
951         Row const & r = pm.rows()[row];
952         return r.pos() + getColumnNearX(pit, r, x, bound);
953 }
954
955
956 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
957 {
958         Buffer const & buffer = bv_->buffer();
959         ParagraphMetrics const & pm = par_metrics_[pit];
960
961         return pm.singleWidth(pos, text_->getFont(buffer, text_->getPar(pit), pos));
962 }
963
964
965 // only used for inset right now. should also be used for main text
966 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
967 {
968         if (par_metrics_.empty())
969                 return;
970         ParMetricsCache::const_iterator it = par_metrics_.begin();
971         ParMetricsCache::const_iterator const end = par_metrics_.end();
972         y -= it->second.ascent();
973         for (; it != end; ++it) {
974                 ParagraphMetrics const & pmi = it->second;
975                 y += pmi.ascent();
976                 drawParagraph(pi, it->first, x, y, true);
977                 y += pmi.descent();
978         }
979 }
980
981
982 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y,
983          bool repaintAll) const
984 {
985 //      lyxerr << "  paintPar: pit: " << pit << " at y: " << y << endl;
986         int const ww = bv_->workHeight();
987
988         bv_->coordCache().parPos()[text_][pit] = Point(x, y);
989
990         ParagraphMetrics const & pm = par_metrics_[pit];
991         if (pm.rows().empty())
992                 return;
993
994         RowList::const_iterator const rb = pm.rows().begin();
995         RowList::const_iterator const re = pm.rows().end();
996
997         Bidi bidi;
998
999         y -= rb->ascent();
1000         for (RowList::const_iterator rit = rb; rit != re; ++rit) {
1001                 y += rit->ascent();
1002                 // Row signature; has row changed since last paint?
1003                 bool row_has_changed = rit->changed();
1004
1005                 // Paint the row if a full repaint has been requested or it has
1006                 // changed.
1007                 if (repaintAll || row_has_changed) {
1008                         bool const inside = (y + rit->descent() >= 0
1009                                 && y - rit->ascent() < ww);
1010                         // it is not needed to draw on screen if we are not inside.
1011                         pi.pain.setDrawingEnabled(inside);
1012                         RowPainter rp(pi, *text_, pit, *rit, bidi, x, y);
1013                         // Clear background of this row
1014                         // (if paragraph background was not cleared)
1015                         if (!repaintAll && row_has_changed)
1016                                 pi.pain.fillRectangle(x, y - rit->ascent(),
1017                                         width(), rit->height(),
1018                                         text_->backgroundColor());
1019
1020                         // Instrumentation for testing row cache (see also
1021                         // 12 lines lower):
1022                         if (lyxerr.debugging(Debug::PAINTING)) {
1023                                 if (text_->isMainText(bv_->buffer()))
1024                                         LYXERR(Debug::PAINTING) << "#";
1025                                 else
1026                                         LYXERR(Debug::PAINTING) << "[" <<
1027                                                 repaintAll << row_has_changed << "]";
1028                         }
1029                         rp.paintAppendix();
1030                         rp.paintDepthBar();
1031                         rp.paintChangeBar();
1032                         if (rit == rb)
1033                                 rp.paintFirst();
1034                         rp.paintText();
1035                         if (rit + 1 == re)
1036                                 rp.paintLast();
1037                 }
1038                 y += rit->descent();
1039         }
1040         // Re-enable screen drawing for future use of the painter.
1041         pi.pain.setDrawingEnabled(true);
1042
1043         LYXERR(Debug::PAINTING) << "." << endl;
1044 }
1045
1046 //int Text::pos2x(pit_type pit, pos_type pos) const
1047 //{
1048 //      ParagraphMetrics const & pm = par_metrics_[pit];
1049 //      Row const & r = pm.rows()[row];
1050 //      int x = 0;
1051 //      pos -= r.pos();
1052 //}
1053
1054
1055 int defaultRowHeight()
1056 {
1057         return int(theFontMetrics(Font(Font::ALL_SANE)).maxHeight() *  1.2);
1058 }
1059
1060 } // namespace lyx