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