https://bugs.webkit.org/show_bug.cgi?id=45164
[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. Pixel snap hit testing.
924     IntRect frameRect = roundedFrameRect();
925     int minX = frameRect.x();
926     int minY = frameRect.y();
927     int width = frameRect.width();
928     int height = frameRect.height();
929
930     // Constrain our hit testing to the line top and bottom if necessary.
931     bool noQuirksMode = renderer()->document()->inNoQuirksMode();
932     if (!hasTextChildren() && !noQuirksMode) {
933         RootInlineBox* rootBox = root();
934         int& top = isHorizontal() ? minY : minX;
935         int& logicalHeight = isHorizontal() ? height : width;
936         int bottom = min(rootBox->lineBottom(), top + logicalHeight);
937         top = max(rootBox->lineTop(), top);
938         logicalHeight = bottom - top;
939     }
940     
941     // Move x/y to our coordinates.
942     IntRect rect(minX, minY, width, height);
943     flipForWritingMode(rect);
944     rect.move(tx, ty);
945
946     if (visibleToHitTesting() && rect.intersects(result.rectForPoint(x, y))) {
947         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.
948         if (!result.addNodeToRectBasedTestResult(renderer()->node(), x, y, rect))
949             return true;
950     }
951     
952     return false;
953 }
954
955 void InlineFlowBox::paint(PaintInfo& paintInfo, int tx, int ty)
956 {
957     IntRect overflowRect(visualOverflowRect());
958     overflowRect.inflate(renderer()->maximalOutlineSize(paintInfo.phase));
959     flipForWritingMode(overflowRect);
960     overflowRect.move(tx, ty);
961     
962     if (!paintInfo.rect.intersects(overflowRect))
963         return;
964
965     if (paintInfo.phase != PaintPhaseChildOutlines) {
966         if (paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) {
967             // Add ourselves to the paint info struct's list of inlines that need to paint their
968             // outlines.
969             if (renderer()->style()->visibility() == VISIBLE && renderer()->hasOutline() && !isRootInlineBox()) {
970                 RenderInline* inlineFlow = toRenderInline(renderer());
971
972                 RenderBlock* cb = 0;
973                 bool containingBlockPaintsContinuationOutline = inlineFlow->continuation() || inlineFlow->isInlineElementContinuation();
974                 if (containingBlockPaintsContinuationOutline) {           
975                     // FIXME: See https://bugs.webkit.org/show_bug.cgi?id=54690. We currently don't reconnect inline continuations
976                     // after a child removal. As a result, those merged inlines do not get seperated and hence not get enclosed by
977                     // anonymous blocks. In this case, it is better to bail out and paint it ourself.
978                     RenderBlock* enclosingAnonymousBlock = renderer()->containingBlock();
979                     if (!enclosingAnonymousBlock->isAnonymousBlock())
980                         containingBlockPaintsContinuationOutline = false;
981                     else {
982                         cb = enclosingAnonymousBlock->containingBlock();
983                         for (RenderBoxModelObject* box = boxModelObject(); box != cb; box = box->parent()->enclosingBoxModelObject()) {
984                             if (box->hasSelfPaintingLayer()) {
985                                 containingBlockPaintsContinuationOutline = false;
986                                 break;
987                             }
988                         }
989                     }
990                 }
991
992                 if (containingBlockPaintsContinuationOutline) {
993                     // Add ourselves to the containing block of the entire continuation so that it can
994                     // paint us atomically.
995                     cb->addContinuationWithOutline(toRenderInline(renderer()->node()->renderer()));
996                 } else if (!inlineFlow->isInlineElementContinuation())
997                     paintInfo.outlineObjects->add(inlineFlow);
998             }
999         } else if (paintInfo.phase == PaintPhaseMask) {
1000             paintMask(paintInfo, tx, ty);
1001             return;
1002         } else {
1003             // Paint our background, border and box-shadow.
1004             paintBoxDecorations(paintInfo, tx, ty);
1005         }
1006     }
1007
1008     if (paintInfo.phase == PaintPhaseMask)
1009         return;
1010
1011     PaintPhase paintPhase = paintInfo.phase == PaintPhaseChildOutlines ? PaintPhaseOutline : paintInfo.phase;
1012     PaintInfo childInfo(paintInfo);
1013     childInfo.phase = paintPhase;
1014     childInfo.updatePaintingRootForChildren(renderer());
1015     
1016     // Paint our children.
1017     if (paintPhase != PaintPhaseSelfOutline) {
1018         for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
1019             if (curr->renderer()->isText() || !curr->boxModelObject()->hasSelfPaintingLayer())
1020                 curr->paint(childInfo, tx, ty);
1021         }
1022     }
1023 }
1024
1025 void InlineFlowBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, int _tx, int _ty, int w, int h, CompositeOperator op)
1026 {
1027     if (!fillLayer)
1028         return;
1029     paintFillLayers(paintInfo, c, fillLayer->next(), _tx, _ty, w, h, op);
1030     paintFillLayer(paintInfo, c, fillLayer, _tx, _ty, w, h, op);
1031 }
1032
1033 void InlineFlowBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, int tx, int ty, int w, int h, CompositeOperator op)
1034 {
1035     StyleImage* img = fillLayer->image();
1036     bool hasFillImage = img && img->canRender(renderer()->style()->effectiveZoom());
1037     if ((!hasFillImage && !renderer()->style()->hasBorderRadius()) || (!prevLineBox() && !nextLineBox()) || !parent())
1038         boxModelObject()->paintFillLayerExtended(paintInfo, c, fillLayer, tx, ty, w, h, this, op);
1039     else {
1040         // We have a fill image that spans multiple lines.
1041         // We need to adjust tx and ty by the width of all previous lines.
1042         // Think of background painting on inlines as though you had one long line, a single continuous
1043         // strip.  Even though that strip has been broken up across multiple lines, you still paint it
1044         // as though you had one single line.  This means each line has to pick up the background where
1045         // the previous line left off.
1046         int logicalOffsetOnLine = 0;
1047         int totalLogicalWidth;
1048         if (renderer()->style()->direction() == LTR) {
1049             for (InlineFlowBox* curr = prevLineBox(); curr; curr = curr->prevLineBox())
1050                 logicalOffsetOnLine += curr->logicalWidth();
1051             totalLogicalWidth = logicalOffsetOnLine;
1052             for (InlineFlowBox* curr = this; curr; curr = curr->nextLineBox())
1053                 totalLogicalWidth += curr->logicalWidth();
1054         } else {
1055             for (InlineFlowBox* curr = nextLineBox(); curr; curr = curr->nextLineBox())
1056                 logicalOffsetOnLine += curr->logicalWidth();
1057             totalLogicalWidth = logicalOffsetOnLine;
1058             for (InlineFlowBox* curr = this; curr; curr = curr->prevLineBox())
1059                 totalLogicalWidth += curr->logicalWidth();
1060         }
1061         int stripX = tx - (isHorizontal() ? logicalOffsetOnLine : 0);
1062         int stripY = ty - (isHorizontal() ? 0 : logicalOffsetOnLine);
1063         int stripWidth = isHorizontal() ? totalLogicalWidth : width();
1064         int stripHeight = isHorizontal() ? height() : totalLogicalWidth;
1065         paintInfo.context->save();
1066         paintInfo.context->clip(IntRect(tx, ty, width(), height()));
1067         boxModelObject()->paintFillLayerExtended(paintInfo, c, fillLayer, stripX, stripY, stripWidth, stripHeight, this, op);
1068         paintInfo.context->restore();
1069     }
1070 }
1071
1072 void InlineFlowBox::paintBoxShadow(GraphicsContext* context, RenderStyle* s, ShadowStyle shadowStyle, int tx, int ty, int w, int h)
1073 {
1074     if ((!prevLineBox() && !nextLineBox()) || !parent())
1075         boxModelObject()->paintBoxShadow(context, tx, ty, w, h, s, shadowStyle);
1076     else {
1077         // FIXME: We can do better here in the multi-line case. We want to push a clip so that the shadow doesn't
1078         // protrude incorrectly at the edges, and we want to possibly include shadows cast from the previous/following lines
1079         boxModelObject()->paintBoxShadow(context, tx, ty, w, h, s, shadowStyle, includeLogicalLeftEdge(), includeLogicalRightEdge());
1080     }
1081 }
1082
1083 void InlineFlowBox::paintBoxDecorations(PaintInfo& paintInfo, int tx, int ty)
1084 {
1085     if (!paintInfo.shouldPaintWithinRoot(renderer()) || renderer()->style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseForeground)
1086         return;
1087
1088     // Pixel snap background/border painting.
1089     IntRect frameRect = roundedFrameRect();
1090     int x = frameRect.x();
1091     int y = frameRect.y();
1092     int w = frameRect.width();
1093     int h = frameRect.height();
1094
1095     // Constrain our background/border painting to the line top and bottom if necessary.
1096     bool noQuirksMode = renderer()->document()->inNoQuirksMode();
1097     if (!hasTextChildren() && !noQuirksMode) {
1098         RootInlineBox* rootBox = root();
1099         int& top = isHorizontal() ? y : x;
1100         int& logicalHeight = isHorizontal() ? h : w;
1101         int bottom = min(rootBox->lineBottom(), top + logicalHeight);
1102         top = max(rootBox->lineTop(), top);
1103         logicalHeight = bottom - top;
1104     }
1105     
1106     // Move x/y to our coordinates.
1107     IntRect localRect(x, y, w, h);
1108     flipForWritingMode(localRect);
1109     tx += localRect.x();
1110     ty += localRect.y();
1111     
1112     GraphicsContext* context = paintInfo.context;
1113     
1114     // You can use p::first-line to specify a background. If so, the root line boxes for
1115     // a line may actually have to paint a background.
1116     RenderStyle* styleToUse = renderer()->style(m_firstLine);
1117     if ((!parent() && m_firstLine && styleToUse != renderer()->style()) || (parent() && renderer()->hasBoxDecorations())) {
1118         // Shadow comes first and is behind the background and border.
1119         paintBoxShadow(context, styleToUse, Normal, tx, ty, w, h);
1120
1121         Color c = styleToUse->visitedDependentColor(CSSPropertyBackgroundColor);
1122         paintFillLayers(paintInfo, c, styleToUse->backgroundLayers(), tx, ty, w, h);
1123         paintBoxShadow(context, styleToUse, Inset, tx, ty, w, h);
1124
1125         // :first-line cannot be used to put borders on a line. Always paint borders with our
1126         // non-first-line style.
1127         if (parent() && renderer()->style()->hasBorder()) {
1128             StyleImage* borderImage = renderer()->style()->borderImage().image();
1129             bool hasBorderImage = borderImage && borderImage->canRender(styleToUse->effectiveZoom());
1130             if (hasBorderImage && !borderImage->isLoaded())
1131                 return; // Don't paint anything while we wait for the image to load.
1132
1133             // The simple case is where we either have no border image or we are the only box for this object.  In those
1134             // cases only a single call to draw is required.
1135             if (!hasBorderImage || (!prevLineBox() && !nextLineBox()))
1136                 boxModelObject()->paintBorder(context, tx, ty, w, h, renderer()->style(), includeLogicalLeftEdge(), includeLogicalRightEdge());
1137             else {
1138                 // We have a border image that spans multiple lines.
1139                 // We need to adjust tx and ty by the width of all previous lines.
1140                 // Think of border image painting on inlines as though you had one long line, a single continuous
1141                 // strip.  Even though that strip has been broken up across multiple lines, you still paint it
1142                 // as though you had one single line.  This means each line has to pick up the image where
1143                 // the previous line left off.
1144                 // FIXME: What the heck do we do with RTL here? The math we're using is obviously not right,
1145                 // but it isn't even clear how this should work at all.
1146                 int logicalOffsetOnLine = 0;
1147                 for (InlineFlowBox* curr = prevLineBox(); curr; curr = curr->prevLineBox())
1148                     logicalOffsetOnLine += curr->logicalWidth();
1149                 int totalLogicalWidth = logicalOffsetOnLine;
1150                 for (InlineFlowBox* curr = this; curr; curr = curr->nextLineBox())
1151                     totalLogicalWidth += curr->logicalWidth();
1152                 int stripX = tx - (isHorizontal() ? logicalOffsetOnLine : 0);
1153                 int stripY = ty - (isHorizontal() ? 0 : logicalOffsetOnLine);
1154                 int stripWidth = isHorizontal() ? totalLogicalWidth : w;
1155                 int stripHeight = isHorizontal() ? h : totalLogicalWidth;
1156                 context->save();
1157                 context->clip(IntRect(tx, ty, w, h));
1158                 boxModelObject()->paintBorder(context, stripX, stripY, stripWidth, stripHeight, renderer()->style());
1159                 context->restore();
1160             }
1161         }
1162     }
1163 }
1164
1165 void InlineFlowBox::paintMask(PaintInfo& paintInfo, int tx, int ty)
1166 {
1167     if (!paintInfo.shouldPaintWithinRoot(renderer()) || renderer()->style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask)
1168         return;
1169
1170     // Pixel snap mask painting.
1171     IntRect frameRect = roundedFrameRect();
1172     int x = frameRect.x();
1173     int y = frameRect.y();
1174     int w = frameRect.width();
1175     int h = frameRect.height();
1176
1177     // Constrain our background/border painting to the line top and bottom if necessary.
1178     bool noQuirksMode = renderer()->document()->inNoQuirksMode();
1179     if (!hasTextChildren() && !noQuirksMode) {
1180         RootInlineBox* rootBox = root();
1181         int& top = isHorizontal() ? y : x;
1182         int& logicalHeight = isHorizontal() ? h : w;
1183         int bottom = min(rootBox->lineBottom(), top + logicalHeight);
1184         top = max(rootBox->lineTop(), top);
1185         logicalHeight = bottom - top;
1186     }
1187     
1188     // Move x/y to our coordinates.
1189     IntRect localRect(x, y, w, h);
1190     flipForWritingMode(localRect);
1191     tx += localRect.x();
1192     ty += localRect.y();
1193
1194     const NinePieceImage& maskNinePieceImage = renderer()->style()->maskBoxImage();
1195     StyleImage* maskBoxImage = renderer()->style()->maskBoxImage().image();
1196
1197     // Figure out if we need to push a transparency layer to render our mask.
1198     bool pushTransparencyLayer = false;
1199     bool compositedMask = renderer()->hasLayer() && boxModelObject()->layer()->hasCompositedMask();
1200     CompositeOperator compositeOp = CompositeSourceOver;
1201     if (!compositedMask) {
1202         if ((maskBoxImage && renderer()->style()->maskLayers()->hasImage()) || renderer()->style()->maskLayers()->next())
1203             pushTransparencyLayer = true;
1204         
1205         compositeOp = CompositeDestinationIn;
1206         if (pushTransparencyLayer) {
1207             paintInfo.context->setCompositeOperation(CompositeDestinationIn);
1208             paintInfo.context->beginTransparencyLayer(1.0f);
1209             compositeOp = CompositeSourceOver;
1210         }
1211     }
1212
1213     paintFillLayers(paintInfo, Color(), renderer()->style()->maskLayers(), tx, ty, w, h, compositeOp);
1214     
1215     bool hasBoxImage = maskBoxImage && maskBoxImage->canRender(renderer()->style()->effectiveZoom());
1216     if (!hasBoxImage || !maskBoxImage->isLoaded())
1217         return; // Don't paint anything while we wait for the image to load.
1218
1219     // The simple case is where we are the only box for this object.  In those
1220     // cases only a single call to draw is required.
1221     if (!prevLineBox() && !nextLineBox()) {
1222         boxModelObject()->paintNinePieceImage(paintInfo.context, tx, ty, w, h, renderer()->style(), maskNinePieceImage, compositeOp);
1223     } else {
1224         // We have a mask image that spans multiple lines.
1225         // We need to adjust _tx and _ty by the width of all previous lines.
1226         int logicalOffsetOnLine = 0;
1227         for (InlineFlowBox* curr = prevLineBox(); curr; curr = curr->prevLineBox())
1228             logicalOffsetOnLine += curr->logicalWidth();
1229         int totalLogicalWidth = logicalOffsetOnLine;
1230         for (InlineFlowBox* curr = this; curr; curr = curr->nextLineBox())
1231             totalLogicalWidth += curr->logicalWidth();
1232         int stripX = tx - (isHorizontal() ? logicalOffsetOnLine : 0);
1233         int stripY = ty - (isHorizontal() ? 0 : logicalOffsetOnLine);
1234         int stripWidth = isHorizontal() ? totalLogicalWidth : w;
1235         int stripHeight = isHorizontal() ? h : totalLogicalWidth;
1236         paintInfo.context->save();
1237         paintInfo.context->clip(IntRect(tx, ty, w, h));
1238         boxModelObject()->paintNinePieceImage(paintInfo.context, stripX, stripY, stripWidth, stripHeight, renderer()->style(), maskNinePieceImage, compositeOp);
1239         paintInfo.context->restore();
1240     }
1241     
1242     if (pushTransparencyLayer)
1243         paintInfo.context->endTransparencyLayer();
1244 }
1245
1246 InlineBox* InlineFlowBox::firstLeafChild() const
1247 {
1248     InlineBox* leaf = 0;
1249     for (InlineBox* child = firstChild(); child && !leaf; child = child->nextOnLine())
1250         leaf = child->isLeaf() ? child : static_cast<InlineFlowBox*>(child)->firstLeafChild();
1251     return leaf;
1252 }
1253
1254 InlineBox* InlineFlowBox::lastLeafChild() const
1255 {
1256     InlineBox* leaf = 0;
1257     for (InlineBox* child = lastChild(); child && !leaf; child = child->prevOnLine())
1258         leaf = child->isLeaf() ? child : static_cast<InlineFlowBox*>(child)->lastLeafChild();
1259     return leaf;
1260 }
1261
1262 RenderObject::SelectionState InlineFlowBox::selectionState()
1263 {
1264     return RenderObject::SelectionNone;
1265 }
1266
1267 bool InlineFlowBox::canAccommodateEllipsis(bool ltr, int blockEdge, int ellipsisWidth)
1268 {
1269     for (InlineBox *box = firstChild(); box; box = box->nextOnLine()) {
1270         if (!box->canAccommodateEllipsis(ltr, blockEdge, ellipsisWidth))
1271             return false;
1272     }
1273     return true;
1274 }
1275
1276 float InlineFlowBox::placeEllipsisBox(bool ltr, float blockLeftEdge, float blockRightEdge, float ellipsisWidth, bool& foundBox)
1277 {
1278     float result = -1;
1279     // We iterate over all children, the foundBox variable tells us when we've found the
1280     // box containing the ellipsis.  All boxes after that one in the flow are hidden.
1281     // If our flow is ltr then iterate over the boxes from left to right, otherwise iterate
1282     // from right to left. Varying the order allows us to correctly hide the boxes following the ellipsis.
1283     InlineBox* box = ltr ? firstChild() : lastChild();
1284
1285     // NOTE: these will cross after foundBox = true.
1286     int visibleLeftEdge = blockLeftEdge;
1287     int visibleRightEdge = blockRightEdge;
1288
1289     while (box) {
1290         int currResult = box->placeEllipsisBox(ltr, visibleLeftEdge, visibleRightEdge, ellipsisWidth, foundBox);
1291         if (currResult != -1 && result == -1)
1292             result = currResult;
1293
1294         if (ltr) {
1295             visibleLeftEdge += box->logicalWidth();
1296             box = box->nextOnLine();
1297         }
1298         else {
1299             visibleRightEdge -= box->logicalWidth();
1300             box = box->prevOnLine();
1301         }
1302     }
1303     return result;
1304 }
1305
1306 void InlineFlowBox::clearTruncation()
1307 {
1308     for (InlineBox *box = firstChild(); box; box = box->nextOnLine())
1309         box->clearTruncation();
1310 }
1311
1312 int InlineFlowBox::computeOverAnnotationAdjustment(int allowedPosition) const
1313 {
1314     int result = 0;
1315     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
1316         if (curr->renderer()->isPositioned())
1317             continue; // Positioned placeholders don't affect calculations.
1318         
1319         if (curr->isInlineFlowBox())
1320             result = max(result, static_cast<InlineFlowBox*>(curr)->computeOverAnnotationAdjustment(allowedPosition));
1321         
1322         if (curr->renderer()->isReplaced() && curr->renderer()->isRubyRun()) {
1323             RenderRubyRun* rubyRun = static_cast<RenderRubyRun*>(curr->renderer());
1324             RenderRubyText* rubyText = rubyRun->rubyText();
1325             if (!rubyText)
1326                 continue;
1327             
1328             if (!rubyRun->style()->isFlippedLinesWritingMode()) {
1329                 int topOfFirstRubyTextLine = rubyText->logicalTop() + (rubyText->firstRootBox() ? rubyText->firstRootBox()->lineTop() : 0);
1330                 if (topOfFirstRubyTextLine >= 0)
1331                     continue;
1332                 topOfFirstRubyTextLine += curr->logicalTop();
1333                 result = max(result, allowedPosition - topOfFirstRubyTextLine);
1334             } else {
1335                 int bottomOfLastRubyTextLine = rubyText->logicalTop() + (rubyText->lastRootBox() ? rubyText->lastRootBox()->lineBottom() : rubyText->logicalHeight());
1336                 if (bottomOfLastRubyTextLine <= curr->logicalHeight())
1337                     continue;
1338                 bottomOfLastRubyTextLine += curr->logicalTop();
1339                 result = max(result, bottomOfLastRubyTextLine - allowedPosition);
1340             }
1341         }
1342
1343         if (curr->isInlineTextBox()) {
1344             RenderStyle* style = curr->renderer()->style(m_firstLine);
1345             TextEmphasisPosition emphasisMarkPosition;
1346             if (style->textEmphasisMark() != TextEmphasisMarkNone && static_cast<InlineTextBox*>(curr)->getEmphasisMarkPosition(style, emphasisMarkPosition) && emphasisMarkPosition == TextEmphasisPositionOver) {
1347                 if (!style->isFlippedLinesWritingMode()) {
1348                     int topOfEmphasisMark = curr->logicalTop() - style->font().emphasisMarkHeight(style->textEmphasisMarkString());
1349                     result = max(result, allowedPosition - topOfEmphasisMark);
1350                 } else {
1351                     int bottomOfEmphasisMark = curr->logicalBottom() + style->font().emphasisMarkHeight(style->textEmphasisMarkString());
1352                     result = max(result, bottomOfEmphasisMark - allowedPosition);
1353                 }
1354             }
1355         }
1356     }
1357     return result;
1358 }
1359
1360 int InlineFlowBox::computeUnderAnnotationAdjustment(int allowedPosition) const
1361 {
1362     int result = 0;
1363     for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
1364         if (curr->renderer()->isPositioned())
1365             continue; // Positioned placeholders don't affect calculations.
1366
1367         if (curr->isInlineFlowBox())
1368             result = max(result, static_cast<InlineFlowBox*>(curr)->computeUnderAnnotationAdjustment(allowedPosition));
1369
1370         if (curr->isInlineTextBox()) {
1371             RenderStyle* style = curr->renderer()->style(m_firstLine);
1372             if (style->textEmphasisMark() != TextEmphasisMarkNone && style->textEmphasisPosition() == TextEmphasisPositionUnder) {
1373                 if (!style->isFlippedLinesWritingMode()) {
1374                     int bottomOfEmphasisMark = curr->logicalBottom() + style->font().emphasisMarkHeight(style->textEmphasisMarkString());
1375                     result = max(result, bottomOfEmphasisMark - allowedPosition);
1376                 } else {
1377                     int topOfEmphasisMark = curr->logicalTop() - style->font().emphasisMarkHeight(style->textEmphasisMarkString());
1378                     result = max(result, allowedPosition - topOfEmphasisMark);
1379                 }
1380             }
1381         }
1382     }
1383     return result;
1384 }
1385
1386 #ifndef NDEBUG
1387
1388 void InlineFlowBox::checkConsistency() const
1389 {
1390 #ifdef CHECK_CONSISTENCY
1391     ASSERT(!m_hasBadChildList);
1392     const InlineBox* prev = 0;
1393     for (const InlineBox* child = m_firstChild; child; child = child->nextOnLine()) {
1394         ASSERT(child->parent() == this);
1395         ASSERT(child->prevOnLine() == prev);
1396         prev = child;
1397     }
1398     ASSERT(prev == m_lastChild);
1399 #endif
1400 }
1401
1402 #endif
1403
1404 } // namespace WebCore