initial import
[vuplus_webkit] / Source / WebCore / rendering / RootInlineBox.cpp
1 /*
2  * Copyright (C) 2003, 2006, 2008 Apple Inc. All rights reserved.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public License
15  * along with this library; see the file COPYING.LIB.  If not, write to
16  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #include "config.h"
21 #include "RootInlineBox.h"
22
23 #include "BidiResolver.h"
24 #include "Chrome.h"
25 #include "ChromeClient.h"
26 #include "Document.h"
27 #include "EllipsisBox.h"
28 #include "Frame.h"
29 #include "GraphicsContext.h"
30 #include "HitTestResult.h"
31 #include "InlineTextBox.h"
32 #include "Page.h"
33 #include "PaintInfo.h"
34 #include "RenderArena.h"
35 #include "RenderBlock.h"
36 #include "VerticalPositionCache.h"
37
38 using namespace std;
39
40 namespace WebCore {
41     
42 typedef WTF::HashMap<const RootInlineBox*, EllipsisBox*> EllipsisBoxMap;
43 static EllipsisBoxMap* gEllipsisBoxMap = 0;
44
45 RootInlineBox::RootInlineBox(RenderBlock* block)
46     : InlineFlowBox(block)
47     , m_lineBreakObj(0)
48     , m_lineBreakPos(0)
49     , m_lineTop(0)
50     , m_lineBottom(0)
51     , m_lineTopWithLeading(0)
52     , m_lineBottomWithLeading(0)
53     , m_paginationStrut(0)
54     , m_baselineType(AlphabeticBaseline)
55     , m_hasAnnotationsBefore(false)
56     , m_hasAnnotationsAfter(false)
57 {
58     setIsHorizontal(block->isHorizontalWritingMode());
59 }
60
61
62 void RootInlineBox::destroy(RenderArena* arena)
63 {
64     detachEllipsisBox(arena);
65     InlineFlowBox::destroy(arena);
66 }
67
68 void RootInlineBox::detachEllipsisBox(RenderArena* arena)
69 {
70     if (hasEllipsisBox()) {
71         EllipsisBox* box = gEllipsisBoxMap->take(this);
72         box->setParent(0);
73         box->destroy(arena);
74         setHasEllipsisBox(false);
75     }
76 }
77
78 RenderLineBoxList* RootInlineBox::rendererLineBoxes() const
79 {
80     return block()->lineBoxes();
81 }
82
83 void RootInlineBox::clearTruncation()
84 {
85     if (hasEllipsisBox()) {
86         detachEllipsisBox(renderer()->renderArena());
87         InlineFlowBox::clearTruncation();
88     }
89 }
90
91 bool RootInlineBox::isHyphenated() const
92 {
93     for (InlineBox* box = firstLeafChild(); box; box = box->nextLeafChild()) {
94         if (box->isInlineTextBox()) {
95             if (toInlineTextBox(box)->hasHyphen())
96                 return true;
97         }
98     }
99
100     return false;
101 }
102
103 bool RootInlineBox::lineCanAccommodateEllipsis(bool ltr, int blockEdge, int lineBoxEdge, int ellipsisWidth)
104 {
105     // First sanity-check the unoverflowed width of the whole line to see if there is sufficient room.
106     int delta = ltr ? lineBoxEdge - blockEdge : blockEdge - lineBoxEdge;
107     if (logicalWidth() - delta < ellipsisWidth)
108         return false;
109
110     // Next iterate over all the line boxes on the line.  If we find a replaced element that intersects
111     // then we refuse to accommodate the ellipsis.  Otherwise we're ok.
112     return InlineFlowBox::canAccommodateEllipsis(ltr, blockEdge, ellipsisWidth);
113 }
114
115 void RootInlineBox::placeEllipsis(const AtomicString& ellipsisStr,  bool ltr, float blockLeftEdge, float blockRightEdge, float ellipsisWidth,
116                                   InlineBox* markupBox)
117 {
118     // Create an ellipsis box.
119     EllipsisBox* ellipsisBox = new (renderer()->renderArena()) EllipsisBox(renderer(), ellipsisStr, this,
120                                                               ellipsisWidth - (markupBox ? markupBox->logicalWidth() : 0), logicalHeight(),
121                                                               y(), !prevRootBox(), isHorizontal(), markupBox);
122     
123     if (!gEllipsisBoxMap)
124         gEllipsisBoxMap = new EllipsisBoxMap();
125     gEllipsisBoxMap->add(this, ellipsisBox);
126     setHasEllipsisBox(true);
127
128     // FIXME: Do we need an RTL version of this?
129     if (ltr && (x() + logicalWidth() + ellipsisWidth) <= blockRightEdge) {
130         ellipsisBox->setX(x() + logicalWidth());
131         return;
132     }
133
134     // Now attempt to find the nearest glyph horizontally and place just to the right (or left in RTL)
135     // of that glyph.  Mark all of the objects that intersect the ellipsis box as not painting (as being
136     // truncated).
137     bool foundBox = false;
138     ellipsisBox->setX(placeEllipsisBox(ltr, blockLeftEdge, blockRightEdge, ellipsisWidth, foundBox));
139 }
140
141 float RootInlineBox::placeEllipsisBox(bool ltr, float blockLeftEdge, float blockRightEdge, float ellipsisWidth, bool& foundBox)
142 {
143     float result = InlineFlowBox::placeEllipsisBox(ltr, blockLeftEdge, blockRightEdge, ellipsisWidth, foundBox);
144     if (result == -1)
145         result = ltr ? blockRightEdge - ellipsisWidth : blockLeftEdge;
146     return result;
147 }
148
149 void RootInlineBox::paintEllipsisBox(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit lineTop, LayoutUnit lineBottom) const
150 {
151     if (hasEllipsisBox() && paintInfo.shouldPaintWithinRoot(renderer()) && renderer()->style()->visibility() == VISIBLE
152             && paintInfo.phase == PaintPhaseForeground)
153         ellipsisBox()->paint(paintInfo, paintOffset, lineTop, lineBottom);
154 }
155
156 #if PLATFORM(MAC)
157
158 void RootInlineBox::addHighlightOverflow()
159 {
160     Frame* frame = renderer()->frame();
161     if (!frame)
162         return;
163     Page* page = frame->page();
164     if (!page)
165         return;
166
167     // Highlight acts as a selection inflation.
168     FloatRect rootRect(0, selectionTop(), logicalWidth(), selectionHeight());
169     IntRect inflatedRect = enclosingIntRect(page->chrome()->client()->customHighlightRect(renderer()->node(), renderer()->style()->highlight(), rootRect));
170     setOverflowFromLogicalRects(inflatedRect, inflatedRect, lineTop(), lineBottom());
171 }
172
173 void RootInlineBox::paintCustomHighlight(PaintInfo& paintInfo, const LayoutPoint& paintOffset, const AtomicString& highlightType)
174 {
175     if (!paintInfo.shouldPaintWithinRoot(renderer()) || renderer()->style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseForeground)
176         return;
177
178     Frame* frame = renderer()->frame();
179     if (!frame)
180         return;
181     Page* page = frame->page();
182     if (!page)
183         return;
184
185     // Get the inflated rect so that we can properly hit test.
186     FloatRect rootRect(paintOffset.x() + x(), paintOffset.y() + selectionTop(), logicalWidth(), selectionHeight());
187     FloatRect inflatedRect = page->chrome()->client()->customHighlightRect(renderer()->node(), highlightType, rootRect);
188     if (inflatedRect.intersects(paintInfo.rect))
189         page->chrome()->client()->paintCustomHighlight(renderer()->node(), highlightType, rootRect, rootRect, false, true);
190 }
191
192 #endif
193
194 void RootInlineBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit lineTop, LayoutUnit lineBottom)
195 {
196     InlineFlowBox::paint(paintInfo, paintOffset, lineTop, lineBottom);
197     paintEllipsisBox(paintInfo, paintOffset, lineTop, lineBottom);
198 #if PLATFORM(MAC)
199     RenderStyle* styleToUse = renderer()->style(m_firstLine);
200     if (styleToUse->highlight() != nullAtom && !paintInfo.context->paintingDisabled())
201         paintCustomHighlight(paintInfo, paintOffset, styleToUse->highlight());
202 #endif
203 }
204
205 bool RootInlineBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom)
206 {
207     if (hasEllipsisBox() && visibleToHitTesting()) {
208         if (ellipsisBox()->nodeAtPoint(request, result, pointInContainer, accumulatedOffset, lineTop, lineBottom)) {
209             renderer()->updateHitTestResult(result, pointInContainer - toLayoutSize(accumulatedOffset));
210             return true;
211         }
212     }
213     return InlineFlowBox::nodeAtPoint(request, result, pointInContainer, accumulatedOffset, lineTop, lineBottom);
214 }
215
216 void RootInlineBox::adjustPosition(float dx, float dy)
217 {
218     InlineFlowBox::adjustPosition(dx, dy);
219     LayoutUnit blockDirectionDelta = isHorizontal() ? dy : dx; // The block direction delta is a LayoutUnit.
220     m_lineTop += blockDirectionDelta;
221     m_lineBottom += blockDirectionDelta;
222     m_lineTopWithLeading += blockDirectionDelta;
223     m_lineBottomWithLeading += blockDirectionDelta;
224 }
225
226 void RootInlineBox::childRemoved(InlineBox* box)
227 {
228     if (box->renderer() == m_lineBreakObj)
229         setLineBreakInfo(0, 0, BidiStatus());
230
231     for (RootInlineBox* prev = prevRootBox(); prev && prev->lineBreakObj() == box->renderer(); prev = prev->prevRootBox()) {
232         prev->setLineBreakInfo(0, 0, BidiStatus());
233         prev->markDirty();
234     }
235 }
236
237 LayoutUnit RootInlineBox::alignBoxesInBlockDirection(LayoutUnit heightOfBlock, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
238 {
239 #if ENABLE(SVG)
240     // SVG will handle vertical alignment on its own.
241     if (isSVGRootInlineBox())
242         return 0;
243 #endif
244
245     LayoutUnit maxPositionTop = 0;
246     LayoutUnit maxPositionBottom = 0;
247     LayoutUnit maxAscent = 0;
248     LayoutUnit maxDescent = 0;
249     bool setMaxAscent = false;
250     bool setMaxDescent = false;
251
252     // Figure out if we're in no-quirks mode.
253     bool noQuirksMode = renderer()->document()->inNoQuirksMode();
254
255     m_baselineType = requiresIdeographicBaseline(textBoxDataMap) ? IdeographicBaseline : AlphabeticBaseline;
256
257     computeLogicalBoxHeights(this, maxPositionTop, maxPositionBottom, maxAscent, maxDescent, setMaxAscent, setMaxDescent, noQuirksMode,
258                              textBoxDataMap, baselineType(), verticalPositionCache);
259
260     if (maxAscent + maxDescent < max(maxPositionTop, maxPositionBottom))
261         adjustMaxAscentAndDescent(maxAscent, maxDescent, maxPositionTop, maxPositionBottom);
262
263     LayoutUnit maxHeight = maxAscent + maxDescent;
264     LayoutUnit lineTop = heightOfBlock;
265     LayoutUnit lineBottom = heightOfBlock;
266     LayoutUnit lineTopIncludingMargins = heightOfBlock;
267     LayoutUnit lineBottomIncludingMargins = heightOfBlock;
268     bool setLineTop = false;
269     bool hasAnnotationsBefore = false;
270     bool hasAnnotationsAfter = false;
271     placeBoxesInBlockDirection(heightOfBlock, maxHeight, maxAscent, noQuirksMode, lineTop, lineBottom, setLineTop,
272                                lineTopIncludingMargins, lineBottomIncludingMargins, hasAnnotationsBefore, hasAnnotationsAfter, baselineType());
273     m_hasAnnotationsBefore = hasAnnotationsBefore;
274     m_hasAnnotationsAfter = hasAnnotationsAfter;
275     
276     maxHeight = max<LayoutUnit>(0, maxHeight); // FIXME: Is this really necessary?
277
278     setLineTopBottomPositions(lineTop, lineBottom, heightOfBlock, heightOfBlock + maxHeight);
279
280     int annotationsAdjustment = beforeAnnotationsAdjustment();
281     if (annotationsAdjustment) {
282         // FIXME: Need to handle pagination here. We might have to move to the next page/column as a result of the
283         // ruby expansion.
284         adjustBlockDirectionPosition(annotationsAdjustment);
285         heightOfBlock += annotationsAdjustment;
286     }
287
288     return heightOfBlock + maxHeight;
289 }
290
291 int RootInlineBox::beforeAnnotationsAdjustment() const
292 {
293     int result = 0;
294
295     if (!renderer()->style()->isFlippedLinesWritingMode()) {
296         // Annotations under the previous line may push us down.
297         if (prevRootBox() && prevRootBox()->hasAnnotationsAfter())
298             result = prevRootBox()->computeUnderAnnotationAdjustment(lineTop());
299
300         if (!hasAnnotationsBefore())
301             return result;
302
303         // Annotations over this line may push us further down.
304         int highestAllowedPosition = prevRootBox() ? min(prevRootBox()->lineBottom(), lineTop()) + result : block()->borderBefore();
305         result = computeOverAnnotationAdjustment(highestAllowedPosition);
306     } else {
307         // Annotations under this line may push us up.
308         if (hasAnnotationsBefore())
309             result = computeUnderAnnotationAdjustment(prevRootBox() ? prevRootBox()->lineBottom() : block()->borderBefore());
310
311         if (!prevRootBox() || !prevRootBox()->hasAnnotationsAfter())
312             return result;
313
314         // We have to compute the expansion for annotations over the previous line to see how much we should move.
315         int lowestAllowedPosition = max(prevRootBox()->lineBottom(), lineTop()) - result;
316         result = prevRootBox()->computeOverAnnotationAdjustment(lowestAllowedPosition);
317     }
318
319     return result;
320 }
321
322 GapRects RootInlineBox::lineSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock, 
323                                          LayoutUnit selTop, LayoutUnit selHeight, const PaintInfo* paintInfo)
324 {
325     RenderObject::SelectionState lineState = selectionState();
326
327     bool leftGap, rightGap;
328     block()->getSelectionGapInfo(lineState, leftGap, rightGap);
329
330     GapRects result;
331
332     InlineBox* firstBox = firstSelectedBox();
333     InlineBox* lastBox = lastSelectedBox();
334     if (leftGap)
335         result.uniteLeft(block()->logicalLeftSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock,
336                                                           firstBox->parent()->renderer(), firstBox->logicalLeft(), selTop, selHeight, paintInfo));
337     if (rightGap)
338         result.uniteRight(block()->logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock,
339                                                             lastBox->parent()->renderer(), lastBox->logicalRight(), selTop, selHeight, paintInfo));
340
341     // When dealing with bidi text, a non-contiguous selection region is possible.
342     // e.g. The logical text aaaAAAbbb (capitals denote RTL text and non-capitals LTR) is layed out
343     // visually as 3 text runs |aaa|bbb|AAA| if we select 4 characters from the start of the text the
344     // selection will look like (underline denotes selection):
345     // |aaa|bbb|AAA|
346     //  ___       _
347     // We can see that the |bbb| run is not part of the selection while the runs around it are.
348     if (firstBox && firstBox != lastBox) {
349         // Now fill in any gaps on the line that occurred between two selected elements.
350         LayoutUnit lastLogicalLeft = firstBox->logicalRight();
351         bool isPreviousBoxSelected = firstBox->selectionState() != RenderObject::SelectionNone;
352         for (InlineBox* box = firstBox->nextLeafChild(); box; box = box->nextLeafChild()) {
353             if (box->selectionState() != RenderObject::SelectionNone) {
354                 LayoutRect logicalRect(lastLogicalLeft, selTop, box->logicalLeft() - lastLogicalLeft, selHeight);
355                 logicalRect.move(renderer()->isHorizontalWritingMode() ? offsetFromRootBlock : LayoutSize(offsetFromRootBlock.height(), offsetFromRootBlock.width()));
356                 LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
357                 if (isPreviousBoxSelected && gapRect.width() > 0 && gapRect.height() > 0) {
358                     if (paintInfo && box->parent()->renderer()->style()->visibility() == VISIBLE)
359                         paintInfo->context->fillRect(gapRect, box->parent()->renderer()->selectionBackgroundColor(), box->parent()->renderer()->style()->colorSpace());
360                     // VisibleSelection may be non-contiguous, see comment above.
361                     result.uniteCenter(gapRect);
362                 }
363                 lastLogicalLeft = box->logicalRight();
364             }
365             if (box == lastBox)
366                 break;
367             isPreviousBoxSelected = box->selectionState() != RenderObject::SelectionNone;
368         }
369     }
370
371     return result;
372 }
373
374 RenderObject::SelectionState RootInlineBox::selectionState()
375 {
376     // Walk over all of the selected boxes.
377     RenderObject::SelectionState state = RenderObject::SelectionNone;
378     for (InlineBox* box = firstLeafChild(); box; box = box->nextLeafChild()) {
379         RenderObject::SelectionState boxState = box->selectionState();
380         if ((boxState == RenderObject::SelectionStart && state == RenderObject::SelectionEnd) ||
381             (boxState == RenderObject::SelectionEnd && state == RenderObject::SelectionStart))
382             state = RenderObject::SelectionBoth;
383         else if (state == RenderObject::SelectionNone ||
384                  ((boxState == RenderObject::SelectionStart || boxState == RenderObject::SelectionEnd) &&
385                   (state == RenderObject::SelectionNone || state == RenderObject::SelectionInside)))
386             state = boxState;
387         if (state == RenderObject::SelectionBoth)
388             break;
389     }
390
391     return state;
392 }
393
394 InlineBox* RootInlineBox::firstSelectedBox()
395 {
396     for (InlineBox* box = firstLeafChild(); box; box = box->nextLeafChild()) {
397         if (box->selectionState() != RenderObject::SelectionNone)
398             return box;
399     }
400
401     return 0;
402 }
403
404 InlineBox* RootInlineBox::lastSelectedBox()
405 {
406     for (InlineBox* box = lastLeafChild(); box; box = box->prevLeafChild()) {
407         if (box->selectionState() != RenderObject::SelectionNone)
408             return box;
409     }
410
411     return 0;
412 }
413
414 LayoutUnit RootInlineBox::selectionTop() const
415 {
416     LayoutUnit selectionTop = m_lineTop;
417
418     if (m_hasAnnotationsBefore)
419         selectionTop -= !renderer()->style()->isFlippedLinesWritingMode() ? computeOverAnnotationAdjustment(m_lineTop) : computeUnderAnnotationAdjustment(m_lineTop);
420
421     if (renderer()->style()->isFlippedLinesWritingMode())
422         return selectionTop;
423
424     LayoutUnit prevBottom = prevRootBox() ? prevRootBox()->selectionBottom() : block()->borderBefore() + block()->paddingBefore();
425     if (prevBottom < selectionTop && block()->containsFloats()) {
426         // This line has actually been moved further down, probably from a large line-height, but possibly because the
427         // line was forced to clear floats.  If so, let's check the offsets, and only be willing to use the previous
428         // line's bottom if the offsets are greater on both sides.
429         LayoutUnit prevLeft = block()->logicalLeftOffsetForLine(prevBottom, false);
430         LayoutUnit prevRight = block()->logicalRightOffsetForLine(prevBottom, false);
431         LayoutUnit newLeft = block()->logicalLeftOffsetForLine(selectionTop, false);
432         LayoutUnit newRight = block()->logicalRightOffsetForLine(selectionTop, false);
433         if (prevLeft > newLeft || prevRight < newRight)
434             return selectionTop;
435     }
436
437     return prevBottom;
438 }
439
440 LayoutUnit RootInlineBox::selectionBottom() const
441 {
442     LayoutUnit selectionBottom = m_lineBottom;
443
444     if (m_hasAnnotationsAfter)
445         selectionBottom += !renderer()->style()->isFlippedLinesWritingMode() ? computeUnderAnnotationAdjustment(m_lineBottom) : computeOverAnnotationAdjustment(m_lineBottom);
446
447     if (!renderer()->style()->isFlippedLinesWritingMode() || !nextRootBox())
448         return selectionBottom;
449
450     LayoutUnit nextTop = nextRootBox()->selectionTop();
451     if (nextTop > selectionBottom && block()->containsFloats()) {
452         // The next line has actually been moved further over, probably from a large line-height, but possibly because the
453         // line was forced to clear floats.  If so, let's check the offsets, and only be willing to use the next
454         // line's top if the offsets are greater on both sides.
455         LayoutUnit nextLeft = block()->logicalLeftOffsetForLine(nextTop, false);
456         LayoutUnit nextRight = block()->logicalRightOffsetForLine(nextTop, false);
457         LayoutUnit newLeft = block()->logicalLeftOffsetForLine(selectionBottom, false);
458         LayoutUnit newRight = block()->logicalRightOffsetForLine(selectionBottom, false);
459         if (nextLeft > newLeft || nextRight < newRight)
460             return selectionBottom;
461     }
462
463     return nextTop;
464 }
465
466 RenderBlock* RootInlineBox::block() const
467 {
468     return toRenderBlock(renderer());
469 }
470
471 static bool isEditableLeaf(InlineBox* leaf)
472 {
473     return leaf && leaf->renderer() && leaf->renderer()->node() && leaf->renderer()->node()->rendererIsEditable();
474 }
475
476 InlineBox* RootInlineBox::closestLeafChildForPoint(const IntPoint& pointInContents, bool onlyEditableLeaves)
477 {
478     return closestLeafChildForLogicalLeftPosition(block()->isHorizontalWritingMode() ? pointInContents.x() : pointInContents.y(), onlyEditableLeaves);
479 }
480
481 InlineBox* RootInlineBox::closestLeafChildForLogicalLeftPosition(int leftPosition, bool onlyEditableLeaves)
482 {
483     InlineBox* firstLeaf = firstLeafChild();
484     InlineBox* lastLeaf = lastLeafChild();
485     if (firstLeaf == lastLeaf && (!onlyEditableLeaves || isEditableLeaf(firstLeaf)))
486         return firstLeaf;
487
488     // Avoid returning a list marker when possible.
489     if (leftPosition <= firstLeaf->logicalLeft() && !firstLeaf->renderer()->isListMarker() && (!onlyEditableLeaves || isEditableLeaf(firstLeaf)))
490         // The leftPosition coordinate is less or equal to left edge of the firstLeaf.
491         // Return it.
492         return firstLeaf;
493
494     if (leftPosition >= lastLeaf->logicalRight() && !lastLeaf->renderer()->isListMarker() && (!onlyEditableLeaves || isEditableLeaf(lastLeaf)))
495         // The leftPosition coordinate is greater or equal to right edge of the lastLeaf.
496         // Return it.
497         return lastLeaf;
498
499     InlineBox* closestLeaf = 0;
500     for (InlineBox* leaf = firstLeaf; leaf; leaf = leaf->nextLeafChild()) {
501         if (!leaf->renderer()->isListMarker() && (!onlyEditableLeaves || isEditableLeaf(leaf))) {
502             closestLeaf = leaf;
503             if (leftPosition < leaf->logicalRight())
504                 // The x coordinate is less than the right edge of the box.
505                 // Return it.
506                 return leaf;
507         }
508     }
509
510     return closestLeaf ? closestLeaf : lastLeaf;
511 }
512
513 BidiStatus RootInlineBox::lineBreakBidiStatus() const
514
515     return BidiStatus(m_lineBreakBidiStatusEor, m_lineBreakBidiStatusLastStrong, m_lineBreakBidiStatusLast, m_lineBreakContext);
516 }
517
518 void RootInlineBox::setLineBreakInfo(RenderObject* obj, unsigned breakPos, const BidiStatus& status)
519 {
520     m_lineBreakObj = obj;
521     m_lineBreakPos = breakPos;
522     m_lineBreakBidiStatusEor = status.eor;
523     m_lineBreakBidiStatusLastStrong = status.lastStrong;
524     m_lineBreakBidiStatusLast = status.last;
525     m_lineBreakContext = status.context;
526 }
527
528 EllipsisBox* RootInlineBox::ellipsisBox() const
529 {
530     if (!hasEllipsisBox())
531         return 0;
532     return gEllipsisBoxMap->get(this);
533 }
534
535 void RootInlineBox::removeLineBoxFromRenderObject()
536 {
537     block()->lineBoxes()->removeLineBox(this);
538 }
539
540 void RootInlineBox::extractLineBoxFromRenderObject()
541 {
542     block()->lineBoxes()->extractLineBox(this);
543 }
544
545 void RootInlineBox::attachLineBoxToRenderObject()
546 {
547     block()->lineBoxes()->attachLineBox(this);
548 }
549
550 LayoutRect RootInlineBox::paddedLayoutOverflowRect(LayoutUnit endPadding) const
551 {
552     LayoutRect lineLayoutOverflow = layoutOverflowRect(lineTop(), lineBottom());
553     if (!endPadding)
554         return lineLayoutOverflow;
555     
556     // FIXME: Audit whether to use pixel snapped values when not using integers for layout: https://bugs.webkit.org/show_bug.cgi?id=63656
557     if (isHorizontal()) {
558         if (isLeftToRightDirection())
559             lineLayoutOverflow.shiftMaxXEdgeTo(max<LayoutUnit>(lineLayoutOverflow.maxX(), pixelSnappedLogicalRight() + endPadding));
560         else
561             lineLayoutOverflow.shiftXEdgeTo(min<LayoutUnit>(lineLayoutOverflow.x(), pixelSnappedLogicalLeft() - endPadding));
562     } else {
563         if (isLeftToRightDirection())
564             lineLayoutOverflow.shiftMaxYEdgeTo(max<LayoutUnit>(lineLayoutOverflow.maxY(), pixelSnappedLogicalRight() + endPadding));
565         else
566             lineLayoutOverflow.shiftYEdgeTo(min<LayoutUnit>(lineLayoutOverflow.y(), pixelSnappedLogicalLeft() - endPadding));
567     }
568     
569     return lineLayoutOverflow;
570 }
571
572 static void setAscentAndDescent(LayoutUnit& ascent, LayoutUnit& descent, LayoutUnit newAscent, LayoutUnit newDescent, bool& ascentDescentSet)
573 {
574     if (!ascentDescentSet) {
575         ascentDescentSet = true;
576         ascent = newAscent;
577         descent = newDescent;
578     } else {
579         ascent = max(ascent, newAscent);
580         descent = max(descent, newDescent);
581     }
582 }
583
584 void RootInlineBox::ascentAndDescentForBox(InlineBox* box, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, LayoutUnit& ascent, LayoutUnit& descent,
585                                            bool& affectsAscent, bool& affectsDescent) const
586 {
587     bool ascentDescentSet = false;
588
589     // Replaced boxes will return 0 for the line-height if line-box-contain says they are
590     // not to be included.
591     if (box->renderer()->isReplaced()) {
592         if (renderer()->style(m_firstLine)->lineBoxContain() & LineBoxContainReplaced) {
593             ascent = box->baselinePosition(baselineType());
594             descent = box->lineHeight() - ascent;
595             
596             // Replaced elements always affect both the ascent and descent.
597             affectsAscent = true;
598             affectsDescent = true;
599         }
600         return;
601     }
602
603     Vector<const SimpleFontData*>* usedFonts = 0;
604     GlyphOverflow* glyphOverflow = 0;
605     if (box->isText()) {
606         GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.find(toInlineTextBox(box));
607         usedFonts = it == textBoxDataMap.end() ? 0 : &it->second.first;
608         glyphOverflow = it == textBoxDataMap.end() ? 0 : &it->second.second;
609     }
610         
611     bool includeLeading = includeLeadingForBox(box);
612     bool includeFont = includeFontForBox(box);
613     
614     bool setUsedFont = false;
615     bool setUsedFontWithLeading = false;
616
617     if (usedFonts && !usedFonts->isEmpty() && (includeFont || (box->renderer()->style(m_firstLine)->lineHeight().isNegative() && includeLeading))) {
618         usedFonts->append(box->renderer()->style(m_firstLine)->font().primaryFont());
619         for (size_t i = 0; i < usedFonts->size(); ++i) {
620             const FontMetrics& fontMetrics = usedFonts->at(i)->fontMetrics();
621             LayoutUnit usedFontAscent = fontMetrics.ascent(baselineType());
622             LayoutUnit usedFontDescent = fontMetrics.descent(baselineType());
623             LayoutUnit halfLeading = (fontMetrics.lineSpacing() - fontMetrics.height()) / 2;
624             LayoutUnit usedFontAscentAndLeading = usedFontAscent + halfLeading;
625             LayoutUnit usedFontDescentAndLeading = fontMetrics.lineSpacing() - usedFontAscentAndLeading;
626             if (includeFont) {
627                 setAscentAndDescent(ascent, descent, usedFontAscent, usedFontDescent, ascentDescentSet);
628                 setUsedFont = true;
629             }
630             if (includeLeading) {
631                 setAscentAndDescent(ascent, descent, usedFontAscentAndLeading, usedFontDescentAndLeading, ascentDescentSet);
632                 setUsedFontWithLeading = true;
633             }
634             if (!affectsAscent)
635                 affectsAscent = usedFontAscent - box->logicalTop() > 0;
636             if (!affectsDescent)
637                 affectsDescent = usedFontDescent + box->logicalTop() > 0;
638         }
639     }
640
641     // If leading is included for the box, then we compute that box.
642     if (includeLeading && !setUsedFontWithLeading) {
643         int ascentWithLeading = box->baselinePosition(baselineType());
644         int descentWithLeading = box->lineHeight() - ascentWithLeading;
645         setAscentAndDescent(ascent, descent, ascentWithLeading, descentWithLeading, ascentDescentSet);
646         
647         // Examine the font box for inline flows and text boxes to see if any part of it is above the baseline.
648         // If the top of our font box relative to the root box baseline is above the root box baseline, then
649         // we are contributing to the maxAscent value. Descent is similar. If any part of our font box is below
650         // the root box's baseline, then we contribute to the maxDescent value.
651         affectsAscent = ascentWithLeading - box->logicalTop() > 0;
652         affectsDescent = descentWithLeading + box->logicalTop() > 0; 
653     }
654     
655     if (includeFontForBox(box) && !setUsedFont) {
656         int fontAscent = box->renderer()->style(m_firstLine)->fontMetrics().ascent();
657         int fontDescent = box->renderer()->style(m_firstLine)->fontMetrics().descent();
658         setAscentAndDescent(ascent, descent, fontAscent, fontDescent, ascentDescentSet);
659         affectsAscent = fontAscent - box->logicalTop() > 0;
660         affectsDescent = fontDescent + box->logicalTop() > 0; 
661     }
662
663     if (includeGlyphsForBox(box) && glyphOverflow && glyphOverflow->computeBounds) {
664         setAscentAndDescent(ascent, descent, glyphOverflow->top, glyphOverflow->bottom, ascentDescentSet);
665         affectsAscent = glyphOverflow->top - box->logicalTop() > 0;
666         affectsDescent = glyphOverflow->bottom + box->logicalTop() > 0; 
667         glyphOverflow->top = min(glyphOverflow->top, max(0, glyphOverflow->top - box->renderer()->style(m_firstLine)->fontMetrics().ascent()));
668         glyphOverflow->bottom = min(glyphOverflow->bottom, max(0, glyphOverflow->bottom - box->renderer()->style(m_firstLine)->fontMetrics().descent()));
669     }
670
671     if (includeMarginForBox(box)) {
672         int ascentWithMargin = box->renderer()->style(m_firstLine)->fontMetrics().ascent();
673         int descentWithMargin = box->renderer()->style(m_firstLine)->fontMetrics().descent();
674         if (box->parent() && !box->renderer()->isText()) {
675             ascentWithMargin += box->boxModelObject()->borderBefore() + box->boxModelObject()->paddingBefore() + box->boxModelObject()->marginBefore();
676             descentWithMargin += box->boxModelObject()->borderAfter() + box->boxModelObject()->paddingAfter() + box->boxModelObject()->marginAfter();
677         }
678         setAscentAndDescent(ascent, descent, ascentWithMargin, descentWithMargin, ascentDescentSet);
679         
680         // Treat like a replaced element, since we're using the margin box.
681         affectsAscent = true;
682         affectsDescent = true;
683     }
684 }
685
686 LayoutUnit RootInlineBox::verticalPositionForBox(InlineBox* box, VerticalPositionCache& verticalPositionCache)
687 {
688     if (box->renderer()->isText())
689         return box->parent()->logicalTop();
690     
691     RenderBoxModelObject* renderer = box->boxModelObject();
692     ASSERT(renderer->isInline());
693     if (!renderer->isInline())
694         return 0;
695
696     // This method determines the vertical position for inline elements.
697     bool firstLine = m_firstLine;
698     if (firstLine && !renderer->document()->usesFirstLineRules())
699         firstLine = false;
700
701     // Check the cache.
702     bool isRenderInline = renderer->isRenderInline();
703     if (isRenderInline && !firstLine) {
704         LayoutUnit verticalPosition = verticalPositionCache.get(renderer, baselineType());
705         if (verticalPosition != PositionUndefined)
706             return verticalPosition;
707     }
708
709     int verticalPosition = 0;
710     EVerticalAlign verticalAlign = renderer->style()->verticalAlign();
711     if (verticalAlign == TOP || verticalAlign == BOTTOM)
712         return 0;
713    
714     RenderObject* parent = renderer->parent();
715     if (parent->isRenderInline() && parent->style()->verticalAlign() != TOP && parent->style()->verticalAlign() != BOTTOM)
716         verticalPosition = box->parent()->logicalTop();
717     
718     if (verticalAlign != BASELINE) {
719         const Font& font = parent->style(firstLine)->font();
720         const FontMetrics& fontMetrics = font.fontMetrics();
721         int fontSize = font.pixelSize();
722
723         LineDirectionMode lineDirection = parent->isHorizontalWritingMode() ? HorizontalLine : VerticalLine;
724
725         if (verticalAlign == SUB)
726             verticalPosition += fontSize / 5 + 1;
727         else if (verticalAlign == SUPER)
728             verticalPosition -= fontSize / 3 + 1;
729         else if (verticalAlign == TEXT_TOP)
730             verticalPosition += renderer->baselinePosition(baselineType(), firstLine, lineDirection) - fontMetrics.ascent(baselineType());
731         else if (verticalAlign == MIDDLE)
732             verticalPosition += -static_cast<int>(fontMetrics.xHeight() / 2) - renderer->lineHeight(firstLine, lineDirection) / 2 + renderer->baselinePosition(baselineType(), firstLine, lineDirection);
733         else if (verticalAlign == TEXT_BOTTOM) {
734             verticalPosition += fontMetrics.descent(baselineType());
735             // lineHeight - baselinePosition is always 0 for replaced elements (except inline blocks), so don't bother wasting time in that case.
736             if (!renderer->isReplaced() || renderer->isInlineBlockOrInlineTable())
737                 verticalPosition -= (renderer->lineHeight(firstLine, lineDirection) - renderer->baselinePosition(baselineType(), firstLine, lineDirection));
738         } else if (verticalAlign == BASELINE_MIDDLE)
739             verticalPosition += -renderer->lineHeight(firstLine, lineDirection) / 2 + renderer->baselinePosition(baselineType(), firstLine, lineDirection);
740         else if (verticalAlign == LENGTH)
741             verticalPosition -= renderer->style()->verticalAlignLength().calcValue(renderer->lineHeight(firstLine, lineDirection));
742     }
743
744     // Store the cached value.
745     if (isRenderInline && !firstLine)
746         verticalPositionCache.set(renderer, baselineType(), verticalPosition);
747
748     return verticalPosition;
749 }
750
751 bool RootInlineBox::includeLeadingForBox(InlineBox* box) const
752 {
753     if (box->renderer()->isReplaced() || (box->renderer()->isText() && !box->isText()))
754         return false;
755
756     LineBoxContain lineBoxContain = renderer()->style()->lineBoxContain();
757     return (lineBoxContain & LineBoxContainInline) || (box == this && (lineBoxContain & LineBoxContainBlock));
758 }
759
760 bool RootInlineBox::includeFontForBox(InlineBox* box) const
761 {
762     if (box->renderer()->isReplaced() || (box->renderer()->isText() && !box->isText()))
763         return false;
764     
765     if (!box->isText() && box->isInlineFlowBox() && !toInlineFlowBox(box)->hasTextChildren())
766         return false;
767
768     // For now map "glyphs" to "font" in vertical text mode until the bounds returned by glyphs aren't garbage.
769     LineBoxContain lineBoxContain = renderer()->style()->lineBoxContain();
770     return (lineBoxContain & LineBoxContainFont) || (!isHorizontal() && (lineBoxContain & LineBoxContainGlyphs));
771 }
772
773 bool RootInlineBox::includeGlyphsForBox(InlineBox* box) const
774 {
775     if (box->renderer()->isReplaced() || (box->renderer()->isText() && !box->isText()))
776         return false;
777     
778     if (!box->isText() && box->isInlineFlowBox() && !toInlineFlowBox(box)->hasTextChildren())
779         return false;
780
781     // FIXME: We can't fit to glyphs yet for vertical text, since the bounds returned are garbage.
782     LineBoxContain lineBoxContain = renderer()->style()->lineBoxContain();
783     return isHorizontal() && (lineBoxContain & LineBoxContainGlyphs);
784 }
785
786 bool RootInlineBox::includeMarginForBox(InlineBox* box) const
787 {
788     if (box->renderer()->isReplaced() || (box->renderer()->isText() && !box->isText()))
789         return false;
790
791     LineBoxContain lineBoxContain = renderer()->style()->lineBoxContain();
792     return lineBoxContain & LineBoxContainInlineBox;
793 }
794
795
796 bool RootInlineBox::fitsToGlyphs() const
797 {
798     // FIXME: We can't fit to glyphs yet for vertical text, since the bounds returned are garbage.
799     LineBoxContain lineBoxContain = renderer()->style()->lineBoxContain();
800     return isHorizontal() && (lineBoxContain & LineBoxContainGlyphs);
801 }
802
803 bool RootInlineBox::includesRootLineBoxFontOrLeading() const
804 {
805     LineBoxContain lineBoxContain = renderer()->style()->lineBoxContain();
806     return (lineBoxContain & LineBoxContainBlock) || (lineBoxContain & LineBoxContainInline) || (lineBoxContain & LineBoxContainFont);
807 }
808
809 Node* RootInlineBox::getLogicalStartBoxWithNode(InlineBox*& startBox) const
810 {
811     Vector<InlineBox*> leafBoxesInLogicalOrder;
812     collectLeafBoxesInLogicalOrder(leafBoxesInLogicalOrder);
813     for (size_t i = 0; i < leafBoxesInLogicalOrder.size(); ++i) {
814         if (leafBoxesInLogicalOrder[i]->renderer()->node()) {
815             startBox = leafBoxesInLogicalOrder[i];
816             return startBox->renderer()->node();
817         }
818     }
819     startBox = 0;
820     return 0;
821 }
822     
823 Node* RootInlineBox::getLogicalEndBoxWithNode(InlineBox*& endBox) const
824 {
825     Vector<InlineBox*> leafBoxesInLogicalOrder;
826     collectLeafBoxesInLogicalOrder(leafBoxesInLogicalOrder);
827     for (size_t i = leafBoxesInLogicalOrder.size(); i > 0; --i) { 
828         if (leafBoxesInLogicalOrder[i - 1]->renderer()->node()) {
829             endBox = leafBoxesInLogicalOrder[i - 1];
830             return endBox->renderer()->node();
831         }
832     }
833     endBox = 0;
834     return 0;
835 }
836
837 #ifndef NDEBUG
838 const char* RootInlineBox::boxName() const
839 {
840     return "RootInlineBox";
841 }
842 #endif
843
844 } // namespace WebCore