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