]> git.lyx.org Git - lyx.git/blob - src/TextMetrics.C
make out-of-bound access impossible
[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 "pariterator.h"
26 #include "coordcache.h"
27 #include "debug.h"
28 #include "funcrequest.h"
29 #include "FontIterator.h"
30 #include "LColor.h"
31 #include "lyxlength.h"
32 #include "lyxtext.h"
33 #include "metricsinfo.h"
34 #include "ParagraphParameters.h"
35 #include "vspace.h"
36
37 #include "frontends/FontMetrics.h"
38 #include "frontends/Painter.h"
39
40 using std::max;
41 using std::min;
42 using std::endl;
43
44 namespace lyx {
45
46 using frontend::FontMetrics;
47
48 namespace {
49
50 int numberOfSeparators(Paragraph const & par, Row const & row)
51 {
52         pos_type const first = max(row.pos(), par.beginOfBody());
53         pos_type const last = row.endpos() - 1;
54         int n = 0;
55         for (pos_type p = first; p < last; ++p) {
56                 if (par.isSeparator(p))
57                         ++n;
58         }
59         return n;
60 }
61
62
63 int numberOfLabelHfills(Paragraph const & par, Row const & row)
64 {
65         pos_type last = row.endpos() - 1;
66         pos_type first = row.pos();
67
68         // hfill *DO* count at the beginning of paragraphs!
69         if (first) {
70                 while (first < last && par.isHfill(first))
71                         ++first;
72         }
73
74         last = min(last, par.beginOfBody());
75         int n = 0;
76         for (pos_type p = first; p < last; ++p) {
77                 if (par.isHfill(p))
78                         ++n;
79         }
80         return n;
81 }
82
83
84 int numberOfHfills(Paragraph const & par, Row const & row)
85 {
86         pos_type last = row.endpos();
87         pos_type first = row.pos();
88         pos_type const par_size = par.size();
89
90         // hfill *DO* count at the beginning of paragraphs!
91         if (first) {
92                 while (first < last && first < par_size && par.isHfill(first))
93                         ++first;
94         }
95
96         first = max(first, par.beginOfBody());
97         last = min(last, par_size);
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         do {
224                 Row row(z);
225                 text_->rowBreakPoint(buffer, right_margin, max_width_, pit, row);
226                 text_->setRowWidth(buffer, right_margin, max_width_, pit, row);
227                 text_->setHeightOfRow(*bv_, pit, row);
228                 pm.rows().push_back(row);
229                 pm.dim().wid = std::max(pm.dim().wid, row.width());
230                 pm.dim().des += row.height();
231                 z = row.endpos();
232         } while (z < par.size());
233
234         // Make sure that if a par ends in newline, there is one more row
235         // under it
236         // FIXME this is a dirty trick. Now the _same_ position in the
237         // paragraph occurs in _two_ different rows, and has two different
238         // display positions, leading to weird behaviour when moving up/down.
239         if (z > 0 && par.isNewline(z - 1)) {
240                 Row row(z - 1);
241                 row.endpos(z - 1);
242                 text_->setRowWidth(buffer, right_margin, max_width_, pit, row);
243                 text_->setHeightOfRow(*bv_, pit, row);
244                 pm.rows().push_back(row);
245                 pm.dim().des += row.height();
246         }
247
248         pm.dim().asc += pm.rows()[0].ascent();
249         pm.dim().des -= pm.rows()[0].ascent();
250
251         // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
252         // redoParagraph() recursively inside parMetrics.
253         Dimension old_dim = parMetrics(pit, false).dim();
254
255         changed |= old_dim.height() != pm.dim().height();
256
257         par_metrics_[pit] = pm;
258
259         return changed;
260 }
261
262 RowMetrics TextMetrics::computeRowMetrics(pit_type const pit,
263                 Row const & row) const
264 {
265         RowMetrics result;
266         Buffer & buffer = *bv_->buffer();
267         Paragraph const & par = text_->getPar(pit);
268
269         double w = dim_.wid - row.width();
270
271         bool const is_rtl = text_->isRTL(buffer, par);
272         if (is_rtl)
273                 result.x = rightMargin(pit);
274         else
275                 result.x = text_->leftMargin(buffer, max_width_, pit, row.pos());
276
277         // is there a manual margin with a manual label
278         LyXLayout_ptr const & layout = par.layout();
279
280         if (layout->margintype == MARGIN_MANUAL
281             && layout->labeltype == LABEL_MANUAL) {
282                 /// We might have real hfills in the label part
283                 int nlh = numberOfLabelHfills(par, row);
284
285                 // A manual label par (e.g. List) has an auto-hfill
286                 // between the label text and the body of the
287                 // paragraph too.
288                 // But we don't want to do this auto hfill if the par
289                 // is empty.
290                 if (!par.empty())
291                         ++nlh;
292
293                 if (nlh && !par.getLabelWidthString().empty())
294                         result.label_hfill = labelFill(par, row) / double(nlh);
295         }
296
297         // are there any hfills in the row?
298         int const nh = numberOfHfills(par, row);
299
300         if (nh) {
301                 if (w > 0)
302                         result.hfill = w / nh;
303         // we don't have to look at the alignment if it is ALIGN_LEFT and
304         // if the row is already larger then the permitted width as then
305         // we force the LEFT_ALIGN'edness!
306         } else if (int(row.width()) < max_width_) {
307                 // is it block, flushleft or flushright?
308                 // set x how you need it
309                 int align;
310                 if (par.params().align() == LYX_ALIGN_LAYOUT)
311                         align = layout->align;
312                 else
313                         align = par.params().align();
314
315                 // Display-style insets should always be on a centred row
316                 // The test on par.size() is to catch zero-size pars, which
317                 // would trigger the assert in Paragraph::getInset().
318                 //inset = par.size() ? par.getInset(row.pos()) : 0;
319                 if (!par.empty()
320                     && par.isInset(row.pos())
321                     && par.getInset(row.pos())->display())
322                 {
323                         align = LYX_ALIGN_CENTER;
324                 }
325
326                 switch (align) {
327                 case LYX_ALIGN_BLOCK: {
328                         int const ns = numberOfSeparators(par, row);
329                         bool disp_inset = false;
330                         if (row.endpos() < par.size()) {
331                                 InsetBase const * in = par.getInset(row.endpos());
332                                 if (in)
333                                         disp_inset = in->display();
334                         }
335                         // If we have separators, this is not the last row of a
336                         // par, does not end in newline, and is not row above a
337                         // display inset... then stretch it
338                         if (ns
339                             && row.endpos() < par.size()
340                             && !par.isNewline(row.endpos() - 1)
341                             && !disp_inset
342                                 ) {
343                                 result.separator = w / ns;
344                         } else if (is_rtl) {
345                                 result.x += w;
346                         }
347                         break;
348                 }
349                 case LYX_ALIGN_RIGHT:
350                         result.x += w;
351                         break;
352                 case LYX_ALIGN_CENTER:
353                         result.x += w / 2;
354                         break;
355                 }
356         }
357
358         text_->bidi.computeTables(par, buffer, row);
359         if (is_rtl) {
360                 pos_type body_pos = par.beginOfBody();
361                 pos_type end = row.endpos();
362
363                 if (body_pos > 0
364                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
365                 {
366                         docstring const lsep = from_utf8(layout->labelsep);
367                         result.x += theFontMetrics(text_->getLabelFont(buffer, par)).width(lsep);
368                         if (body_pos <= end)
369                                 result.x += result.label_hfill;
370                 }
371         }
372
373         return result;
374 }
375
376
377 int TextMetrics::labelFill(Paragraph const & par, Row const & row) const
378 {
379         Buffer & buffer = *bv_->buffer();
380
381         pos_type last = par.beginOfBody();
382         BOOST_ASSERT(last > 0);
383
384         // -1 because a label ends with a space that is in the label
385         --last;
386
387         // a separator at this end does not count
388         if (par.isLineSeparator(last))
389                 --last;
390
391         int w = 0;
392         for (pos_type i = row.pos(); i <= last; ++i)
393                 w += text_->singleWidth(buffer, par, i);
394
395         docstring const & label = par.params().labelWidthString();
396         if (label.empty())
397                 return 0;
398
399         FontMetrics const & fm 
400                 = theFontMetrics(text_->getLabelFont(buffer, par));
401
402         return max(0, fm.width(label) - w);
403 }
404
405
406 int defaultRowHeight()
407 {
408         return int(theFontMetrics(LyXFont(LyXFont::ALL_SANE)).maxHeight() *  1.2);
409 }
410
411 } // namespace lyx