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