https://bugs.webkit.org/show_bug.cgi?id=48540, support the text-orientation CSS property.
[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 "GraphicsContext.h"
28 #include "InlineTextBox.h"
29 #include "HitTestResult.h"
30 #include "RootInlineBox.h"
31 #include "RenderBlock.h"
32 #include "RenderInline.h"
33 #include "RenderLayer.h"
34 #include "RenderListMarker.h"
35 #include "RenderRubyBase.h"
36 #include "RenderRubyRun.h"
37 #include "RenderRubyText.h"
38 #include "RenderTableCell.h"
39 #include "RootInlineBox.h"
40 #include "Text.h"
41 #include "VerticalPositionCache.h"
42
43 #include <math.h>
44
45 using namespace std;
46
47 namespace WebCore {
48
49 #ifndef NDEBUG
50
51 InlineFlowBox::~InlineFlowBox()
52 {
53     if (!m_hasBadChildList)
54         for (InlineBox* child = firstChild(); child; child = child->nextOnLine())
55             child->setHasBadParent();
56 }
57
58 #endif
59
60 int InlineFlowBox::getFlowSpacingLogicalWidth()
61 {
62     int totWidth = marginBorderPaddingLogicalLeft() + marginBorderPaddingLogicalRight();
63     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
64         if (curr->isInlineFlowBox())
65             totWidth += static_cast<InlineFlowBox*>(curr)->getFlowSpacingLogicalWidth();
66     }
67     return totWidth;
68 }
69
70 IntRect InlineFlowBox::roundedFrameRect() const
71 {
72     // Begin by snapping the x and y coordinates to the nearest pixel.
73     int snappedX = lroundf(x());
74     int snappedY = lroundf(y());
75     
76     int snappedMaxX = lroundf(x() + width());
77     int snappedMaxY = lroundf(y() + height());
78     
79     return IntRect(snappedX, snappedY, snappedMaxX - snappedX, snappedMaxY - snappedY);
80 }
81
82 void InlineFlowBox::addToLine(InlineBox* child) 
83 {
84     ASSERT(!child->parent());
85     ASSERT(!child->nextOnLine());
86     ASSERT(!child->prevOnLine());
87     checkConsistency();
88
89     child->setParent(this);
90     if (!m_firstChild) {
91         m_firstChild = child;
92         m_lastChild = child;
93     } else {
94         m_lastChild->setNextOnLine(child);
95         child->setPrevOnLine(m_lastChild);
96         m_lastChild = child;
97     }
98     child->setFirstLineStyleBit(m_firstLine);
99     child->setIsHorizontal(isHorizontal());
100     if (child->isText())
101         m_hasTextChildren = true;
102
103     checkConsistency();
104 }
105
106 void InlineFlowBox::removeChild(InlineBox* child)
107 {
108     checkConsistency();
109
110     if (!m_dirty)
111         dirtyLineBoxes();
112
113     root()->childRemoved(child);
114
115     if (child == m_firstChild)
116         m_firstChild = child->nextOnLine();
117     if (child == m_lastChild)
118         m_lastChild = child->prevOnLine();
119     if (child->nextOnLine())
120         child->nextOnLine()->setPrevOnLine(child->prevOnLine());
121     if (child->prevOnLine())
122         child->prevOnLine()->setNextOnLine(child->nextOnLine());
123     
124     child->setParent(0);
125
126     checkConsistency();
127 }
128
129 void InlineFlowBox::deleteLine(RenderArena* arena)
130 {
131     InlineBox* child = firstChild();
132     InlineBox* next = 0;
133     while (child) {
134         ASSERT(this == child->parent());
135         next = child->nextOnLine();
136 #ifndef NDEBUG
137         child->setParent(0);
138 #endif
139         child->deleteLine(arena);
140         child = next;
141     }
142 #ifndef NDEBUG
143     m_firstChild = 0;
144     m_lastChild = 0;
145 #endif
146
147     removeLineBoxFromRenderObject();
148     destroy(arena);
149 }
150
151 void InlineFlowBox::removeLineBoxFromRenderObject()
152 {
153     toRenderInline(renderer())->lineBoxes()->removeLineBox(this);
154 }
155
156 void InlineFlowBox::extractLine()
157 {
158     if (!m_extracted)
159         extractLineBoxFromRenderObject();
160     for (InlineBox* child = firstChild(); child; child = child->nextOnLine())
161         child->extractLine();
162 }
163
164 void InlineFlowBox::extractLineBoxFromRenderObject()
165 {
166     toRenderInline(renderer())->lineBoxes()->extractLineBox(this);
167 }
168
169 void InlineFlowBox::attachLine()
170 {
171     if (m_extracted)
172         attachLineBoxToRenderObject();
173     for (InlineBox* child = firstChild(); child; child = child->nextOnLine())
174         child->attachLine();
175 }
176
177 void InlineFlowBox::attachLineBoxToRenderObject()
178 {
179     toRenderInline(renderer())->lineBoxes()->attachLineBox(this);
180 }
181
182 void InlineFlowBox::adjustPosition(float dx, float dy)
183 {
184     InlineBox::adjustPosition(dx, dy);
185     for (InlineBox* child = firstChild(); child; child = child->nextOnLine())
186         child->adjustPosition(dx, dy);
187     if (m_overflow)
188         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.
189 }
190
191 RenderLineBoxList* InlineFlowBox::rendererLineBoxes() const
192 {
193     return toRenderInline(renderer())->lineBoxes();
194 }
195
196 bool InlineFlowBox::onEndChain(RenderObject* endObject)
197 {
198     if (!endObject)
199         return false;
200     
201     if (endObject == renderer())
202         return true;
203
204     RenderObject* curr = endObject;
205     RenderObject* parent = curr->parent();
206     while (parent && !parent->isRenderBlock()) {
207         if (parent->lastChild() != curr || parent == renderer())
208             return false;
209             
210         curr = parent;
211         parent = curr->parent();
212     }
213
214     return true;
215 }
216
217 void InlineFlowBox::determineSpacingForFlowBoxes(bool lastLine, RenderObject* endObject)
218 {
219     // All boxes start off open.  They will not apply any margins/border/padding on
220     // any side.
221     bool includeLeftEdge = false;
222     bool includeRightEdge = false;
223
224     // The root inline box never has borders/margins/padding.
225     if (parent()) {
226         bool ltr = renderer()->style()->isLeftToRightDirection();
227
228         // Check to see if all initial lines are unconstructed.  If so, then
229         // we know the inline began on this line (unless we are a continuation).
230         RenderLineBoxList* lineBoxList = rendererLineBoxes();
231         if (!lineBoxList->firstLineBox()->isConstructed() && !renderer()->isInlineElementContinuation()) {
232             if (ltr && lineBoxList->firstLineBox() == this)
233                 includeLeftEdge = true;
234             else if (!ltr && lineBoxList->lastLineBox() == this)
235                 includeRightEdge = true;
236         }
237     
238         // In order to determine if the inline ends on this line, we check three things:
239         // (1) If we are the last line and we don't have a continuation(), then we can
240         // close up.
241         // (2) If the last line box for the flow has an object following it on the line (ltr,
242         // reverse for rtl), then the inline has closed.
243         // (3) The line may end on the inline.  If we are the last child (climbing up
244         // the end object's chain), then we just closed as well.
245         if (!lineBoxList->lastLineBox()->isConstructed()) {
246             RenderInline* inlineFlow = toRenderInline(renderer());
247             if (ltr) {
248                 if (!nextLineBox() &&
249                     ((lastLine && !inlineFlow->continuation()) || nextOnLineExists() || onEndChain(endObject)))
250                     includeRightEdge = true;
251             } else {
252                 if ((!prevLineBox() || prevLineBox()->isConstructed()) &&
253                     ((lastLine && !inlineFlow->continuation()) || prevOnLineExists() || onEndChain(endObject)))
254                     includeLeftEdge = true;
255             }
256         }
257     }
258
259     setEdges(includeLeftEdge, includeRightEdge);
260
261     // Recur into our children.
262     for (InlineBox* currChild = firstChild(); currChild; currChild = currChild->nextOnLine()) {
263         if (currChild->isInlineFlowBox()) {
264             InlineFlowBox* currFlow = static_cast<InlineFlowBox*>(currChild);
265             currFlow->determineSpacingForFlowBoxes(lastLine, endObject);
266         }
267     }
268 }
269
270 float InlineFlowBox::placeBoxesInInlineDirection(float logicalLeft, bool& needsWordSpacing, GlyphOverflowAndFallbackFontsMap& textBoxDataMap)
271 {
272     // Set our x position.
273     setLogicalLeft(logicalLeft);
274   
275     float startLogicalLeft = logicalLeft;
276     logicalLeft += borderLogicalLeft() + paddingLogicalLeft();
277     
278     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
279         if (curr->renderer()->isText()) {
280             InlineTextBox* text = static_cast<InlineTextBox*>(curr);
281             RenderText* rt = toRenderText(text->renderer());
282             if (rt->textLength()) {
283                 if (needsWordSpacing && isSpaceOrNewline(rt->characters()[text->start()]))
284                     logicalLeft += rt->style(m_firstLine)->font().wordSpacing();
285                 needsWordSpacing = !isSpaceOrNewline(rt->characters()[text->end()]);
286             }
287             text->setLogicalLeft(logicalLeft);
288             logicalLeft += text->logicalWidth();
289         } else {
290             if (curr->renderer()->isPositioned()) {
291                 if (curr->renderer()->parent()->style()->isLeftToRightDirection())
292                     curr->setLogicalLeft(logicalLeft);
293                 else
294                     // Our offset that we cache needs to be from the edge of the right border box and
295                     // not the left border box.  We have to subtract |x| from the width of the block
296                     // (which can be obtained from the root line box).
297                     curr->setLogicalLeft(root()->block()->logicalWidth() - logicalLeft);
298                 continue; // The positioned object has no effect on the width.
299             }
300             if (curr->renderer()->isRenderInline()) {
301                 InlineFlowBox* flow = static_cast<InlineFlowBox*>(curr);
302                 logicalLeft += flow->marginLogicalLeft();
303                 logicalLeft = flow->placeBoxesInInlineDirection(logicalLeft, needsWordSpacing, textBoxDataMap);
304                 logicalLeft += flow->marginLogicalRight();
305             } else if (!curr->renderer()->isListMarker() || toRenderListMarker(curr->renderer())->isInside()) {
306                 // The box can have a different writing-mode than the overall line, so this is a bit complicated.
307                 // Just get all the physical margin and overflow values by hand based off |isVertical|.
308                 int logicalLeftMargin = isHorizontal() ? curr->boxModelObject()->marginLeft() : curr->boxModelObject()->marginTop();
309                 int logicalRightMargin = isHorizontal() ? curr->boxModelObject()->marginRight() : curr->boxModelObject()->marginBottom();
310                 
311                 logicalLeft += logicalLeftMargin;
312                 curr->setLogicalLeft(logicalLeft);
313                 logicalLeft += curr->logicalWidth() + logicalRightMargin;
314             }
315         }
316     }
317
318     logicalLeft += borderLogicalRight() + paddingLogicalRight();
319     setLogicalWidth(logicalLeft - startLogicalLeft);
320     return logicalLeft;
321 }
322
323 bool InlineFlowBox::requiresIdeographicBaseline(const GlyphOverflowAndFallbackFontsMap& textBoxDataMap) const
324 {
325     if (isHorizontal())
326         return false;
327     
328     if (renderer()->style(m_firstLine)->fontDescription().textOrientation() == TextOrientationUpright
329         || renderer()->style(m_firstLine)->font().primaryFont()->hasVerticalGlyphs())
330         return true;
331
332     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
333         if (curr->renderer()->isPositioned())
334             continue; // Positioned placeholders don't affect calculations.
335         
336         if (curr->isInlineFlowBox()) {
337             if (static_cast<InlineFlowBox*>(curr)->requiresIdeographicBaseline(textBoxDataMap))
338                 return true;
339         } else {
340             if (curr->renderer()->style(m_firstLine)->font().primaryFont()->hasVerticalGlyphs())
341                 return true;
342             
343             const Vector<const SimpleFontData*>* usedFonts = 0;
344             if (curr->isInlineTextBox()) {
345                 GlyphOverflowAndFallbackFontsMap::const_iterator it = textBoxDataMap.find(static_cast<InlineTextBox*>(curr));
346                 usedFonts = it == textBoxDataMap.end() ? 0 : &it->second.first;
347             }
348
349             if (usedFonts) {
350                 for (size_t i = 0; i < usedFonts->size(); ++i) {
351                     if (usedFonts->at(i)->hasVerticalGlyphs())
352                         return true;
353                 }
354             }
355         }
356     }
357     
358     return false;
359 }
360
361 void InlineFlowBox::adjustMaxAscentAndDescent(int& maxAscent, int& maxDescent, int maxPositionTop, int maxPositionBottom)
362 {
363     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
364         // The computed lineheight needs to be extended for the
365         // positioned elements
366         if (curr->renderer()->isPositioned())
367             continue; // Positioned placeholders don't affect calculations.
368         if (curr->verticalAlign() == TOP || curr->verticalAlign() == BOTTOM) {
369             int lineHeight = curr->lineHeight();
370             if (curr->verticalAlign() == TOP) {
371                 if (maxAscent + maxDescent < lineHeight)
372                     maxDescent = lineHeight - maxAscent;
373             }
374             else {
375                 if (maxAscent + maxDescent < lineHeight)
376                     maxAscent = lineHeight - maxDescent;
377             }
378
379             if (maxAscent + maxDescent >= max(maxPositionTop, maxPositionBottom))
380                 break;
381         }
382
383         if (curr->isInlineFlowBox())
384             static_cast<InlineFlowBox*>(curr)->adjustMaxAscentAndDescent(maxAscent, maxDescent, maxPositionTop, maxPositionBottom);
385     }
386 }
387
388 static int verticalPositionForBox(InlineBox* box, FontBaseline baselineType, bool firstLine, VerticalPositionCache& verticalPositionCache)
389 {
390     if (box->renderer()->isText())
391         return box->parent()->logicalTop();
392     
393     RenderBoxModelObject* renderer = box->boxModelObject();
394     ASSERT(renderer->isInline());
395     if (!renderer->isInline())
396         return 0;
397
398     // This method determines the vertical position for inline elements.
399     if (firstLine && !renderer->document()->usesFirstLineRules())
400         firstLine = false;
401
402     // Check the cache.
403     bool isRenderInline = renderer->isRenderInline();
404     if (isRenderInline && !firstLine) {
405         int verticalPosition = verticalPositionCache.get(renderer, baselineType);
406         if (verticalPosition != PositionUndefined)
407             return verticalPosition;
408     }
409
410     int verticalPosition = 0;
411     EVerticalAlign verticalAlign = renderer->style()->verticalAlign();
412     if (verticalAlign == TOP || verticalAlign == BOTTOM)
413         return 0;
414    
415     RenderObject* parent = renderer->parent();
416     if (parent->isRenderInline() && parent->style()->verticalAlign() != TOP && parent->style()->verticalAlign() != BOTTOM)
417         verticalPosition = box->parent()->logicalTop();
418     
419     if (verticalAlign != BASELINE) {
420         const Font& font = parent->style(firstLine)->font();
421         const FontMetrics& fontMetrics = font.fontMetrics();
422         int fontSize = font.pixelSize();
423
424         LineDirectionMode lineDirection = parent->style()->isHorizontalWritingMode() ? HorizontalLine : VerticalLine;
425
426         if (verticalAlign == SUB)
427             verticalPosition += fontSize / 5 + 1;
428         else if (verticalAlign == SUPER)
429             verticalPosition -= fontSize / 3 + 1;
430         else if (verticalAlign == TEXT_TOP)
431             verticalPosition += renderer->baselinePosition(baselineType, firstLine, lineDirection) - fontMetrics.ascent(baselineType);
432         else if (verticalAlign == MIDDLE)
433             verticalPosition += -static_cast<int>(fontMetrics.xHeight() / 2) - renderer->lineHeight(firstLine, lineDirection) / 2 + renderer->baselinePosition(baselineType, firstLine, lineDirection);
434         else if (verticalAlign == TEXT_BOTTOM) {
435             verticalPosition += fontMetrics.descent(baselineType);
436             // lineHeight - baselinePosition is always 0 for replaced elements (except inline blocks), so don't bother wasting time in that case.
437             if (!renderer->isReplaced() || renderer->isInlineBlockOrInlineTable())
438                 verticalPosition -= (renderer->lineHeight(firstLine, lineDirection) - renderer->baselinePosition(baselineType, firstLine, lineDirection));
439         } else if (verticalAlign == BASELINE_MIDDLE)
440             verticalPosition += -renderer->lineHeight(firstLine, lineDirection) / 2 + renderer->baselinePosition(baselineType, firstLine, lineDirection);
441         else if (verticalAlign == LENGTH)
442             verticalPosition -= renderer->style()->verticalAlignLength().calcValue(renderer->lineHeight(firstLine, lineDirection));
443     }
444
445     // Store the cached value.
446     if (isRenderInline && !firstLine)
447         verticalPositionCache.set(renderer, baselineType, verticalPosition);
448
449     return verticalPosition;
450 }
451
452 void InlineFlowBox::computeLogicalBoxHeights(int& maxPositionTop, int& maxPositionBottom,
453                                              int& maxAscent, int& maxDescent, bool& setMaxAscent, bool& setMaxDescent,
454                                              bool strictMode, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
455                                              FontBaseline baselineType, VerticalPositionCache& verticalPositionCache)
456 {
457     // The primary purpose of this function is to compute the maximal ascent and descent values for
458     // a line.
459     //
460     // The maxAscent value represents the distance of the highest point of any box (including line-height) from
461     // the root box's baseline.  The maxDescent value represents the distance of the lowest point of any box
462     // (also including line-height) from the root box baseline.  These values can be negative.
463     //
464     // A secondary purpose of this function is to store the offset of very box's baseline from the root box's
465     // baseline.  This information is cached in the logicalTop() of every box. We're effectively just using
466     // the logicalTop() as scratch space. 
467     if (isRootInlineBox()) {
468         // Examine our root box.
469         int height = lineHeight();
470         int baseline = baselinePosition(baselineType);
471         if (hasTextChildren() || strictMode) {
472             int ascent = baseline;
473             int descent = height - ascent;
474             if (maxAscent < ascent || !setMaxAscent) {
475                 maxAscent = ascent;
476                 setMaxAscent = true;
477             }
478             if (maxDescent < descent || !setMaxDescent) {
479                 maxDescent = descent;
480                 setMaxDescent = true;
481             }
482         }
483     }
484
485     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
486         if (curr->renderer()->isPositioned())
487             continue; // Positioned placeholders don't affect calculations.
488         
489         bool isInlineFlow = curr->isInlineFlowBox();
490         
491         // Because a box can be positioned such that it ends up fully above or fully below the
492         // root line box, we only consider it to affect the maxAscent and maxDescent values if some
493         // part of the box (EXCLUDING line-height) is above (for ascent) or below (for descent) the root box's baseline.
494         bool affectsAscent = false;
495         bool affectsDescent = false;
496         
497         // The verticalPositionForBox function returns the distance between the child box's baseline
498         // and the root box's baseline.  The value is negative if the child box's baseline is above the
499         // root box's baseline, and it is positive if the child box's baseline is below the root box's baseline.
500         curr->setLogicalTop(verticalPositionForBox(curr, baselineType, m_firstLine, verticalPositionCache));
501         
502         int lineHeight;
503         int baseline;
504         Vector<const SimpleFontData*>* usedFonts = 0;
505         if (curr->isInlineTextBox()) {
506             GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.find(static_cast<InlineTextBox*>(curr));
507             usedFonts = it == textBoxDataMap.end() ? 0 : &it->second.first;
508         }
509
510         if (usedFonts && !usedFonts->isEmpty() && curr->renderer()->style(m_firstLine)->lineHeight().isNegative()) {
511             usedFonts->append(curr->renderer()->style(m_firstLine)->font().primaryFont());
512             bool baselineSet = false;
513             baseline = 0;
514             int baselineToBottom = 0;
515             for (size_t i = 0; i < usedFonts->size(); ++i) {
516                 const FontMetrics& fontMetrics = usedFonts->at(i)->fontMetrics();
517                 int halfLeading = (fontMetrics.lineSpacing() - fontMetrics.height()) / 2;
518                 int usedFontBaseline = halfLeading + fontMetrics.ascent(baselineType);
519                 int usedFontBaselineToBottom = fontMetrics.lineSpacing() - usedFontBaseline;
520                 if (!baselineSet) {
521                     baselineSet = true;
522                     baseline = usedFontBaseline;
523                     baselineToBottom = usedFontBaselineToBottom;
524                 } else {
525                     baseline = max(baseline, usedFontBaseline);
526                     baselineToBottom = max(baselineToBottom, usedFontBaselineToBottom);
527                 }
528                 if (!affectsAscent)
529                     affectsAscent = fontMetrics.ascent() - curr->logicalTop() > 0;
530                 if (!affectsDescent)
531                     affectsDescent = fontMetrics.descent() + curr->logicalTop() > 0;
532             }
533             lineHeight = baseline + baselineToBottom;
534         } else {
535             lineHeight = curr->lineHeight();
536             baseline = curr->baselinePosition(baselineType);
537             if (curr->isText() || isInlineFlow) {
538                 // Examine the font box for inline flows and text boxes to see if any part of it is above the baseline.
539                 // If the top of our font box relative to the root box baseline is above the root box baseline, then
540                 // we are contributing to the maxAscent value.
541                 const FontMetrics& fontMetrics = curr->renderer()->style(m_firstLine)->fontMetrics();
542                 affectsAscent = fontMetrics.ascent(baselineType) - curr->logicalTop() > 0;
543                 
544                 // Descent is similar.  If any part of our font box is below the root box's baseline, then
545                 // we contribute to the maxDescent value.
546                 affectsDescent = fontMetrics.descent(baselineType) + curr->logicalTop() > 0;
547             } else {
548                 // Replaced elements always affect both the ascent and descent.
549                 affectsAscent = true;
550                 affectsDescent = true;
551             }
552         }
553
554         if (curr->verticalAlign() == TOP) {
555             if (maxPositionTop < lineHeight)
556                 maxPositionTop = lineHeight;
557         } else if (curr->verticalAlign() == BOTTOM) {
558             if (maxPositionBottom < lineHeight)
559                 maxPositionBottom = lineHeight;
560         } else if ((!isInlineFlow || static_cast<InlineFlowBox*>(curr)->hasTextChildren()) || curr->boxModelObject()->hasInlineDirectionBordersOrPadding() || strictMode) {
561             // Note that these values can be negative.  Even though we only affect the maxAscent and maxDescent values
562             // if our box (excluding line-height) was above (for ascent) or below (for descent) the root baseline, once you factor in line-height
563             // the final box can end up being fully above or fully below the root box's baseline!  This is ok, but what it
564             // means is that ascent and descent (including leading), can end up being negative.  The setMaxAscent and
565             // setMaxDescent booleans are used to ensure that we're willing to initially set maxAscent/Descent to negative
566             // values.
567             int ascent = baseline - curr->logicalTop();
568             int descent = lineHeight - ascent;
569             if (affectsAscent && (maxAscent < ascent || !setMaxAscent)) {
570                 maxAscent = ascent;
571                 setMaxAscent = true;
572             }
573             if (affectsDescent && (maxDescent < descent || !setMaxDescent)) {
574                 maxDescent = descent;
575                 setMaxDescent = true;
576             }
577         }
578
579         if (curr->isInlineFlowBox())
580             static_cast<InlineFlowBox*>(curr)->computeLogicalBoxHeights(maxPositionTop, maxPositionBottom, maxAscent, maxDescent,
581                                                                         setMaxAscent, setMaxDescent, strictMode, textBoxDataMap,
582                                                                         baselineType, verticalPositionCache);
583     }
584 }
585
586 void InlineFlowBox::placeBoxesInBlockDirection(int top, int maxHeight, int maxAscent, bool strictMode, int& lineTop, int& lineBottom, bool& setLineTop,
587                                                int& lineTopIncludingMargins, int& lineBottomIncludingMargins, bool& hasAnnotationsBefore, bool& hasAnnotationsAfter, FontBaseline baselineType)
588 {
589     if (isRootInlineBox())
590         setLogicalTop(top + maxAscent - baselinePosition(baselineType)); // Place our root box.
591
592     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
593         if (curr->renderer()->isPositioned())
594             continue; // Positioned placeholders don't affect calculations.
595         
596         // Adjust boxes to use their real box y/height and not the logical height (as dictated by
597         // line-height).
598         bool isInlineFlow = curr->isInlineFlowBox();
599         if (isInlineFlow)
600             static_cast<InlineFlowBox*>(curr)->placeBoxesInBlockDirection(top, maxHeight, maxAscent, strictMode, lineTop, lineBottom, setLineTop,
601                                                                           lineTopIncludingMargins, lineBottomIncludingMargins, hasAnnotationsBefore, hasAnnotationsAfter, baselineType);
602
603         bool childAffectsTopBottomPos = true;
604         if (curr->verticalAlign() == TOP)
605             curr->setLogicalTop(top);
606         else if (curr->verticalAlign() == BOTTOM)
607             curr->setLogicalTop(top + maxHeight - curr->lineHeight());
608         else {
609             if ((isInlineFlow && !static_cast<InlineFlowBox*>(curr)->hasTextChildren()) && !curr->boxModelObject()->hasInlineDirectionBordersOrPadding() && !strictMode)
610                 childAffectsTopBottomPos = false;
611             int posAdjust = maxAscent - curr->baselinePosition(baselineType);
612             curr->setLogicalTop(curr->logicalTop() + top + posAdjust);
613         }
614         
615         int newLogicalTop = curr->logicalTop();
616         int newLogicalTopIncludingMargins = newLogicalTop;
617         int boxHeight = curr->logicalHeight();
618         int boxHeightIncludingMargins = boxHeight;
619             
620         if (curr->isText() || curr->isInlineFlowBox()) {
621             const FontMetrics& fontMetrics = curr->renderer()->style(m_firstLine)->fontMetrics();
622             newLogicalTop += curr->baselinePosition(baselineType) - fontMetrics.ascent(baselineType);
623             if (curr->isInlineFlowBox()) {
624                 RenderBoxModelObject* boxObject = toRenderBoxModelObject(curr->renderer());
625                 newLogicalTop -= boxObject->style(m_firstLine)->isHorizontalWritingMode() ? boxObject->borderTop() + boxObject->paddingTop() : 
626                                  boxObject->borderRight() + boxObject->paddingRight();
627             }
628             newLogicalTopIncludingMargins = newLogicalTop;
629         } else if (!curr->renderer()->isBR()) {
630             RenderBox* box = toRenderBox(curr->renderer());
631             newLogicalTopIncludingMargins = newLogicalTop;
632             int overSideMargin = curr->isHorizontal() ? box->marginTop() : box->marginRight();
633             int underSideMargin = curr->isHorizontal() ? box->marginBottom() : box->marginLeft();
634             newLogicalTop += overSideMargin;
635             boxHeightIncludingMargins += overSideMargin + underSideMargin;
636         }
637
638         curr->setLogicalTop(newLogicalTop);
639
640         if (childAffectsTopBottomPos) {
641             if (curr->renderer()->isRubyRun()) {
642                 // Treat the leading on the first and last lines of ruby runs as not being part of the overall lineTop/lineBottom.
643                 // Really this is a workaround hack for the fact that ruby should have been done as line layout and not done using
644                 // inline-block.
645                 if (!renderer()->style()->isFlippedLinesWritingMode())
646                     hasAnnotationsBefore = true;
647                 else
648                     hasAnnotationsAfter = true;
649
650                 RenderRubyRun* rubyRun = static_cast<RenderRubyRun*>(curr->renderer());
651                 if (RenderRubyBase* rubyBase = rubyRun->rubyBase()) {
652                     int bottomRubyBaseLeading = (curr->logicalHeight() - rubyBase->logicalBottom()) + rubyBase->logicalHeight() - (rubyBase->lastRootBox() ? rubyBase->lastRootBox()->lineBottom() : 0);
653                     int topRubyBaseLeading = rubyBase->logicalTop() + (rubyBase->firstRootBox() ? rubyBase->firstRootBox()->lineTop() : 0);
654                     newLogicalTop += !renderer()->style()->isFlippedLinesWritingMode() ? topRubyBaseLeading : bottomRubyBaseLeading;
655                     boxHeight -= (topRubyBaseLeading + bottomRubyBaseLeading);
656                 }
657             }
658             if (curr->isInlineTextBox()) {
659                 TextEmphasisPosition emphasisMarkPosition;
660                 if (static_cast<InlineTextBox*>(curr)->getEmphasisMarkPosition(curr->renderer()->style(m_firstLine), emphasisMarkPosition)) {
661                     bool emphasisMarkIsOver = emphasisMarkPosition == TextEmphasisPositionOver;
662                     if (emphasisMarkIsOver != curr->renderer()->style(m_firstLine)->isFlippedLinesWritingMode())
663                         hasAnnotationsBefore = true;
664                     else
665                         hasAnnotationsAfter = true;
666                 }
667             }
668
669             if (!setLineTop) {
670                 setLineTop = true;
671                 lineTop = newLogicalTop;
672                 lineTopIncludingMargins = min(lineTop, newLogicalTopIncludingMargins);
673             } else {
674                 lineTop = min(lineTop, newLogicalTop);
675                 lineTopIncludingMargins = min(lineTop, min(lineTopIncludingMargins, newLogicalTopIncludingMargins));
676             }
677             lineBottom = max(lineBottom, newLogicalTop + boxHeight);
678             lineBottomIncludingMargins = max(lineBottom, max(lineBottomIncludingMargins, newLogicalTopIncludingMargins + boxHeightIncludingMargins));
679         }
680     }
681
682     if (isRootInlineBox()) {
683         const FontMetrics& fontMetrics = renderer()->style(m_firstLine)->fontMetrics();
684         setLogicalTop(logicalTop() + baselinePosition(baselineType) - fontMetrics.ascent(baselineType));
685         
686         if (hasTextChildren() || strictMode) {
687             if (!setLineTop) {
688                 setLineTop = true;
689                 lineTop = logicalTop();
690                 lineTopIncludingMargins = lineTop;
691             } else {
692                 lineTop = min(lineTop, logicalTop());
693                 lineTopIncludingMargins = min(lineTop, lineTopIncludingMargins);
694             }
695             lineBottom = max(lineBottom, logicalTop() + logicalHeight());
696             lineBottomIncludingMargins = max(lineBottom, lineBottomIncludingMargins);
697         }
698         
699         if (renderer()->style()->isFlippedLinesWritingMode())
700             flipLinesInBlockDirection(lineTopIncludingMargins, lineBottomIncludingMargins);
701     }
702 }
703
704 void InlineFlowBox::flipLinesInBlockDirection(int lineTop, int lineBottom)
705 {
706     // Flip the box on the line such that the top is now relative to the lineBottom instead of the lineTop.
707     setLogicalTop(lineBottom - (logicalTop() - lineTop) - logicalHeight());
708     
709     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
710         if (curr->renderer()->isPositioned())
711             continue; // Positioned placeholders aren't affected here.
712         
713         if (curr->isInlineFlowBox())
714             static_cast<InlineFlowBox*>(curr)->flipLinesInBlockDirection(lineTop, lineBottom);
715         else
716             curr->setLogicalTop(lineBottom - (curr->logicalTop() - lineTop) - curr->logicalHeight());
717     }
718 }
719
720 void InlineFlowBox::addBoxShadowVisualOverflow(IntRect& logicalVisualOverflow)
721 {
722     if (!parent())
723         return; // Box-shadow doesn't apply to root line boxes.
724
725     int boxShadowLogicalTop;
726     int boxShadowLogicalBottom;
727     renderer()->style(m_firstLine)->getBoxShadowBlockDirectionExtent(boxShadowLogicalTop, boxShadowLogicalBottom);
728     
729     int logicalTopVisualOverflow = min(logicalTop() + boxShadowLogicalTop, logicalVisualOverflow.y());
730     int logicalBottomVisualOverflow = max(logicalBottom() + boxShadowLogicalBottom, logicalVisualOverflow.maxY());
731     
732     int boxShadowLogicalLeft;
733     int boxShadowLogicalRight;
734     renderer()->style(m_firstLine)->getBoxShadowInlineDirectionExtent(boxShadowLogicalLeft, boxShadowLogicalRight);
735
736     int logicalLeftVisualOverflow = min(pixelSnappedLogicalLeft() + boxShadowLogicalLeft, logicalVisualOverflow.x());
737     int logicalRightVisualOverflow = max(pixelSnappedLogicalRight() + boxShadowLogicalRight, logicalVisualOverflow.maxX());
738     
739     logicalVisualOverflow = IntRect(logicalLeftVisualOverflow, logicalTopVisualOverflow,
740                                     logicalRightVisualOverflow - logicalLeftVisualOverflow, logicalBottomVisualOverflow - logicalTopVisualOverflow);
741 }
742
743 void InlineFlowBox::addTextBoxVisualOverflow(const InlineTextBox* textBox, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, IntRect& logicalVisualOverflow)
744 {
745     RenderStyle* style = renderer()->style(m_firstLine);
746     int strokeOverflow = static_cast<int>(ceilf(style->textStrokeWidth() / 2.0f));
747
748     GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.find(textBox);
749     GlyphOverflow* glyphOverflow = it == textBoxDataMap.end() ? 0 : &it->second.second;
750
751     bool isFlippedLine = style->isFlippedLinesWritingMode();
752
753     int topGlyphEdge = glyphOverflow ? (isFlippedLine ? glyphOverflow->bottom : glyphOverflow->top) : 0;
754     int bottomGlyphEdge = glyphOverflow ? (isFlippedLine ? glyphOverflow->top : glyphOverflow->bottom) : 0;
755     int leftGlyphEdge = glyphOverflow ? glyphOverflow->left : 0;
756     int rightGlyphEdge = glyphOverflow ? glyphOverflow->right : 0;
757
758     int topGlyphOverflow = -strokeOverflow - topGlyphEdge;
759     int bottomGlyphOverflow = strokeOverflow + bottomGlyphEdge;
760     int leftGlyphOverflow = -strokeOverflow - leftGlyphEdge;
761     int rightGlyphOverflow = strokeOverflow + rightGlyphEdge;
762
763     TextEmphasisPosition emphasisMarkPosition;
764     if (style->textEmphasisMark() != TextEmphasisMarkNone && textBox->getEmphasisMarkPosition(style, emphasisMarkPosition)) {
765         int emphasisMarkHeight = style->font().emphasisMarkHeight(style->textEmphasisMarkString());
766         if ((emphasisMarkPosition == TextEmphasisPositionOver) == (!style->isFlippedLinesWritingMode()))
767             topGlyphOverflow = min(topGlyphOverflow, -emphasisMarkHeight);
768         else
769             bottomGlyphOverflow = max(bottomGlyphOverflow, emphasisMarkHeight);
770     }
771
772     // If letter-spacing is negative, we should factor that into right layout overflow. (Even in RTL, letter-spacing is
773     // applied to the right, so this is not an issue with left overflow.
774     int letterSpacing = min(0, (int)style->font().letterSpacing());
775     rightGlyphOverflow -= letterSpacing;
776
777     int textShadowLogicalTop;
778     int textShadowLogicalBottom;
779     style->getTextShadowBlockDirectionExtent(textShadowLogicalTop, textShadowLogicalBottom);
780     
781     int childOverflowLogicalTop = min(textShadowLogicalTop + topGlyphOverflow, topGlyphOverflow);
782     int childOverflowLogicalBottom = max(textShadowLogicalBottom + bottomGlyphOverflow, bottomGlyphOverflow);
783    
784     int textShadowLogicalLeft;
785     int textShadowLogicalRight;
786     style->getTextShadowInlineDirectionExtent(textShadowLogicalLeft, textShadowLogicalRight);
787    
788     int childOverflowLogicalLeft = min(textShadowLogicalLeft + leftGlyphOverflow, leftGlyphOverflow);
789     int childOverflowLogicalRight = max(textShadowLogicalRight + rightGlyphOverflow, rightGlyphOverflow);
790
791     int logicalTopVisualOverflow = min(textBox->logicalTop() + childOverflowLogicalTop, logicalVisualOverflow.y());
792     int logicalBottomVisualOverflow = max(textBox->logicalBottom() + childOverflowLogicalBottom, logicalVisualOverflow.maxY());
793     int logicalLeftVisualOverflow = min(textBox->pixelSnappedLogicalLeft() + childOverflowLogicalLeft, logicalVisualOverflow.x());
794     int logicalRightVisualOverflow = max(textBox->pixelSnappedLogicalRight() + childOverflowLogicalRight, logicalVisualOverflow.maxX());
795     
796     logicalVisualOverflow = IntRect(logicalLeftVisualOverflow, logicalTopVisualOverflow,
797                                     logicalRightVisualOverflow - logicalLeftVisualOverflow, logicalBottomVisualOverflow - logicalTopVisualOverflow);
798 }
799
800 void InlineFlowBox::addReplacedChildOverflow(const InlineBox* inlineBox, IntRect& logicalLayoutOverflow, IntRect& logicalVisualOverflow)
801 {
802     RenderBox* box = toRenderBox(inlineBox->renderer());
803     
804     // Visual overflow only propagates if the box doesn't have a self-painting layer.  This rectangle does not include
805     // transforms or relative positioning (since those objects always have self-painting layers), but it does need to be adjusted
806     // for writing-mode differences.
807     if (!box->hasSelfPaintingLayer()) {
808         IntRect childLogicalVisualOverflow = box->logicalVisualOverflowRectForPropagation(renderer()->style());
809         childLogicalVisualOverflow.move(inlineBox->logicalLeft(), inlineBox->logicalTop());
810         logicalVisualOverflow.unite(childLogicalVisualOverflow);
811     }
812
813     // Layout overflow internal to the child box only propagates if the child box doesn't have overflow clip set.
814     // Otherwise the child border box propagates as layout overflow.  This rectangle must include transforms and relative positioning
815     // and be adjusted for writing-mode differences.
816     IntRect childLogicalLayoutOverflow = box->logicalLayoutOverflowRectForPropagation(renderer()->style());
817     childLogicalLayoutOverflow.move(inlineBox->logicalLeft(), inlineBox->logicalTop());
818     logicalLayoutOverflow.unite(childLogicalLayoutOverflow);
819 }
820
821 void InlineFlowBox::computeOverflow(int lineTop, int lineBottom, bool strictMode, GlyphOverflowAndFallbackFontsMap& textBoxDataMap)
822 {
823     // Any spillage outside of the line top and bottom is not considered overflow.  We just ignore this, since it only happens
824     // from the "your ascent/descent don't affect the line" quirk.
825     int topOverflow = max(logicalTop(), lineTop);
826     int bottomOverflow = min(logicalBottom(), lineBottom);
827     
828     // Visual overflow just includes overflow for stuff we need to repaint ourselves.  Self-painting layers are ignored.
829     // Layout overflow is used to determine scrolling extent, so it still includes child layers and also factors in
830     // transforms, relative positioning, etc.
831     IntRect logicalLayoutOverflow(enclosingIntRect(FloatRect(logicalLeft(), topOverflow, logicalWidth(), bottomOverflow - topOverflow)));
832     IntRect logicalVisualOverflow(logicalLayoutOverflow);
833   
834     // box-shadow on root line boxes is applying to the block and not to the lines.
835     addBoxShadowVisualOverflow(logicalVisualOverflow);
836
837     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
838         if (curr->renderer()->isPositioned())
839             continue; // Positioned placeholders don't affect calculations.
840         
841         if (curr->renderer()->isText()) {
842             InlineTextBox* text = static_cast<InlineTextBox*>(curr);
843             RenderText* rt = toRenderText(text->renderer());
844             if (rt->isBR())
845                 continue;
846             addTextBoxVisualOverflow(text, textBoxDataMap, logicalVisualOverflow);
847         } else  if (curr->renderer()->isRenderInline()) {
848             InlineFlowBox* flow = static_cast<InlineFlowBox*>(curr);
849             flow->computeOverflow(lineTop, lineBottom, strictMode, textBoxDataMap);
850             if (!flow->boxModelObject()->hasSelfPaintingLayer())
851                 logicalVisualOverflow.unite(flow->logicalVisualOverflowRect());
852             IntRect childLayoutOverflow = flow->logicalLayoutOverflowRect();
853             childLayoutOverflow.move(flow->boxModelObject()->relativePositionLogicalOffset());
854             logicalLayoutOverflow.unite(childLayoutOverflow);
855         } else
856             addReplacedChildOverflow(curr, logicalLayoutOverflow, logicalVisualOverflow);
857     }
858     
859     setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow);
860 }
861
862 // FIXME: You will notice there is no contains() check here.  If the rect is smaller than the frame box it actually
863 // becomes the new overflow.  The reason for this is that in quirks mode we don't let inline flow boxes paint
864 // outside of the root line box's lineTop and lineBottom values.  We accomplish this visual clamping by actually
865 // insetting the overflow rect so that it's smaller than the frame rect.
866 //
867 // The reason we don't just mutate the frameRect in quirks mode is that we'd have to put the m_height member variable
868 // back into InlineBox.  Basically the tradeoff is 4 bytes in all modes (for m_height) added to InlineFlowBox, or
869 // the allocation of a RenderOverflow struct for InlineFlowBoxes in quirks mode only.  For now, we're opting to award
870 // the smaller memory consumption to strict mode pages.
871 //
872 // It might be possible to hash a custom height, or to require that lineTop and lineBottom be passed in to
873 // all functions that query overflow.   
874 void InlineFlowBox::setLayoutOverflow(const IntRect& rect)
875 {
876     IntRect frameBox = enclosingIntRect(FloatRect(x(), y(), width(), height()));
877     if (frameBox == rect || rect.isEmpty())
878         return;
879         
880     if (!m_overflow)
881         m_overflow.set(new RenderOverflow(frameBox, frameBox));
882     
883     m_overflow->setLayoutOverflow(rect);
884 }
885
886 void InlineFlowBox::setVisualOverflow(const IntRect& rect)
887 {
888     IntRect frameBox = enclosingIntRect(FloatRect(x(), y(), width(), height()));
889     if (frameBox == rect || rect.isEmpty())
890         return;
891         
892     if (!m_overflow)
893         m_overflow.set(new RenderOverflow(frameBox, frameBox));
894     
895     m_overflow->setVisualOverflow(rect);
896 }
897
898 void InlineFlowBox::setOverflowFromLogicalRects(const IntRect& logicalLayoutOverflow, const IntRect& logicalVisualOverflow)
899 {
900     IntRect layoutOverflow(isHorizontal() ? logicalLayoutOverflow : logicalLayoutOverflow.transposedRect());
901     setLayoutOverflow(layoutOverflow);
902     
903     IntRect visualOverflow(isHorizontal() ? logicalVisualOverflow : logicalVisualOverflow.transposedRect());
904     setVisualOverflow(visualOverflow);
905 }
906
907 bool InlineFlowBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, int x, int y, int tx, int ty)
908 {
909     IntRect overflowRect(visualOverflowRect());
910     flipForWritingMode(overflowRect);
911     overflowRect.move(tx, ty);
912     if (!overflowRect.intersects(result.rectForPoint(x, y)))
913         return false;
914
915     // Check children first.
916     for (InlineBox* curr = lastChild(); curr; curr = curr->prevOnLine()) {
917         if ((curr->renderer()->isText() || !curr->boxModelObject()->hasSelfPaintingLayer()) && curr->nodeAtPoint(request, result, x, y, tx, ty)) {
918             renderer()->updateHitTestResult(result, IntPoint(x - tx, y - ty));
919             return true;
920         }
921     }
922
923     // Now check ourselves.
924     FloatPoint boxOrigin = locationIncludingFlipping();
925     boxOrigin.move(tx, ty);
926     FloatRect rect(boxOrigin, IntSize(width(), height()));
927     if (visibleToHitTesting() && rect.intersects(result.rectForPoint(x, y))) {
928         renderer()->updateHitTestResult(result, flipForWritingMode(IntPoint(x - tx, y - ty))); // Don't add in m_x or m_y here, we want coords in the containing block's space.
929         if (!result.addNodeToRectBasedTestResult(renderer()->node(), x, y, rect))
930             return true;
931     }
932     
933     return false;
934 }
935
936 void InlineFlowBox::paint(PaintInfo& paintInfo, int tx, int ty)
937 {
938     IntRect overflowRect(visualOverflowRect());
939     overflowRect.inflate(renderer()->maximalOutlineSize(paintInfo.phase));
940     flipForWritingMode(overflowRect);
941     overflowRect.move(tx, ty);
942     
943     if (!paintInfo.rect.intersects(overflowRect))
944         return;
945
946     if (paintInfo.phase != PaintPhaseChildOutlines) {
947         if (paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) {
948             // Add ourselves to the paint info struct's list of inlines that need to paint their
949             // outlines.
950             if (renderer()->style()->visibility() == VISIBLE && renderer()->hasOutline() && !isRootInlineBox()) {
951                 RenderInline* inlineFlow = toRenderInline(renderer());
952
953                 RenderBlock* cb = 0;
954                 bool containingBlockPaintsContinuationOutline = inlineFlow->continuation() || inlineFlow->isInlineElementContinuation();
955                 if (containingBlockPaintsContinuationOutline) {           
956                     // FIXME: See https://bugs.webkit.org/show_bug.cgi?id=54690. We currently don't reconnect inline continuations
957                     // after a child removal. As a result, those merged inlines do not get seperated and hence not get enclosed by
958                     // anonymous blocks. In this case, it is better to bail out and paint it ourself.
959                     RenderBlock* enclosingAnonymousBlock = renderer()->containingBlock();
960                     if (!enclosingAnonymousBlock->isAnonymousBlock())
961                         containingBlockPaintsContinuationOutline = false;
962                     else {
963                         cb = enclosingAnonymousBlock->containingBlock();
964                         for (RenderBoxModelObject* box = boxModelObject(); box != cb; box = box->parent()->enclosingBoxModelObject()) {
965                             if (box->hasSelfPaintingLayer()) {
966                                 containingBlockPaintsContinuationOutline = false;
967                                 break;
968                             }
969                         }
970                     }
971                 }
972
973                 if (containingBlockPaintsContinuationOutline) {
974                     // Add ourselves to the containing block of the entire continuation so that it can
975                     // paint us atomically.
976                     cb->addContinuationWithOutline(toRenderInline(renderer()->node()->renderer()));
977                 } else if (!inlineFlow->isInlineElementContinuation())
978                     paintInfo.outlineObjects->add(inlineFlow);
979             }
980         } else if (paintInfo.phase == PaintPhaseMask) {
981             paintMask(paintInfo, tx, ty);
982             return;
983         } else {
984             // Paint our background, border and box-shadow.
985             paintBoxDecorations(paintInfo, tx, ty);
986         }
987     }
988
989     if (paintInfo.phase == PaintPhaseMask)
990         return;
991
992     PaintPhase paintPhase = paintInfo.phase == PaintPhaseChildOutlines ? PaintPhaseOutline : paintInfo.phase;
993     PaintInfo childInfo(paintInfo);
994     childInfo.phase = paintPhase;
995     childInfo.updatePaintingRootForChildren(renderer());
996     
997     // Paint our children.
998     if (paintPhase != PaintPhaseSelfOutline) {
999         for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
1000             if (curr->renderer()->isText() || !curr->boxModelObject()->hasSelfPaintingLayer())
1001                 curr->paint(childInfo, tx, ty);
1002         }
1003     }
1004 }
1005
1006 void InlineFlowBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, int _tx, int _ty, int w, int h, CompositeOperator op)
1007 {
1008     if (!fillLayer)
1009         return;
1010     paintFillLayers(paintInfo, c, fillLayer->next(), _tx, _ty, w, h, op);
1011     paintFillLayer(paintInfo, c, fillLayer, _tx, _ty, w, h, op);
1012 }
1013
1014 void InlineFlowBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, int tx, int ty, int w, int h, CompositeOperator op)
1015 {
1016     StyleImage* img = fillLayer->image();
1017     bool hasFillImage = img && img->canRender(renderer()->style()->effectiveZoom());
1018     if ((!hasFillImage && !renderer()->style()->hasBorderRadius()) || (!prevLineBox() && !nextLineBox()) || !parent())
1019         boxModelObject()->paintFillLayerExtended(paintInfo, c, fillLayer, tx, ty, w, h, this, op);
1020     else {
1021         // We have a fill image that spans multiple lines.
1022         // We need to adjust tx and ty by the width of all previous lines.
1023         // Think of background painting on inlines as though you had one long line, a single continuous
1024         // strip.  Even though that strip has been broken up across multiple lines, you still paint it
1025         // as though you had one single line.  This means each line has to pick up the background where
1026         // the previous line left off.
1027         int logicalOffsetOnLine = 0;
1028         int totalLogicalWidth;
1029         if (renderer()->style()->direction() == LTR) {
1030             for (InlineFlowBox* curr = prevLineBox(); curr; curr = curr->prevLineBox())
1031                 logicalOffsetOnLine += curr->logicalWidth();
1032             totalLogicalWidth = logicalOffsetOnLine;
1033             for (InlineFlowBox* curr = this; curr; curr = curr->nextLineBox())
1034                 totalLogicalWidth += curr->logicalWidth();
1035         } else {
1036             for (InlineFlowBox* curr = nextLineBox(); curr; curr = curr->nextLineBox())
1037                 logicalOffsetOnLine += curr->logicalWidth();
1038             totalLogicalWidth = logicalOffsetOnLine;
1039             for (InlineFlowBox* curr = this; curr; curr = curr->prevLineBox())
1040                 totalLogicalWidth += curr->logicalWidth();
1041         }
1042         int stripX = tx - (isHorizontal() ? logicalOffsetOnLine : 0);
1043         int stripY = ty - (isHorizontal() ? 0 : logicalOffsetOnLine);
1044         int stripWidth = isHorizontal() ? totalLogicalWidth : width();
1045         int stripHeight = isHorizontal() ? height() : totalLogicalWidth;
1046         paintInfo.context->save();
1047         paintInfo.context->clip(IntRect(tx, ty, width(), height()));
1048         boxModelObject()->paintFillLayerExtended(paintInfo, c, fillLayer, stripX, stripY, stripWidth, stripHeight, this, op);
1049         paintInfo.context->restore();
1050     }
1051 }
1052
1053 void InlineFlowBox::paintBoxShadow(GraphicsContext* context, RenderStyle* s, ShadowStyle shadowStyle, int tx, int ty, int w, int h)
1054 {
1055     if ((!prevLineBox() && !nextLineBox()) || !parent())
1056         boxModelObject()->paintBoxShadow(context, tx, ty, w, h, s, shadowStyle);
1057     else {
1058         // FIXME: We can do better here in the multi-line case. We want to push a clip so that the shadow doesn't
1059         // protrude incorrectly at the edges, and we want to possibly include shadows cast from the previous/following lines
1060         boxModelObject()->paintBoxShadow(context, tx, ty, w, h, s, shadowStyle, includeLogicalLeftEdge(), includeLogicalRightEdge());
1061     }
1062 }
1063
1064 void InlineFlowBox::paintBoxDecorations(PaintInfo& paintInfo, int tx, int ty)
1065 {
1066     if (!paintInfo.shouldPaintWithinRoot(renderer()) || renderer()->style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseForeground)
1067         return;
1068
1069     // Pixel snap background/border painting.
1070     IntRect frameRect = roundedFrameRect();
1071     int x = frameRect.x();
1072     int y = frameRect.y();
1073     int w = frameRect.width();
1074     int h = frameRect.height();
1075
1076     // Constrain our background/border painting to the line top and bottom if necessary.
1077     bool noQuirksMode = renderer()->document()->inNoQuirksMode();
1078     if (!hasTextChildren() && !noQuirksMode) {
1079         RootInlineBox* rootBox = root();
1080         int& top = isHorizontal() ? y : x;
1081         int& logicalHeight = isHorizontal() ? h : w;
1082         int bottom = min(rootBox->lineBottom(), top + logicalHeight);
1083         top = max(rootBox->lineTop(), top);
1084         logicalHeight = bottom - top;
1085     }
1086     
1087     // Move x/y to our coordinates.
1088     IntRect localRect(x, y, w, h);
1089     flipForWritingMode(localRect);
1090     tx += localRect.x();
1091     ty += localRect.y();
1092     
1093     GraphicsContext* context = paintInfo.context;
1094     
1095     // You can use p::first-line to specify a background. If so, the root line boxes for
1096     // a line may actually have to paint a background.
1097     RenderStyle* styleToUse = renderer()->style(m_firstLine);
1098     if ((!parent() && m_firstLine && styleToUse != renderer()->style()) || (parent() && renderer()->hasBoxDecorations())) {
1099         // Shadow comes first and is behind the background and border.
1100         paintBoxShadow(context, styleToUse, Normal, tx, ty, w, h);
1101
1102         Color c = styleToUse->visitedDependentColor(CSSPropertyBackgroundColor);
1103         paintFillLayers(paintInfo, c, styleToUse->backgroundLayers(), tx, ty, w, h);
1104         paintBoxShadow(context, styleToUse, Inset, tx, ty, w, h);
1105
1106         // :first-line cannot be used to put borders on a line. Always paint borders with our
1107         // non-first-line style.
1108         if (parent() && renderer()->style()->hasBorder()) {
1109             StyleImage* borderImage = renderer()->style()->borderImage().image();
1110             bool hasBorderImage = borderImage && borderImage->canRender(styleToUse->effectiveZoom());
1111             if (hasBorderImage && !borderImage->isLoaded())
1112                 return; // Don't paint anything while we wait for the image to load.
1113
1114             // The simple case is where we either have no border image or we are the only box for this object.  In those
1115             // cases only a single call to draw is required.
1116             if (!hasBorderImage || (!prevLineBox() && !nextLineBox()))
1117                 boxModelObject()->paintBorder(context, tx, ty, w, h, renderer()->style(), includeLogicalLeftEdge(), includeLogicalRightEdge());
1118             else {
1119                 // We have a border image that spans multiple lines.
1120                 // We need to adjust tx and ty by the width of all previous lines.
1121                 // Think of border image painting on inlines as though you had one long line, a single continuous
1122                 // strip.  Even though that strip has been broken up across multiple lines, you still paint it
1123                 // as though you had one single line.  This means each line has to pick up the image where
1124                 // the previous line left off.
1125                 // FIXME: What the heck do we do with RTL here? The math we're using is obviously not right,
1126                 // but it isn't even clear how this should work at all.
1127                 int logicalOffsetOnLine = 0;
1128                 for (InlineFlowBox* curr = prevLineBox(); curr; curr = curr->prevLineBox())
1129                     logicalOffsetOnLine += curr->logicalWidth();
1130                 int totalLogicalWidth = logicalOffsetOnLine;
1131                 for (InlineFlowBox* curr = this; curr; curr = curr->nextLineBox())
1132                     totalLogicalWidth += curr->logicalWidth();
1133                 int stripX = tx - (isHorizontal() ? logicalOffsetOnLine : 0);
1134                 int stripY = ty - (isHorizontal() ? 0 : logicalOffsetOnLine);
1135                 int stripWidth = isHorizontal() ? totalLogicalWidth : w;
1136                 int stripHeight = isHorizontal() ? h : totalLogicalWidth;
1137                 context->save();
1138                 context->clip(IntRect(tx, ty, w, h));
1139                 boxModelObject()->paintBorder(context, stripX, stripY, stripWidth, stripHeight, renderer()->style());
1140                 context->restore();
1141             }
1142         }
1143     }
1144 }
1145
1146 void InlineFlowBox::paintMask(PaintInfo& paintInfo, int tx, int ty)
1147 {
1148     if (!paintInfo.shouldPaintWithinRoot(renderer()) || renderer()->style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask)
1149         return;
1150
1151     // Pixel snap mask painting.
1152     IntRect frameRect = roundedFrameRect();
1153     int x = frameRect.x();
1154     int y = frameRect.y();
1155     int w = frameRect.width();
1156     int h = frameRect.height();
1157
1158     // Constrain our background/border painting to the line top and bottom if necessary.
1159     bool noQuirksMode = renderer()->document()->inNoQuirksMode();
1160     if (!hasTextChildren() && !noQuirksMode) {
1161         RootInlineBox* rootBox = root();
1162         int& top = isHorizontal() ? y : x;
1163         int& logicalHeight = isHorizontal() ? h : w;
1164         int bottom = min(rootBox->lineBottom(), top + logicalHeight);
1165         top = max(rootBox->lineTop(), top);
1166         logicalHeight = bottom - top;
1167     }
1168     
1169     // Move x/y to our coordinates.
1170     IntRect localRect(x, y, w, h);
1171     flipForWritingMode(localRect);
1172     tx += localRect.x();
1173     ty += localRect.y();
1174
1175     const NinePieceImage& maskNinePieceImage = renderer()->style()->maskBoxImage();
1176     StyleImage* maskBoxImage = renderer()->style()->maskBoxImage().image();
1177
1178     // Figure out if we need to push a transparency layer to render our mask.
1179     bool pushTransparencyLayer = false;
1180     bool compositedMask = renderer()->hasLayer() && boxModelObject()->layer()->hasCompositedMask();
1181     CompositeOperator compositeOp = CompositeSourceOver;
1182     if (!compositedMask) {
1183         if ((maskBoxImage && renderer()->style()->maskLayers()->hasImage()) || renderer()->style()->maskLayers()->next())
1184             pushTransparencyLayer = true;
1185         
1186         compositeOp = CompositeDestinationIn;
1187         if (pushTransparencyLayer) {
1188             paintInfo.context->setCompositeOperation(CompositeDestinationIn);
1189             paintInfo.context->beginTransparencyLayer(1.0f);
1190             compositeOp = CompositeSourceOver;
1191         }
1192     }
1193
1194     paintFillLayers(paintInfo, Color(), renderer()->style()->maskLayers(), tx, ty, w, h, compositeOp);
1195     
1196     bool hasBoxImage = maskBoxImage && maskBoxImage->canRender(renderer()->style()->effectiveZoom());
1197     if (!hasBoxImage || !maskBoxImage->isLoaded())
1198         return; // Don't paint anything while we wait for the image to load.
1199
1200     // The simple case is where we are the only box for this object.  In those
1201     // cases only a single call to draw is required.
1202     if (!prevLineBox() && !nextLineBox()) {
1203         boxModelObject()->paintNinePieceImage(paintInfo.context, tx, ty, w, h, renderer()->style(), maskNinePieceImage, compositeOp);
1204     } else {
1205         // We have a mask image that spans multiple lines.
1206         // We need to adjust _tx and _ty by the width of all previous lines.
1207         int logicalOffsetOnLine = 0;
1208         for (InlineFlowBox* curr = prevLineBox(); curr; curr = curr->prevLineBox())
1209             logicalOffsetOnLine += curr->logicalWidth();
1210         int totalLogicalWidth = logicalOffsetOnLine;
1211         for (InlineFlowBox* curr = this; curr; curr = curr->nextLineBox())
1212             totalLogicalWidth += curr->logicalWidth();
1213         int stripX = tx - (isHorizontal() ? logicalOffsetOnLine : 0);
1214         int stripY = ty - (isHorizontal() ? 0 : logicalOffsetOnLine);
1215         int stripWidth = isHorizontal() ? totalLogicalWidth : w;
1216         int stripHeight = isHorizontal() ? h : totalLogicalWidth;
1217         paintInfo.context->save();
1218         paintInfo.context->clip(IntRect(tx, ty, w, h));
1219         boxModelObject()->paintNinePieceImage(paintInfo.context, stripX, stripY, stripWidth, stripHeight, renderer()->style(), maskNinePieceImage, compositeOp);
1220         paintInfo.context->restore();
1221     }
1222     
1223     if (pushTransparencyLayer)
1224         paintInfo.context->endTransparencyLayer();
1225 }
1226
1227 InlineBox* InlineFlowBox::firstLeafChild() const
1228 {
1229     InlineBox* leaf = 0;
1230     for (InlineBox* child = firstChild(); child && !leaf; child = child->nextOnLine())
1231         leaf = child->isLeaf() ? child : static_cast<InlineFlowBox*>(child)->firstLeafChild();
1232     return leaf;
1233 }
1234
1235 InlineBox* InlineFlowBox::lastLeafChild() const
1236 {
1237     InlineBox* leaf = 0;
1238     for (InlineBox* child = lastChild(); child && !leaf; child = child->prevOnLine())
1239         leaf = child->isLeaf() ? child : static_cast<InlineFlowBox*>(child)->lastLeafChild();
1240     return leaf;
1241 }
1242
1243 RenderObject::SelectionState InlineFlowBox::selectionState()
1244 {
1245     return RenderObject::SelectionNone;
1246 }
1247
1248 bool InlineFlowBox::canAccommodateEllipsis(bool ltr, int blockEdge, int ellipsisWidth)
1249 {
1250     for (InlineBox *box = firstChild(); box; box = box->nextOnLine()) {
1251         if (!box->canAccommodateEllipsis(ltr, blockEdge, ellipsisWidth))
1252             return false;
1253     }
1254     return true;
1255 }
1256
1257 float InlineFlowBox::placeEllipsisBox(bool ltr, float blockLeftEdge, float blockRightEdge, float ellipsisWidth, bool& foundBox)
1258 {
1259     float result = -1;
1260     // We iterate over all children, the foundBox variable tells us when we've found the
1261     // box containing the ellipsis.  All boxes after that one in the flow are hidden.
1262     // If our flow is ltr then iterate over the boxes from left to right, otherwise iterate
1263     // from right to left. Varying the order allows us to correctly hide the boxes following the ellipsis.
1264     InlineBox* box = ltr ? firstChild() : lastChild();
1265
1266     // NOTE: these will cross after foundBox = true.
1267     int visibleLeftEdge = blockLeftEdge;
1268     int visibleRightEdge = blockRightEdge;
1269
1270     while (box) {
1271         int currResult = box->placeEllipsisBox(ltr, visibleLeftEdge, visibleRightEdge, ellipsisWidth, foundBox);
1272         if (currResult != -1 && result == -1)
1273             result = currResult;
1274
1275         if (ltr) {
1276             visibleLeftEdge += box->logicalWidth();
1277             box = box->nextOnLine();
1278         }
1279         else {
1280             visibleRightEdge -= box->logicalWidth();
1281             box = box->prevOnLine();
1282         }
1283     }
1284     return result;
1285 }
1286
1287 void InlineFlowBox::clearTruncation()
1288 {
1289     for (InlineBox *box = firstChild(); box; box = box->nextOnLine())
1290         box->clearTruncation();
1291 }
1292
1293 int InlineFlowBox::computeOverAnnotationAdjustment(int allowedPosition) const
1294 {
1295     int result = 0;
1296     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
1297         if (curr->renderer()->isPositioned())
1298             continue; // Positioned placeholders don't affect calculations.
1299         
1300         if (curr->isInlineFlowBox())
1301             result = max(result, static_cast<InlineFlowBox*>(curr)->computeOverAnnotationAdjustment(allowedPosition));
1302         
1303         if (curr->renderer()->isReplaced() && curr->renderer()->isRubyRun()) {
1304             RenderRubyRun* rubyRun = static_cast<RenderRubyRun*>(curr->renderer());
1305             RenderRubyText* rubyText = rubyRun->rubyText();
1306             if (!rubyText)
1307                 continue;
1308             
1309             if (!rubyRun->style()->isFlippedLinesWritingMode()) {
1310                 int topOfFirstRubyTextLine = rubyText->logicalTop() + (rubyText->firstRootBox() ? rubyText->firstRootBox()->lineTop() : 0);
1311                 if (topOfFirstRubyTextLine >= 0)
1312                     continue;
1313                 topOfFirstRubyTextLine += curr->logicalTop();
1314                 result = max(result, allowedPosition - topOfFirstRubyTextLine);
1315             } else {
1316                 int bottomOfLastRubyTextLine = rubyText->logicalTop() + (rubyText->lastRootBox() ? rubyText->lastRootBox()->lineBottom() : rubyText->logicalHeight());
1317                 if (bottomOfLastRubyTextLine <= curr->logicalHeight())
1318                     continue;
1319                 bottomOfLastRubyTextLine += curr->logicalTop();
1320                 result = max(result, bottomOfLastRubyTextLine - allowedPosition);
1321             }
1322         }
1323
1324         if (curr->isInlineTextBox()) {
1325             RenderStyle* style = curr->renderer()->style(m_firstLine);
1326             TextEmphasisPosition emphasisMarkPosition;
1327             if (style->textEmphasisMark() != TextEmphasisMarkNone && static_cast<InlineTextBox*>(curr)->getEmphasisMarkPosition(style, emphasisMarkPosition) && emphasisMarkPosition == TextEmphasisPositionOver) {
1328                 if (!style->isFlippedLinesWritingMode()) {
1329                     int topOfEmphasisMark = curr->logicalTop() - style->font().emphasisMarkHeight(style->textEmphasisMarkString());
1330                     result = max(result, allowedPosition - topOfEmphasisMark);
1331                 } else {
1332                     int bottomOfEmphasisMark = curr->logicalBottom() + style->font().emphasisMarkHeight(style->textEmphasisMarkString());
1333                     result = max(result, bottomOfEmphasisMark - allowedPosition);
1334                 }
1335             }
1336         }
1337     }
1338     return result;
1339 }
1340
1341 int InlineFlowBox::computeUnderAnnotationAdjustment(int allowedPosition) const
1342 {
1343     int result = 0;
1344     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
1345         if (curr->renderer()->isPositioned())
1346             continue; // Positioned placeholders don't affect calculations.
1347
1348         if (curr->isInlineFlowBox())
1349             result = max(result, static_cast<InlineFlowBox*>(curr)->computeUnderAnnotationAdjustment(allowedPosition));
1350
1351         if (curr->isInlineTextBox()) {
1352             RenderStyle* style = curr->renderer()->style(m_firstLine);
1353             if (style->textEmphasisMark() != TextEmphasisMarkNone && style->textEmphasisPosition() == TextEmphasisPositionUnder) {
1354                 if (!style->isFlippedLinesWritingMode()) {
1355                     int bottomOfEmphasisMark = curr->logicalBottom() + style->font().emphasisMarkHeight(style->textEmphasisMarkString());
1356                     result = max(result, bottomOfEmphasisMark - allowedPosition);
1357                 } else {
1358                     int topOfEmphasisMark = curr->logicalTop() - style->font().emphasisMarkHeight(style->textEmphasisMarkString());
1359                     result = max(result, allowedPosition - topOfEmphasisMark);
1360                 }
1361             }
1362         }
1363     }
1364     return result;
1365 }
1366
1367 #ifndef NDEBUG
1368
1369 void InlineFlowBox::checkConsistency() const
1370 {
1371 #ifdef CHECK_CONSISTENCY
1372     ASSERT(!m_hasBadChildList);
1373     const InlineBox* prev = 0;
1374     for (const InlineBox* child = m_firstChild; child; child = child->nextOnLine()) {
1375         ASSERT(child->parent() == this);
1376         ASSERT(child->prevOnLine() == prev);
1377         prev = child;
1378     }
1379     ASSERT(prev == m_lastChild);
1380 #endif
1381 }
1382
1383 #endif
1384
1385 } // namespace WebCore