Improve "bad parent" and "bad child list" assertions in line boxes
[WebKit-https.git] / Source / WebCore / rendering / InlineFlowBox.cpp
1 /*
2  * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 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 "InlineFlowBox.h"
22
23 #include "CSSPropertyNames.h"
24 #include "Document.h"
25 #include "EllipsisBox.h"
26 #include "Font.h"
27 #include "GraphicsContext.h"
28 #include "InlineTextBox.h"
29 #include "HitTestResult.h"
30 #include "RenderBlock.h"
31 #include "RenderInline.h"
32 #include "RenderLayer.h"
33 #include "RenderListMarker.h"
34 #include "RenderRubyBase.h"
35 #include "RenderRubyRun.h"
36 #include "RenderRubyText.h"
37 #include "RenderTableCell.h"
38 #include "RenderView.h"
39 #include "RootInlineBox.h"
40 #include "Text.h"
41 #include <math.h>
42
43 namespace WebCore {
44
45 struct SameSizeAsInlineFlowBox : public InlineBox {
46     void* pointers[5];
47     uint32_t bitfields : 23;
48 };
49
50 COMPILE_ASSERT(sizeof(InlineFlowBox) == sizeof(SameSizeAsInlineFlowBox), InlineFlowBox_should_stay_small);
51
52 #if !ASSERT_WITH_SECURITY_IMPLICATION_DISABLED
53
54 InlineFlowBox::~InlineFlowBox()
55 {
56     setHasBadChildList();
57 }
58
59 void InlineFlowBox::setHasBadChildList()
60 {
61     assertNotDeleted();
62     if (m_hasBadChildList)
63         return;
64     for (InlineBox* child = firstChild(); child; child = child->nextOnLine())
65         child->setHasBadParent();
66     m_hasBadChildList = true;
67 }
68
69 #endif
70
71 LayoutUnit InlineFlowBox::getFlowSpacingLogicalWidth()
72 {
73     LayoutUnit totWidth = marginBorderPaddingLogicalLeft() + marginBorderPaddingLogicalRight();
74     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
75         if (curr->isInlineFlowBox())
76             totWidth += toInlineFlowBox(curr)->getFlowSpacingLogicalWidth();
77     }
78     return totWidth;
79 }
80
81 IntRect InlineFlowBox::roundedFrameRect() const
82 {
83     // Begin by snapping the x and y coordinates to the nearest pixel.
84     int snappedX = lroundf(x());
85     int snappedY = lroundf(y());
86     
87     int snappedMaxX = lroundf(x() + width());
88     int snappedMaxY = lroundf(y() + height());
89     
90     return IntRect(snappedX, snappedY, snappedMaxX - snappedX, snappedMaxY - snappedY);
91 }
92
93 static void setHasTextDescendantsOnAncestors(InlineFlowBox* box)
94 {
95     while (box && !box->hasTextDescendants()) {
96         box->setHasTextDescendants();
97         box = box->parent();
98     }
99 }
100
101 void InlineFlowBox::addToLine(InlineBox* child) 
102 {
103     ASSERT(!child->parent());
104     ASSERT(!child->nextOnLine());
105     ASSERT(!child->prevOnLine());
106     checkConsistency();
107
108     child->setParent(this);
109     if (!m_firstChild) {
110         m_firstChild = child;
111         m_lastChild = child;
112     } else {
113         m_lastChild->setNextOnLine(child);
114         child->setPrevOnLine(m_lastChild);
115         m_lastChild = child;
116     }
117     child->setIsFirstLine(isFirstLine());
118     child->setIsHorizontal(isHorizontal());
119     if (child->behavesLikeText()) {
120         if (child->renderer().parent() == &renderer())
121             m_hasTextChildren = true;
122         setHasTextDescendantsOnAncestors(this);
123     } else if (child->isInlineFlowBox()) {
124         if (toInlineFlowBox(child)->hasTextDescendants())
125             setHasTextDescendantsOnAncestors(this);
126     }
127
128     if (descendantsHaveSameLineHeightAndBaseline() && !child->renderer().isOutOfFlowPositioned()) {
129         const RenderStyle& parentStyle = lineStyle();
130         const RenderStyle& childStyle = child->lineStyle();
131         bool shouldClearDescendantsHaveSameLineHeightAndBaseline = false;
132         if (child->renderer().isReplaced())
133             shouldClearDescendantsHaveSameLineHeightAndBaseline = true;
134         else if (child->behavesLikeText()) {
135             if (child->renderer().isLineBreak() || child->renderer().parent() != &renderer()) {
136                 if (!parentStyle.font().fontMetrics().hasIdenticalAscentDescentAndLineGap(childStyle.font().fontMetrics())
137                     || parentStyle.lineHeight() != childStyle.lineHeight()
138                     || (parentStyle.verticalAlign() != BASELINE && !isRootInlineBox()) || childStyle.verticalAlign() != BASELINE)
139                     shouldClearDescendantsHaveSameLineHeightAndBaseline = true;
140             }
141             if (childStyle.hasTextCombine() || childStyle.textEmphasisMark() != TextEmphasisMarkNone)
142                 shouldClearDescendantsHaveSameLineHeightAndBaseline = true;
143         } else {
144             if (child->renderer().isLineBreak()) {
145                 // FIXME: This is dumb. We only turn off because current layout test results expect the <br> to be 0-height on the baseline.
146                 // Other than making a zillion tests have to regenerate results, there's no reason to ditch the optimization here.
147                 shouldClearDescendantsHaveSameLineHeightAndBaseline = child->renderer().isBR();
148             } else {
149                 ASSERT(isInlineFlowBox());
150                 InlineFlowBox* childFlowBox = toInlineFlowBox(child);
151                 // Check the child's bit, and then also check for differences in font, line-height, vertical-align
152                 if (!childFlowBox->descendantsHaveSameLineHeightAndBaseline()
153                     || !parentStyle.font().fontMetrics().hasIdenticalAscentDescentAndLineGap(childStyle.font().fontMetrics())
154                     || parentStyle.lineHeight() != childStyle.lineHeight()
155                     || (parentStyle.verticalAlign() != BASELINE && !isRootInlineBox()) || childStyle.verticalAlign() != BASELINE
156                     || childStyle.hasBorder() || childStyle.hasPadding() || childStyle.hasTextCombine())
157                     shouldClearDescendantsHaveSameLineHeightAndBaseline = true;
158             }
159         }
160
161         if (shouldClearDescendantsHaveSameLineHeightAndBaseline)
162             clearDescendantsHaveSameLineHeightAndBaseline();
163     }
164
165     if (!child->renderer().isOutOfFlowPositioned()) {
166         const RenderStyle& childStyle = child->lineStyle();
167         if (child->behavesLikeText()) {
168             const RenderStyle* childStyle = &child->lineStyle();
169             if (childStyle->letterSpacing() < 0 || childStyle->textShadow() || childStyle->textEmphasisMark() != TextEmphasisMarkNone || childStyle->textStrokeWidth())
170                 child->clearKnownToHaveNoOverflow();
171         } else if (child->renderer().isReplaced()) {
172             const RenderBox& box = toRenderBox(child->renderer());
173             if (box.hasRenderOverflow() || box.hasSelfPaintingLayer())
174                 child->clearKnownToHaveNoOverflow();
175         } else if (!child->renderer().isLineBreak() && (childStyle.boxShadow() || child->boxModelObject()->hasSelfPaintingLayer()
176             || (child->renderer().isListMarker() && !toRenderListMarker(child->renderer()).isInside())
177             || childStyle.hasBorderImageOutsets()))
178             child->clearKnownToHaveNoOverflow();
179         
180         if (knownToHaveNoOverflow() && child->isInlineFlowBox() && !toInlineFlowBox(child)->knownToHaveNoOverflow())
181             clearKnownToHaveNoOverflow();
182     }
183
184     checkConsistency();
185 }
186
187 void InlineFlowBox::removeChild(InlineBox* child)
188 {
189     checkConsistency();
190
191     if (!isDirty())
192         dirtyLineBoxes();
193
194     root().childRemoved(child);
195
196     if (child == m_firstChild)
197         m_firstChild = child->nextOnLine();
198     if (child == m_lastChild)
199         m_lastChild = child->prevOnLine();
200     if (child->nextOnLine())
201         child->nextOnLine()->setPrevOnLine(child->prevOnLine());
202     if (child->prevOnLine())
203         child->prevOnLine()->setNextOnLine(child->nextOnLine());
204     
205     child->setParent(0);
206
207     checkConsistency();
208 }
209
210 void InlineFlowBox::deleteLine()
211 {
212     InlineBox* child = firstChild();
213     InlineBox* next = 0;
214     while (child) {
215         ASSERT(this == child->parent());
216         next = child->nextOnLine();
217 #ifndef NDEBUG
218         child->setParent(0);
219 #endif
220         child->deleteLine();
221         child = next;
222     }
223 #ifndef NDEBUG
224     m_firstChild = 0;
225     m_lastChild = 0;
226 #endif
227
228     removeLineBoxFromRenderObject();
229     delete this;
230 }
231
232 void InlineFlowBox::removeLineBoxFromRenderObject()
233 {
234     toRenderInline(renderer()).lineBoxes().removeLineBox(this);
235 }
236
237 void InlineFlowBox::extractLine()
238 {
239     if (!extracted())
240         extractLineBoxFromRenderObject();
241     for (InlineBox* child = firstChild(); child; child = child->nextOnLine())
242         child->extractLine();
243 }
244
245 void InlineFlowBox::extractLineBoxFromRenderObject()
246 {
247     toRenderInline(renderer()).lineBoxes().extractLineBox(this);
248 }
249
250 void InlineFlowBox::attachLine()
251 {
252     if (extracted())
253         attachLineBoxToRenderObject();
254     for (InlineBox* child = firstChild(); child; child = child->nextOnLine())
255         child->attachLine();
256 }
257
258 void InlineFlowBox::attachLineBoxToRenderObject()
259 {
260     toRenderInline(renderer()).lineBoxes().attachLineBox(this);
261 }
262
263 void InlineFlowBox::adjustPosition(float dx, float dy)
264 {
265     InlineBox::adjustPosition(dx, dy);
266     for (InlineBox* child = firstChild(); child; child = child->nextOnLine())
267         child->adjustPosition(dx, dy);
268     if (m_overflow)
269         m_overflow->move(dx, dy); // FIXME: Rounding error here since overflow was pixel snapped, but nobody other than list markers passes non-integral values here.
270 }
271
272 static inline bool isLastChildForRenderer(const RenderElement& ancestor, const RenderObject* child)
273 {
274     if (!child)
275         return false;
276     
277     if (child == &ancestor)
278         return true;
279
280     const RenderObject* curr = child;
281     const RenderElement* parent = curr->parent();
282     while (parent && (!parent->isRenderBlock() || parent->isInline())) {
283         if (parent->lastChild() != curr)
284             return false;
285         if (parent == &ancestor)
286             return true;
287             
288         curr = parent;
289         parent = curr->parent();
290     }
291
292     return true;
293 }
294
295 static bool isAncestorAndWithinBlock(const RenderInline& ancestor, const RenderObject* child)
296 {
297     const RenderObject* object = child;
298     while (object && (!object->isRenderBlock() || object->isInline())) {
299         if (object == &ancestor)
300             return true;
301         object = object->parent();
302     }
303     return false;
304 }
305
306 void InlineFlowBox::determineSpacingForFlowBoxes(bool lastLine, bool isLogicallyLastRunWrapped, RenderObject* logicallyLastRunRenderer)
307 {
308     // All boxes start off open.  They will not apply any margins/border/padding on
309     // any side.
310     bool includeLeftEdge = false;
311     bool includeRightEdge = false;
312
313     // The root inline box never has borders/margins/padding.
314     if (parent()) {
315         const auto& inlineFlow = toRenderInline(renderer());
316
317         bool ltr = renderer().style().isLeftToRightDirection();
318
319         // Check to see if all initial lines are unconstructed.  If so, then
320         // we know the inline began on this line (unless we are a continuation).
321         const auto& lineBoxList = inlineFlow.lineBoxes();
322         if (!lineBoxList.firstLineBox()->isConstructed() && !renderer().isInlineElementContinuation()) {
323 #if ENABLE(CSS_BOX_DECORATION_BREAK)
324             if (renderer().style().boxDecorationBreak() == DCLONE)
325                 includeLeftEdge = includeRightEdge = true;
326             else
327 #endif
328             if (ltr && lineBoxList.firstLineBox() == this)
329                 includeLeftEdge = true;
330             else if (!ltr && lineBoxList.lastLineBox() == this)
331                 includeRightEdge = true;
332         }
333
334         if (!lineBoxList.lastLineBox()->isConstructed()) {
335             bool isLastObjectOnLine = !isAncestorAndWithinBlock(inlineFlow, logicallyLastRunRenderer) || (isLastChildForRenderer(renderer(), logicallyLastRunRenderer) && !isLogicallyLastRunWrapped);
336
337             // We include the border under these conditions:
338             // (1) The next line was not created, or it is constructed. We check the previous line for rtl.
339             // (2) The logicallyLastRun is not a descendant of this renderer.
340             // (3) The logicallyLastRun is a descendant of this renderer, but it is the last child of this renderer and it does not wrap to the next line.
341 #if ENABLE(CSS_BOX_DECORATION_BREAK)
342             // (4) The decoration break is set to clone therefore there will be borders on every sides.
343             if (renderer().style().boxDecorationBreak() == DCLONE)
344                 includeLeftEdge = includeRightEdge = true;
345             else
346 #endif
347             if (ltr) {
348                 if (!nextLineBox()
349                     && ((lastLine || isLastObjectOnLine) && !inlineFlow.continuation()))
350                     includeRightEdge = true;
351             } else {
352                 if ((!prevLineBox() || prevLineBox()->isConstructed())
353                     && ((lastLine || isLastObjectOnLine) && !inlineFlow.continuation()))
354                     includeLeftEdge = true;
355             }
356         }
357     }
358
359     setEdges(includeLeftEdge, includeRightEdge);
360
361     // Recur into our children.
362     for (InlineBox* currChild = firstChild(); currChild; currChild = currChild->nextOnLine()) {
363         if (currChild->isInlineFlowBox()) {
364             InlineFlowBox* currFlow = toInlineFlowBox(currChild);
365             currFlow->determineSpacingForFlowBoxes(lastLine, isLogicallyLastRunWrapped, logicallyLastRunRenderer);
366         }
367     }
368 }
369
370 float InlineFlowBox::placeBoxesInInlineDirection(float logicalLeft, bool& needsWordSpacing, GlyphOverflowAndFallbackFontsMap& textBoxDataMap)
371 {
372     // Set our x position.
373     beginPlacingBoxRangesInInlineDirection(logicalLeft);
374
375     float startLogicalLeft = logicalLeft;
376     logicalLeft += borderLogicalLeft() + paddingLogicalLeft();
377
378     float minLogicalLeft = startLogicalLeft;
379     float maxLogicalRight = logicalLeft;
380
381     placeBoxRangeInInlineDirection(firstChild(), 0, logicalLeft, minLogicalLeft, maxLogicalRight, needsWordSpacing, textBoxDataMap);
382
383     logicalLeft += borderLogicalRight() + paddingLogicalRight();
384     endPlacingBoxRangesInInlineDirection(startLogicalLeft, logicalLeft, minLogicalLeft, maxLogicalRight);
385     return logicalLeft;
386 }
387
388 float InlineFlowBox::placeBoxRangeInInlineDirection(InlineBox* firstChild, InlineBox* lastChild, float& logicalLeft, float& minLogicalLeft, float& maxLogicalRight, bool& needsWordSpacing, GlyphOverflowAndFallbackFontsMap& textBoxDataMap)
389 {
390     for (InlineBox* curr = firstChild; curr && curr != lastChild; curr = curr->nextOnLine()) {
391         if (curr->renderer().isText()) {
392             InlineTextBox* text = toInlineTextBox(curr);
393             RenderText& rt = text->renderer();
394             if (rt.textLength()) {
395                 if (needsWordSpacing && isSpaceOrNewline(rt.characterAt(text->start())))
396                     logicalLeft += text->lineStyle().font().wordSpacing();
397                 needsWordSpacing = !isSpaceOrNewline(rt.characterAt(text->end()));
398             }
399             text->setLogicalLeft(logicalLeft);
400             if (knownToHaveNoOverflow())
401                 minLogicalLeft = std::min(logicalLeft, minLogicalLeft);
402             logicalLeft += text->logicalWidth();
403             if (knownToHaveNoOverflow())
404                 maxLogicalRight = std::max(logicalLeft, maxLogicalRight);
405         } else {
406             if (curr->renderer().isOutOfFlowPositioned()) {
407                 if (curr->renderer().parent()->style().isLeftToRightDirection())
408                     curr->setLogicalLeft(logicalLeft);
409                 else
410                     // Our offset that we cache needs to be from the edge of the right border box and
411                     // not the left border box.  We have to subtract |x| from the width of the block
412                     // (which can be obtained from the root line box).
413                     curr->setLogicalLeft(root().blockFlow().logicalWidth() - logicalLeft);
414                 continue; // The positioned object has no effect on the width.
415             }
416             if (curr->renderer().isRenderInline()) {
417                 InlineFlowBox* flow = toInlineFlowBox(curr);
418                 logicalLeft += flow->marginLogicalLeft();
419                 if (knownToHaveNoOverflow())
420                     minLogicalLeft = std::min(logicalLeft, minLogicalLeft);
421                 logicalLeft = flow->placeBoxesInInlineDirection(logicalLeft, needsWordSpacing, textBoxDataMap);
422                 if (knownToHaveNoOverflow())
423                     maxLogicalRight = std::max(logicalLeft, maxLogicalRight);
424                 logicalLeft += flow->marginLogicalRight();
425             } else if (!curr->renderer().isListMarker() || toRenderListMarker(curr->renderer()).isInside()) {
426                 // The box can have a different writing-mode than the overall line, so this is a bit complicated.
427                 // Just get all the physical margin and overflow values by hand based off |isVertical|.
428                 LayoutUnit logicalLeftMargin = isHorizontal() ? curr->boxModelObject()->marginLeft() : curr->boxModelObject()->marginTop();
429                 LayoutUnit logicalRightMargin = isHorizontal() ? curr->boxModelObject()->marginRight() : curr->boxModelObject()->marginBottom();
430                 
431                 logicalLeft += logicalLeftMargin;
432                 curr->setLogicalLeft(logicalLeft);
433                 if (knownToHaveNoOverflow())
434                     minLogicalLeft = std::min(logicalLeft, minLogicalLeft);
435                 logicalLeft += curr->logicalWidth();
436                 if (knownToHaveNoOverflow())
437                     maxLogicalRight = std::max(logicalLeft, maxLogicalRight);
438                 logicalLeft += logicalRightMargin;
439                 // If we encounter any space after this inline block then ensure it is treated as the space between two words.
440                 needsWordSpacing = true;
441             }
442         }
443     }
444     return logicalLeft;
445 }
446
447 bool InlineFlowBox::requiresIdeographicBaseline(const GlyphOverflowAndFallbackFontsMap& textBoxDataMap) const
448 {
449     if (isHorizontal())
450         return false;
451
452     const RenderStyle& lineStyle = this->lineStyle();
453     if (lineStyle.fontDescription().nonCJKGlyphOrientation() == NonCJKGlyphOrientationUpright
454         || lineStyle.font().primaryFont()->hasVerticalGlyphs())
455         return true;
456
457     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
458         if (curr->renderer().isOutOfFlowPositioned())
459             continue; // Positioned placeholders don't affect calculations.
460         
461         if (curr->isInlineFlowBox()) {
462             if (toInlineFlowBox(curr)->requiresIdeographicBaseline(textBoxDataMap))
463                 return true;
464         } else {
465             if (curr->lineStyle().font().primaryFont()->hasVerticalGlyphs())
466                 return true;
467             
468             const Vector<const SimpleFontData*>* usedFonts = 0;
469             if (curr->isInlineTextBox()) {
470                 GlyphOverflowAndFallbackFontsMap::const_iterator it = textBoxDataMap.find(toInlineTextBox(curr));
471                 usedFonts = it == textBoxDataMap.end() ? 0 : &it->value.first;
472             }
473
474             if (usedFonts) {
475                 for (size_t i = 0; i < usedFonts->size(); ++i) {
476                     if (usedFonts->at(i)->hasVerticalGlyphs())
477                         return true;
478                 }
479             }
480         }
481     }
482     
483     return false;
484 }
485
486 static bool verticalAlignApplies(const RenderObject& renderer)
487 {
488     // http://www.w3.org/TR/CSS2/visudet.html#propdef-vertical-align - vertical-align
489     // only applies to inline level and table-cell elements
490     return !renderer.isText() || renderer.parent()->isInline() || renderer.parent()->isTableCell();
491 }
492
493 void InlineFlowBox::adjustMaxAscentAndDescent(int& maxAscent, int& maxDescent, int maxPositionTop, int maxPositionBottom)
494 {
495     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
496         // The computed lineheight needs to be extended for the
497         // positioned elements
498         if (curr->renderer().isOutOfFlowPositioned())
499             continue; // Positioned placeholders don't affect calculations.
500
501         if ((curr->verticalAlign() == TOP || curr->verticalAlign() == BOTTOM) && verticalAlignApplies(curr->renderer())) {
502             int lineHeight = curr->lineHeight();
503             if (curr->verticalAlign() == TOP) {
504                 if (maxAscent + maxDescent < lineHeight)
505                     maxDescent = lineHeight - maxAscent;
506             }
507             else {
508                 if (maxAscent + maxDescent < lineHeight)
509                     maxAscent = lineHeight - maxDescent;
510             }
511
512             if (maxAscent + maxDescent >= std::max(maxPositionTop, maxPositionBottom))
513                 break;
514         }
515
516         if (curr->isInlineFlowBox())
517             toInlineFlowBox(curr)->adjustMaxAscentAndDescent(maxAscent, maxDescent, maxPositionTop, maxPositionBottom);
518     }
519 }
520
521 void InlineFlowBox::computeLogicalBoxHeights(RootInlineBox* rootBox, LayoutUnit& maxPositionTop, LayoutUnit& maxPositionBottom,
522                                              int& maxAscent, int& maxDescent, bool& setMaxAscent, bool& setMaxDescent,
523                                              bool strictMode, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
524                                              FontBaseline baselineType, VerticalPositionCache& verticalPositionCache)
525 {
526     // The primary purpose of this function is to compute the maximal ascent and descent values for
527     // a line. These values are computed based off the block's line-box-contain property, which indicates
528     // what parts of descendant boxes have to fit within the line.
529     //
530     // The maxAscent value represents the distance of the highest point of any box (typically including line-height) from
531     // the root box's baseline. The maxDescent value represents the distance of the lowest point of any box
532     // (also typically including line-height) from the root box baseline. These values can be negative.
533     //
534     // A secondary purpose of this function is to store the offset of every box's baseline from the root box's
535     // baseline. This information is cached in the logicalTop() of every box. We're effectively just using
536     // the logicalTop() as scratch space.
537     //
538     // Because a box can be positioned such that it ends up fully above or fully below the
539     // root line box, we only consider it to affect the maxAscent and maxDescent values if some
540     // part of the box (EXCLUDING leading) is above (for ascent) or below (for descent) the root box's baseline.
541     bool affectsAscent = false;
542     bool affectsDescent = false;
543     bool checkChildren = !descendantsHaveSameLineHeightAndBaseline();
544     
545     if (isRootInlineBox()) {
546         // Examine our root box.
547         int ascent = 0;
548         int descent = 0;
549         rootBox->ascentAndDescentForBox(rootBox, textBoxDataMap, ascent, descent, affectsAscent, affectsDescent);
550         if (strictMode || hasTextChildren() || (!checkChildren && hasTextDescendants())) {
551             if (maxAscent < ascent || !setMaxAscent) {
552                 maxAscent = ascent;
553                 setMaxAscent = true;
554             }
555             if (maxDescent < descent || !setMaxDescent) {
556                 maxDescent = descent;
557                 setMaxDescent = true;
558             }
559         }
560     }
561
562     if (!checkChildren)
563         return;
564
565     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
566         if (curr->renderer().isOutOfFlowPositioned())
567             continue; // Positioned placeholders don't affect calculations.
568         
569         InlineFlowBox* inlineFlowBox = curr->isInlineFlowBox() ? toInlineFlowBox(curr) : 0;
570         
571         bool affectsAscent = false;
572         bool affectsDescent = false;
573         
574         // The verticalPositionForBox function returns the distance between the child box's baseline
575         // and the root box's baseline.  The value is negative if the child box's baseline is above the
576         // root box's baseline, and it is positive if the child box's baseline is below the root box's baseline.
577         curr->setLogicalTop(rootBox->verticalPositionForBox(curr, verticalPositionCache));
578         
579         int ascent = 0;
580         int descent = 0;
581         rootBox->ascentAndDescentForBox(curr, textBoxDataMap, ascent, descent, affectsAscent, affectsDescent);
582
583         LayoutUnit boxHeight = ascent + descent;
584         if (curr->verticalAlign() == TOP && verticalAlignApplies(curr->renderer())) {
585             if (maxPositionTop < boxHeight)
586                 maxPositionTop = boxHeight;
587         } else if (curr->verticalAlign() == BOTTOM && verticalAlignApplies(curr->renderer())) {
588             if (maxPositionBottom < boxHeight)
589                 maxPositionBottom = boxHeight;
590         } else if (!inlineFlowBox || strictMode || inlineFlowBox->hasTextChildren() || (inlineFlowBox->descendantsHaveSameLineHeightAndBaseline() && inlineFlowBox->hasTextDescendants())
591                    || inlineFlowBox->renderer().hasInlineDirectionBordersOrPadding()) {
592             // Note that these values can be negative.  Even though we only affect the maxAscent and maxDescent values
593             // if our box (excluding line-height) was above (for ascent) or below (for descent) the root baseline, once you factor in line-height
594             // the final box can end up being fully above or fully below the root box's baseline!  This is ok, but what it
595             // means is that ascent and descent (including leading), can end up being negative.  The setMaxAscent and
596             // setMaxDescent booleans are used to ensure that we're willing to initially set maxAscent/Descent to negative
597             // values.
598             ascent -= curr->logicalTop();
599             descent += curr->logicalTop();
600             if (affectsAscent && (maxAscent < ascent || !setMaxAscent)) {
601                 maxAscent = ascent;
602                 setMaxAscent = true;
603             }
604
605             if (affectsDescent && (maxDescent < descent || !setMaxDescent)) {
606                 maxDescent = descent;
607                 setMaxDescent = true;
608             }
609         }
610
611         if (inlineFlowBox)
612             inlineFlowBox->computeLogicalBoxHeights(rootBox, maxPositionTop, maxPositionBottom, maxAscent, maxDescent,
613                                                     setMaxAscent, setMaxDescent, strictMode, textBoxDataMap,
614                                                     baselineType, verticalPositionCache);
615     }
616 }
617
618 void InlineFlowBox::placeBoxesInBlockDirection(LayoutUnit top, LayoutUnit maxHeight, int maxAscent, bool strictMode, LayoutUnit& lineTop, LayoutUnit& lineBottom, bool& setLineTop,
619                                                LayoutUnit& lineTopIncludingMargins, LayoutUnit& lineBottomIncludingMargins, bool& hasAnnotationsBefore, bool& hasAnnotationsAfter, FontBaseline baselineType)
620 {
621     bool isRootBox = isRootInlineBox();
622     if (isRootBox) {
623         const FontMetrics& fontMetrics = lineStyle().fontMetrics();
624         // RootInlineBoxes are always placed on at pixel boundaries in their logical y direction. Not doing
625         // so results in incorrect rendering of text decorations, most notably underlines.
626         setLogicalTop(roundToInt(top + maxAscent - fontMetrics.ascent(baselineType)));
627     }
628
629     LayoutUnit adjustmentForChildrenWithSameLineHeightAndBaseline = 0;
630     if (descendantsHaveSameLineHeightAndBaseline()) {
631         adjustmentForChildrenWithSameLineHeightAndBaseline = logicalTop();
632         if (parent())
633             adjustmentForChildrenWithSameLineHeightAndBaseline += renderer().borderAndPaddingBefore();
634     }
635
636     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
637         if (curr->renderer().isOutOfFlowPositioned())
638             continue; // Positioned placeholders don't affect calculations.
639
640         if (descendantsHaveSameLineHeightAndBaseline()) {
641             curr->adjustBlockDirectionPosition(adjustmentForChildrenWithSameLineHeightAndBaseline);
642             continue;
643         }
644
645         InlineFlowBox* inlineFlowBox = curr->isInlineFlowBox() ? toInlineFlowBox(curr) : 0;
646         bool childAffectsTopBottomPos = true;
647
648         if (curr->verticalAlign() == TOP && verticalAlignApplies(curr->renderer()))
649             curr->setLogicalTop(top);
650         else if (curr->verticalAlign() == BOTTOM && verticalAlignApplies(curr->renderer()))
651             curr->setLogicalTop(top + maxHeight - curr->lineHeight());
652         else {
653             if (!strictMode && inlineFlowBox && !inlineFlowBox->hasTextChildren() && !inlineFlowBox->renderer().hasInlineDirectionBordersOrPadding()
654                 && !(inlineFlowBox->descendantsHaveSameLineHeightAndBaseline() && inlineFlowBox->hasTextDescendants()))
655                 childAffectsTopBottomPos = false;
656             LayoutUnit posAdjust = maxAscent - curr->baselinePosition(baselineType);
657             curr->setLogicalTop(curr->logicalTop() + top + posAdjust);
658         }
659         
660         LayoutUnit newLogicalTop = curr->logicalTop();
661         LayoutUnit newLogicalTopIncludingMargins = newLogicalTop;
662         LayoutUnit boxHeight = curr->logicalHeight();
663         LayoutUnit boxHeightIncludingMargins = boxHeight;
664
665         const RenderStyle& childLineStyle = curr->lineStyle();
666         if (curr->behavesLikeText() || curr->isInlineFlowBox()) {
667             const FontMetrics& fontMetrics = childLineStyle.fontMetrics();
668             newLogicalTop += curr->baselinePosition(baselineType) - fontMetrics.ascent(baselineType);
669             if (curr->isInlineFlowBox()) {
670                 RenderBoxModelObject& boxObject = toRenderBoxModelObject(curr->renderer());
671                 newLogicalTop -= childLineStyle.isHorizontalWritingMode()
672                     ? boxObject.borderTop() + boxObject.paddingTop()
673                     : boxObject.borderRight() + boxObject.paddingRight();
674             }
675             newLogicalTopIncludingMargins = newLogicalTop;
676         } else if (!curr->renderer().isBR()) {
677             const RenderBox& box = toRenderBox(curr->renderer());
678             newLogicalTopIncludingMargins = newLogicalTop;
679             LayoutUnit overSideMargin = curr->isHorizontal() ? box.marginTop() : box.marginRight();
680             LayoutUnit underSideMargin = curr->isHorizontal() ? box.marginBottom() : box.marginLeft();
681             newLogicalTop += overSideMargin;
682             boxHeightIncludingMargins += overSideMargin + underSideMargin;
683         }
684
685         curr->setLogicalTop(newLogicalTop);
686
687         if (childAffectsTopBottomPos) {
688             if (curr->renderer().isRubyRun()) {
689                 // Treat the leading on the first and last lines of ruby runs as not being part of the overall lineTop/lineBottom.
690                 // Really this is a workaround hack for the fact that ruby should have been done as line layout and not done using
691                 // inline-block.
692                 if (renderer().style().isFlippedLinesWritingMode() == (curr->renderer().style().rubyPosition() == RubyPositionAfter))
693                     hasAnnotationsBefore = true;
694                 else
695                     hasAnnotationsAfter = true;
696
697                 RenderRubyRun& rubyRun = toRenderRubyRun(curr->renderer());
698                 if (RenderRubyBase* rubyBase = rubyRun.rubyBase()) {
699                     LayoutUnit bottomRubyBaseLeading = (curr->logicalHeight() - rubyBase->logicalBottom()) + rubyBase->logicalHeight() - (rubyBase->lastRootBox() ? rubyBase->lastRootBox()->lineBottom() : LayoutUnit());
700                     LayoutUnit topRubyBaseLeading = rubyBase->logicalTop() + (rubyBase->firstRootBox() ? rubyBase->firstRootBox()->lineTop() : LayoutUnit());
701                     newLogicalTop += !renderer().style().isFlippedLinesWritingMode() ? topRubyBaseLeading : bottomRubyBaseLeading;
702                     boxHeight -= (topRubyBaseLeading + bottomRubyBaseLeading);
703                 }
704             }
705             if (curr->isInlineTextBox()) {
706                 bool emphasisMarkIsOver;
707                 if (toInlineTextBox(curr)->emphasisMarkExistsAndIsAbove(childLineStyle, emphasisMarkIsOver)) {
708                     if (emphasisMarkIsOver != childLineStyle.isFlippedLinesWritingMode())
709                         hasAnnotationsBefore = true;
710                     else
711                         hasAnnotationsAfter = true;
712                 }
713             }
714
715             if (!setLineTop) {
716                 setLineTop = true;
717                 lineTop = newLogicalTop;
718                 lineTopIncludingMargins = std::min(lineTop, newLogicalTopIncludingMargins);
719             } else {
720                 lineTop = std::min(lineTop, newLogicalTop);
721                 lineTopIncludingMargins = std::min(lineTop, std::min(lineTopIncludingMargins, newLogicalTopIncludingMargins));
722             }
723             lineBottom = std::max(lineBottom, newLogicalTop + boxHeight);
724             lineBottomIncludingMargins = std::max(lineBottom, std::max(lineBottomIncludingMargins, newLogicalTopIncludingMargins + boxHeightIncludingMargins));
725         }
726
727         // Adjust boxes to use their real box y/height and not the logical height (as dictated by
728         // line-height).
729         if (inlineFlowBox)
730             inlineFlowBox->placeBoxesInBlockDirection(top, maxHeight, maxAscent, strictMode, lineTop, lineBottom, setLineTop,
731                                                       lineTopIncludingMargins, lineBottomIncludingMargins, hasAnnotationsBefore, hasAnnotationsAfter, baselineType);
732     }
733
734     if (isRootBox) {
735         if (strictMode || hasTextChildren() || (descendantsHaveSameLineHeightAndBaseline() && hasTextDescendants())) {
736             if (!setLineTop) {
737                 setLineTop = true;
738                 lineTop = pixelSnappedLogicalTop();
739                 lineTopIncludingMargins = lineTop;
740             } else {
741                 lineTop = std::min<LayoutUnit>(lineTop, pixelSnappedLogicalTop());
742                 lineTopIncludingMargins = std::min(lineTop, lineTopIncludingMargins);
743             }
744             lineBottom = std::max<LayoutUnit>(lineBottom, pixelSnappedLogicalBottom());
745             lineBottomIncludingMargins = std::max(lineBottom, lineBottomIncludingMargins);
746         }
747         
748         if (renderer().style().isFlippedLinesWritingMode())
749             flipLinesInBlockDirection(lineTopIncludingMargins, lineBottomIncludingMargins);
750     }
751 }
752
753 void InlineFlowBox::computeMaxLogicalTop(float& maxLogicalTop) const
754 {
755     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
756         if (curr->renderer().isOutOfFlowPositioned())
757             continue; // Positioned placeholders don't affect calculations.
758
759         if (descendantsHaveSameLineHeightAndBaseline())
760             continue;
761
762         maxLogicalTop = std::max<float>(maxLogicalTop, curr->y());
763         float localMaxLogicalTop = 0;
764         if (curr->isInlineFlowBox())
765             toInlineFlowBox(curr)->computeMaxLogicalTop(localMaxLogicalTop);
766         maxLogicalTop = std::max<float>(maxLogicalTop, localMaxLogicalTop);
767     }
768 }
769
770 void InlineFlowBox::flipLinesInBlockDirection(LayoutUnit lineTop, LayoutUnit lineBottom)
771 {
772     // Flip the box on the line such that the top is now relative to the lineBottom instead of the lineTop.
773     setLogicalTop(lineBottom - (logicalTop() - lineTop) - logicalHeight());
774     
775     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
776         if (curr->renderer().isOutOfFlowPositioned())
777             continue; // Positioned placeholders aren't affected here.
778         
779         if (curr->isInlineFlowBox())
780             toInlineFlowBox(curr)->flipLinesInBlockDirection(lineTop, lineBottom);
781         else
782             curr->setLogicalTop(lineBottom - (curr->logicalTop() - lineTop) - curr->logicalHeight());
783     }
784 }
785
786 inline void InlineFlowBox::addBoxShadowVisualOverflow(LayoutRect& logicalVisualOverflow)
787 {
788     // box-shadow on root line boxes is applying to the block and not to the lines.
789     if (!parent())
790         return;
791
792     const RenderStyle& lineStyle = this->lineStyle();
793     if (!lineStyle.boxShadow())
794         return;
795
796     LayoutUnit boxShadowLogicalTop;
797     LayoutUnit boxShadowLogicalBottom;
798     lineStyle.getBoxShadowBlockDirectionExtent(boxShadowLogicalTop, boxShadowLogicalBottom);
799     
800     // Similar to how glyph overflow works, if our lines are flipped, then it's actually the opposite shadow that applies, since
801     // the line is "upside down" in terms of block coordinates.
802     LayoutUnit shadowLogicalTop = lineStyle.isFlippedLinesWritingMode() ? -boxShadowLogicalBottom : boxShadowLogicalTop;
803     LayoutUnit shadowLogicalBottom = lineStyle.isFlippedLinesWritingMode() ? -boxShadowLogicalTop : boxShadowLogicalBottom;
804     
805     LayoutUnit logicalTopVisualOverflow = std::min(pixelSnappedLogicalTop() + shadowLogicalTop, logicalVisualOverflow.y());
806     LayoutUnit logicalBottomVisualOverflow = std::max(pixelSnappedLogicalBottom() + shadowLogicalBottom, logicalVisualOverflow.maxY());
807     
808     LayoutUnit boxShadowLogicalLeft;
809     LayoutUnit boxShadowLogicalRight;
810     lineStyle.getBoxShadowInlineDirectionExtent(boxShadowLogicalLeft, boxShadowLogicalRight);
811
812     LayoutUnit logicalLeftVisualOverflow = std::min(pixelSnappedLogicalLeft() + boxShadowLogicalLeft, logicalVisualOverflow.x());
813     LayoutUnit logicalRightVisualOverflow = std::max(pixelSnappedLogicalRight() + boxShadowLogicalRight, logicalVisualOverflow.maxX());
814     
815     logicalVisualOverflow = LayoutRect(logicalLeftVisualOverflow, logicalTopVisualOverflow,
816                                        logicalRightVisualOverflow - logicalLeftVisualOverflow, logicalBottomVisualOverflow - logicalTopVisualOverflow);
817 }
818
819 inline void InlineFlowBox::addBorderOutsetVisualOverflow(LayoutRect& logicalVisualOverflow)
820 {
821     // border-image-outset on root line boxes is applying to the block and not to the lines.
822     if (!parent())
823         return;
824     
825     const RenderStyle& lineStyle = this->lineStyle();
826     if (!lineStyle.hasBorderImageOutsets())
827         return;
828
829     LayoutBoxExtent borderOutsets = lineStyle.borderImageOutsets();
830
831     LayoutUnit borderOutsetLogicalTop = borderOutsets.logicalTop(lineStyle.writingMode());
832     LayoutUnit borderOutsetLogicalBottom = borderOutsets.logicalBottom(lineStyle.writingMode());
833     LayoutUnit borderOutsetLogicalLeft = borderOutsets.logicalLeft(lineStyle.writingMode());
834     LayoutUnit borderOutsetLogicalRight = borderOutsets.logicalRight(lineStyle.writingMode());
835
836     // Similar to how glyph overflow works, if our lines are flipped, then it's actually the opposite border that applies, since
837     // the line is "upside down" in terms of block coordinates. vertical-rl and horizontal-bt are the flipped line modes.
838     LayoutUnit outsetLogicalTop = lineStyle.isFlippedLinesWritingMode() ? borderOutsetLogicalBottom : borderOutsetLogicalTop;
839     LayoutUnit outsetLogicalBottom = lineStyle.isFlippedLinesWritingMode() ? borderOutsetLogicalTop : borderOutsetLogicalBottom;
840
841     LayoutUnit logicalTopVisualOverflow = std::min(pixelSnappedLogicalTop() - outsetLogicalTop, logicalVisualOverflow.y());
842     LayoutUnit logicalBottomVisualOverflow = std::max(pixelSnappedLogicalBottom() + outsetLogicalBottom, logicalVisualOverflow.maxY());
843
844     LayoutUnit outsetLogicalLeft = includeLogicalLeftEdge() ? borderOutsetLogicalLeft : LayoutUnit();
845     LayoutUnit outsetLogicalRight = includeLogicalRightEdge() ? borderOutsetLogicalRight : LayoutUnit();
846
847     LayoutUnit logicalLeftVisualOverflow = std::min(pixelSnappedLogicalLeft() - outsetLogicalLeft, logicalVisualOverflow.x());
848     LayoutUnit logicalRightVisualOverflow = std::max(pixelSnappedLogicalRight() + outsetLogicalRight, logicalVisualOverflow.maxX());
849     
850     logicalVisualOverflow = LayoutRect(logicalLeftVisualOverflow, logicalTopVisualOverflow,
851                                        logicalRightVisualOverflow - logicalLeftVisualOverflow, logicalBottomVisualOverflow - logicalTopVisualOverflow);
852 }
853
854 inline void InlineFlowBox::addTextBoxVisualOverflow(InlineTextBox* textBox, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, LayoutRect& logicalVisualOverflow)
855 {
856     if (textBox->knownToHaveNoOverflow())
857         return;
858
859     const RenderStyle& lineStyle = this->lineStyle();
860     
861     GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.find(textBox);
862     GlyphOverflow* glyphOverflow = it == textBoxDataMap.end() ? 0 : &it->value.second;
863     bool isFlippedLine = lineStyle.isFlippedLinesWritingMode();
864
865     int topGlyphEdge = glyphOverflow ? (isFlippedLine ? glyphOverflow->bottom : glyphOverflow->top) : 0;
866     int bottomGlyphEdge = glyphOverflow ? (isFlippedLine ? glyphOverflow->top : glyphOverflow->bottom) : 0;
867     int leftGlyphEdge = glyphOverflow ? glyphOverflow->left : 0;
868     int rightGlyphEdge = glyphOverflow ? glyphOverflow->right : 0;
869
870     int strokeOverflow = static_cast<int>(ceilf(lineStyle.textStrokeWidth() / 2.0f));
871     int topGlyphOverflow = -strokeOverflow - topGlyphEdge;
872     int bottomGlyphOverflow = strokeOverflow + bottomGlyphEdge;
873     int leftGlyphOverflow = -strokeOverflow - leftGlyphEdge;
874     int rightGlyphOverflow = strokeOverflow + rightGlyphEdge;
875
876     bool emphasisMarkIsAbove;
877     if (lineStyle.textEmphasisMark() != TextEmphasisMarkNone && textBox->emphasisMarkExistsAndIsAbove(lineStyle, emphasisMarkIsAbove)) {
878         int emphasisMarkHeight = lineStyle.font().emphasisMarkHeight(lineStyle.textEmphasisMarkString());
879         if (emphasisMarkIsAbove == !lineStyle.isFlippedLinesWritingMode())
880             topGlyphOverflow = std::min(topGlyphOverflow, -emphasisMarkHeight);
881         else
882             bottomGlyphOverflow = std::max(bottomGlyphOverflow, emphasisMarkHeight);
883     }
884
885     // If letter-spacing is negative, we should factor that into right layout overflow. (Even in RTL, letter-spacing is
886     // applied to the right, so this is not an issue with left overflow.
887     rightGlyphOverflow -= std::min(0, (int)lineStyle.font().letterSpacing());
888
889     LayoutUnit textShadowLogicalTop;
890     LayoutUnit textShadowLogicalBottom;
891     lineStyle.getTextShadowBlockDirectionExtent(textShadowLogicalTop, textShadowLogicalBottom);
892     
893     LayoutUnit childOverflowLogicalTop = std::min<LayoutUnit>(textShadowLogicalTop + topGlyphOverflow, topGlyphOverflow);
894     LayoutUnit childOverflowLogicalBottom = std::max<LayoutUnit>(textShadowLogicalBottom + bottomGlyphOverflow, bottomGlyphOverflow);
895    
896     LayoutUnit textShadowLogicalLeft;
897     LayoutUnit textShadowLogicalRight;
898     lineStyle.getTextShadowInlineDirectionExtent(textShadowLogicalLeft, textShadowLogicalRight);
899    
900     LayoutUnit childOverflowLogicalLeft = std::min<LayoutUnit>(textShadowLogicalLeft + leftGlyphOverflow, leftGlyphOverflow);
901     LayoutUnit childOverflowLogicalRight = std::max<LayoutUnit>(textShadowLogicalRight + rightGlyphOverflow, rightGlyphOverflow);
902
903     LayoutUnit logicalTopVisualOverflow = std::min(textBox->pixelSnappedLogicalTop() + childOverflowLogicalTop, logicalVisualOverflow.y());
904     LayoutUnit logicalBottomVisualOverflow = std::max(textBox->pixelSnappedLogicalBottom() + childOverflowLogicalBottom, logicalVisualOverflow.maxY());
905     LayoutUnit logicalLeftVisualOverflow = std::min(textBox->pixelSnappedLogicalLeft() + childOverflowLogicalLeft, logicalVisualOverflow.x());
906     LayoutUnit logicalRightVisualOverflow = std::max(textBox->pixelSnappedLogicalRight() + childOverflowLogicalRight, logicalVisualOverflow.maxX());
907     
908     logicalVisualOverflow = LayoutRect(logicalLeftVisualOverflow, logicalTopVisualOverflow,
909                                        logicalRightVisualOverflow - logicalLeftVisualOverflow, logicalBottomVisualOverflow - logicalTopVisualOverflow);
910                                     
911     textBox->setLogicalOverflowRect(logicalVisualOverflow);
912 }
913
914 inline void InlineFlowBox::addReplacedChildOverflow(const InlineBox* inlineBox, LayoutRect& logicalLayoutOverflow, LayoutRect& logicalVisualOverflow)
915 {
916     const RenderBox& box = toRenderBox(inlineBox->renderer());
917     
918     // Visual overflow only propagates if the box doesn't have a self-painting layer.  This rectangle does not include
919     // transforms or relative positioning (since those objects always have self-painting layers), but it does need to be adjusted
920     // for writing-mode differences.
921     if (!box.hasSelfPaintingLayer()) {
922         LayoutRect childLogicalVisualOverflow = box.logicalVisualOverflowRectForPropagation(&renderer().style());
923         childLogicalVisualOverflow.move(inlineBox->logicalLeft(), inlineBox->logicalTop());
924         logicalVisualOverflow.unite(childLogicalVisualOverflow);
925     }
926
927     // Layout overflow internal to the child box only propagates if the child box doesn't have overflow clip set.
928     // Otherwise the child border box propagates as layout overflow.  This rectangle must include transforms and relative positioning
929     // and be adjusted for writing-mode differences.
930     LayoutRect childLogicalLayoutOverflow = box.logicalLayoutOverflowRectForPropagation(&renderer().style());
931     childLogicalLayoutOverflow.move(inlineBox->logicalLeft(), inlineBox->logicalTop());
932     logicalLayoutOverflow.unite(childLogicalLayoutOverflow);
933 }
934
935 void InlineFlowBox::computeOverflow(LayoutUnit lineTop, LayoutUnit lineBottom, GlyphOverflowAndFallbackFontsMap& textBoxDataMap)
936 {
937     // If we know we have no overflow, we can just bail.
938     if (knownToHaveNoOverflow())
939         return;
940
941     // Visual overflow just includes overflow for stuff we need to repaint ourselves.  Self-painting layers are ignored.
942     // Layout overflow is used to determine scrolling extent, so it still includes child layers and also factors in
943     // transforms, relative positioning, etc.
944     LayoutRect logicalLayoutOverflow(enclosingLayoutRect(logicalFrameRectIncludingLineHeight(lineTop, lineBottom)));
945     LayoutRect logicalVisualOverflow(logicalLayoutOverflow);
946   
947     addBoxShadowVisualOverflow(logicalVisualOverflow);
948     addBorderOutsetVisualOverflow(logicalVisualOverflow);
949
950     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
951         if (curr->renderer().isOutOfFlowPositioned())
952             continue; // Positioned placeholders don't affect calculations.
953
954         if (curr->renderer().isLineBreak())
955             continue;
956         if (curr->renderer().isText()) {
957             InlineTextBox* text = toInlineTextBox(curr);
958             LayoutRect textBoxOverflow(enclosingLayoutRect(text->logicalFrameRect()));
959             addTextBoxVisualOverflow(text, textBoxDataMap, textBoxOverflow);
960             logicalVisualOverflow.unite(textBoxOverflow);
961         } else if (curr->renderer().isRenderInline()) {
962             InlineFlowBox* flow = toInlineFlowBox(curr);
963             flow->computeOverflow(lineTop, lineBottom, textBoxDataMap);
964             if (!flow->renderer().hasSelfPaintingLayer())
965                 logicalVisualOverflow.unite(flow->logicalVisualOverflowRect(lineTop, lineBottom));
966             LayoutRect childLayoutOverflow = flow->logicalLayoutOverflowRect(lineTop, lineBottom);
967             childLayoutOverflow.move(flow->renderer().relativePositionLogicalOffset());
968             logicalLayoutOverflow.unite(childLayoutOverflow);
969         } else
970             addReplacedChildOverflow(curr, logicalLayoutOverflow, logicalVisualOverflow);
971     }
972     
973     setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow, lineTop, lineBottom);
974 }
975
976 void InlineFlowBox::setLayoutOverflow(const LayoutRect& rect, LayoutUnit lineTop, LayoutUnit lineBottom)
977 {
978     LayoutRect frameBox = enclosingLayoutRect(frameRectIncludingLineHeight(lineTop, lineBottom));
979     if (frameBox.contains(rect) || rect.isEmpty())
980         return;
981
982     if (!m_overflow)
983         m_overflow = adoptRef(new RenderOverflow(frameBox, frameBox));
984     
985     m_overflow->setLayoutOverflow(rect);
986 }
987
988 void InlineFlowBox::setVisualOverflow(const LayoutRect& rect, LayoutUnit lineTop, LayoutUnit lineBottom)
989 {
990     LayoutRect frameBox = enclosingLayoutRect(frameRectIncludingLineHeight(lineTop, lineBottom));
991     if (frameBox.contains(rect) || rect.isEmpty())
992         return;
993         
994     if (!m_overflow)
995         m_overflow = adoptRef(new RenderOverflow(frameBox, frameBox));
996     
997     m_overflow->setVisualOverflow(rect);
998 }
999
1000 void InlineFlowBox::setOverflowFromLogicalRects(const LayoutRect& logicalLayoutOverflow, const LayoutRect& logicalVisualOverflow, LayoutUnit lineTop, LayoutUnit lineBottom)
1001 {
1002     LayoutRect layoutOverflow(isHorizontal() ? logicalLayoutOverflow : logicalLayoutOverflow.transposedRect());
1003     setLayoutOverflow(layoutOverflow, lineTop, lineBottom);
1004     
1005     LayoutRect visualOverflow(isHorizontal() ? logicalVisualOverflow : logicalVisualOverflow.transposedRect());
1006     setVisualOverflow(visualOverflow, lineTop, lineBottom);
1007 }
1008
1009 bool InlineFlowBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom)
1010 {
1011     LayoutRect overflowRect(visualOverflowRect(lineTop, lineBottom));
1012     flipForWritingMode(overflowRect);
1013     overflowRect.moveBy(accumulatedOffset);
1014     if (!locationInContainer.intersects(overflowRect))
1015         return false;
1016
1017     // Check children first.
1018     // We need to account for culled inline parents of the hit-tested nodes, so that they may also get included in area-based hit-tests.
1019     RenderElement* culledParent = 0;
1020     for (InlineBox* curr = lastChild(); curr; curr = curr->prevOnLine()) {
1021         if (curr->renderer().isText() || !curr->boxModelObject()->hasSelfPaintingLayer()) {
1022             RenderElement* newParent = 0;
1023             // Culled parents are only relevant for area-based hit-tests, so ignore it in point-based ones.
1024             if (locationInContainer.isRectBasedTest()) {
1025                 newParent = curr->renderer().parent();
1026                 if (newParent == &renderer())
1027                     newParent = 0;
1028             }
1029             // Check the culled parent after all its children have been checked, to do this we wait until
1030             // we are about to test an element with a different parent.
1031             if (newParent != culledParent) {
1032                 if (!newParent || !newParent->isDescendantOf(culledParent)) {
1033                     while (culledParent && culledParent != &renderer() && culledParent != newParent) {
1034                         if (culledParent->isRenderInline() && toRenderInline(culledParent)->hitTestCulledInline(request, result, locationInContainer, accumulatedOffset))
1035                             return true;
1036                         culledParent = culledParent->parent();
1037                     }
1038                 }
1039                 culledParent = newParent;
1040             }
1041             if (curr->nodeAtPoint(request, result, locationInContainer, accumulatedOffset, lineTop, lineBottom)) {
1042                 renderer().updateHitTestResult(result, locationInContainer.point() - toLayoutSize(accumulatedOffset));
1043                 return true;
1044             }
1045         }
1046     }
1047     // Check any culled ancestor of the final children tested.
1048     while (culledParent && culledParent != &renderer()) {
1049         if (culledParent->isRenderInline() && toRenderInline(culledParent)->hitTestCulledInline(request, result, locationInContainer, accumulatedOffset))
1050             return true;
1051         culledParent = culledParent->parent();
1052     }
1053
1054     // Now check ourselves. Pixel snap hit testing.
1055     if (!visibleToHitTesting())
1056         return false;
1057
1058     // Do not hittest content beyond the ellipsis box.
1059     if (isRootInlineBox() && hasEllipsisBox()) {
1060         const EllipsisBox* ellipsisBox = root().ellipsisBox();
1061         LayoutRect boundsRect(roundedFrameRect());
1062
1063         if (isHorizontal())
1064             renderer().style().isLeftToRightDirection() ? boundsRect.shiftXEdgeTo(ellipsisBox->right()) : boundsRect.setWidth(ellipsisBox->left() - left());
1065         else
1066             boundsRect.shiftYEdgeTo(ellipsisBox->right());
1067
1068         flipForWritingMode(boundsRect);
1069         boundsRect.moveBy(accumulatedOffset);
1070         // We are beyond the ellipsis box.
1071         if (locationInContainer.intersects(boundsRect))
1072             return false;
1073     }
1074
1075     LayoutRect frameRect = roundedFrameRect();
1076     LayoutUnit minX = frameRect.x();
1077     LayoutUnit minY = frameRect.y();
1078     LayoutUnit width = frameRect.width();
1079     LayoutUnit height = frameRect.height();
1080
1081     // Constrain our hit testing to the line top and bottom if necessary.
1082     bool noQuirksMode = renderer().document().inNoQuirksMode();
1083     if (!noQuirksMode && !hasTextChildren() && !(descendantsHaveSameLineHeightAndBaseline() && hasTextDescendants())) {
1084         RootInlineBox& rootBox = root();
1085         LayoutUnit& top = isHorizontal() ? minY : minX;
1086         LayoutUnit& logicalHeight = isHorizontal() ? height : width;
1087         LayoutUnit bottom = std::min(rootBox.lineBottom(), top + logicalHeight);
1088         top = std::max(rootBox.lineTop(), top);
1089         logicalHeight = bottom - top;
1090     }
1091
1092     // Move x/y to our coordinates.
1093     LayoutRect rect(minX, minY, width, height);
1094     flipForWritingMode(rect);
1095     rect.moveBy(accumulatedOffset);
1096
1097     if (locationInContainer.intersects(rect)) {
1098         renderer().updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - toLayoutSize(accumulatedOffset))); // Don't add in m_x or m_y here, we want coords in the containing block's space.
1099         if (!result.addNodeToRectBasedTestResult(renderer().element(), request, locationInContainer, rect))
1100             return true;
1101     }
1102
1103     return false;
1104 }
1105
1106 void InlineFlowBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit lineTop, LayoutUnit lineBottom)
1107 {
1108     LayoutRect overflowRect(visualOverflowRect(lineTop, lineBottom));
1109     overflowRect.inflate(renderer().maximalOutlineSize(paintInfo.phase));
1110     flipForWritingMode(overflowRect);
1111     overflowRect.moveBy(paintOffset);
1112     
1113     if (!paintInfo.rect.intersects(pixelSnappedIntRect(overflowRect)))
1114         return;
1115
1116     if (paintInfo.phase != PaintPhaseChildOutlines) {
1117         if (paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) {
1118             // Add ourselves to the paint info struct's list of inlines that need to paint their
1119             // outlines.
1120             if (renderer().style().visibility() == VISIBLE && renderer().hasOutline() && !isRootInlineBox()) {
1121                 RenderInline& inlineFlow = toRenderInline(renderer());
1122
1123                 RenderBlock* cb = 0;
1124                 bool containingBlockPaintsContinuationOutline = inlineFlow.continuation() || inlineFlow.isInlineElementContinuation();
1125                 if (containingBlockPaintsContinuationOutline) {           
1126                     // FIXME: See https://bugs.webkit.org/show_bug.cgi?id=54690. We currently don't reconnect inline continuations
1127                     // after a child removal. As a result, those merged inlines do not get seperated and hence not get enclosed by
1128                     // anonymous blocks. In this case, it is better to bail out and paint it ourself.
1129                     RenderBlock* enclosingAnonymousBlock = renderer().containingBlock();
1130                     if (!enclosingAnonymousBlock->isAnonymousBlock())
1131                         containingBlockPaintsContinuationOutline = false;
1132                     else {
1133                         cb = enclosingAnonymousBlock->containingBlock();
1134                         for (auto box = &renderer(); box != cb; box = box->parent()->enclosingBoxModelObject()) {
1135                             if (box->hasSelfPaintingLayer()) {
1136                                 containingBlockPaintsContinuationOutline = false;
1137                                 break;
1138                             }
1139                         }
1140                     }
1141                 }
1142
1143                 if (containingBlockPaintsContinuationOutline) {
1144                     // Add ourselves to the containing block of the entire continuation so that it can
1145                     // paint us atomically.
1146                     cb->addContinuationWithOutline(toRenderInline(renderer().element()->renderer()));
1147                 } else if (!inlineFlow.isInlineElementContinuation())
1148                     paintInfo.outlineObjects->add(&inlineFlow);
1149             }
1150         } else if (paintInfo.phase == PaintPhaseMask) {
1151             paintMask(paintInfo, paintOffset);
1152             return;
1153         } else {
1154             // Paint our background, border and box-shadow.
1155             paintBoxDecorations(paintInfo, paintOffset);
1156         }
1157     }
1158
1159     if (paintInfo.phase == PaintPhaseMask)
1160         return;
1161
1162     PaintPhase paintPhase = paintInfo.phase == PaintPhaseChildOutlines ? PaintPhaseOutline : paintInfo.phase;
1163     PaintInfo childInfo(paintInfo);
1164     childInfo.phase = paintPhase;
1165     childInfo.updateSubtreePaintRootForChildren(&renderer());
1166     
1167     // Paint our children.
1168     if (paintPhase != PaintPhaseSelfOutline) {
1169         for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
1170             if (curr->renderer().isText() || !curr->boxModelObject()->hasSelfPaintingLayer())
1171                 curr->paint(childInfo, paintOffset, lineTop, lineBottom);
1172         }
1173     }
1174 }
1175
1176 void InlineFlowBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect, CompositeOperator op)
1177 {
1178     if (!fillLayer)
1179         return;
1180     paintFillLayers(paintInfo, c, fillLayer->next(), rect, op);
1181     paintFillLayer(paintInfo, c, fillLayer, rect, op);
1182 }
1183
1184 bool InlineFlowBox::boxShadowCanBeAppliedToBackground(const FillLayer& lastBackgroundLayer) const
1185 {
1186     // The checks here match how paintFillLayer() decides whether to clip (if it does, the shadow
1187     // would be clipped out, so it has to be drawn separately).
1188     StyleImage* image = lastBackgroundLayer.image();
1189     bool hasFillImage = image && image->canRender(&renderer(), renderer().style().effectiveZoom());
1190     return (!hasFillImage && !renderer().style().hasBorderRadius()) || (!prevLineBox() && !nextLineBox()) || !parent();
1191 }
1192
1193 void InlineFlowBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect, CompositeOperator op)
1194 {
1195     StyleImage* img = fillLayer->image();
1196     bool hasFillImage = img && img->canRender(&renderer(), renderer().style().effectiveZoom());
1197     if ((!hasFillImage && !renderer().style().hasBorderRadius()) || (!prevLineBox() && !nextLineBox()) || !parent())
1198         renderer().paintFillLayerExtended(paintInfo, c, fillLayer, rect, BackgroundBleedNone, this, rect.size(), op);
1199 #if ENABLE(CSS_BOX_DECORATION_BREAK)
1200     else if (renderer().style().boxDecorationBreak() == DCLONE) {
1201         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1202         paintInfo.context->clip(LayoutRect(rect.x(), rect.y(), width(), height()));
1203         renderer().paintFillLayerExtended(paintInfo, c, fillLayer, rect, BackgroundBleedNone, this, rect.size(), op);
1204     }
1205 #endif
1206     else {
1207         // We have a fill image that spans multiple lines.
1208         // We need to adjust tx and ty by the width of all previous lines.
1209         // Think of background painting on inlines as though you had one long line, a single continuous
1210         // strip.  Even though that strip has been broken up across multiple lines, you still paint it
1211         // as though you had one single line.  This means each line has to pick up the background where
1212         // the previous line left off.
1213         LayoutUnit logicalOffsetOnLine = 0;
1214         LayoutUnit totalLogicalWidth;
1215         if (renderer().style().direction() == LTR) {
1216             for (InlineFlowBox* curr = prevLineBox(); curr; curr = curr->prevLineBox())
1217                 logicalOffsetOnLine += curr->logicalWidth();
1218             totalLogicalWidth = logicalOffsetOnLine;
1219             for (InlineFlowBox* curr = this; curr; curr = curr->nextLineBox())
1220                 totalLogicalWidth += curr->logicalWidth();
1221         } else {
1222             for (InlineFlowBox* curr = nextLineBox(); curr; curr = curr->nextLineBox())
1223                 logicalOffsetOnLine += curr->logicalWidth();
1224             totalLogicalWidth = logicalOffsetOnLine;
1225             for (InlineFlowBox* curr = this; curr; curr = curr->prevLineBox())
1226                 totalLogicalWidth += curr->logicalWidth();
1227         }
1228         LayoutUnit stripX = rect.x() - (isHorizontal() ? logicalOffsetOnLine : LayoutUnit());
1229         LayoutUnit stripY = rect.y() - (isHorizontal() ? LayoutUnit() : logicalOffsetOnLine);
1230         LayoutUnit stripWidth = isHorizontal() ? totalLogicalWidth : LayoutUnit(width());
1231         LayoutUnit stripHeight = isHorizontal() ? LayoutUnit(height()) : totalLogicalWidth;
1232
1233         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1234         paintInfo.context->clip(LayoutRect(rect.x(), rect.y(), width(), height()));
1235         renderer().paintFillLayerExtended(paintInfo, c, fillLayer, LayoutRect(stripX, stripY, stripWidth, stripHeight), BackgroundBleedNone, this, rect.size(), op);
1236     }
1237 }
1238
1239 void InlineFlowBox::paintBoxShadow(const PaintInfo& info, const RenderStyle& style, ShadowStyle shadowStyle, const LayoutRect& paintRect)
1240 {
1241     if ((!prevLineBox() && !nextLineBox()) || !parent())
1242         renderer().paintBoxShadow(info, paintRect, &style, shadowStyle);
1243     else {
1244         // FIXME: We can do better here in the multi-line case. We want to push a clip so that the shadow doesn't
1245         // protrude incorrectly at the edges, and we want to possibly include shadows cast from the previous/following lines
1246         renderer().paintBoxShadow(info, paintRect, &style, shadowStyle, includeLogicalLeftEdge(), includeLogicalRightEdge());
1247     }
1248 }
1249
1250 void InlineFlowBox::constrainToLineTopAndBottomIfNeeded(LayoutRect& rect) const
1251 {
1252     bool noQuirksMode = renderer().document().inNoQuirksMode();
1253     if (!noQuirksMode && !hasTextChildren() && !(descendantsHaveSameLineHeightAndBaseline() && hasTextDescendants())) {
1254         const RootInlineBox& rootBox = root();
1255         LayoutUnit logicalTop = isHorizontal() ? rect.y() : rect.x();
1256         LayoutUnit logicalHeight = isHorizontal() ? rect.height() : rect.width();
1257         LayoutUnit bottom = std::min(rootBox.lineBottom(), logicalTop + logicalHeight);
1258         logicalTop = std::max(rootBox.lineTop(), logicalTop);
1259         logicalHeight = bottom - logicalTop;
1260         if (isHorizontal()) {
1261             rect.setY(logicalTop);
1262             rect.setHeight(logicalHeight);
1263         } else {
1264             rect.setX(logicalTop);
1265             rect.setWidth(logicalHeight);
1266         }
1267     }
1268 }
1269
1270 static LayoutRect clipRectForNinePieceImageStrip(InlineFlowBox* box, const NinePieceImage& image, const LayoutRect& paintRect)
1271 {
1272     LayoutRect clipRect(paintRect);
1273     RenderStyle& style = box->renderer().style();
1274     LayoutBoxExtent outsets = style.imageOutsets(image);
1275     if (box->isHorizontal()) {
1276         clipRect.setY(paintRect.y() - outsets.top());
1277         clipRect.setHeight(paintRect.height() + outsets.top() + outsets.bottom());
1278         if (box->includeLogicalLeftEdge()) {
1279             clipRect.setX(paintRect.x() - outsets.left());
1280             clipRect.setWidth(paintRect.width() + outsets.left());
1281         }
1282         if (box->includeLogicalRightEdge())
1283             clipRect.setWidth(clipRect.width() + outsets.right());
1284     } else {
1285         clipRect.setX(paintRect.x() - outsets.left());
1286         clipRect.setWidth(paintRect.width() + outsets.left() + outsets.right());
1287         if (box->includeLogicalLeftEdge()) {
1288             clipRect.setY(paintRect.y() - outsets.top());
1289             clipRect.setHeight(paintRect.height() + outsets.top());
1290         }
1291         if (box->includeLogicalRightEdge())
1292             clipRect.setHeight(clipRect.height() + outsets.bottom());
1293     }
1294     return clipRect;
1295 }
1296
1297 void InlineFlowBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1298 {
1299     if (!paintInfo.shouldPaintWithinRoot(renderer()) || renderer().style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseForeground)
1300         return;
1301
1302     // Pixel snap background/border painting.
1303     LayoutRect frameRect = roundedFrameRect();
1304
1305     constrainToLineTopAndBottomIfNeeded(frameRect);
1306     
1307     // Move x/y to our coordinates.
1308     LayoutRect localRect(frameRect);
1309     flipForWritingMode(localRect);
1310
1311     // You can use p::first-line to specify a background. If so, the root line boxes for
1312     // a line may actually have to paint a background.
1313     if (parent() && !renderer().hasBoxDecorations())
1314         return;
1315     const RenderStyle& lineStyle = this->lineStyle();
1316     if (!parent() && (!isFirstLine() || &lineStyle == &renderer().style()))
1317         return;
1318
1319     LayoutPoint adjustedPaintoffset = paintOffset + localRect.location();
1320     GraphicsContext* context = paintInfo.context;
1321     LayoutRect paintRect = LayoutRect(adjustedPaintoffset, frameRect.size());
1322     // Shadow comes first and is behind the background and border.
1323     if (!renderer().boxShadowShouldBeAppliedToBackground(BackgroundBleedNone, this))
1324         paintBoxShadow(paintInfo, lineStyle, Normal, paintRect);
1325
1326     Color c = lineStyle.visitedDependentColor(CSSPropertyBackgroundColor);
1327     paintFillLayers(paintInfo, c, lineStyle.backgroundLayers(), paintRect);
1328     paintBoxShadow(paintInfo, lineStyle, Inset, paintRect);
1329
1330     // :first-line cannot be used to put borders on a line. Always paint borders with our
1331     // non-first-line style.
1332     if (!parent() || !renderer().style().hasBorder())
1333         return;
1334     const NinePieceImage& borderImage = renderer().style().borderImage();
1335     StyleImage* borderImageSource = borderImage.image();
1336     bool hasBorderImage = borderImageSource && borderImageSource->canRender(&renderer(), lineStyle.effectiveZoom());
1337     if (hasBorderImage && !borderImageSource->isLoaded())
1338         return; // Don't paint anything while we wait for the image to load.
1339
1340     // The simple case is where we either have no border image or we are the only box for this object. In those
1341     // cases only a single call to draw is required.
1342     if (!hasBorderImage || (!prevLineBox() && !nextLineBox()))
1343         renderer().paintBorder(paintInfo, paintRect, &lineStyle, BackgroundBleedNone, includeLogicalLeftEdge(), includeLogicalRightEdge());
1344     else {
1345         // We have a border image that spans multiple lines.
1346         // We need to adjust tx and ty by the width of all previous lines.
1347         // Think of border image painting on inlines as though you had one long line, a single continuous
1348         // strip. Even though that strip has been broken up across multiple lines, you still paint it
1349         // as though you had one single line. This means each line has to pick up the image where
1350         // the previous line left off.
1351         // FIXME: What the heck do we do with RTL here? The math we're using is obviously not right,
1352         // but it isn't even clear how this should work at all.
1353         LayoutUnit logicalOffsetOnLine = 0;
1354         for (InlineFlowBox* curr = prevLineBox(); curr; curr = curr->prevLineBox())
1355             logicalOffsetOnLine += curr->logicalWidth();
1356         LayoutUnit totalLogicalWidth = logicalOffsetOnLine;
1357         for (InlineFlowBox* curr = this; curr; curr = curr->nextLineBox())
1358             totalLogicalWidth += curr->logicalWidth();
1359         LayoutUnit stripX = adjustedPaintoffset.x() - (isHorizontal() ? logicalOffsetOnLine : LayoutUnit());
1360         LayoutUnit stripY = adjustedPaintoffset.y() - (isHorizontal() ? LayoutUnit() : logicalOffsetOnLine);
1361         LayoutUnit stripWidth = isHorizontal() ? totalLogicalWidth : frameRect.width();
1362         LayoutUnit stripHeight = isHorizontal() ? frameRect.height() : totalLogicalWidth;
1363
1364         LayoutRect clipRect = clipRectForNinePieceImageStrip(this, borderImage, paintRect);
1365         GraphicsContextStateSaver stateSaver(*context);
1366         context->clip(clipRect);
1367         renderer().paintBorder(paintInfo, LayoutRect(stripX, stripY, stripWidth, stripHeight), &lineStyle);
1368     }
1369 }
1370
1371 void InlineFlowBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1372 {
1373     if (!paintInfo.shouldPaintWithinRoot(renderer()) || renderer().style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask)
1374         return;
1375
1376     // Pixel snap mask painting.
1377     LayoutRect frameRect = roundedFrameRect();
1378
1379     constrainToLineTopAndBottomIfNeeded(frameRect);
1380     
1381     // Move x/y to our coordinates.
1382     LayoutRect localRect(frameRect);
1383     flipForWritingMode(localRect);
1384     LayoutPoint adjustedPaintOffset = paintOffset + localRect.location();
1385
1386     const NinePieceImage& maskNinePieceImage = renderer().style().maskBoxImage();
1387     StyleImage* maskBoxImage = renderer().style().maskBoxImage().image();
1388
1389     // Figure out if we need to push a transparency layer to render our mask.
1390     bool pushTransparencyLayer = false;
1391     bool compositedMask = renderer().hasLayer() && renderer().layer()->hasCompositedMask();
1392     bool flattenCompositingLayers = renderer().view().frameView().paintBehavior() & PaintBehaviorFlattenCompositingLayers;
1393     CompositeOperator compositeOp = CompositeSourceOver;
1394     if (!compositedMask || flattenCompositingLayers) {
1395         if ((maskBoxImage && renderer().style().maskLayers()->hasImage()) || renderer().style().maskLayers()->next())
1396             pushTransparencyLayer = true;
1397         
1398         compositeOp = CompositeDestinationIn;
1399         if (pushTransparencyLayer) {
1400             paintInfo.context->setCompositeOperation(CompositeDestinationIn);
1401             paintInfo.context->beginTransparencyLayer(1.0f);
1402             compositeOp = CompositeSourceOver;
1403         }
1404     }
1405
1406     LayoutRect paintRect = LayoutRect(adjustedPaintOffset, frameRect.size());
1407     paintFillLayers(paintInfo, Color(), renderer().style().maskLayers(), paintRect, compositeOp);
1408     
1409     bool hasBoxImage = maskBoxImage && maskBoxImage->canRender(&renderer(), renderer().style().effectiveZoom());
1410     if (!hasBoxImage || !maskBoxImage->isLoaded()) {
1411         if (pushTransparencyLayer)
1412             paintInfo.context->endTransparencyLayer();
1413         return; // Don't paint anything while we wait for the image to load.
1414     }
1415
1416     // The simple case is where we are the only box for this object.  In those
1417     // cases only a single call to draw is required.
1418     if (!prevLineBox() && !nextLineBox()) {
1419         renderer().paintNinePieceImage(paintInfo.context, LayoutRect(adjustedPaintOffset, frameRect.size()), &renderer().style(), maskNinePieceImage, compositeOp);
1420     } else {
1421         // We have a mask image that spans multiple lines.
1422         // We need to adjust _tx and _ty by the width of all previous lines.
1423         LayoutUnit logicalOffsetOnLine = 0;
1424         for (InlineFlowBox* curr = prevLineBox(); curr; curr = curr->prevLineBox())
1425             logicalOffsetOnLine += curr->logicalWidth();
1426         LayoutUnit totalLogicalWidth = logicalOffsetOnLine;
1427         for (InlineFlowBox* curr = this; curr; curr = curr->nextLineBox())
1428             totalLogicalWidth += curr->logicalWidth();
1429         LayoutUnit stripX = adjustedPaintOffset.x() - (isHorizontal() ? logicalOffsetOnLine : LayoutUnit());
1430         LayoutUnit stripY = adjustedPaintOffset.y() - (isHorizontal() ? LayoutUnit() : logicalOffsetOnLine);
1431         LayoutUnit stripWidth = isHorizontal() ? totalLogicalWidth : frameRect.width();
1432         LayoutUnit stripHeight = isHorizontal() ? frameRect.height() : totalLogicalWidth;
1433
1434         LayoutRect clipRect = clipRectForNinePieceImageStrip(this, maskNinePieceImage, paintRect);
1435         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1436         paintInfo.context->clip(clipRect);
1437         renderer().paintNinePieceImage(paintInfo.context, LayoutRect(stripX, stripY, stripWidth, stripHeight), &renderer().style(), maskNinePieceImage, compositeOp);
1438     }
1439     
1440     if (pushTransparencyLayer)
1441         paintInfo.context->endTransparencyLayer();
1442 }
1443
1444 InlineBox* InlineFlowBox::firstLeafChild() const
1445 {
1446     InlineBox* leaf = 0;
1447     for (InlineBox* child = firstChild(); child && !leaf; child = child->nextOnLine())
1448         leaf = child->isLeaf() ? child : toInlineFlowBox(child)->firstLeafChild();
1449     return leaf;
1450 }
1451
1452 InlineBox* InlineFlowBox::lastLeafChild() const
1453 {
1454     InlineBox* leaf = 0;
1455     for (InlineBox* child = lastChild(); child && !leaf; child = child->prevOnLine())
1456         leaf = child->isLeaf() ? child : toInlineFlowBox(child)->lastLeafChild();
1457     return leaf;
1458 }
1459
1460 RenderObject::SelectionState InlineFlowBox::selectionState()
1461 {
1462     return RenderObject::SelectionNone;
1463 }
1464
1465 bool InlineFlowBox::canAccommodateEllipsis(bool ltr, int blockEdge, int ellipsisWidth) const
1466 {
1467     for (InlineBox *box = firstChild(); box; box = box->nextOnLine()) {
1468         if (!box->canAccommodateEllipsis(ltr, blockEdge, ellipsisWidth))
1469             return false;
1470     }
1471     return true;
1472 }
1473
1474 float InlineFlowBox::placeEllipsisBox(bool ltr, float blockLeftEdge, float blockRightEdge, float ellipsisWidth, float &truncatedWidth, bool& foundBox)
1475 {
1476     float result = -1;
1477     // We iterate over all children, the foundBox variable tells us when we've found the
1478     // box containing the ellipsis.  All boxes after that one in the flow are hidden.
1479     // If our flow is ltr then iterate over the boxes from left to right, otherwise iterate
1480     // from right to left. Varying the order allows us to correctly hide the boxes following the ellipsis.
1481     InlineBox* box = ltr ? firstChild() : lastChild();
1482
1483     // NOTE: these will cross after foundBox = true.
1484     int visibleLeftEdge = blockLeftEdge;
1485     int visibleRightEdge = blockRightEdge;
1486
1487     while (box) {
1488         int currResult = box->placeEllipsisBox(ltr, visibleLeftEdge, visibleRightEdge, ellipsisWidth, truncatedWidth, foundBox);
1489         if (currResult != -1 && result == -1)
1490             result = currResult;
1491
1492         if (ltr) {
1493             visibleLeftEdge += box->logicalWidth();
1494             box = box->nextOnLine();
1495         }
1496         else {
1497             visibleRightEdge -= box->logicalWidth();
1498             box = box->prevOnLine();
1499         }
1500     }
1501     return result;
1502 }
1503
1504 void InlineFlowBox::clearTruncation()
1505 {
1506     for (InlineBox *box = firstChild(); box; box = box->nextOnLine())
1507         box->clearTruncation();
1508 }
1509
1510 LayoutUnit InlineFlowBox::computeOverAnnotationAdjustment(LayoutUnit allowedPosition) const
1511 {
1512     LayoutUnit result = 0;
1513     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
1514         if (curr->renderer().isOutOfFlowPositioned())
1515             continue; // Positioned placeholders don't affect calculations.
1516         
1517         if (curr->isInlineFlowBox())
1518             result = std::max(result, toInlineFlowBox(curr)->computeOverAnnotationAdjustment(allowedPosition));
1519         
1520         if (curr->renderer().isReplaced() && curr->renderer().isRubyRun() && curr->renderer().style().rubyPosition() == RubyPositionBefore) {
1521             RenderRubyRun& rubyRun = toRenderRubyRun(curr->renderer());
1522             RenderRubyText* rubyText = rubyRun.rubyText();
1523             if (!rubyText)
1524                 continue;
1525             
1526             if (!rubyRun.style().isFlippedLinesWritingMode()) {
1527                 LayoutUnit topOfFirstRubyTextLine = rubyText->logicalTop() + (rubyText->firstRootBox() ? rubyText->firstRootBox()->lineTop() : LayoutUnit());
1528                 if (topOfFirstRubyTextLine >= 0)
1529                     continue;
1530                 topOfFirstRubyTextLine += curr->logicalTop();
1531                 result = std::max(result, allowedPosition - topOfFirstRubyTextLine);
1532             } else {
1533                 LayoutUnit bottomOfLastRubyTextLine = rubyText->logicalTop() + (rubyText->lastRootBox() ? rubyText->lastRootBox()->lineBottom() : rubyText->logicalHeight());
1534                 if (bottomOfLastRubyTextLine <= curr->logicalHeight())
1535                     continue;
1536                 bottomOfLastRubyTextLine += curr->logicalTop();
1537                 result = std::max(result, bottomOfLastRubyTextLine - allowedPosition);
1538             }
1539         }
1540
1541         if (curr->isInlineTextBox()) {
1542             const RenderStyle& childLineStyle = curr->lineStyle();
1543             bool emphasisMarkIsAbove;
1544             if (childLineStyle.textEmphasisMark() != TextEmphasisMarkNone && toInlineTextBox(curr)->emphasisMarkExistsAndIsAbove(childLineStyle, emphasisMarkIsAbove) && emphasisMarkIsAbove) {
1545                 if (!childLineStyle.isFlippedLinesWritingMode()) {
1546                     int topOfEmphasisMark = curr->logicalTop() - childLineStyle.font().emphasisMarkHeight(childLineStyle.textEmphasisMarkString());
1547                     result = std::max(result, allowedPosition - topOfEmphasisMark);
1548                 } else {
1549                     int bottomOfEmphasisMark = curr->logicalBottom() + childLineStyle.font().emphasisMarkHeight(childLineStyle.textEmphasisMarkString());
1550                     result = std::max(result, bottomOfEmphasisMark - allowedPosition);
1551                 }
1552             }
1553         }
1554     }
1555     return result;
1556 }
1557
1558 LayoutUnit InlineFlowBox::computeUnderAnnotationAdjustment(LayoutUnit allowedPosition) const
1559 {
1560     LayoutUnit result = 0;
1561     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
1562         if (curr->renderer().isOutOfFlowPositioned())
1563             continue; // Positioned placeholders don't affect calculations.
1564
1565         if (curr->isInlineFlowBox())
1566             result = std::max(result, toInlineFlowBox(curr)->computeUnderAnnotationAdjustment(allowedPosition));
1567
1568         if (curr->renderer().isReplaced() && curr->renderer().isRubyRun() && curr->renderer().style().rubyPosition() == RubyPositionAfter) {
1569             RenderRubyRun& rubyRun = toRenderRubyRun(curr->renderer());
1570             RenderRubyText* rubyText = rubyRun.rubyText();
1571             if (!rubyText)
1572                 continue;
1573
1574             if (rubyRun.style().isFlippedLinesWritingMode()) {
1575                 LayoutUnit topOfFirstRubyTextLine = rubyText->logicalTop() + (rubyText->firstRootBox() ? rubyText->firstRootBox()->lineTop() : LayoutUnit());
1576                 if (topOfFirstRubyTextLine >= 0)
1577                     continue;
1578                 topOfFirstRubyTextLine += curr->logicalTop();
1579                 result = std::max(result, allowedPosition - topOfFirstRubyTextLine);
1580             } else {
1581                 LayoutUnit bottomOfLastRubyTextLine = rubyText->logicalTop() + (rubyText->lastRootBox() ? rubyText->lastRootBox()->lineBottom() : rubyText->logicalHeight());
1582                 if (bottomOfLastRubyTextLine <= curr->logicalHeight())
1583                     continue;
1584                 bottomOfLastRubyTextLine += curr->logicalTop();
1585                 result = std::max(result, bottomOfLastRubyTextLine - allowedPosition);
1586             }
1587         }
1588
1589         if (curr->isInlineTextBox()) {
1590             const RenderStyle& childLineStyle = curr->lineStyle();
1591             bool emphasisMarkIsAbove;
1592             toInlineTextBox(curr)->emphasisMarkExistsAndIsAbove(childLineStyle, emphasisMarkIsAbove);
1593             if (childLineStyle.textEmphasisMark() != TextEmphasisMarkNone && !emphasisMarkIsAbove) {
1594                 if (!childLineStyle.isFlippedLinesWritingMode()) {
1595                     LayoutUnit bottomOfEmphasisMark = curr->logicalBottom() + childLineStyle.font().emphasisMarkHeight(childLineStyle.textEmphasisMarkString());
1596                     result = std::max(result, bottomOfEmphasisMark - allowedPosition);
1597                 } else {
1598                     LayoutUnit topOfEmphasisMark = curr->logicalTop() - childLineStyle.font().emphasisMarkHeight(childLineStyle.textEmphasisMarkString());
1599                     result = std::max(result, allowedPosition - topOfEmphasisMark);
1600                 }
1601             }
1602         }
1603     }
1604     return result;
1605 }
1606
1607 void InlineFlowBox::collectLeafBoxesInLogicalOrder(Vector<InlineBox*>& leafBoxesInLogicalOrder, CustomInlineBoxRangeReverse customReverseImplementation, void* userData) const
1608 {
1609     InlineBox* leaf = firstLeafChild();
1610
1611     // FIXME: The reordering code is a copy of parts from BidiResolver::createBidiRunsForLine, operating directly on InlineBoxes, instead of BidiRuns.
1612     // Investigate on how this code could possibly be shared.
1613     unsigned char minLevel = 128;
1614     unsigned char maxLevel = 0;
1615
1616     // First find highest and lowest levels, and initialize leafBoxesInLogicalOrder with the leaf boxes in visual order.
1617     for (; leaf; leaf = leaf->nextLeafChild()) {
1618         minLevel = std::min(minLevel, leaf->bidiLevel());
1619         maxLevel = std::max(maxLevel, leaf->bidiLevel());
1620         leafBoxesInLogicalOrder.append(leaf);
1621     }
1622
1623     if (renderer().style().rtlOrdering() == VisualOrder)
1624         return;
1625
1626     // Reverse of reordering of the line (L2 according to Bidi spec):
1627     // L2. From the highest level found in the text to the lowest odd level on each line,
1628     // reverse any contiguous sequence of characters that are at that level or higher.
1629
1630     // Reversing the reordering of the line is only done up to the lowest odd level.
1631     if (!(minLevel % 2))
1632         ++minLevel;
1633
1634     Vector<InlineBox*>::iterator end = leafBoxesInLogicalOrder.end();
1635     while (minLevel <= maxLevel) {
1636         Vector<InlineBox*>::iterator it = leafBoxesInLogicalOrder.begin();
1637         while (it != end) {
1638             while (it != end) {
1639                 if ((*it)->bidiLevel() >= minLevel)
1640                     break;
1641                 ++it;
1642             }
1643             Vector<InlineBox*>::iterator first = it;
1644             while (it != end) {
1645                 if ((*it)->bidiLevel() < minLevel)
1646                     break;
1647                 ++it;
1648             }
1649             Vector<InlineBox*>::iterator last = it;
1650             if (customReverseImplementation) {
1651                 ASSERT(userData);
1652                 (*customReverseImplementation)(userData, first, last);
1653             } else
1654                 std::reverse(first, last);
1655         }                
1656         ++minLevel;
1657     }
1658 }
1659
1660 #ifndef NDEBUG
1661
1662 const char* InlineFlowBox::boxName() const
1663 {
1664     return "InlineFlowBox";
1665 }
1666
1667 void InlineFlowBox::showLineTreeAndMark(const InlineBox* markedBox1, const char* markedLabel1, const InlineBox* markedBox2, const char* markedLabel2, const RenderObject* obj, int depth) const
1668 {
1669     InlineBox::showLineTreeAndMark(markedBox1, markedLabel1, markedBox2, markedLabel2, obj, depth);
1670     for (const InlineBox* box = firstChild(); box; box = box->nextOnLine())
1671         box->showLineTreeAndMark(markedBox1, markedLabel1, markedBox2, markedLabel2, obj, depth + 1);
1672 }
1673
1674 void InlineFlowBox::checkConsistency() const
1675 {
1676     assertNotDeleted();
1677     ASSERT_WITH_SECURITY_IMPLICATION(!m_hasBadChildList);
1678 #ifdef CHECK_CONSISTENCY
1679     const InlineBox* previousChild = nullptr;
1680     for (const InlineBox* child = firstChild(); child; child = child->nextOnLine()) {
1681         ASSERT(child->parent() == this);
1682         ASSERT(child->prevOnLine() == previousChild);
1683         previousChild = child;
1684     }
1685     ASSERT(previousChild == m_lastChild);
1686 #endif
1687 }
1688
1689 #endif
1690
1691 } // namespace WebCore