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