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