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