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