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