]> git.lyx.org Git - lyx.git/blob - src/TextMetrics.cpp
bc74d71efe4069e67d15d0d96bf46d08c0bb8d74
[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 "Bidi.h"
23 #include "Buffer.h"
24 #include "buffer_funcs.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "CoordCache.h"
28 #include "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "debug.h"
31 #include "FontIterator.h"
32 #include "FuncRequest.h"
33 #include "InsetList.h"
34 #include "Layout.h"
35 #include "Length.h"
36 #include "LyXRC.h"
37 #include "MetricsInfo.h"
38 #include "paragraph_funcs.h"
39 #include "ParagraphParameters.h"
40 #include "ParIterator.h"
41 #include "rowpainter.h"
42 #include "Text.h"
43 #include "TextClass.h"
44 #include "VSpace.h"
45
46 #include "mathed/MacroTable.h"
47 #include "mathed/MathMacroTemplate.h"
48
49 #include "frontends/FontMetrics.h"
50 #include "frontends/Painter.h"
51
52 #include <boost/current_function.hpp>
53
54 using std::make_pair;
55 using std::max;
56 using std::min;
57 using std::endl;
58 using std::pair;
59
60 namespace lyx {
61
62 using frontend::FontMetrics;
63
64 namespace {
65
66 int numberOfSeparators(Paragraph const & par, Row const & row)
67 {
68         pos_type const first = max(row.pos(), par.beginOfBody());
69         pos_type const last = row.endpos() - 1;
70         int n = 0;
71         for (pos_type p = first; p < last; ++p) {
72                 if (par.isSeparator(p))
73                         ++n;
74         }
75         return n;
76 }
77
78
79 int numberOfLabelHfills(Paragraph const & par, Row const & row)
80 {
81         pos_type last = row.endpos() - 1;
82         pos_type first = row.pos();
83
84         // hfill *DO* count at the beginning of paragraphs!
85         if (first) {
86                 while (first < last && par.isHfill(first))
87                         ++first;
88         }
89
90         last = min(last, par.beginOfBody());
91         int n = 0;
92         for (pos_type p = first; p < last; ++p) {
93                 if (par.isHfill(p))
94                         ++n;
95         }
96         return n;
97 }
98
99
100 int numberOfHfills(Paragraph const & par, Row const & row)
101 {
102         pos_type const last = row.endpos();
103         pos_type first = row.pos();
104
105         // hfill *DO* count at the beginning of paragraphs!
106         if (first) {
107                 while (first < last && par.isHfill(first))
108                         ++first;
109         }
110
111         first = max(first, par.beginOfBody());
112
113         int n = 0;
114         for (pos_type p = first; p < last; ++p) {
115                 if (par.isHfill(p))
116                         ++n;
117         }
118         return n;
119 }
120
121 } // namespace anon
122
123 TextMetrics::TextMetrics(BufferView * bv, Text * text)
124         : bv_(bv), text_(text)
125 {
126         BOOST_ASSERT(bv_);
127         max_width_ = bv_->workWidth();
128         dim_.wid = max_width_;
129         dim_.asc = 10;
130         dim_.des = 10;
131
132         //text_->updateLabels(bv->buffer());
133 }
134
135
136 bool TextMetrics::has(pit_type pit) const
137 {
138         return par_metrics_.find(pit) != par_metrics_.end();
139 }
140
141
142 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
143 {
144         return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
145 }
146
147
148
149 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
150 {
151         ParMetricsCache::const_iterator it = par_metrics_.begin();
152         return make_pair(it->first, &it->second);
153 }
154
155
156 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
157 {
158         ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
159         return make_pair(it->first, &it->second);
160 }
161
162
163 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
164 {
165         ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
166         if (pmc_it == par_metrics_.end()) {
167                 pmc_it = par_metrics_.insert(
168                         make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
169         }
170         if (pmc_it->second.rows().empty() && redo)
171                 redoParagraph(pit);
172         return pmc_it->second;
173 }
174
175
176 int TextMetrics::parPosition(pit_type pit) const
177 {
178         if (pit < par_metrics_.begin()->first)
179                 return -1000000;
180         if (pit > par_metrics_.rbegin()->first)
181                 return +1000000;
182
183         return par_metrics_[pit].position();
184 }
185
186
187 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
188 {
189         BOOST_ASSERT(mi.base.textwidth);
190         max_width_ = mi.base.textwidth;
191         // backup old dimension.
192         Dimension const old_dim = dim_;
193         // reset dimension.
194         dim_ = Dimension();
195         dim_.wid = min_width;
196         pit_type const npar = text_->paragraphs().size();
197         if (npar > 1)
198                 // If there is more than one row, expand the text to 
199                 // the full allowable width.
200                 dim_.wid = max_width_;
201
202         //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
203         //      << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
204
205         bool changed = false;
206         unsigned int h = 0;
207         for (pit_type pit = 0; pit != npar; ++pit) {
208                 changed |= redoParagraph(pit);
209                 ParagraphMetrics const & pm = par_metrics_[pit];
210                 h += pm.height();
211                 if (dim_.wid < pm.width())
212                         dim_.wid = pm.width();
213         }
214
215         dim_.asc = par_metrics_[0].ascent();
216         dim_.des = h - dim_.asc;
217         //lyxerr << "dim_.wid " << dim_.wid << endl;
218         //lyxerr << "dim_.asc " << dim_.asc << endl;
219         //lyxerr << "dim_.des " << dim_.des << endl;
220
221         changed |= dim_ != old_dim;
222         dim = dim_;
223         return changed;
224 }
225
226
227 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
228 {
229         return main_text_? pm.rightMargin(bv_->buffer()) : 0;
230 }
231
232
233 int TextMetrics::rightMargin(pit_type const pit) const
234 {
235         return main_text_? par_metrics_[pit].rightMargin(bv_->buffer()) : 0;
236 }
237
238
239 void TextMetrics::applyOuterFont(Font & font) const
240 {
241         Font lf(font_);
242         lf.fontInfo().reduce(bv_->buffer().params().getFont().fontInfo());
243         lf.fontInfo().realize(font.fontInfo());
244         lf.setLanguage(font.language());
245         font = lf;
246 }
247
248
249 Font TextMetrics::getDisplayFont(pit_type pit, pos_type pos) const
250 {
251         BOOST_ASSERT(pos >= 0);
252
253         ParagraphList const & pars = text_->paragraphs();
254         Paragraph const & par = pars[pit];
255         LayoutPtr const & layout = par.layout();
256         Buffer const & buffer = bv_->buffer();
257         // FIXME: broken?
258         BufferParams const & params = buffer.params();
259         pos_type const body_pos = par.beginOfBody();
260
261         // We specialize the 95% common case:
262         if (!par.getDepth()) {
263                 Font f = par.getFontSettings(params, pos);
264                 if (!text_->isMainText(buffer))
265                         applyOuterFont(f);
266                 bool lab = layout->labeltype == LABEL_MANUAL && pos < body_pos;
267
268                 FontInfo const & lf = lab ? layout->labelfont : layout->font;
269                 FontInfo rlf = lab ? layout->reslabelfont : layout->resfont;
270                 
271                 // In case the default family has been customized
272                 if (lf.family() == INHERIT_FAMILY)
273                         rlf.setFamily(params.getFont().fontInfo().family());
274                 f.fontInfo().realize(rlf);
275                 return f;
276         }
277
278         // The uncommon case need not be optimized as much
279         FontInfo const & layoutfont = pos < body_pos ? 
280                 layout->labelfont : layout->font;
281
282         Font font = par.getFontSettings(params, pos);
283         font.fontInfo().realize(layoutfont);
284
285         if (!text_->isMainText(buffer))
286                 applyOuterFont(font);
287
288         // Realize against environment font information
289         // NOTE: the cast to pit_type should be removed when pit_type
290         // changes to a unsigned integer.
291         if (pit < pit_type(pars.size()))
292                 font.fontInfo().realize(outerFont(pit, pars).fontInfo());
293
294         // Realize with the fonts of lesser depth.
295         font.fontInfo().realize(params.getFont().fontInfo());
296
297         return font;
298 }
299
300
301 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
302 {
303         if (!lyxrc.rtl_support || !sl.text())
304                 return false;
305
306         int correction = 0;
307         if (boundary && sl.pos() > 0)
308                 correction = -1;
309                 
310         return getDisplayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
311 }
312
313
314 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
315 {
316         if (!lyxrc.rtl_support)
317                 return false;
318
319         // no RTL boundary at line start
320         if (pos == 0)
321                 return false;
322
323         Paragraph const & par = text_->getPar(pit);
324
325         bool left = getDisplayFont(pit, pos - 1).isVisibleRightToLeft();
326         bool right;
327         if (pos == par.size())
328                 right = par.isRTL(bv_->buffer().params());
329         else
330                 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
331         return left != right;
332 }
333
334
335 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
336                 Font const & font) const
337 {
338         if (!lyxrc.rtl_support)
339                 return false;
340
341         Paragraph const & par = text_->getPar(pit);
342         bool left = font.isVisibleRightToLeft();
343         bool right;
344         if (pos == par.size())
345                 right = par.isRTL(bv_->buffer().params());
346         else
347                 right = getDisplayFont(pit, pos).isVisibleRightToLeft();
348         return left != right;
349 }
350
351
352 bool TextMetrics::redoParagraph(pit_type const pit)
353 {
354         Paragraph & par = text_->getPar(pit);
355         // IMPORTANT NOTE: We pass 'false' explicitely in order to not call
356         // redoParagraph() recursively inside parMetrics.
357         Dimension old_dim = parMetrics(pit, false).dim();
358         ParagraphMetrics & pm = par_metrics_[pit];
359         pm.reset(par);
360
361         Buffer & buffer = bv_->buffer();
362         BufferParams const & bparams = buffer.params();
363         main_text_ = (text_ == &buffer.text());
364         bool changed = false;
365
366         // FIXME This check ought to be done somewhere else. It is the reason
367         // why text_ is not     const. But then, where else to do it?
368         // Well, how can you end up with either (a) a biblio environment that
369         // has no InsetBibitem or (b) a biblio environment with more than one
370         // InsetBibitem? I think the answer is: when paragraphs are merged;
371         // when layout is set; when material is pasted.
372         int const moveCursor = par.checkBiblio(buffer.params().trackChanges);
373         if (moveCursor > 0)
374                 const_cast<Cursor &>(bv_->cursor()).posForward();
375         else if (moveCursor < 0) {
376                 Cursor & cursor = const_cast<Cursor &>(bv_->cursor());
377                 if (cursor.pos() >= -moveCursor)
378                         cursor.posBackward();
379         }
380
381         // Optimisation: this is used in the next two loops
382         // so better to calculate that once here.
383         int const right_margin = rightMargin(pm);
384
385         // redo insets
386         // FIXME: We should always use getFont(), see documentation of
387         // noFontChange() in Inset.h.
388         Font const bufferfont = buffer.params().getFont();
389         MacroContext mc(buffer, par);
390         InsetList::const_iterator ii = par.insetList().begin();
391         InsetList::const_iterator iend = par.insetList().end();
392         for (; ii != iend; ++ii) {
393                 // the macro must come here, _before_ the metric call, because
394                 // the macro should see itself to detect recursions. To find out
395                 // whether the macro definition is a redefinition it will look
396                 // at the MacroData::redefinition_. So it doesn't get confused
397                 // by the already existing macro definition of itself in the 
398                 // macro context.
399                 if (ii->inset->lyxCode() == MATHMACRO_CODE) {
400                         // get macro data
401                         MathMacroTemplate const & macroTemplate
402                         = static_cast<MathMacroTemplate const &>(*ii->inset);
403
404                         // valid?
405                         if (macroTemplate.validMacro()) {
406                                 MacroData macro = macroTemplate.asMacroData();
407
408                                 // redefinition?
409                                 macro.setRedefinition(mc.has(macroTemplate.name()));
410
411                                 // register macro (possibly overwrite the previous one of this paragraph)
412                                 mc.insert(macroTemplate.name(), macro);
413                         }
414                 }
415
416                 // do the metric calculation
417                 Dimension dim;
418                 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
419                         - right_margin;
420                 Font const & font = ii->inset->noFontChange() ?
421                         bufferfont : getDisplayFont(pit, ii->pos);
422                 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
423                 ii->inset->metrics(mi, dim);
424                 Dimension const old_dim = pm.insetDimension(ii->inset);
425                 pm.setInsetDimension(ii->inset, dim);
426                 changed |= (old_dim != dim);
427         }
428
429         Cursor const & cur = bv_->cursor();
430         DocIterator sel_beg = cur.selectionBegin();
431         DocIterator sel_end = cur.selectionEnd();
432         bool selection = cur.selection()
433                 // This is out text.
434                 && cur.text() == text_
435                 // if the anchor is outside, this is not our selection 
436                 && cur.anchor().text() == text_
437                 && pit >= sel_beg.pit() && pit <= sel_end.pit();
438
439         // We care only about visible selection.
440         if (selection) {
441                 if (pit != sel_beg.pit()) {
442                         sel_beg.pit() = pit;
443                         sel_beg.pos() = 0;
444                 }
445                 if (pit != sel_end.pit()) {
446                         sel_end.pit() = pit;
447                         sel_end.pos() = sel_end.lastpos();
448                 }
449         }
450
451         par.setBeginOfBody();
452         pos_type first = 0;
453         size_t row_index = 0;
454         // maximum pixel width of a row
455         int width = max_width_ - right_margin; // - leftMargin(max_width_, pit, row);
456         do {
457                 Dimension dim;
458                 pos_type end = rowBreakPoint(width, pit, first);
459                 if (row_index || end < par.size())
460                         // If there is more than one row, expand the text to 
461                         // the full allowable width. This setting here is needed
462                         // for the computeRowMetrics() below.
463                         dim_.wid = max_width_;
464
465                 dim = rowHeight(pit, first, end);
466                 dim.wid = rowWidth(right_margin, pit, first, end);
467                 if (row_index == pm.rows().size())
468                         pm.rows().push_back(Row());
469                 Row & row = pm.rows()[row_index];
470                 row.setChanged(false);
471                 row.pos(first);
472                 row.endpos(end);
473                 if (selection)
474                         row.setSelection(sel_beg.pos(), sel_end.pos());
475                 else
476                         row.setSelection(-1, -1);
477                 row.setDimension(dim);
478                 int const max_row_width = max(dim_.wid, dim.wid);
479                 computeRowMetrics(pit, row, max_row_width);
480                 pm.computeRowSignature(row, bparams);
481                 first = end;
482                 ++row_index;
483
484                 pm.dim().wid = std::max(pm.dim().wid, dim.wid);
485                 pm.dim().des += dim.height();
486         } while (first < par.size());
487
488         if (row_index < pm.rows().size())
489                 pm.rows().resize(row_index);
490
491         // Make sure that if a par ends in newline, there is one more row
492         // under it
493         if (first > 0 && par.isNewline(first - 1)) {
494                 Dimension dim = rowHeight(pit, first, first);
495                 dim.wid = rowWidth(right_margin, pit, first, first);
496                 if (row_index == pm.rows().size())
497                         pm.rows().push_back(Row());
498                 Row & row = pm.rows()[row_index];
499                 row.setChanged(false);
500                 row.pos(first);
501                 row.endpos(first);
502                 row.setDimension(dim);
503                 int const max_row_width = max(dim_.wid, dim.wid);
504                 computeRowMetrics(pit, row, max_row_width);
505                 pm.computeRowSignature(row, bparams);
506                 pm.dim().des += dim.height();
507         }
508
509         pm.dim().asc += pm.rows()[0].ascent();
510         pm.dim().des -= pm.rows()[0].ascent();
511
512         changed |= old_dim.height() != pm.dim().height();
513
514         return changed;
515 }
516
517
518 void TextMetrics::computeRowMetrics(pit_type const pit,
519                 Row & row, int width) const
520 {
521
522         row.label_hfill = 0;
523         row.hfill = 0;
524         row.separator = 0;
525
526         Buffer & buffer = bv_->buffer();
527         Paragraph const & par = text_->getPar(pit);
528
529         double w = width - row.width();
530         // FIXME: put back this assertion when the crash on new doc is solved.
531         //BOOST_ASSERT(w >= 0);
532
533         //lyxerr << "\ndim_.wid " << dim_.wid << endl;
534         //lyxerr << "row.width() " << row.width() << endl;
535         //lyxerr << "w " << w << endl;
536
537         bool const is_rtl = text_->isRTL(buffer, par);
538         if (is_rtl)
539                 row.x = rightMargin(pit);
540         else
541                 row.x = leftMargin(max_width_, pit, row.pos());
542
543         // is there a manual margin with a manual label
544         LayoutPtr const & layout = par.layout();
545
546         if (layout->margintype == MARGIN_MANUAL
547             && layout->labeltype == LABEL_MANUAL) {
548                 /// We might have real hfills in the label part
549                 int nlh = numberOfLabelHfills(par, row);
550
551                 // A manual label par (e.g. List) has an auto-hfill
552                 // between the label text and the body of the
553                 // paragraph too.
554                 // But we don't want to do this auto hfill if the par
555                 // is empty.
556                 if (!par.empty())
557                         ++nlh;
558
559                 if (nlh && !par.getLabelWidthString().empty())
560                         row.label_hfill = labelFill(pit, row) / double(nlh);
561         }
562
563         // are there any hfills in the row?
564         int const nh = numberOfHfills(par, row);
565
566         if (nh) {
567                 if (w > 0)
568                         row.hfill = w / nh;
569         // we don't have to look at the alignment if it is ALIGN_LEFT and
570         // if the row is already larger then the permitted width as then
571         // we force the LEFT_ALIGN'edness!
572         } else if (int(row.width()) < max_width_) {
573                 // is it block, flushleft or flushright?
574                 // set x how you need it
575                 int align;
576                 if (par.params().align() == LYX_ALIGN_LAYOUT)
577                         align = layout->align;
578                 else
579                         align = par.params().align();
580
581                 // Display-style insets should always be on a centred row
582                 // The test on par.size() is to catch zero-size pars, which
583                 // would trigger the assert in Paragraph::getInset().
584                 //inset = par.size() ? par.getInset(row.pos()) : 0;
585                 if (row.pos() < par.size() && par.isInset(row.pos())) {
586                         switch(par.getInset(row.pos())->display()) {
587                                 case Inset::AlignLeft:
588                                         align = LYX_ALIGN_BLOCK;
589                                         break;
590                                 case Inset::AlignCenter:
591                                         align = LYX_ALIGN_CENTER;
592                                         break;
593                                 case Inset::Inline:
594                                 case Inset::AlignRight:
595                                         // unchanged (use align)
596                                         break;
597                         }
598                 }
599
600                 switch (align) {
601                 case LYX_ALIGN_BLOCK: {
602                         int const ns = numberOfSeparators(par, row);
603                         bool disp_inset = false;
604                         if (row.endpos() < par.size()) {
605                                 Inset const * in = par.getInset(row.endpos());
606                                 if (in)
607                                         disp_inset = in->display();
608                         }
609                         // If we have separators, this is not the last row of a
610                         // par, does not end in newline, and is not row above a
611                         // display inset... then stretch it
612                         if (ns
613                             && row.endpos() < par.size()
614                             && !par.isNewline(row.endpos() - 1)
615                             && !disp_inset
616                                 ) {
617                                 row.separator = w / ns;
618                                 //lyxerr << "row.separator " << row.separator << endl;
619                                 //lyxerr << "ns " << ns << endl;
620                         } else if (is_rtl) {
621                                 row.x += w;
622                         }
623                         break;
624                 }
625                 case LYX_ALIGN_RIGHT:
626                         row.x += w;
627                         break;
628                 case LYX_ALIGN_CENTER:
629                         row.x += w / 2;
630                         break;
631                 }
632         }
633
634         if (is_rtl) {
635                 pos_type body_pos = par.beginOfBody();
636                 pos_type end = row.endpos();
637
638                 if (body_pos > 0
639                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
640                 {
641                         row.x += theFontMetrics(text_->getLabelFont(buffer, par)).
642                                 width(layout->labelsep);
643                         if (body_pos <= end)
644                                 row.x += row.label_hfill;
645                 }
646         }
647 }
648
649
650 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
651 {
652         Buffer & buffer = bv_->buffer();
653         Paragraph const & par = text_->getPar(pit);
654
655         pos_type last = par.beginOfBody();
656         BOOST_ASSERT(last > 0);
657
658         // -1 because a label ends with a space that is in the label
659         --last;
660
661         // a separator at this end does not count
662         if (par.isLineSeparator(last))
663                 --last;
664
665         int w = 0;
666         for (pos_type i = row.pos(); i <= last; ++i)
667                 w += singleWidth(pit, i);
668
669         docstring const & label = par.params().labelWidthString();
670         if (label.empty())
671                 return 0;
672
673         FontMetrics const & fm
674                 = theFontMetrics(text_->getLabelFont(buffer, par));
675
676         return max(0, fm.width(label) - w);
677 }
678
679
680 // this needs special handling - only newlines count as a break point
681 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
682 {
683         pos_type const end = par.size();
684
685         for (; i < end; ++i)
686                 if (par.isNewline(i))
687                         return i + 1;
688
689         return end;
690 }
691
692
693 int TextMetrics::labelEnd(pit_type const pit) const
694 {
695         // labelEnd is only needed if the layout fills a flushleft label.
696         if (text_->getPar(pit).layout()->margintype != MARGIN_MANUAL)
697                 return 0;
698         // return the beginning of the body
699         return leftMargin(max_width_, pit);
700 }
701
702
703 pit_type TextMetrics::rowBreakPoint(int width, pit_type const pit,
704                 pit_type pos) const
705 {
706         Buffer & buffer = bv_->buffer();
707         ParagraphMetrics const & pm = par_metrics_[pit];
708         Paragraph const & par = text_->getPar(pit);
709         pos_type const end = par.size();
710         if (pos == end || width < 0)
711                 return end;
712
713         LayoutPtr const & layout = par.layout();
714
715         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
716                 return addressBreakPoint(pos, par);
717
718         pos_type const body_pos = par.beginOfBody();
719
720
721         // Now we iterate through until we reach the right margin
722         // or the end of the par, then choose the possible break
723         // nearest that.
724
725         int label_end = labelEnd(pit);
726         int const left = leftMargin(max_width_, pit, pos);
727         int x = left;
728
729         // pixel width since last breakpoint
730         int chunkwidth = 0;
731
732         FontIterator fi = FontIterator(*this, par, pit, pos);
733         pos_type point = end;
734         pos_type i = pos;
735         for ( ; i < end; ++i, ++fi) {
736                 int thiswidth = pm.singleWidth(i, *fi);
737
738                 // add the auto-hfill from label end to the body
739                 if (body_pos && i == body_pos) {
740                         FontMetrics const & fm = theFontMetrics(
741                                 text_->getLabelFont(buffer, par));
742                         int add = fm.width(layout->labelsep);
743                         if (par.isLineSeparator(i - 1))
744                                 add -= singleWidth(pit, i - 1);
745
746                         add = std::max(add, label_end - x);
747                         thiswidth += add;
748                 }
749
750                 x += thiswidth;
751                 chunkwidth += thiswidth;
752
753                 // break before a character that will fall off
754                 // the right of the row
755                 if (x >= width) {
756                         // if no break before, break here
757                         if (point == end || chunkwidth >= width - left) {
758                                 if (i > pos)
759                                         point = i;
760                                 else
761                                         point = i + 1;
762                         }
763                         // exit on last registered breakpoint:
764                         break;
765                 }
766
767                 if (par.isNewline(i)) {
768                         point = i + 1;
769                         break;
770                 }
771                 // Break before...
772                 if (i + 1 < end) {
773                         if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
774                                 point = i + 1;
775                                 break;
776                         }
777                         // ...and after.
778                         if (par.isInset(i) && par.getInset(i)->display()) {
779                                 point = i + 1;
780                                 break;
781                         }
782                 }
783
784                 if (!par.isInset(i) || par.getInset(i)->isChar()) {
785                         // some insets are line separators too
786                         if (par.isLineSeparator(i)) {
787                                 // register breakpoint:
788                                 point = i + 1;
789                                 chunkwidth = 0;
790                         }
791                 }
792         }
793
794         // maybe found one, but the par is short enough.
795         if (i == end && x < width)
796                 point = end;
797
798         // manual labels cannot be broken in LaTeX. But we
799         // want to make our on-screen rendering of footnotes
800         // etc. still break
801         if (body_pos && point < body_pos)
802                 point = body_pos;
803
804         return point;
805 }
806
807
808 int TextMetrics::rowWidth(int right_margin, pit_type const pit,
809                 pos_type const first, pos_type const end) const
810 {
811         Buffer & buffer = bv_->buffer();
812         // get the pure distance
813         ParagraphMetrics const & pm = par_metrics_[pit];
814         Paragraph const & par = text_->getPar(pit);
815         int w = leftMargin(max_width_, pit, first);
816         int label_end = labelEnd(pit);
817
818         pos_type const body_pos = par.beginOfBody();
819         pos_type i = first;
820
821         if (i < end) {
822                 FontIterator fi = FontIterator(*this, par, pit, i);
823                 for ( ; i < end; ++i, ++fi) {
824                         if (body_pos > 0 && i == body_pos) {
825                                 FontMetrics const & fm = theFontMetrics(
826                                         text_->getLabelFont(buffer, par));
827                                 w += fm.width(par.layout()->labelsep);
828                                 if (par.isLineSeparator(i - 1))
829                                         w -= singleWidth(pit, i - 1);
830                                 w = max(w, label_end);
831                         }
832                         w += pm.singleWidth(i, *fi);
833                 }
834         }
835
836         if (body_pos > 0 && body_pos >= end) {
837                 FontMetrics const & fm = theFontMetrics(
838                         text_->getLabelFont(buffer, par));
839                 w += fm.width(par.layout()->labelsep);
840                 if (end > 0 && par.isLineSeparator(end - 1))
841                         w -= singleWidth(pit, end - 1);
842                 w = max(w, label_end);
843         }
844
845         return w + right_margin;
846 }
847
848
849 Dimension TextMetrics::rowHeight(pit_type const pit, pos_type const first,
850                 pos_type const end) const
851 {
852         Paragraph const & par = text_->getPar(pit);
853         // get the maximum ascent and the maximum descent
854         double layoutasc = 0;
855         double layoutdesc = 0;
856         double const dh = defaultRowHeight();
857
858         // ok, let us initialize the maxasc and maxdesc value.
859         // Only the fontsize count. The other properties
860         // are taken from the layoutfont. Nicer on the screen :)
861         LayoutPtr const & layout = par.layout();
862
863         // as max get the first character of this row then it can
864         // increase but not decrease the height. Just some point to
865         // start with so we don't have to do the assignment below too
866         // often.
867         Buffer const & buffer = bv_->buffer();
868         Font font = getDisplayFont(pit, first);
869         FontSize const tmpsize = font.fontInfo().size();
870         font.fontInfo() = text_->getLayoutFont(buffer, pit);
871         FontSize const size = font.fontInfo().size();
872         font.fontInfo().setSize(tmpsize);
873
874         FontInfo labelfont = text_->getLabelFont(buffer, par);
875
876         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
877         FontMetrics const & fontmetrics = theFontMetrics(font);
878
879         // these are minimum values
880         double const spacing_val = layout->spacing.getValue()
881                 * text_->spacing(buffer, par);
882         //lyxerr << "spacing_val = " << spacing_val << endl;
883         int maxasc  = int(fontmetrics.maxAscent()  * spacing_val);
884         int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
885
886         // insets may be taller
887         ParagraphMetrics const & pm = par_metrics_[pit];
888         InsetList::const_iterator ii = par.insetList().begin();
889         InsetList::const_iterator iend = par.insetList().end();
890         for ( ; ii != iend; ++ii) {
891                 Dimension const & dim = pm.insetDimension(ii->inset);
892                 if (ii->pos >= first && ii->pos < end) {
893                         maxasc  = max(maxasc,  dim.ascent());
894                         maxdesc = max(maxdesc, dim.descent());
895                 }
896         }
897
898         // Check if any custom fonts are larger (Asger)
899         // This is not completely correct, but we can live with the small,
900         // cosmetic error for now.
901         int labeladdon = 0;
902
903         FontSize maxsize =
904                 par.highestFontInRange(first, end, size);
905         if (maxsize > font.fontInfo().size()) {
906                 // use standard paragraph font with the maximal size
907                 FontInfo maxfont = font.fontInfo();
908                 maxfont.setSize(maxsize);
909                 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
910                 maxasc  = max(maxasc,  maxfontmetrics.maxAscent());
911                 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
912         }
913
914         // This is nicer with box insets:
915         ++maxasc;
916         ++maxdesc;
917
918         ParagraphList const & pars = text_->paragraphs();
919
920         // is it a top line?
921         if (first == 0) {
922                 BufferParams const & bufparams = buffer.params();
923                 // some parskips VERY EASY IMPLEMENTATION
924                 if (bufparams.paragraph_separation
925                     == BufferParams::PARSEP_SKIP
926                         && par.ownerCode() != ERT_CODE
927                         && par.ownerCode() != LISTINGS_CODE
928                         && pit > 0
929                         && ((layout->isParagraph() && par.getDepth() == 0)
930                             || (pars[pit - 1].layout()->isParagraph()
931                                 && pars[pit - 1].getDepth() == 0)))
932                 {
933                                 maxasc += bufparams.getDefSkip().inPixels(*bv_);
934                 }
935
936                 if (par.params().startOfAppendix())
937                         maxasc += int(3 * dh);
938
939                 // This is special code for the chapter, since the label of this
940                 // layout is printed in an extra row
941                 if (layout->counter == "chapter"
942                     && !par.params().labelString().empty()) {
943                         labeladdon = int(labelfont_metrics.maxHeight()
944                                      * layout->spacing.getValue()
945                                      * text_->spacing(buffer, par));
946                 }
947
948                 // special code for the top label
949                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
950                      || layout->labeltype == LABEL_BIBLIO
951                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
952                     && isFirstInSequence(pit, pars)
953                     && !par.getLabelstring().empty())
954                 {
955                         labeladdon = int(
956                                   labelfont_metrics.maxHeight()
957                                         * layout->spacing.getValue()
958                                         * text_->spacing(buffer, par)
959                                 + (layout->topsep + layout->labelbottomsep) * dh);
960                 }
961
962                 // Add the layout spaces, for example before and after
963                 // a section, or between the items of a itemize or enumerate
964                 // environment.
965
966                 pit_type prev = depthHook(pit, pars, par.getDepth());
967                 Paragraph const & prevpar = pars[prev];
968                 if (prev != pit
969                     && prevpar.layout() == layout
970                     && prevpar.getDepth() == par.getDepth()
971                     && prevpar.getLabelWidthString()
972                                         == par.getLabelWidthString()) {
973                         layoutasc = layout->itemsep * dh;
974                 } else if (pit != 0 || first != 0) {
975                         if (layout->topsep > 0)
976                                 layoutasc = layout->topsep * dh;
977                 }
978
979                 prev = outerHook(pit, pars);
980                 if (prev != pit_type(pars.size())) {
981                         maxasc += int(pars[prev].layout()->parsep * dh);
982                 } else if (pit != 0) {
983                         Paragraph const & prevpar = pars[pit - 1];
984                         if (prevpar.getDepth() != 0 ||
985                                         prevpar.layout() == layout) {
986                                 maxasc += int(layout->parsep * dh);
987                         }
988                 }
989         }
990
991         // is it a bottom line?
992         if (end >= par.size()) {
993                 // add the layout spaces, for example before and after
994                 // a section, or between the items of a itemize or enumerate
995                 // environment
996                 pit_type nextpit = pit + 1;
997                 if (nextpit != pit_type(pars.size())) {
998                         pit_type cpit = pit;
999                         double usual = 0;
1000                         double unusual = 0;
1001
1002                         if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1003                                 usual = pars[cpit].layout()->bottomsep * dh;
1004                                 cpit = depthHook(cpit, pars, pars[nextpit].getDepth());
1005                                 if (pars[cpit].layout() != pars[nextpit].layout()
1006                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1007                                 {
1008                                         unusual = pars[cpit].layout()->bottomsep * dh;
1009                                 }
1010                                 layoutdesc = max(unusual, usual);
1011                         } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1012                                 if (pars[cpit].layout() != pars[nextpit].layout()
1013                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1014                                         layoutdesc = int(pars[cpit].layout()->bottomsep * dh);
1015                         }
1016                 }
1017         }
1018
1019         // incalculate the layout spaces
1020         maxasc  += int(layoutasc  * 2 / (2 + pars[pit].getDepth()));
1021         maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1022
1023         // FIXME: the correct way is to do the following is to move the
1024         // following code in another method specially tailored for the
1025         // main Text. The following test is thus bogus.
1026         // Top and bottom margin of the document (only at top-level)
1027         if (main_text_) {
1028                 if (pit == 0 && first == 0)
1029                         maxasc += 20;
1030                 if (pit + 1 == pit_type(pars.size()) &&
1031                     end == par.size() &&
1032                                 !(end > 0 && par.isNewline(end - 1)))
1033                         maxdesc += 20;
1034         }
1035
1036         return Dimension(0, maxasc + labeladdon, maxdesc);
1037 }
1038
1039
1040 // x is an absolute screen coord
1041 // returns the column near the specified x-coordinate of the row
1042 // x is set to the real beginning of this column
1043 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1044                 Row const & row, int & x, bool & boundary) const
1045 {
1046         Buffer const & buffer = bv_->buffer();
1047
1048         /// For the main Text, it is possible that this pit is not
1049         /// yet in the CoordCache when moving cursor up.
1050         /// x Paragraph coordinate is always 0 for main text anyway.
1051         int const xo = origin_.x_;
1052         x -= xo;
1053         Paragraph const & par = text_->getPar(pit);
1054         ParagraphMetrics const & pm = par_metrics_[pit];
1055         Bidi bidi;
1056         bidi.computeTables(par, buffer, row);
1057
1058         pos_type vc = row.pos();
1059         pos_type end = row.endpos();
1060         pos_type c = 0;
1061         LayoutPtr const & layout = par.layout();
1062
1063         bool left_side = false;
1064
1065         pos_type body_pos = par.beginOfBody();
1066
1067         double tmpx = row.x;
1068         double last_tmpx = tmpx;
1069
1070         if (body_pos > 0 &&
1071             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1072                 body_pos = 0;
1073
1074         // check for empty row
1075         if (vc == end) {
1076                 x = int(tmpx) + xo;
1077                 return 0;
1078         }
1079
1080         while (vc < end && tmpx <= x) {
1081                 c = bidi.vis2log(vc);
1082                 last_tmpx = tmpx;
1083                 if (body_pos > 0 && c == body_pos - 1) {
1084                         FontMetrics const & fm = theFontMetrics(
1085                                 text_->getLabelFont(buffer, par));
1086                         tmpx += row.label_hfill + fm.width(layout->labelsep);
1087                         if (par.isLineSeparator(body_pos - 1))
1088                                 tmpx -= singleWidth(pit, body_pos - 1);
1089                 }
1090
1091                 if (pm.hfillExpansion(row, c)) {
1092                         tmpx += singleWidth(pit, c);
1093                         if (c >= body_pos)
1094                                 tmpx += row.hfill;
1095                         else
1096                                 tmpx += row.label_hfill;
1097                 } else if (par.isSeparator(c)) {
1098                         tmpx += singleWidth(pit, c);
1099                         if (c >= body_pos)
1100                                 tmpx += row.separator;
1101                 } else {
1102                         tmpx += singleWidth(pit, c);
1103                 }
1104                 ++vc;
1105         }
1106
1107         if ((tmpx + last_tmpx) / 2 > x) {
1108                 tmpx = last_tmpx;
1109                 left_side = true;
1110         }
1111
1112         BOOST_ASSERT(vc <= end);  // This shouldn't happen.
1113
1114         boundary = false;
1115         // This (rtl_support test) is not needed, but gives
1116         // some speedup if rtl_support == false
1117         bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1118
1119         // If lastrow is false, we don't need to compute
1120         // the value of rtl.
1121         bool const rtl = lastrow ? text_->isRTL(buffer, par) : false;
1122         if (lastrow &&
1123             ((rtl  &&  left_side && vc == row.pos() && x < tmpx - 5) ||
1124              (!rtl && !left_side && vc == end  && x > tmpx + 5)))
1125                 c = end;
1126         else if (vc == row.pos()) {
1127                 c = bidi.vis2log(vc);
1128                 if (bidi.level(c) % 2 == 1)
1129                         ++c;
1130         } else {
1131                 c = bidi.vis2log(vc - 1);
1132                 bool const rtl = (bidi.level(c) % 2 == 1);
1133                 if (left_side == rtl) {
1134                         ++c;
1135                         boundary = isRTLBoundary(pit, c);
1136                 }
1137         }
1138
1139 // I believe this code is not needed anymore (Jug 20050717)
1140 #if 0
1141         // The following code is necessary because the cursor position past
1142         // the last char in a row is logically equivalent to that before
1143         // the first char in the next row. That's why insets causing row
1144         // divisions -- Newline and display-style insets -- must be treated
1145         // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1146         // Newline inset, air gap below:
1147         if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1148                 if (bidi.level(end -1) % 2 == 0)
1149                         tmpx -= singleWidth(pit, end - 1);
1150                 else
1151                         tmpx += singleWidth(pit, end - 1);
1152                 c = end - 1;
1153         }
1154
1155         // Air gap above display inset:
1156         if (row.pos() < end && c >= end && end < par.size()
1157             && par.isInset(end) && par.getInset(end)->display()) {
1158                 c = end - 1;
1159         }
1160         // Air gap below display inset:
1161         if (row.pos() < end && c >= end && par.isInset(end - 1)
1162             && par.getInset(end - 1)->display()) {
1163                 c = end - 1;
1164         }
1165 #endif
1166
1167         x = int(tmpx) + xo;
1168         pos_type const col = c - row.pos();
1169
1170         if (!c || end == par.size())
1171                 return col;
1172
1173         if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1174                 boundary = true;
1175                 return col;
1176         }
1177
1178         return min(col, end - 1 - row.pos());
1179 }
1180
1181
1182 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1183 {
1184         // We play safe and use parMetrics(pit) to make sure the
1185         // ParagraphMetrics will be redone and OK to use if needed.
1186         // Otherwise we would use an empty ParagraphMetrics in
1187         // upDownInText() while in selection mode.
1188         ParagraphMetrics const & pm = parMetrics(pit);
1189
1190         BOOST_ASSERT(row < int(pm.rows().size()));
1191         bool bound = false;
1192         Row const & r = pm.rows()[row];
1193         return r.pos() + getColumnNearX(pit, r, x, bound);
1194 }
1195
1196
1197 void TextMetrics::newParMetricsDown()
1198 {
1199         pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1200         pit_type const pit = last.first + 1;
1201         if (pit == int(text_->paragraphs().size()))
1202                 return;
1203
1204         // do it and update its position.
1205         redoParagraph(pit);
1206         par_metrics_[pit].setPosition(last.second.position()
1207                 + last.second.descent());
1208 }
1209
1210
1211 void TextMetrics::newParMetricsUp()
1212 {
1213         pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1214         if (first.first == 0)
1215                 return;
1216
1217         pit_type const pit = first.first - 1;
1218         // do it and update its position.
1219         redoParagraph(pit);
1220         par_metrics_[pit].setPosition(first.second.position()
1221                 - first.second.ascent());
1222 }
1223
1224 // y is screen coordinate
1225 pit_type TextMetrics::getPitNearY(int y)
1226 {
1227         BOOST_ASSERT(!text_->paragraphs().empty());
1228         LYXERR(Debug::DEBUG)
1229                 << BOOST_CURRENT_FUNCTION
1230                 << ": y: " << y << " cache size: " << par_metrics_.size()
1231                 << endl;
1232
1233         // look for highest numbered paragraph with y coordinate less than given y
1234         pit_type pit = 0;
1235         int yy = -1;
1236         ParMetricsCache::const_iterator it = par_metrics_.begin();
1237         ParMetricsCache::const_iterator et = par_metrics_.end();
1238         ParMetricsCache::const_iterator last = et; last--;
1239
1240         ParagraphMetrics const & pm = it->second;
1241
1242         // If we are off-screen (before the visible part)
1243         if (y < 0
1244                 // and even before the first paragraph in the cache.
1245                 && y < it->second.position() - int(pm.ascent())) {
1246                 //  and we are not at the first paragraph in the inset.
1247                 if (it->first == 0)
1248                         return 0;
1249                 // then this is the paragraph we are looking for.
1250                 pit = it->first - 1;
1251                 // rebreak it and update the CoordCache.
1252                 redoParagraph(pit);
1253                 par_metrics_[pit].setPosition(it->second.position() - pm.descent());
1254                 return pit;
1255         }
1256
1257         ParagraphMetrics const & pm_last = par_metrics_[last->first];
1258
1259         // If we are off-screen (after the visible part)
1260         if (y > bv_->workHeight()
1261                 // and even after the first paragraph in the cache.
1262                 && y >= last->second.position() + int(pm_last.descent())) {
1263                 pit = last->first + 1;
1264                 //  and we are not at the last paragraph in the inset.
1265                 if (pit == int(text_->paragraphs().size()))
1266                         return last->first;
1267                 // then this is the paragraph we are looking for.
1268                 // rebreak it and update the CoordCache.
1269                 redoParagraph(pit);
1270                 par_metrics_[pit].setPosition(last->second.position() + pm_last.ascent());
1271                 return pit;
1272         }
1273
1274         for (; it != et; ++it) {
1275                 LYXERR(Debug::DEBUG)
1276                         << BOOST_CURRENT_FUNCTION
1277                         << "  examining: pit: " << it->first
1278                         << " y: " << it->second.position()
1279                         << endl;
1280
1281                 ParagraphMetrics const & pm = par_metrics_[it->first];
1282
1283                 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1284                         pit = it->first;
1285                         yy = it->second.position();
1286                 }
1287         }
1288
1289         LYXERR(Debug::DEBUG)
1290                 << BOOST_CURRENT_FUNCTION
1291                 << ": found best y: " << yy << " for pit: " << pit
1292                 << endl;
1293
1294         return pit;
1295 }
1296
1297
1298 Row const & TextMetrics::getRowNearY(int y, pit_type pit) const
1299 {
1300         ParagraphMetrics const & pm = par_metrics_[pit];
1301
1302         int yy = pm.position() - pm.ascent();
1303         BOOST_ASSERT(!pm.rows().empty());
1304         RowList::const_iterator rit = pm.rows().begin();
1305         RowList::const_iterator rlast = pm.rows().end();
1306         --rlast;
1307         for (; rit != rlast; yy += rit->height(), ++rit)
1308                 if (yy + rit->height() > y)
1309                         break;
1310         return *rit;
1311 }
1312
1313
1314 // x,y are absolute screen coordinates
1315 // sets cursor recursively descending into nested editable insets
1316 Inset * TextMetrics::editXY(Cursor & cur, int x, int y)
1317 {
1318         if (lyxerr.debugging(Debug::WORKAREA)) {
1319                 lyxerr << "TextMetrics::editXY(cur, " << x << ", " << y << ")" << std::endl;
1320                 cur.bv().coordCache().dump();
1321         }
1322         pit_type pit = getPitNearY(y);
1323         BOOST_ASSERT(pit != -1);
1324
1325         Row const & row = getRowNearY(y, pit);
1326         bool bound = false;
1327
1328         int xx = x; // is modified by getColumnNearX
1329         pos_type const pos = row.pos()
1330                 + getColumnNearX(pit, row, xx, bound);
1331         cur.pit() = pit;
1332         cur.pos() = pos;
1333         cur.boundary(bound);
1334         cur.setTargetX(x);
1335
1336         // try to descend into nested insets
1337         Inset * inset = checkInsetHit(x, y);
1338         //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1339         if (!inset) {
1340                 // Either we deconst editXY or better we move current_font
1341                 // and real_current_font to Cursor
1342                 // FIXME: what is needed now that current_font and real_current_font
1343                 // are transferred?
1344                 cur.setCurrentFont();
1345                 return 0;
1346         }
1347
1348         ParagraphList const & pars = text_->paragraphs();
1349         Inset const * insetBefore = pos? pars[pit].getInset(pos - 1): 0;
1350         //Inset * insetBehind = pars[pit].getInset(pos);
1351
1352         // This should be just before or just behind the
1353         // cursor position set above.
1354         BOOST_ASSERT((pos != 0 && inset == insetBefore)
1355                 || inset == pars[pit].getInset(pos));
1356
1357         // Make sure the cursor points to the position before
1358         // this inset.
1359         if (inset == insetBefore) {
1360                 --cur.pos();
1361                 cur.boundary(false);
1362         }
1363
1364         // Try to descend recursively inside the inset.
1365         inset = inset->editXY(cur, x, y);
1366
1367         if (cur.top().text() == text_)
1368                 cur.setCurrentFont();
1369         return inset;
1370 }
1371
1372
1373 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1374 {
1375         BOOST_ASSERT(text_ == cur.text());
1376         pit_type pit = getPitNearY(y);
1377
1378         ParagraphMetrics const & pm = par_metrics_[pit];
1379
1380         int yy = pm.position() - pm.ascent();
1381         LYXERR(Debug::DEBUG)
1382                 << BOOST_CURRENT_FUNCTION
1383                 << ": x: " << x
1384                 << " y: " << y
1385                 << " pit: " << pit
1386                 << " yy: " << yy << endl;
1387
1388         int r = 0;
1389         BOOST_ASSERT(pm.rows().size());
1390         for (; r < int(pm.rows().size()) - 1; ++r) {
1391                 Row const & row = pm.rows()[r];
1392                 if (int(yy + row.height()) > y)
1393                         break;
1394                 yy += row.height();
1395         }
1396
1397         Row const & row = pm.rows()[r];
1398
1399         LYXERR(Debug::DEBUG)
1400                 << BOOST_CURRENT_FUNCTION
1401                 << ": row " << r
1402                 << " from pos: " << row.pos()
1403                 << endl;
1404
1405         bool bound = false;
1406         int xx = x;
1407         pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1408
1409         LYXERR(Debug::DEBUG)
1410                 << BOOST_CURRENT_FUNCTION
1411                 << ": setting cursor pit: " << pit
1412                 << " pos: " << pos
1413                 << endl;
1414
1415         text_->setCursor(cur, pit, pos, true, bound);
1416         // remember new position.
1417         cur.setTargetX();
1418 }
1419
1420
1421 //takes screen x,y coordinates
1422 Inset * TextMetrics::checkInsetHit(int x, int y)
1423 {
1424         pit_type pit = getPitNearY(y);
1425         BOOST_ASSERT(pit != -1);
1426
1427         Paragraph const & par = text_->paragraphs()[pit];
1428         ParagraphMetrics const & pm = par_metrics_[pit];
1429
1430         LYXERR(Debug::DEBUG)
1431                 << BOOST_CURRENT_FUNCTION
1432                 << ": x: " << x
1433                 << " y: " << y
1434                 << "  pit: " << pit
1435                 << endl;
1436         InsetList::const_iterator iit = par.insetList().begin();
1437         InsetList::const_iterator iend = par.insetList().end();
1438         for (; iit != iend; ++iit) {
1439                 Inset * inset = iit->inset;
1440
1441                 LYXERR(Debug::DEBUG)
1442                         << BOOST_CURRENT_FUNCTION
1443                         << ": examining inset " << inset << endl;
1444
1445                 if (!bv_->coordCache().getInsets().has(inset)) {
1446                         LYXERR(Debug::DEBUG)
1447                                 << BOOST_CURRENT_FUNCTION
1448                                 << ": inset has no cached position" << endl;
1449                         return 0;
1450                 }
1451
1452                 Dimension const & dim = pm.insetDimension(inset);
1453                 Point p = bv_->coordCache().getInsets().xy(inset);
1454
1455                 LYXERR(Debug::DEBUG)
1456                         << BOOST_CURRENT_FUNCTION
1457                         << ": xo: " << p.x_ << "..." << p.x_ + dim.wid
1458                         << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des
1459                         << endl;
1460
1461                 if (x >= p.x_
1462                         && x <= p.x_ + dim.wid
1463                         && y >= p.y_ - dim.asc
1464                         && y <= p.y_ + dim.des) {
1465                         LYXERR(Debug::DEBUG)
1466                                 << BOOST_CURRENT_FUNCTION
1467                                 << ": Hit inset: " << inset << endl;
1468                         return inset;
1469                 }
1470         }
1471
1472         LYXERR(Debug::DEBUG)
1473                 << BOOST_CURRENT_FUNCTION
1474                 << ": No inset hit. " << endl;
1475         return 0;
1476 }
1477
1478
1479 int TextMetrics::cursorX(CursorSlice const & sl,
1480                 bool boundary) const
1481 {
1482         BOOST_ASSERT(sl.text() == text_);
1483         pit_type const pit = sl.pit();
1484         Paragraph const & par = text_->paragraphs()[pit];
1485         ParagraphMetrics const & pm = par_metrics_[pit];
1486         if (pm.rows().empty())
1487                 return 0;
1488
1489         pos_type ppos = sl.pos();
1490         // Correct position in front of big insets
1491         bool const boundary_correction = ppos != 0 && boundary;
1492         if (boundary_correction)
1493                 --ppos;
1494
1495         Row const & row = pm.getRow(sl.pos(), boundary);
1496
1497         pos_type cursor_vpos = 0;
1498
1499         Buffer const & buffer = bv_->buffer();
1500         double x = row.x;
1501         Bidi bidi;
1502         bidi.computeTables(par, buffer, row);
1503
1504         pos_type const row_pos  = row.pos();
1505         pos_type const end      = row.endpos();
1506         // Spaces at logical line breaks in bidi text must be skipped during 
1507         // cursor positioning. However, they may appear visually in the middle
1508         // of a row; they must be skipped, wherever they are...
1509         // * logically "abc_[HEBREW_\nHEBREW]"
1510         // * visually "abc_[_WERBEH\nWERBEH]"
1511         pos_type skipped_sep_vpos = -1;
1512
1513         if (end <= row_pos)
1514                 cursor_vpos = row_pos;
1515         else if (ppos >= end)
1516                 cursor_vpos = text_->isRTL(buffer, par) ? row_pos : end;
1517         else if (ppos > row_pos && ppos >= end)
1518                 // Place cursor after char at (logical) position pos - 1
1519                 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1520                         ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1521         else
1522                 // Place cursor before char at (logical) position ppos
1523                 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1524                         ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1525
1526         pos_type body_pos = par.beginOfBody();
1527         if (body_pos > 0 &&
1528             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1529                 body_pos = 0;
1530
1531         // Use font span to speed things up, see below
1532         FontSpan font_span;
1533         Font font;
1534
1535         // If the last logical character is a separator, skip it, unless
1536         // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1537         if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1538                 skipped_sep_vpos = bidi.log2vis(end - 1);
1539         
1540         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1541                 // Skip the separator which is at the logical end of the row
1542                 if (vpos == skipped_sep_vpos)
1543                         continue;
1544                 pos_type pos = bidi.vis2log(vpos);
1545                 if (body_pos > 0 && pos == body_pos - 1) {
1546                         FontMetrics const & labelfm = theFontMetrics(
1547                                 text_->getLabelFont(buffer, par));
1548                         x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1549                         if (par.isLineSeparator(body_pos - 1))
1550                                 x -= singleWidth(pit, body_pos - 1);
1551                 }
1552
1553                 // Use font span to speed things up, see above
1554                 if (pos < font_span.first || pos > font_span.last) {
1555                         font_span = par.fontSpan(pos);
1556                         font = getDisplayFont(pit, pos);
1557                 }
1558
1559                 x += pm.singleWidth(pos, font);
1560
1561                 if (pm.hfillExpansion(row, pos))
1562                         x += (pos >= body_pos) ? row.hfill : row.label_hfill;
1563                 else if (par.isSeparator(pos) && pos >= body_pos)
1564                         x += row.separator;
1565         }
1566
1567         // see correction above
1568         if (boundary_correction) {
1569                 if (isRTL(sl, boundary))
1570                         x -= singleWidth(pit, ppos);
1571                 else
1572                         x += singleWidth(pit, ppos);
1573         }
1574
1575         return int(x);
1576 }
1577
1578
1579 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1580 {
1581         //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << std::endl;
1582         ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1583         if (pm.rows().empty())
1584                 return 0;
1585
1586         int h = 0;
1587         h -= par_metrics_[0].rows()[0].ascent();
1588         for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1589                 h += par_metrics_[pit].height();
1590         }
1591         int pos = sl.pos();
1592         if (pos && boundary)
1593                 --pos;
1594         size_t const rend = pm.pos2row(pos);
1595         for (size_t rit = 0; rit != rend; ++rit)
1596                 h += pm.rows()[rit].height();
1597         h += pm.rows()[rend].ascent();
1598         return h;
1599 }
1600
1601
1602 void TextMetrics::cursorPrevious(Cursor & cur)
1603 {
1604         pos_type cpos = cur.pos();
1605         pit_type cpar = cur.pit();
1606
1607         int x = cur.x_target();
1608         setCursorFromCoordinates(cur, x, 0);
1609         cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1610
1611         if (cpar == cur.pit() && cpos == cur.pos())
1612                 // we have a row which is taller than the workarea. The
1613                 // simplest solution is to move to the previous row instead.
1614                 cur.dispatch(FuncRequest(cur.selection()? LFUN_UP_SELECT: LFUN_UP));
1615
1616         cur.finishUndo();
1617         cur.updateFlags(Update::Force | Update::FitCursor);
1618 }
1619
1620
1621 void TextMetrics::cursorNext(Cursor & cur)
1622 {
1623         pos_type cpos = cur.pos();
1624         pit_type cpar = cur.pit();
1625
1626         int x = cur.x_target();
1627         setCursorFromCoordinates(cur, x, cur.bv().workHeight() - 1);
1628         cur.dispatch(FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1629
1630         if (cpar == cur.pit() && cpos == cur.pos())
1631                 // we have a row which is taller than the workarea. The
1632                 // simplest solution is to move to the next row instead.
1633                 cur.dispatch(
1634                         FuncRequest(cur.selection()? LFUN_DOWN_SELECT: LFUN_DOWN));
1635
1636         cur.finishUndo();
1637         cur.updateFlags(Update::Force | Update::FitCursor);
1638 }
1639
1640
1641 // the cursor set functions have a special mechanism. When they
1642 // realize you left an empty paragraph, they will delete it.
1643
1644 bool TextMetrics::cursorHome(Cursor & cur)
1645 {
1646         BOOST_ASSERT(text_ == cur.text());
1647         ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1648         Row const & row = pm.getRow(cur.pos(),cur.boundary());
1649         return text_->setCursor(cur, cur.pit(), row.pos());
1650 }
1651
1652
1653 bool TextMetrics::cursorEnd(Cursor & cur)
1654 {
1655         BOOST_ASSERT(text_ == cur.text());
1656         // if not on the last row of the par, put the cursor before
1657         // the final space exept if I have a spanning inset or one string
1658         // is so long that we force a break.
1659         pos_type end = cur.textRow().endpos();
1660         if (end == 0)
1661                 // empty text, end-1 is no valid position
1662                 return false;
1663         bool boundary = false;
1664         if (end != cur.lastpos()) {
1665                 if (!cur.paragraph().isLineSeparator(end-1)
1666                     && !cur.paragraph().isNewline(end-1))
1667                         boundary = true;
1668                 else
1669                         --end;
1670         }
1671         return text_->setCursor(cur, cur.pit(), end, true, boundary);
1672 }
1673
1674
1675 void TextMetrics::deleteLineForward(Cursor & cur)
1676 {
1677         BOOST_ASSERT(text_ == cur.text());
1678         if (cur.lastpos() == 0) {
1679                 // Paragraph is empty, so we just go forward
1680                 text_->cursorForward(cur);
1681         } else {
1682                 cur.resetAnchor();
1683                 cur.selection() = true; // to avoid deletion
1684                 cursorEnd(cur);
1685                 cur.setSelection();
1686                 // What is this test for ??? (JMarc)
1687                 if (!cur.selection())
1688                         text_->deleteWordForward(cur);
1689                 else
1690                         cap::cutSelection(cur, true, false);
1691                 checkBufferStructure(cur.buffer(), cur);
1692         }
1693 }
1694
1695
1696 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1697 {
1698         ParagraphList const & pars = text_->paragraphs();
1699         return row.endpos() >= pars[pit].size()
1700                 && pit + 1 == pit_type(pars.size());
1701 }
1702
1703
1704 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1705 {
1706         return row.pos() == 0 && pit == 0;
1707 }
1708
1709
1710 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1711 {
1712         BOOST_ASSERT(pit >= 0);
1713         BOOST_ASSERT(pit < int(text_->paragraphs().size()));
1714         return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1715 }
1716
1717
1718 int TextMetrics::leftMargin(int max_width,
1719                 pit_type const pit, pos_type const pos) const
1720 {
1721         ParagraphList const & pars = text_->paragraphs();
1722
1723         BOOST_ASSERT(pit >= 0);
1724         BOOST_ASSERT(pit < int(pars.size()));
1725         Paragraph const & par = pars[pit];
1726         BOOST_ASSERT(pos >= 0);
1727         BOOST_ASSERT(pos <= par.size());
1728         Buffer const & buffer = bv_->buffer();
1729         //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1730         TextClass const & tclass = buffer.params().getTextClass();
1731         LayoutPtr const & layout = par.layout();
1732
1733         docstring parindent = layout->parindent;
1734
1735         int l_margin = 0;
1736
1737         if (text_->isMainText(buffer))
1738                 l_margin += changebarMargin();
1739
1740         l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1741                 tclass.leftmargin());
1742
1743         if (par.getDepth() != 0) {
1744                 // find the next level paragraph
1745                 pit_type newpar = outerHook(pit, pars);
1746                 if (newpar != pit_type(pars.size())) {
1747                         if (pars[newpar].layout()->isEnvironment()) {
1748                                 l_margin = leftMargin(max_width, newpar);
1749                         }
1750                         if (par.layout() == tclass.defaultLayout()) {
1751                                 if (pars[newpar].params().noindent())
1752                                         parindent.erase();
1753                                 else
1754                                         parindent = pars[newpar].layout()->parindent;
1755                         }
1756                 }
1757         }
1758
1759         // This happens after sections in standard classes. The 1.3.x
1760         // code compared depths too, but it does not seem necessary
1761         // (JMarc)
1762         if (par.layout() == tclass.defaultLayout()
1763             && pit > 0 && pars[pit - 1].layout()->nextnoindent)
1764                 parindent.erase();
1765
1766         FontInfo const labelfont = text_->getLabelFont(buffer, par);
1767         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1768
1769         switch (layout->margintype) {
1770         case MARGIN_DYNAMIC:
1771                 if (!layout->leftmargin.empty()) {
1772                         l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1773                                 layout->leftmargin);
1774                 }
1775                 if (!par.getLabelstring().empty()) {
1776                         l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1777                         l_margin += labelfont_metrics.width(par.getLabelstring());
1778                         l_margin += labelfont_metrics.width(layout->labelsep);
1779                 }
1780                 break;
1781
1782         case MARGIN_MANUAL: {
1783                 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1784                 // The width of an empty par, even with manual label, should be 0
1785                 if (!par.empty() && pos >= par.beginOfBody()) {
1786                         if (!par.getLabelWidthString().empty()) {
1787                                 docstring labstr = par.getLabelWidthString();
1788                                 l_margin += labelfont_metrics.width(labstr);
1789                                 l_margin += labelfont_metrics.width(layout->labelsep);
1790                         }
1791                 }
1792                 break;
1793         }
1794
1795         case MARGIN_STATIC: {
1796                 l_margin += theFontMetrics(buffer.params().getFont()).
1797                         signedWidth(layout->leftmargin) * 4     / (par.getDepth() + 4);
1798                 break;
1799         }
1800
1801         case MARGIN_FIRST_DYNAMIC:
1802                 if (layout->labeltype == LABEL_MANUAL) {
1803                         if (pos >= par.beginOfBody()) {
1804                                 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1805                         } else {
1806                                 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1807                         }
1808                 } else if (pos != 0
1809                            // Special case to fix problems with
1810                            // theorems (JMarc)
1811                            || (layout->labeltype == LABEL_STATIC
1812                                && layout->latextype == LATEX_ENVIRONMENT
1813                                && !isFirstInSequence(pit, pars))) {
1814                         l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
1815                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
1816                            && layout->labeltype != LABEL_BIBLIO
1817                            && layout->labeltype !=
1818                            LABEL_CENTERED_TOP_ENVIRONMENT) {
1819                         l_margin += labelfont_metrics.signedWidth(layout->labelindent);
1820                         l_margin += labelfont_metrics.width(layout->labelsep);
1821                         l_margin += labelfont_metrics.width(par.getLabelstring());
1822                 }
1823                 break;
1824
1825         case MARGIN_RIGHT_ADDRESS_BOX: {
1826 #if 0
1827                 // ok, a terrible hack. The left margin depends on the widest
1828                 // row in this paragraph.
1829                 RowList::iterator rit = par.rows().begin();
1830                 RowList::iterator end = par.rows().end();
1831                 // FIXME: This is wrong.
1832                 int minfill = max_width;
1833                 for ( ; rit != end; ++rit)
1834                         if (rit->fill() < minfill)
1835                                 minfill = rit->fill();
1836                 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
1837                 l_margin += minfill;
1838 #endif
1839                 // also wrong, but much shorter.
1840                 l_margin += max_width / 2;
1841                 break;
1842         }
1843         }
1844
1845         if (!par.params().leftIndent().zero())
1846                 l_margin += par.params().leftIndent().inPixels(max_width);
1847
1848         LyXAlignment align;
1849
1850         if (par.params().align() == LYX_ALIGN_LAYOUT)
1851                 align = layout->align;
1852         else
1853                 align = par.params().align();
1854
1855         // set the correct parindent
1856         if (pos == 0
1857             && (layout->labeltype == LABEL_NO_LABEL
1858                || layout->labeltype == LABEL_TOP_ENVIRONMENT
1859                || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
1860                || (layout->labeltype == LABEL_STATIC
1861                    && layout->latextype == LATEX_ENVIRONMENT
1862                    && !isFirstInSequence(pit, pars)))
1863             && align == LYX_ALIGN_BLOCK
1864             && !par.params().noindent()
1865             // in some insets, paragraphs are never indented
1866             && !(par.inInset() && par.inInset()->neverIndent(buffer))
1867             // display style insets are always centered, omit indentation
1868             && !(!par.empty()
1869                     && par.isInset(pos)
1870                     && par.getInset(pos)->display())
1871             && (par.layout() != tclass.defaultLayout()
1872                 || buffer.params().paragraph_separation ==
1873                    BufferParams::PARSEP_INDENT))
1874         {
1875                 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1876                         parindent);
1877         }
1878
1879         return l_margin;
1880 }
1881
1882
1883 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
1884 {
1885         ParagraphMetrics const & pm = par_metrics_[pit];
1886
1887         return pm.singleWidth(pos, getDisplayFont(pit, pos));
1888 }
1889
1890
1891 // only used for inset right now. should also be used for main text
1892 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1893 {
1894         if (par_metrics_.empty())
1895                 return;
1896
1897         origin_.x_ = x;
1898         origin_.y_ = y;
1899
1900         ParMetricsCache::iterator it = par_metrics_.begin();
1901         ParMetricsCache::iterator const pm_end = par_metrics_.end();
1902         y -= it->second.ascent();
1903         for (; it != pm_end; ++it) {
1904                 ParagraphMetrics const & pmi = it->second;
1905                 y += pmi.ascent();
1906                 pit_type const pit = it->first;
1907                 // Save the paragraph position in the cache.
1908                 it->second.setPosition(y);
1909                 drawParagraph(pi, pit, x, y);
1910                 y += pmi.descent();
1911         }
1912 }
1913
1914
1915 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
1916 {
1917 //      lyxerr << "  paintPar: pit: " << pit << " at y: " << y << endl;
1918         int const ww = bv_->workHeight();
1919
1920         ParagraphMetrics const & pm = par_metrics_[pit];
1921         if (pm.rows().empty())
1922                 return;
1923
1924         RowList::const_iterator const rb = pm.rows().begin();
1925         RowList::const_iterator const re = pm.rows().end();
1926
1927         Bidi bidi;
1928
1929         bool const original_drawing_state = pi.pain.isDrawingEnabled();
1930
1931         y -= rb->ascent();
1932         for (RowList::const_iterator rit = rb; rit != re; ++rit) {
1933                 y += rit->ascent();
1934
1935                 bool const inside = (y + rit->descent() >= 0
1936                         && y - rit->ascent() < ww);
1937                 // it is not needed to draw on screen if we are not inside.
1938                 pi.pain.setDrawingEnabled(inside && original_drawing_state);
1939                 RowPainter rp(pi, *text_, pit, *rit, bidi, x, y);
1940
1941                 // Row signature; has row changed since last paint?
1942                 bool row_has_changed = rit->changed();
1943                 
1944                 bool row_selection = rit->sel_beg != -1 && rit->sel_end != -1;
1945
1946                 if (!row_selection && !pi.full_repaint && !row_has_changed) {
1947                         // Paint the only the insets if the text itself is
1948                         // unchanged.
1949                         rp.paintOnlyInsets();
1950                         y += rit->descent();
1951                         continue;
1952                 }
1953
1954                 // Paint the row if a full repaint has been requested or it has
1955                 // changed.
1956                 // Clear background of this row
1957                 // (if paragraph background was not cleared)
1958                 if (row_selection || (!pi.full_repaint && row_has_changed)) {
1959                         pi.pain.fillRectangle(x, y - rit->ascent(),
1960                                 width(), rit->height(), pi.background_color);
1961                 }
1962                 if (row_selection) {
1963                         DocIterator beg = bv_->cursor().selectionBegin();
1964                         DocIterator end = bv_->cursor().selectionEnd();
1965                         beg.pit() = pit;
1966                         beg.pos() = rit->sel_beg;
1967                         if (pit == end.pit()) {
1968                                 end.pos() = rit->sel_end;
1969                         } else {
1970                                 end.pit() = pit + 1;
1971                                 end.pos() = 0;
1972                         }
1973                         drawSelection(pi, beg, end, x);
1974                 }
1975
1976                 // Instrumentation for testing row cache (see also
1977                 // 12 lines lower):
1978                 if (lyxerr.debugging(Debug::PAINTING)) {
1979                         if (text_->isMainText(bv_->buffer()))
1980                                 LYXERR(Debug::PAINTING) << "\n{" << inside <<
1981                                 pi.full_repaint << row_has_changed << "}";
1982                         else
1983                                 LYXERR(Debug::PAINTING) << "[" << inside <<
1984                                 pi.full_repaint << row_has_changed << "]";
1985                 }
1986
1987                 // Backup full_repaint status and force full repaint
1988                 // for inner insets as the Row has been cleared out.
1989                 bool tmp = pi.full_repaint;
1990                 pi.full_repaint = true;
1991                 rp.paintAppendix();
1992                 rp.paintDepthBar();
1993                 rp.paintChangeBar();
1994                 if (rit == rb)
1995                         rp.paintFirst();
1996                 rp.paintText();
1997                 if (rit + 1 == re)
1998                         rp.paintLast();
1999                 y += rit->descent();
2000                 // Restore full_repaint status.
2001                 pi.full_repaint = tmp;
2002         }
2003         // Re-enable screen drawing for future use of the painter.
2004         pi.pain.setDrawingEnabled(original_drawing_state);
2005
2006         //LYXERR(Debug::PAINTING) << "." << endl;
2007 }
2008
2009
2010 // FIXME: only take care of one row!
2011 void TextMetrics::drawSelection(PainterInfo & pi,
2012         DocIterator const & beg, DocIterator const & end, int x) const
2013 {
2014         ParagraphMetrics const & pm1 = parMetrics(beg.pit());
2015         ParagraphMetrics const & pm2 = parMetrics(end.pit());
2016         Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
2017         Row const & row2 = pm2.getRow(end.pos(), end.boundary());
2018
2019         // clip above
2020         int middleTop;
2021         bool const clipAbove = (bv_->cursorStatus(beg) == CUR_ABOVE);
2022         if (clipAbove)
2023                 middleTop = 0;
2024         else
2025                 middleTop = bv_->getPos(beg, beg.boundary()).y_ + row1.descent();
2026         
2027         // clip below
2028         int middleBottom;
2029         bool const clipBelow = (bv_->cursorStatus(end) == CUR_BELOW);
2030         if (clipBelow)
2031                 middleBottom = bv_->workHeight();
2032         else
2033                 middleBottom = bv_->getPos(end, end.boundary()).y_ - row2.ascent();
2034
2035         // start and end in the same line?
2036         if (!clipAbove && !clipBelow && &row1 == &row2)
2037                 // then only draw this row's selection
2038                 drawRowSelection(pi, x, row1, beg, end, false, false);
2039         else {
2040                 if (!clipAbove) {
2041                         // get row end
2042                         DocIterator begRowEnd = beg;
2043                         begRowEnd.pos() = row1.endpos();
2044                         begRowEnd.boundary(true);
2045                         
2046                         // draw upper rectangle
2047                         drawRowSelection(pi, x, row1, beg, begRowEnd, false, true);
2048                 }
2049                         
2050                 if (middleTop < middleBottom) {
2051                         // draw middle rectangle
2052                         pi.pain.fillRectangle(x, middleTop, width(), middleBottom - middleTop,
2053                                 Color_selection);
2054                 }
2055
2056                 if (!clipBelow) {
2057                         // get row begin
2058                         DocIterator endRowBeg = end;
2059                         endRowBeg.pos() = row2.pos();
2060                         endRowBeg.boundary(false);
2061                         
2062                         // draw low rectangle
2063                         drawRowSelection(pi, x, row2, endRowBeg, end, true, false);
2064                 }
2065         }
2066 }
2067
2068
2069 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2070                 DocIterator const & beg, DocIterator const & end,
2071                 bool drawOnBegMargin, bool drawOnEndMargin) const
2072 {
2073         Buffer & buffer = bv_->buffer();
2074         DocIterator cur = beg;
2075         int x1 = cursorX(beg.top(), beg.boundary());
2076         int x2 = cursorX(end.top(), end.boundary());
2077         int y1 = bv_->getPos(cur, cur.boundary()).y_ - row.ascent();
2078         int y2 = y1 + row.height();
2079         
2080         // draw the margins
2081         if (drawOnBegMargin) {
2082                 if (text_->isRTL(buffer, beg.paragraph()))
2083                         pi.pain.fillRectangle(x + x1, y1, width() - x1, y2 - y1, Color_selection);
2084                 else
2085                         pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color_selection);
2086         }
2087         
2088         if (drawOnEndMargin) {
2089                 if (text_->isRTL(buffer, beg.paragraph()))
2090                         pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color_selection);
2091                 else
2092                         pi.pain.fillRectangle(x + x2, y1, width() - x2, y2 - y1, Color_selection);
2093         }
2094         
2095         // if we are on a boundary from the beginning, it's probably
2096         // a RTL boundary and we jump to the other side directly as this
2097         // segement is 0-size and confuses the logic below
2098         if (cur.boundary())
2099                 cur.boundary(false);
2100         
2101         // go through row and draw from RTL boundary to RTL boundary
2102         while (cur < end) {
2103                 bool drawNow = false;
2104                 
2105                 // simplified cursorForward code below which does not
2106                 // descend into insets and which does not go into the
2107                 // next line. Compare the logic with the original cursorForward
2108                 
2109                 // if left of boundary -> just jump to right side
2110                 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2111                 if (cur.boundary()) {
2112                         cur.boundary(false);
2113                 }       else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2114                         // in front of RTL boundary -> Stay on this side of the boundary because:
2115                         //   ab|cDDEEFFghi -> abc|DDEEFFghi
2116                         ++cur.pos();
2117                         cur.boundary(true);
2118                         drawNow = true;
2119                 } else {
2120                         // move right
2121                         ++cur.pos();
2122                         
2123                         // line end?
2124                         if (cur.pos() == row.endpos())
2125                                 cur.boundary(true);
2126                 }
2127                         
2128                 if (x1 == -1) {
2129                         // the previous segment was just drawn, now the next starts
2130                         x1 = cursorX(cur.top(), cur.boundary());
2131                 }
2132                 
2133                 if (!(cur < end) || drawNow) {
2134                         x2 = cursorX(cur.top(), cur.boundary());
2135                         pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2136                                 Color_selection);
2137                         
2138                         // reset x1, so it is set again next round (which will be on the 
2139                         // right side of a boundary or at the selection end)
2140                         x1 = -1;
2141                 }
2142         }
2143 }
2144
2145 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2146 //{
2147 //      ParagraphMetrics const & pm = par_metrics_[pit];
2148 //      Row const & r = pm.rows()[row];
2149 //      int x = 0;
2150 //      pos -= r.pos();
2151 //}
2152
2153
2154 int defaultRowHeight()
2155 {
2156         return int(theFontMetrics(sane_font).maxHeight() *  1.2);
2157 }
2158
2159 } // namespace lyx