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