feac67fead2d0039a64377b481a9ef156d3642a0
[WebKit-https.git] / Source / WebCore / rendering / RenderBlock.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2007 David Smith (catfish.man@gmail.com)
5  * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
6  * Copyright (C) Research In Motion Limited 2010. All rights reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 #include "config.h"
25 #include "RenderBlock.h"
26
27 #include "AXObjectCache.h"
28 #include "ColumnInfo.h"
29 #include "Document.h"
30 #include "Editor.h"
31 #include "Element.h"
32 #include "FloatQuad.h"
33 #include "Frame.h"
34 #include "FrameSelection.h"
35 #include "FrameView.h"
36 #include "GraphicsContext.h"
37 #include "HTMLInputElement.h"
38 #include "HTMLNames.h"
39 #include "HitTestLocation.h"
40 #include "HitTestResult.h"
41 #include "InlineIterator.h"
42 #include "InlineTextBox.h"
43 #include "LayoutRepainter.h"
44 #include "LogicalSelectionOffsetCaches.h"
45 #include "OverflowEvent.h"
46 #include "Page.h"
47 #include "PaintInfo.h"
48 #include "RenderBoxRegionInfo.h"
49 #include "RenderCombineText.h"
50 #include "RenderDeprecatedFlexibleBox.h"
51 #include "RenderFlexibleBox.h"
52 #include "RenderInline.h"
53 #include "RenderLayer.h"
54 #include "RenderMarquee.h"
55 #include "RenderNamedFlowThread.h"
56 #include "RenderRegion.h"
57 #include "RenderTableCell.h"
58 #include "RenderTextFragment.h"
59 #include "RenderTheme.h"
60 #include "RenderView.h"
61 #include "SVGTextRunRenderingContext.h"
62 #include "Settings.h"
63 #include "ShadowRoot.h"
64 #include "TransformState.h"
65 #include <wtf/StackStats.h>
66 #include <wtf/TemporaryChange.h>
67
68 #if ENABLE(CSS_SHAPES)
69 #include "ShapeInsideInfo.h"
70 #include "ShapeOutsideInfo.h"
71 #endif
72
73 using namespace std;
74 using namespace WTF;
75 using namespace Unicode;
76
77 namespace WebCore {
78
79 using namespace HTMLNames;
80
81 struct SameSizeAsRenderBlock : public RenderBox {
82     void* pointers[2];
83     RenderObjectChildList children;
84     RenderLineBoxList lineBoxes;
85     uint32_t bitfields;
86 };
87
88 COMPILE_ASSERT(sizeof(RenderBlock) == sizeof(SameSizeAsRenderBlock), RenderBlock_should_stay_small);
89
90 struct SameSizeAsFloatingObject {
91     void* pointers[2];
92     LayoutRect rect;
93     int paginationStrut;
94     uint32_t bitfields : 8;
95 };
96
97 COMPILE_ASSERT(sizeof(RenderBlock::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
98
99 struct SameSizeAsMarginInfo {
100     uint32_t bitfields : 16;
101     LayoutUnit margins[2];
102 };
103
104 typedef WTF::HashMap<const RenderBox*, OwnPtr<ColumnInfo> > ColumnInfoMap;
105 static ColumnInfoMap* gColumnInfoMap = 0;
106
107 static TrackedDescendantsMap* gPositionedDescendantsMap = 0;
108 static TrackedDescendantsMap* gPercentHeightDescendantsMap = 0;
109
110 static TrackedContainerMap* gPositionedContainerMap = 0;
111 static TrackedContainerMap* gPercentHeightContainerMap = 0;
112     
113 typedef WTF::HashMap<RenderBlock*, OwnPtr<ListHashSet<RenderInline*> > > ContinuationOutlineTableMap;
114
115 typedef WTF::HashSet<RenderBlock*> DelayedUpdateScrollInfoSet;
116 static int gDelayUpdateScrollInfo = 0;
117 static DelayedUpdateScrollInfoSet* gDelayedUpdateScrollInfoSet = 0;
118
119 static bool gColumnFlowSplitEnabled = true;
120
121 bool RenderBlock::s_canPropagateFloatIntoSibling = false;
122
123 // This class helps dispatching the 'overflow' event on layout change. overflow can be set on RenderBoxes, yet the existing code
124 // only works on RenderBlocks. If this change, this class should be shared with other RenderBoxes.
125 class OverflowEventDispatcher {
126     WTF_MAKE_NONCOPYABLE(OverflowEventDispatcher);
127 public:
128     OverflowEventDispatcher(const RenderBlock* block)
129         : m_block(block)
130         , m_hadHorizontalLayoutOverflow(false)
131         , m_hadVerticalLayoutOverflow(false)
132     {
133         m_shouldDispatchEvent = !m_block->isAnonymous() && m_block->hasOverflowClip() && m_block->document()->hasListenerType(Document::OVERFLOWCHANGED_LISTENER);
134         if (m_shouldDispatchEvent) {
135             m_hadHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
136             m_hadVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
137         }
138     }
139
140     ~OverflowEventDispatcher()
141     {
142         if (!m_shouldDispatchEvent)
143             return;
144
145         bool hasHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
146         bool hasVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
147
148         bool horizontalLayoutOverflowChanged = hasHorizontalLayoutOverflow != m_hadHorizontalLayoutOverflow;
149         bool verticalLayoutOverflowChanged = hasVerticalLayoutOverflow != m_hadVerticalLayoutOverflow;
150         if (horizontalLayoutOverflowChanged || verticalLayoutOverflowChanged) {
151             if (FrameView* frameView = m_block->document()->view())
152                 frameView->scheduleEvent(OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow), m_block->node());
153         }
154     }
155
156 private:
157     const RenderBlock* m_block;
158     bool m_shouldDispatchEvent;
159     bool m_hadHorizontalLayoutOverflow;
160     bool m_hadVerticalLayoutOverflow;
161 };
162
163 // Our MarginInfo state used when laying out block children.
164 RenderBlock::MarginInfo::MarginInfo(RenderBlock* block, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
165     : m_atBeforeSideOfBlock(true)
166     , m_atAfterSideOfBlock(false)
167     , m_hasMarginBeforeQuirk(false)
168     , m_hasMarginAfterQuirk(false)
169     , m_determinedMarginBeforeQuirk(false)
170     , m_discardMargin(false)
171 {
172     RenderStyle* blockStyle = block->style();
173     ASSERT(block->isRenderView() || block->parent());
174     m_canCollapseWithChildren = !block->isRenderView() && !block->isRoot() && !block->isOutOfFlowPositioned()
175         && !block->isFloating() && !block->isTableCell() && !block->hasOverflowClip() && !block->isInlineBlockOrInlineTable()
176         && !block->isRenderFlowThread() && !block->isWritingModeRoot() && !block->parent()->isFlexibleBox()
177         && blockStyle->hasAutoColumnCount() && blockStyle->hasAutoColumnWidth() && !blockStyle->columnSpan();
178
179     m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
180
181     // If any height other than auto is specified in CSS, then we don't collapse our bottom
182     // margins with our children's margins.  To do otherwise would be to risk odd visual
183     // effects when the children overflow out of the parent block and yet still collapse
184     // with it.  We also don't collapse if we have any bottom border/padding.
185     m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && (afterBorderPadding == 0) &&
186         (blockStyle->logicalHeight().isAuto() && !blockStyle->logicalHeight().value()) && blockStyle->marginAfterCollapse() != MSEPARATE;
187     
188     m_quirkContainer = block->isTableCell() || block->isBody();
189
190     m_discardMargin = m_canCollapseMarginBeforeWithChildren && block->mustDiscardMarginBefore();
191
192     m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !block->mustDiscardMarginBefore()) ? block->maxPositiveMarginBefore() : LayoutUnit();
193     m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !block->mustDiscardMarginBefore()) ? block->maxNegativeMarginBefore() : LayoutUnit();
194 }
195
196 // -------------------------------------------------------------------------------------------------------
197
198 RenderBlock::RenderBlock(ContainerNode* node)
199     : RenderBox(node)
200     , m_lineHeight(-1)
201     , m_hasMarginBeforeQuirk(false)
202     , m_hasMarginAfterQuirk(false)
203     , m_beingDestroyed(false)
204     , m_hasMarkupTruncation(false)
205     , m_hasBorderOrPaddingLogicalWidthChanged(false)
206 {
207     setChildrenInline(true);
208     COMPILE_ASSERT(sizeof(RenderBlock::FloatingObject) == sizeof(SameSizeAsFloatingObject), FloatingObject_should_stay_small);
209     COMPILE_ASSERT(sizeof(RenderBlock::MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
210 }
211
212 static void removeBlockFromDescendantAndContainerMaps(RenderBlock* block, TrackedDescendantsMap*& descendantMap, TrackedContainerMap*& containerMap)
213 {
214     if (OwnPtr<TrackedRendererListHashSet> descendantSet = descendantMap->take(block)) {
215         TrackedRendererListHashSet::iterator end = descendantSet->end();
216         for (TrackedRendererListHashSet::iterator descendant = descendantSet->begin(); descendant != end; ++descendant) {
217             TrackedContainerMap::iterator it = containerMap->find(*descendant);
218             ASSERT(it != containerMap->end());
219             if (it == containerMap->end())
220                 continue;
221             HashSet<RenderBlock*>* containerSet = it->value.get();
222             ASSERT(containerSet->contains(block));
223             containerSet->remove(block);
224             if (containerSet->isEmpty())
225                 containerMap->remove(it);
226         }
227     }
228 }
229
230 RenderBlock::~RenderBlock()
231 {
232     if (m_floatingObjects)
233         deleteAllValues(m_floatingObjects->set());
234     
235     if (hasColumns())
236         gColumnInfoMap->take(this);
237
238     if (gPercentHeightDescendantsMap)
239         removeBlockFromDescendantAndContainerMaps(this, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
240     if (gPositionedDescendantsMap)
241         removeBlockFromDescendantAndContainerMaps(this, gPositionedDescendantsMap, gPositionedContainerMap);
242 }
243
244 RenderBlock* RenderBlock::createAnonymous(Document* document)
245 {
246     RenderBlock* renderer = new (document->renderArena()) RenderBlock(0);
247     renderer->setDocumentForAnonymous(document);
248     return renderer;
249 }
250
251 void RenderBlock::willBeDestroyed()
252 {
253     // Mark as being destroyed to avoid trouble with merges in removeChild().
254     m_beingDestroyed = true;
255
256     if (!documentBeingDestroyed()) {
257         if (firstChild() && firstChild()->isRunIn())
258             moveRunInToOriginalPosition(firstChild());
259     }
260
261     // Make sure to destroy anonymous children first while they are still connected to the rest of the tree, so that they will
262     // properly dirty line boxes that they are removed from. Effects that do :before/:after only on hover could crash otherwise.
263     children()->destroyLeftoverChildren();
264
265     // Destroy our continuation before anything other than anonymous children.
266     // The reason we don't destroy it before anonymous children is that they may
267     // have continuations of their own that are anonymous children of our continuation.
268     RenderBoxModelObject* continuation = this->continuation();
269     if (continuation) {
270         continuation->destroy();
271         setContinuation(0);
272     }
273     
274     if (!documentBeingDestroyed()) {
275         if (firstLineBox()) {
276             // We can't wait for RenderBox::destroy to clear the selection,
277             // because by then we will have nuked the line boxes.
278             // FIXME: The FrameSelection should be responsible for this when it
279             // is notified of DOM mutations.
280             if (isSelectionBorder())
281                 view()->clearSelection();
282
283             // If we are an anonymous block, then our line boxes might have children
284             // that will outlast this block. In the non-anonymous block case those
285             // children will be destroyed by the time we return from this function.
286             if (isAnonymousBlock()) {
287                 for (InlineFlowBox* box = firstLineBox(); box; box = box->nextLineBox()) {
288                     while (InlineBox* childBox = box->firstChild())
289                         childBox->remove();
290                 }
291             }
292         } else if (parent())
293             parent()->dirtyLinesFromChangedChild(this);
294     }
295
296     m_lineBoxes.deleteLineBoxes(renderArena());
297
298     if (lineGridBox())
299         lineGridBox()->destroy(renderArena());
300
301     if (UNLIKELY(gDelayedUpdateScrollInfoSet != 0))
302         gDelayedUpdateScrollInfoSet->remove(this);
303
304     RenderBox::willBeDestroyed();
305 }
306
307 void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
308 {
309     RenderStyle* oldStyle = style();
310     s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
311
312     setReplaced(newStyle->isDisplayInlineType());
313     
314     if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle->position()) {
315         if (newStyle->position() == StaticPosition)
316             // Clear our positioned objects list. Our absolutely positioned descendants will be
317             // inserted into our containing block's positioned objects list during layout.
318             removePositionedObjects(0, NewContainingBlock);
319         else if (oldStyle->position() == StaticPosition) {
320             // Remove our absolutely positioned descendants from their current containing block.
321             // They will be inserted into our positioned objects list during layout.
322             RenderObject* cb = parent();
323             while (cb && (cb->style()->position() == StaticPosition || (cb->isInline() && !cb->isReplaced())) && !cb->isRenderView()) {
324                 if (cb->style()->position() == RelativePosition && cb->isInline() && !cb->isReplaced()) {
325                     cb = cb->containingBlock();
326                     break;
327                 }
328                 cb = cb->parent();
329             }
330             
331             if (cb->isRenderBlock())
332                 toRenderBlock(cb)->removePositionedObjects(this, NewContainingBlock);
333         }
334
335         if (containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
336             markAllDescendantsWithFloatsForLayout();
337     }
338
339     RenderBox::styleWillChange(diff, newStyle);
340 }
341
342 static bool borderOrPaddingLogicalWidthChanged(const RenderStyle* oldStyle, const RenderStyle* newStyle)
343 {
344     if (newStyle->isHorizontalWritingMode())
345         return oldStyle->borderLeftWidth() != newStyle->borderLeftWidth()
346             || oldStyle->borderRightWidth() != newStyle->borderRightWidth()
347             || oldStyle->paddingLeft() != newStyle->paddingLeft()
348             || oldStyle->paddingRight() != newStyle->paddingRight();
349
350     return oldStyle->borderTopWidth() != newStyle->borderTopWidth()
351         || oldStyle->borderBottomWidth() != newStyle->borderBottomWidth()
352         || oldStyle->paddingTop() != newStyle->paddingTop()
353         || oldStyle->paddingBottom() != newStyle->paddingBottom();
354 }
355
356 void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
357 {
358     RenderBox::styleDidChange(diff, oldStyle);
359     
360     RenderStyle* newStyle = style();
361     
362 #if ENABLE(CSS_SHAPES)
363     updateShapeInsideInfoAfterStyleChange(newStyle->resolvedShapeInside(), oldStyle ? oldStyle->resolvedShapeInside() : 0);
364 #endif
365
366     if (!isAnonymousBlock()) {
367         // Ensure that all of our continuation blocks pick up the new style.
368         for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
369             RenderBoxModelObject* nextCont = currCont->continuation();
370             currCont->setContinuation(0);
371             currCont->setStyle(newStyle);
372             currCont->setContinuation(nextCont);
373         }
374     }
375
376     propagateStyleToAnonymousChildren(true);    
377     m_lineHeight = -1;
378
379     // After our style changed, if we lose our ability to propagate floats into next sibling
380     // blocks, then we need to find the top most parent containing that overhanging float and
381     // then mark its descendants with floats for layout and clear all floats from its next
382     // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
383     bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
384     if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
385         RenderBlock* parentBlock = this;
386         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
387         FloatingObjectSetIterator end = floatingObjectSet.end();
388
389         for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
390             if (curr->isRenderBlock()) {
391                 RenderBlock* currBlock = toRenderBlock(curr);
392
393                 if (currBlock->hasOverhangingFloats()) {
394                     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
395                         RenderBox* renderer = (*it)->renderer();
396                         if (currBlock->hasOverhangingFloat(renderer)) {
397                             parentBlock = currBlock;
398                             break;
399                         }
400                     }
401                 }
402             }
403         }
404               
405         parentBlock->markAllDescendantsWithFloatsForLayout();
406         parentBlock->markSiblingsWithFloatsForLayout();
407     }
408     
409     // It's possible for our border/padding to change, but for the overall logical width of the block to
410     // end up being the same. We keep track of this change so in layoutBlock, we can know to set relayoutChildren=true.
411     m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff == StyleDifferenceLayout && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle);
412 }
413
414 RenderBlock* RenderBlock::continuationBefore(RenderObject* beforeChild)
415 {
416     if (beforeChild && beforeChild->parent() == this)
417         return this;
418
419     RenderBlock* curr = toRenderBlock(continuation());
420     RenderBlock* nextToLast = this;
421     RenderBlock* last = this;
422     while (curr) {
423         if (beforeChild && beforeChild->parent() == curr) {
424             if (curr->firstChild() == beforeChild)
425                 return last;
426             return curr;
427         }
428
429         nextToLast = last;
430         last = curr;
431         curr = toRenderBlock(curr->continuation());
432     }
433
434     if (!beforeChild && !last->firstChild())
435         return nextToLast;
436     return last;
437 }
438
439 void RenderBlock::addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild)
440 {
441     RenderBlock* flow = continuationBefore(beforeChild);
442     ASSERT(!beforeChild || beforeChild->parent()->isAnonymousColumnSpanBlock() || beforeChild->parent()->isRenderBlock());
443     RenderBoxModelObject* beforeChildParent = 0;
444     if (beforeChild)
445         beforeChildParent = toRenderBoxModelObject(beforeChild->parent());
446     else {
447         RenderBoxModelObject* cont = flow->continuation();
448         if (cont)
449             beforeChildParent = cont;
450         else
451             beforeChildParent = flow;
452     }
453
454     if (newChild->isFloatingOrOutOfFlowPositioned()) {
455         beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
456         return;
457     }
458
459     // A continuation always consists of two potential candidates: a block or an anonymous
460     // column span box holding column span children.
461     bool childIsNormal = newChild->isInline() || !newChild->style()->columnSpan();
462     bool bcpIsNormal = beforeChildParent->isInline() || !beforeChildParent->style()->columnSpan();
463     bool flowIsNormal = flow->isInline() || !flow->style()->columnSpan();
464
465     if (flow == beforeChildParent) {
466         flow->addChildIgnoringContinuation(newChild, beforeChild);
467         return;
468     }
469     
470     // The goal here is to match up if we can, so that we can coalesce and create the
471     // minimal # of continuations needed for the inline.
472     if (childIsNormal == bcpIsNormal) {
473         beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
474         return;
475     }
476     if (flowIsNormal == childIsNormal) {
477         flow->addChildIgnoringContinuation(newChild, 0); // Just treat like an append.
478         return;
479     }
480     beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
481 }
482
483
484 void RenderBlock::addChildToAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
485 {
486     ASSERT(!continuation()); // We don't yet support column spans that aren't immediate children of the multi-column block.
487         
488     // The goal is to locate a suitable box in which to place our child.
489     RenderBlock* beforeChildParent = 0;
490     if (beforeChild) {
491         RenderObject* curr = beforeChild;
492         while (curr && curr->parent() != this)
493             curr = curr->parent();
494         beforeChildParent = toRenderBlock(curr);
495         ASSERT(beforeChildParent);
496         ASSERT(beforeChildParent->isAnonymousColumnsBlock() || beforeChildParent->isAnonymousColumnSpanBlock());
497     } else
498         beforeChildParent = toRenderBlock(lastChild());
499
500     // If the new child is floating or positioned it can just go in that block.
501     if (newChild->isFloatingOrOutOfFlowPositioned()) {
502         beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
503         return;
504     }
505
506     // See if the child can be placed in the box.
507     bool newChildHasColumnSpan = newChild->style()->columnSpan() && !newChild->isInline();
508     bool beforeChildParentHoldsColumnSpans = beforeChildParent->isAnonymousColumnSpanBlock();
509
510     if (newChildHasColumnSpan == beforeChildParentHoldsColumnSpans) {
511         beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
512         return;
513     }
514
515     if (!beforeChild) {
516         // Create a new block of the correct type.
517         RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
518         children()->appendChildNode(this, newBox);
519         newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
520         return;
521     }
522
523     RenderObject* immediateChild = beforeChild;
524     bool isPreviousBlockViable = true;
525     while (immediateChild->parent() != this) {
526         if (isPreviousBlockViable)
527             isPreviousBlockViable = !immediateChild->previousSibling();
528         immediateChild = immediateChild->parent();
529     }
530     if (isPreviousBlockViable && immediateChild->previousSibling()) {
531         toRenderBlock(immediateChild->previousSibling())->addChildIgnoringAnonymousColumnBlocks(newChild, 0); // Treat like an append.
532         return;
533     }
534         
535     // Split our anonymous blocks.
536     RenderObject* newBeforeChild = splitAnonymousBoxesAroundChild(beforeChild);
537
538     
539     // Create a new anonymous box of the appropriate type.
540     RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
541     children()->insertChildNode(this, newBox, newBeforeChild);
542     newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
543     return;
544 }
545
546 RenderBlock* RenderBlock::containingColumnsBlock(bool allowAnonymousColumnBlock)
547 {
548     RenderBlock* firstChildIgnoringAnonymousWrappers = 0;
549     for (RenderObject* curr = this; curr; curr = curr->parent()) {
550         if (!curr->isRenderBlock() || curr->isFloatingOrOutOfFlowPositioned() || curr->isTableCell() || curr->isRoot() || curr->isRenderView() || curr->hasOverflowClip()
551             || curr->isInlineBlockOrInlineTable())
552             return 0;
553
554         // FIXME: Tables, RenderButtons, and RenderListItems all do special management
555         // of their children that breaks when the flow is split through them. Disabling
556         // multi-column for them to avoid this problem.
557         if (curr->isTable() || curr->isRenderButton() || curr->isListItem())
558             return 0;
559         
560         RenderBlock* currBlock = toRenderBlock(curr);
561         if (!currBlock->createsAnonymousWrapper())
562             firstChildIgnoringAnonymousWrappers = currBlock;
563
564         if (currBlock->style()->specifiesColumns() && (allowAnonymousColumnBlock || !currBlock->isAnonymousColumnsBlock()))
565             return firstChildIgnoringAnonymousWrappers;
566             
567         if (currBlock->isAnonymousColumnSpanBlock())
568             return 0;
569     }
570     return 0;
571 }
572
573 RenderBlock* RenderBlock::clone() const
574 {
575     RenderBlock* cloneBlock;
576     if (isAnonymousBlock()) {
577         cloneBlock = createAnonymousBlock();
578         cloneBlock->setChildrenInline(childrenInline());
579     }
580     else {
581         RenderObject* cloneRenderer = toElement(node())->createRenderer(renderArena(), style());
582         cloneBlock = toRenderBlock(cloneRenderer);
583         cloneBlock->setStyle(style());
584
585         // This takes care of setting the right value of childrenInline in case
586         // generated content is added to cloneBlock and 'this' does not have
587         // generated content added yet.
588         cloneBlock->setChildrenInline(cloneBlock->firstChild() ? cloneBlock->firstChild()->isInline() : childrenInline());
589     }
590     cloneBlock->setFlowThreadState(flowThreadState());
591     return cloneBlock;
592 }
593
594 void RenderBlock::splitBlocks(RenderBlock* fromBlock, RenderBlock* toBlock,
595                               RenderBlock* middleBlock,
596                               RenderObject* beforeChild, RenderBoxModelObject* oldCont)
597 {
598     // Create a clone of this inline.
599     RenderBlock* cloneBlock = clone();
600     if (!isAnonymousBlock())
601         cloneBlock->setContinuation(oldCont);
602
603     if (!beforeChild && isAfterContent(lastChild()))
604         beforeChild = lastChild();
605
606     // If we are moving inline children from |this| to cloneBlock, then we need
607     // to clear our line box tree.
608     if (beforeChild && childrenInline())
609         deleteLineBoxTree();
610
611     // Now take all of the children from beforeChild to the end and remove
612     // them from |this| and place them in the clone.
613     moveChildrenTo(cloneBlock, beforeChild, 0, true);
614     
615     // Hook |clone| up as the continuation of the middle block.
616     if (!cloneBlock->isAnonymousBlock())
617         middleBlock->setContinuation(cloneBlock);
618
619     // We have been reparented and are now under the fromBlock.  We need
620     // to walk up our block parent chain until we hit the containing anonymous columns block.
621     // Once we hit the anonymous columns block we're done.
622     RenderBoxModelObject* curr = toRenderBoxModelObject(parent());
623     RenderBoxModelObject* currChild = this;
624     RenderObject* currChildNextSibling = currChild->nextSibling();
625
626     while (curr && curr != fromBlock) {
627         ASSERT_WITH_SECURITY_IMPLICATION(curr->isRenderBlock());
628         
629         RenderBlock* blockCurr = toRenderBlock(curr);
630         
631         // Create a new clone.
632         RenderBlock* cloneChild = cloneBlock;
633         cloneBlock = blockCurr->clone();
634
635         // Insert our child clone as the first child.
636         cloneBlock->addChildIgnoringContinuation(cloneChild, 0);
637
638         // Hook the clone up as a continuation of |curr|.  Note we do encounter
639         // anonymous blocks possibly as we walk up the block chain.  When we split an
640         // anonymous block, there's no need to do any continuation hookup, since we haven't
641         // actually split a real element.
642         if (!blockCurr->isAnonymousBlock()) {
643             oldCont = blockCurr->continuation();
644             blockCurr->setContinuation(cloneBlock);
645             cloneBlock->setContinuation(oldCont);
646         }
647
648         // Now we need to take all of the children starting from the first child
649         // *after* currChild and append them all to the clone.
650         blockCurr->moveChildrenTo(cloneBlock, currChildNextSibling, 0, true);
651
652         // Keep walking up the chain.
653         currChild = curr;
654         currChildNextSibling = currChild->nextSibling();
655         curr = toRenderBoxModelObject(curr->parent());
656     }
657
658     // Now we are at the columns block level. We need to put the clone into the toBlock.
659     toBlock->children()->appendChildNode(toBlock, cloneBlock);
660
661     // Now take all the children after currChild and remove them from the fromBlock
662     // and put them in the toBlock.
663     fromBlock->moveChildrenTo(toBlock, currChildNextSibling, 0, true);
664 }
665
666 void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
667                             RenderObject* newChild, RenderBoxModelObject* oldCont)
668 {
669     RenderBlock* pre = 0;
670     RenderBlock* block = containingColumnsBlock();
671     
672     // Delete our line boxes before we do the inline split into continuations.
673     block->deleteLineBoxTree();
674     
675     bool madeNewBeforeBlock = false;
676     if (block->isAnonymousColumnsBlock()) {
677         // We can reuse this block and make it the preBlock of the next continuation.
678         pre = block;
679         pre->removePositionedObjects(0);
680         pre->removeFloatingObjects();
681         block = toRenderBlock(block->parent());
682     } else {
683         // No anonymous block available for use.  Make one.
684         pre = block->createAnonymousColumnsBlock();
685         pre->setChildrenInline(false);
686         madeNewBeforeBlock = true;
687     }
688
689     RenderBlock* post = block->createAnonymousColumnsBlock();
690     post->setChildrenInline(false);
691
692     RenderObject* boxFirst = madeNewBeforeBlock ? block->firstChild() : pre->nextSibling();
693     if (madeNewBeforeBlock)
694         block->children()->insertChildNode(block, pre, boxFirst);
695     block->children()->insertChildNode(block, newBlockBox, boxFirst);
696     block->children()->insertChildNode(block, post, boxFirst);
697     block->setChildrenInline(false);
698     
699     if (madeNewBeforeBlock)
700         block->moveChildrenTo(pre, boxFirst, 0, true);
701
702     splitBlocks(pre, post, newBlockBox, beforeChild, oldCont);
703
704     // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
705     // time in makeChildrenNonInline by just setting this explicitly up front.
706     newBlockBox->setChildrenInline(false);
707
708     // We delayed adding the newChild until now so that the |newBlockBox| would be fully
709     // connected, thus allowing newChild access to a renderArena should it need
710     // to wrap itself in additional boxes (e.g., table construction).
711     newBlockBox->addChild(newChild);
712
713     // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
714     // get deleted properly.  Because objects moves from the pre block into the post block, we want to
715     // make new line boxes instead of leaving the old line boxes around.
716     pre->setNeedsLayoutAndPrefWidthsRecalc();
717     block->setNeedsLayoutAndPrefWidthsRecalc();
718     post->setNeedsLayoutAndPrefWidthsRecalc();
719 }
720
721 void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlock* newBlockBox, RenderObject* newChild)
722 {
723     RenderBlock* pre = 0;
724     RenderBlock* post = 0;
725     RenderBlock* block = this; // Eventually block will not just be |this|, but will also be a block nested inside |this|.  Assign to a variable
726                                // so that we don't have to patch all of the rest of the code later on.
727     
728     // Delete the block's line boxes before we do the split.
729     block->deleteLineBoxTree();
730
731     if (beforeChild && beforeChild->parent() != this)
732         beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
733
734     if (beforeChild != firstChild()) {
735         pre = block->createAnonymousColumnsBlock();
736         pre->setChildrenInline(block->childrenInline());
737     }
738
739     if (beforeChild) {
740         post = block->createAnonymousColumnsBlock();
741         post->setChildrenInline(block->childrenInline());
742     }
743
744     RenderObject* boxFirst = block->firstChild();
745     if (pre)
746         block->children()->insertChildNode(block, pre, boxFirst);
747     block->children()->insertChildNode(block, newBlockBox, boxFirst);
748     if (post)
749         block->children()->insertChildNode(block, post, boxFirst);
750     block->setChildrenInline(false);
751     
752     // The pre/post blocks always have layers, so we know to always do a full insert/remove (so we pass true as the last argument).
753     block->moveChildrenTo(pre, boxFirst, beforeChild, true);
754     block->moveChildrenTo(post, beforeChild, 0, true);
755
756     // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
757     // time in makeChildrenNonInline by just setting this explicitly up front.
758     newBlockBox->setChildrenInline(false);
759
760     // We delayed adding the newChild until now so that the |newBlockBox| would be fully
761     // connected, thus allowing newChild access to a renderArena should it need
762     // to wrap itself in additional boxes (e.g., table construction).
763     newBlockBox->addChild(newChild);
764
765     // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
766     // get deleted properly.  Because objects moved from the pre block into the post block, we want to
767     // make new line boxes instead of leaving the old line boxes around.
768     if (pre)
769         pre->setNeedsLayoutAndPrefWidthsRecalc();
770     block->setNeedsLayoutAndPrefWidthsRecalc();
771     if (post)
772         post->setNeedsLayoutAndPrefWidthsRecalc();
773 }
774
775 RenderBlock* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
776 {
777     // FIXME: This function is the gateway for the addition of column-span support.  It will
778     // be added to in three stages:
779     // (1) Immediate children of a multi-column block can span.
780     // (2) Nested block-level children with only block-level ancestors between them and the multi-column block can span.
781     // (3) Nested children with block or inline ancestors between them and the multi-column block can span (this is when we
782     // cross the streams and have to cope with both types of continuations mixed together).
783     // This function currently supports (1) and (2).
784     RenderBlock* columnsBlockAncestor = 0;
785     if (!newChild->isText() && newChild->style()->columnSpan() && !newChild->isBeforeOrAfterContent()
786         && !newChild->isFloatingOrOutOfFlowPositioned() && !newChild->isInline() && !isAnonymousColumnSpanBlock()) {
787         columnsBlockAncestor = containingColumnsBlock(false);
788         if (columnsBlockAncestor) {
789             // Make sure that none of the parent ancestors have a continuation.
790             // If yes, we do not want split the block into continuations.
791             RenderObject* curr = this;
792             while (curr && curr != columnsBlockAncestor) {
793                 if (curr->isRenderBlock() && toRenderBlock(curr)->continuation()) {
794                     columnsBlockAncestor = 0;
795                     break;
796                 }
797                 curr = curr->parent();
798             }
799         }
800     }
801     return columnsBlockAncestor;
802 }
803
804 void RenderBlock::addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
805 {
806     if (beforeChild && beforeChild->parent() != this) {
807         RenderObject* beforeChildContainer = beforeChild->parent();
808         while (beforeChildContainer->parent() != this)
809             beforeChildContainer = beforeChildContainer->parent();
810         ASSERT(beforeChildContainer);
811
812         if (beforeChildContainer->isAnonymous()) {
813             // If the requested beforeChild is not one of our children, then this is because
814             // there is an anonymous container within this object that contains the beforeChild.
815             RenderObject* beforeChildAnonymousContainer = beforeChildContainer;
816             if (beforeChildAnonymousContainer->isAnonymousBlock()
817 #if ENABLE(FULLSCREEN_API)
818                 // Full screen renderers and full screen placeholders act as anonymous blocks, not tables:
819                 || beforeChildAnonymousContainer->isRenderFullScreen()
820                 || beforeChildAnonymousContainer->isRenderFullScreenPlaceholder()
821 #endif
822                 ) {
823                 // Insert the child into the anonymous block box instead of here.
824                 if (newChild->isInline() || beforeChild->parent()->firstChild() != beforeChild)
825                     beforeChild->parent()->addChild(newChild, beforeChild);
826                 else
827                     addChild(newChild, beforeChild->parent());
828                 return;
829             }
830
831             ASSERT(beforeChildAnonymousContainer->isTable());
832             if (newChild->isTablePart()) {
833                 // Insert into the anonymous table.
834                 beforeChildAnonymousContainer->addChild(newChild, beforeChild);
835                 return;
836             }
837
838             beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
839
840             ASSERT(beforeChild->parent() == this);
841             if (beforeChild->parent() != this) {
842                 // We should never reach here. If we do, we need to use the
843                 // safe fallback to use the topmost beforeChild container.
844                 beforeChild = beforeChildContainer;
845             }
846         } else {
847             // We will reach here when beforeChild is a run-in element.
848             // If run-in element precedes a block-level element, it becomes the
849             // the first inline child of that block level element. The insertion
850             // point will be before that block-level element.
851             ASSERT(beforeChild->isRunIn());
852             beforeChild = beforeChildContainer;
853         }
854     }
855
856     // Nothing goes before the intruded run-in.
857     if (beforeChild && beforeChild->isRunIn() && runInIsPlacedIntoSiblingBlock(beforeChild))
858         beforeChild = beforeChild->nextSibling();
859
860     // Check for a spanning element in columns.
861     if (gColumnFlowSplitEnabled) {
862         RenderBlock* columnsBlockAncestor = columnsBlockForSpanningElement(newChild);
863         if (columnsBlockAncestor) {
864             TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
865             // We are placing a column-span element inside a block.
866             RenderBlock* newBox = createAnonymousColumnSpanBlock();
867         
868             if (columnsBlockAncestor != this && !isRenderFlowThread()) {
869                 // We are nested inside a multi-column element and are being split by the span. We have to break up
870                 // our block into continuations.
871                 RenderBoxModelObject* oldContinuation = continuation();
872
873                 // When we split an anonymous block, there's no need to do any continuation hookup,
874                 // since we haven't actually split a real element.
875                 if (!isAnonymousBlock())
876                     setContinuation(newBox);
877
878                 splitFlow(beforeChild, newBox, newChild, oldContinuation);
879                 return;
880             }
881
882             // We have to perform a split of this block's children. This involves creating an anonymous block box to hold
883             // the column-spanning |newChild|. We take all of the children from before |newChild| and put them into
884             // one anonymous columns block, and all of the children after |newChild| go into another anonymous block.
885             makeChildrenAnonymousColumnBlocks(beforeChild, newBox, newChild);
886             return;
887         }
888     }
889
890     bool madeBoxesNonInline = false;
891
892     // A block has to either have all of its children inline, or all of its children as blocks.
893     // So, if our children are currently inline and a block child has to be inserted, we move all our
894     // inline children into anonymous block boxes.
895     if (childrenInline() && !newChild->isInline() && !newChild->isFloatingOrOutOfFlowPositioned()) {
896         // This is a block with inline content. Wrap the inline content in anonymous blocks.
897         makeChildrenNonInline(beforeChild);
898         madeBoxesNonInline = true;
899
900         if (beforeChild && beforeChild->parent() != this) {
901             beforeChild = beforeChild->parent();
902             ASSERT(beforeChild->isAnonymousBlock());
903             ASSERT(beforeChild->parent() == this);
904         }
905     } else if (!childrenInline() && (newChild->isFloatingOrOutOfFlowPositioned() || newChild->isInline())) {
906         // If we're inserting an inline child but all of our children are blocks, then we have to make sure
907         // it is put into an anomyous block box. We try to use an existing anonymous box if possible, otherwise
908         // a new one is created and inserted into our list of children in the appropriate position.
909         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : lastChild();
910
911         if (afterChild && afterChild->isAnonymousBlock()) {
912             afterChild->addChild(newChild);
913             return;
914         }
915
916         if (newChild->isInline()) {
917             // No suitable existing anonymous box - create a new one.
918             RenderBlock* newBox = createAnonymousBlock();
919             RenderBox::addChild(newBox, beforeChild);
920             newBox->addChild(newChild);
921             return;
922         }
923     }
924
925     RenderBox::addChild(newChild, beforeChild);
926  
927     // Handle placement of run-ins.
928     placeRunInIfNeeded(newChild);
929
930     if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
931         toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
932     // this object may be dead here
933 }
934
935 void RenderBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
936 {
937     if (continuation() && !isAnonymousBlock())
938         addChildToContinuation(newChild, beforeChild);
939     else
940         addChildIgnoringContinuation(newChild, beforeChild);
941 }
942
943 void RenderBlock::addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild)
944 {
945     if (!isAnonymousBlock() && firstChild() && (firstChild()->isAnonymousColumnsBlock() || firstChild()->isAnonymousColumnSpanBlock()))
946         addChildToAnonymousColumnBlocks(newChild, beforeChild);
947     else
948         addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
949 }
950
951 static void getInlineRun(RenderObject* start, RenderObject* boundary,
952                          RenderObject*& inlineRunStart,
953                          RenderObject*& inlineRunEnd)
954 {
955     // Beginning at |start| we find the largest contiguous run of inlines that
956     // we can.  We denote the run with start and end points, |inlineRunStart|
957     // and |inlineRunEnd|.  Note that these two values may be the same if
958     // we encounter only one inline.
959     //
960     // We skip any non-inlines we encounter as long as we haven't found any
961     // inlines yet.
962     //
963     // |boundary| indicates a non-inclusive boundary point.  Regardless of whether |boundary|
964     // is inline or not, we will not include it in a run with inlines before it.  It's as though we encountered
965     // a non-inline.
966     
967     // Start by skipping as many non-inlines as we can.
968     RenderObject * curr = start;
969     bool sawInline;
970     do {
971         while (curr && !(curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()))
972             curr = curr->nextSibling();
973         
974         inlineRunStart = inlineRunEnd = curr;
975         
976         if (!curr)
977             return; // No more inline children to be found.
978         
979         sawInline = curr->isInline();
980         
981         curr = curr->nextSibling();
982         while (curr && (curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()) && (curr != boundary)) {
983             inlineRunEnd = curr;
984             if (curr->isInline())
985                 sawInline = true;
986             curr = curr->nextSibling();
987         }
988     } while (!sawInline);
989 }
990
991 void RenderBlock::deleteLineBoxTree()
992 {
993     if (containsFloats()) {
994         // Clear references to originating lines, since the lines are being deleted
995         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
996         FloatingObjectSetIterator end = floatingObjectSet.end();
997         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
998             ASSERT(!((*it)->originatingLine()) || (*it)->originatingLine()->renderer() == this);
999             (*it)->setOriginatingLine(0);
1000         }
1001     }
1002     m_lineBoxes.deleteLineBoxTree(renderArena());
1003
1004     if (AXObjectCache* cache = document()->existingAXObjectCache())
1005         cache->recomputeIsIgnored(this);
1006 }
1007
1008 RootInlineBox* RenderBlock::createRootInlineBox()
1009 {
1010     return new (renderArena()) RootInlineBox(this);
1011 }
1012
1013 RootInlineBox* RenderBlock::createAndAppendRootInlineBox()
1014 {
1015     RootInlineBox* rootBox = createRootInlineBox();
1016     m_lineBoxes.appendLineBox(rootBox);
1017
1018     if (UNLIKELY(AXObjectCache::accessibilityEnabled()) && m_lineBoxes.firstLineBox() == rootBox) {
1019         if (AXObjectCache* cache = document()->existingAXObjectCache())
1020             cache->recomputeIsIgnored(this);
1021     }
1022
1023     return rootBox;
1024 }
1025
1026 void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
1027 {    
1028     // makeChildrenNonInline takes a block whose children are *all* inline and it
1029     // makes sure that inline children are coalesced under anonymous
1030     // blocks.  If |insertionPoint| is defined, then it represents the insertion point for
1031     // the new block child that is causing us to have to wrap all the inlines.  This
1032     // means that we cannot coalesce inlines before |insertionPoint| with inlines following
1033     // |insertionPoint|, because the new child is going to be inserted in between the inlines,
1034     // splitting them.
1035     ASSERT(isInlineBlockOrInlineTable() || !isInline());
1036     ASSERT(!insertionPoint || insertionPoint->parent() == this);
1037
1038     setChildrenInline(false);
1039
1040     RenderObject *child = firstChild();
1041     if (!child)
1042         return;
1043
1044     deleteLineBoxTree();
1045
1046     // Since we are going to have block children, we have to move
1047     // back the run-in to its original place.
1048     if (child->isRunIn()) {
1049         moveRunInToOriginalPosition(child);
1050         child = firstChild();
1051     }
1052
1053     while (child) {
1054         RenderObject *inlineRunStart, *inlineRunEnd;
1055         getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
1056
1057         if (!inlineRunStart)
1058             break;
1059
1060         child = inlineRunEnd->nextSibling();
1061
1062         RenderBlock* block = createAnonymousBlock();
1063         children()->insertChildNode(this, block, inlineRunStart);
1064         moveChildrenTo(block, inlineRunStart, child);
1065     }
1066
1067 #ifndef NDEBUG
1068     for (RenderObject *c = firstChild(); c; c = c->nextSibling())
1069         ASSERT(!c->isInline());
1070 #endif
1071
1072     repaint();
1073 }
1074
1075 void RenderBlock::removeLeftoverAnonymousBlock(RenderBlock* child)
1076 {
1077     ASSERT(child->isAnonymousBlock());
1078     ASSERT(!child->childrenInline());
1079     
1080     if (child->continuation() || (child->firstChild() && (child->isAnonymousColumnSpanBlock() || child->isAnonymousColumnsBlock())))
1081         return;
1082     
1083     RenderObject* firstAnChild = child->m_children.firstChild();
1084     RenderObject* lastAnChild = child->m_children.lastChild();
1085     if (firstAnChild) {
1086         RenderObject* o = firstAnChild;
1087         while (o) {
1088             o->setParent(this);
1089             o = o->nextSibling();
1090         }
1091         firstAnChild->setPreviousSibling(child->previousSibling());
1092         lastAnChild->setNextSibling(child->nextSibling());
1093         if (child->previousSibling())
1094             child->previousSibling()->setNextSibling(firstAnChild);
1095         if (child->nextSibling())
1096             child->nextSibling()->setPreviousSibling(lastAnChild);
1097             
1098         if (child == m_children.firstChild())
1099             m_children.setFirstChild(firstAnChild);
1100         if (child == m_children.lastChild())
1101             m_children.setLastChild(lastAnChild);
1102     } else {
1103         if (child == m_children.firstChild())
1104             m_children.setFirstChild(child->nextSibling());
1105         if (child == m_children.lastChild())
1106             m_children.setLastChild(child->previousSibling());
1107
1108         if (child->previousSibling())
1109             child->previousSibling()->setNextSibling(child->nextSibling());
1110         if (child->nextSibling())
1111             child->nextSibling()->setPreviousSibling(child->previousSibling());
1112     }
1113
1114     child->children()->setFirstChild(0);
1115     child->m_next = 0;
1116
1117     // Remove all the information in the flow thread associated with the leftover anonymous block.
1118     child->removeFromRenderFlowThread();
1119
1120     child->setParent(0);
1121     child->setPreviousSibling(0);
1122     child->setNextSibling(0);
1123
1124     child->destroy();
1125 }
1126
1127 static bool canMergeContiguousAnonymousBlocks(RenderObject* oldChild, RenderObject* prev, RenderObject* next)
1128 {
1129     if (oldChild->documentBeingDestroyed() || oldChild->isInline() || oldChild->virtualContinuation())
1130         return false;
1131
1132     if ((prev && (!prev->isAnonymousBlock() || toRenderBlock(prev)->continuation() || toRenderBlock(prev)->beingDestroyed()))
1133         || (next && (!next->isAnonymousBlock() || toRenderBlock(next)->continuation() || toRenderBlock(next)->beingDestroyed())))
1134         return false;
1135
1136     // FIXME: This check isn't required when inline run-ins can't be split into continuations.
1137     if (prev && prev->firstChild() && prev->firstChild()->isInline() && prev->firstChild()->isRunIn())
1138         return false;
1139
1140     if ((prev && (prev->isRubyRun() || prev->isRubyBase()))
1141         || (next && (next->isRubyRun() || next->isRubyBase())))
1142         return false;
1143
1144     if (!prev || !next)
1145         return true;
1146
1147     // Make sure the types of the anonymous blocks match up.
1148     return prev->isAnonymousColumnsBlock() == next->isAnonymousColumnsBlock()
1149            && prev->isAnonymousColumnSpanBlock() == next->isAnonymousColumnSpanBlock();
1150 }
1151
1152 void RenderBlock::collapseAnonymousBoxChild(RenderBlock* parent, RenderObject* child)
1153 {
1154     parent->setNeedsLayoutAndPrefWidthsRecalc();
1155     parent->setChildrenInline(child->childrenInline());
1156     RenderObject* nextSibling = child->nextSibling();
1157
1158     RenderFlowThread* childFlowThread = child->flowThreadContainingBlock();
1159     CurrentRenderFlowThreadMaintainer flowThreadMaintainer(childFlowThread);
1160     
1161     RenderBlock* anonBlock = toRenderBlock(parent->children()->removeChildNode(parent, child, child->hasLayer()));
1162     anonBlock->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
1163     // Delete the now-empty block's lines and nuke it.
1164     anonBlock->deleteLineBoxTree();
1165     if (childFlowThread && childFlowThread->isRenderNamedFlowThread())
1166         toRenderNamedFlowThread(childFlowThread)->removeFlowChildInfo(anonBlock);
1167     anonBlock->destroy();
1168 }
1169
1170 void RenderBlock::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
1171 {
1172     moveAllChildrenTo(toBlock, fullRemoveInsert);
1173
1174     // When a portion of the render tree is being detached, anonymous blocks
1175     // will be combined as their children are deleted. In this process, the
1176     // anonymous block later in the tree is merged into the one preceeding it.
1177     // It can happen that the later block (this) contains floats that the
1178     // previous block (toBlock) did not contain, and thus are not in the
1179     // floating objects list for toBlock. This can result in toBlock containing
1180     // floats that are not in it's floating objects list, but are in the
1181     // floating objects lists of siblings and parents. This can cause problems
1182     // when the float itself is deleted, since the deletion code assumes that
1183     // if a float is not in it's containing block's floating objects list, it
1184     // isn't in any floating objects list. In order to preserve this condition
1185     // (removing it has serious performance implications), we need to copy the
1186     // floating objects from the old block (this) to the new block (toBlock).
1187     // The float's metrics will likely all be wrong, but since toBlock is
1188     // already marked for layout, this will get fixed before anything gets
1189     // displayed.
1190     // See bug https://bugs.webkit.org/show_bug.cgi?id=115566
1191     if (m_floatingObjects) {
1192         if (!toBlock->m_floatingObjects)
1193             toBlock->createFloatingObjects();
1194
1195         const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
1196         FloatingObjectSetIterator end = fromFloatingObjectSet.end();
1197
1198         for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
1199             FloatingObject* floatingObject = *it;
1200
1201             // Don't insert the object again if it's already in the list
1202             if (toBlock->containsFloat(floatingObject->renderer()))
1203                 continue;
1204
1205             toBlock->m_floatingObjects->add(floatingObject->clone());
1206         }
1207     }
1208 }
1209
1210 void RenderBlock::removeChild(RenderObject* oldChild)
1211 {
1212     // No need to waste time in merging or removing empty anonymous blocks.
1213     // We can just bail out if our document is getting destroyed.
1214     if (documentBeingDestroyed()) {
1215         RenderBox::removeChild(oldChild);
1216         return;
1217     }
1218
1219     // This protects against column split flows when anonymous blocks are getting merged.
1220     TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
1221
1222     // If this child is a block, and if our previous and next siblings are
1223     // both anonymous blocks with inline content, then we can go ahead and
1224     // fold the inline content back together.
1225     RenderObject* prev = oldChild->previousSibling();
1226     RenderObject* next = oldChild->nextSibling();
1227     bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
1228     if (canMergeAnonymousBlocks && prev && next) {
1229         prev->setNeedsLayoutAndPrefWidthsRecalc();
1230         RenderBlock* nextBlock = toRenderBlock(next);
1231         RenderBlock* prevBlock = toRenderBlock(prev);
1232        
1233         if (prev->childrenInline() != next->childrenInline()) {
1234             RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
1235             RenderBlock* blockChildrenBlock = prev->childrenInline() ? nextBlock : prevBlock;
1236             
1237             // Place the inline children block inside of the block children block instead of deleting it.
1238             // In order to reuse it, we have to reset it to just be a generic anonymous block.  Make sure
1239             // to clear out inherited column properties by just making a new style, and to also clear the
1240             // column span flag if it is set.
1241             ASSERT(!inlineChildrenBlock->continuation());
1242             RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK);
1243             // Cache this value as it might get changed in setStyle() call.
1244             bool inlineChildrenBlockHasLayer = inlineChildrenBlock->hasLayer();
1245             inlineChildrenBlock->setStyle(newStyle);
1246             children()->removeChildNode(this, inlineChildrenBlock, inlineChildrenBlockHasLayer);
1247             
1248             // Now just put the inlineChildrenBlock inside the blockChildrenBlock.
1249             blockChildrenBlock->children()->insertChildNode(blockChildrenBlock, inlineChildrenBlock, prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : 0,
1250                                                             inlineChildrenBlockHasLayer || blockChildrenBlock->hasLayer());
1251             next->setNeedsLayoutAndPrefWidthsRecalc();
1252             
1253             // inlineChildrenBlock got reparented to blockChildrenBlock, so it is no longer a child
1254             // of "this". we null out prev or next so that is not used later in the function.
1255             if (inlineChildrenBlock == prevBlock)
1256                 prev = 0;
1257             else
1258                 next = 0;
1259         } else {
1260             // Take all the children out of the |next| block and put them in
1261             // the |prev| block.
1262             nextBlock->moveAllChildrenIncludingFloatsTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());
1263             
1264             // Delete the now-empty block's lines and nuke it.
1265             nextBlock->deleteLineBoxTree();
1266             nextBlock->destroy();
1267             next = 0;
1268         }
1269     }
1270
1271     RenderBox::removeChild(oldChild);
1272
1273     RenderObject* child = prev ? prev : next;
1274     if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && canCollapseAnonymousBlockChild()) {
1275         // The removal has knocked us down to containing only a single anonymous
1276         // box.  We can go ahead and pull the content right back up into our
1277         // box.
1278         collapseAnonymousBoxChild(this, child);
1279     } else if (((prev && prev->isAnonymousBlock()) || (next && next->isAnonymousBlock())) && canCollapseAnonymousBlockChild()) {
1280         // It's possible that the removal has knocked us down to a single anonymous
1281         // block with pseudo-style element siblings (e.g. first-letter). If these
1282         // are floating, then we need to pull the content up also.
1283         RenderBlock* anonBlock = toRenderBlock((prev && prev->isAnonymousBlock()) ? prev : next);
1284         if ((anonBlock->previousSibling() || anonBlock->nextSibling())
1285             && (!anonBlock->previousSibling() || (anonBlock->previousSibling()->style()->styleType() != NOPSEUDO && anonBlock->previousSibling()->isFloating() && !anonBlock->previousSibling()->previousSibling()))
1286             && (!anonBlock->nextSibling() || (anonBlock->nextSibling()->style()->styleType() != NOPSEUDO && anonBlock->nextSibling()->isFloating() && !anonBlock->nextSibling()->nextSibling()))) {
1287             collapseAnonymousBoxChild(this, anonBlock);
1288         }
1289     }
1290
1291     if (!firstChild()) {
1292         // If this was our last child be sure to clear out our line boxes.
1293         if (childrenInline())
1294             deleteLineBoxTree();
1295
1296         // If we are an empty anonymous block in the continuation chain,
1297         // we need to remove ourself and fix the continuation chain.
1298         if (!beingDestroyed() && isAnonymousBlockContinuation() && !oldChild->isListMarker()) {
1299             RenderObject* containingBlockIgnoringAnonymous = containingBlock();
1300             while (containingBlockIgnoringAnonymous && containingBlockIgnoringAnonymous->isAnonymousBlock())
1301                 containingBlockIgnoringAnonymous = containingBlockIgnoringAnonymous->containingBlock();
1302             for (RenderObject* curr = this; curr; curr = curr->previousInPreOrder(containingBlockIgnoringAnonymous)) {
1303                 if (curr->virtualContinuation() != this)
1304                     continue;
1305
1306                 // Found our previous continuation. We just need to point it to
1307                 // |this|'s next continuation.
1308                 RenderBoxModelObject* nextContinuation = continuation();
1309                 if (curr->isRenderInline())
1310                     toRenderInline(curr)->setContinuation(nextContinuation);
1311                 else if (curr->isRenderBlock())
1312                     toRenderBlock(curr)->setContinuation(nextContinuation);
1313                 else
1314                     ASSERT_NOT_REACHED();
1315
1316                 break;
1317             }
1318             setContinuation(0);
1319             destroy();
1320         }
1321     }
1322 }
1323
1324 bool RenderBlock::isSelfCollapsingBlock() const
1325 {
1326     // We are not self-collapsing if we
1327     // (a) have a non-zero height according to layout (an optimization to avoid wasting time)
1328     // (b) are a table,
1329     // (c) have border/padding,
1330     // (d) have a min-height
1331     // (e) have specified that one of our margins can't collapse using a CSS extension
1332     if (logicalHeight() > 0
1333         || isTable() || borderAndPaddingLogicalHeight()
1334         || style()->logicalMinHeight().isPositive()
1335         || style()->marginBeforeCollapse() == MSEPARATE || style()->marginAfterCollapse() == MSEPARATE)
1336         return false;
1337
1338     Length logicalHeightLength = style()->logicalHeight();
1339     bool hasAutoHeight = logicalHeightLength.isAuto();
1340     if (logicalHeightLength.isPercent() && !document()->inQuirksMode()) {
1341         hasAutoHeight = true;
1342         for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
1343             if (cb->style()->logicalHeight().isFixed() || cb->isTableCell())
1344                 hasAutoHeight = false;
1345         }
1346     }
1347
1348     // If the height is 0 or auto, then whether or not we are a self-collapsing block depends
1349     // on whether we have content that is all self-collapsing or not.
1350     if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
1351         // If the block has inline children, see if we generated any line boxes.  If we have any
1352         // line boxes, then we can't be self-collapsing, since we have content.
1353         if (childrenInline())
1354             return !firstLineBox();
1355         
1356         // Whether or not we collapse is dependent on whether all our normal flow children
1357         // are also self-collapsing.
1358         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1359             if (child->isFloatingOrOutOfFlowPositioned())
1360                 continue;
1361             if (!child->isSelfCollapsingBlock())
1362                 return false;
1363         }
1364         return true;
1365     }
1366     return false;
1367 }
1368
1369 void RenderBlock::startDelayUpdateScrollInfo()
1370 {
1371     if (gDelayUpdateScrollInfo == 0) {
1372         ASSERT(!gDelayedUpdateScrollInfoSet);
1373         gDelayedUpdateScrollInfoSet = new DelayedUpdateScrollInfoSet;
1374     }
1375     ASSERT(gDelayedUpdateScrollInfoSet);
1376     ++gDelayUpdateScrollInfo;
1377 }
1378
1379 void RenderBlock::finishDelayUpdateScrollInfo()
1380 {
1381     --gDelayUpdateScrollInfo;
1382     ASSERT(gDelayUpdateScrollInfo >= 0);
1383     if (gDelayUpdateScrollInfo == 0) {
1384         ASSERT(gDelayedUpdateScrollInfoSet);
1385
1386         OwnPtr<DelayedUpdateScrollInfoSet> infoSet(adoptPtr(gDelayedUpdateScrollInfoSet));
1387         gDelayedUpdateScrollInfoSet = 0;
1388
1389         for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
1390             RenderBlock* block = *it;
1391             if (block->hasOverflowClip()) {
1392                 block->layer()->updateScrollInfoAfterLayout();
1393                 block->clearLayoutOverflow();
1394             }
1395         }
1396     }
1397 }
1398
1399 void RenderBlock::updateScrollInfoAfterLayout()
1400 {
1401     if (hasOverflowClip()) {
1402         if (style()->isFlippedBlocksWritingMode()) {
1403             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=97937
1404             // Workaround for now. We cannot delay the scroll info for overflow
1405             // for items with opposite writing directions, as the contents needs
1406             // to overflow in that direction
1407             layer()->updateScrollInfoAfterLayout();
1408             return;
1409         }
1410
1411         if (gDelayUpdateScrollInfo)
1412             gDelayedUpdateScrollInfoSet->add(this);
1413         else
1414             layer()->updateScrollInfoAfterLayout();
1415     }
1416 }
1417
1418 void RenderBlock::layout()
1419 {
1420     StackStats::LayoutCheckPoint layoutCheckPoint;
1421     OverflowEventDispatcher dispatcher(this);
1422
1423     // Update our first letter info now.
1424     updateFirstLetter();
1425
1426     // Table cells call layoutBlock directly, so don't add any logic here.  Put code into
1427     // layoutBlock().
1428     layoutBlock(false);
1429     
1430     // It's safe to check for control clip here, since controls can never be table cells.
1431     // If we have a lightweight clip, there can never be any overflow from children.
1432     if (hasControlClip() && m_overflow && !gDelayUpdateScrollInfo)
1433         clearLayoutOverflow();
1434
1435     invalidateBackgroundObscurationStatus();
1436 }
1437
1438 #if ENABLE(CSS_SHAPES)
1439 void RenderBlock::imageChanged(WrappedImagePtr image, const IntRect*)
1440 {
1441     RenderBox::imageChanged(image);
1442
1443     if (!parent())
1444         return;
1445
1446     ShapeValue* shapeValue = style()->shapeInside();
1447     if (shapeValue && shapeValue->image() && shapeValue->image()->data() == image) {
1448         ShapeInsideInfo* shapeInsideInfo = ensureShapeInsideInfo();
1449         shapeInsideInfo->dirtyShapeSize();
1450         markShapeInsideDescendantsForLayout();
1451     }
1452 }
1453
1454 void RenderBlock::updateShapeInsideInfoAfterStyleChange(const ShapeValue* shapeInside, const ShapeValue* oldShapeInside)
1455 {
1456     // FIXME: A future optimization would do a deep comparison for equality.
1457     if (shapeInside == oldShapeInside)
1458         return;
1459
1460     if (shapeInside) {
1461         ShapeInsideInfo* shapeInsideInfo = ensureShapeInsideInfo();
1462         shapeInsideInfo->dirtyShapeSize();
1463     } else {
1464         setShapeInsideInfo(nullptr);
1465         markShapeInsideDescendantsForLayout();
1466     }
1467 }
1468
1469 void RenderBlock::markShapeInsideDescendantsForLayout()
1470 {
1471     if (!everHadLayout())
1472         return;
1473     if (childrenInline()) {
1474         setNeedsLayout(true);
1475         return;
1476     }
1477     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1478         if (!child->isRenderBlock())
1479             continue;
1480         RenderBlock* childBlock = toRenderBlock(child);
1481         childBlock->markShapeInsideDescendantsForLayout();
1482     }
1483 }
1484 #endif
1485
1486 #if ENABLE(CSS_SHAPES)
1487 static inline bool shapeInfoRequiresRelayout(const RenderBlock* block)
1488 {
1489     ShapeInsideInfo* info = block->shapeInsideInfo();
1490     if (info)
1491         info->setNeedsLayout(info->shapeSizeDirty());
1492     else
1493         info = block->layoutShapeInsideInfo();
1494     return info && info->needsLayout();
1495 }
1496 #endif
1497
1498 bool RenderBlock::updateShapesBeforeBlockLayout()
1499 {
1500 #if ENABLE(CSS_SHAPES)
1501     if (!flowThreadContainingBlock() && !shapeInsideInfo())
1502         return shapeInfoRequiresRelayout(this);
1503
1504     LayoutUnit oldHeight = logicalHeight();
1505     LayoutUnit oldTop = logicalTop();
1506
1507     // Compute the maximum logical height content may cause this block to expand to
1508     // FIXME: These should eventually use the const computeLogicalHeight rather than updateLogicalHeight
1509     setLogicalHeight(RenderFlowThread::maxLogicalHeight());
1510     updateLogicalHeight();
1511
1512     computeShapeSize();
1513
1514     setLogicalHeight(oldHeight);
1515     setLogicalTop(oldTop);
1516
1517     return shapeInfoRequiresRelayout(this);
1518 #else
1519     return false;
1520 #endif
1521 }
1522
1523 #if ENABLE(CSS_SHAPES)
1524 void RenderBlock::computeShapeSize()
1525 {
1526     ShapeInsideInfo* shapeInsideInfo = this->shapeInsideInfo();
1527     if (shapeInsideInfo) {
1528         bool percentageLogicalHeightResolvable = percentageLogicalHeightIsResolvableFromBlock(this, false);
1529         shapeInsideInfo->setShapeSize(logicalWidth(), percentageLogicalHeightResolvable ? logicalHeight() : LayoutUnit());
1530     }
1531 }
1532 #endif
1533
1534 void RenderBlock::updateShapesAfterBlockLayout(bool heightChanged)
1535 {
1536 #if ENABLE(CSS_SHAPES)
1537     // A previous sibling has changed dimension, so we need to relayout the shape with the content
1538     ShapeInsideInfo* shapeInsideInfo = layoutShapeInsideInfo();
1539     if (heightChanged && shapeInsideInfo)
1540         shapeInsideInfo->dirtyShapeSize();
1541 #else
1542     UNUSED_PARAM(heightChanged);
1543 #endif
1544 }
1545
1546 bool RenderBlock::updateLogicalWidthAndColumnWidth()
1547 {
1548     LayoutUnit oldWidth = logicalWidth();
1549     LayoutUnit oldColumnWidth = desiredColumnWidth();
1550
1551     updateLogicalWidth();
1552     calcColumnWidth();
1553
1554     bool hasBorderOrPaddingLogicalWidthChanged = m_hasBorderOrPaddingLogicalWidthChanged;
1555     m_hasBorderOrPaddingLogicalWidthChanged = false;
1556
1557     return oldWidth != logicalWidth() || oldColumnWidth != desiredColumnWidth() || hasBorderOrPaddingLogicalWidthChanged;
1558 }
1559
1560 void RenderBlock::checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight)
1561 {
1562     ColumnInfo* colInfo = columnInfo();
1563     if (hasColumns()) {
1564         if (!pageLogicalHeight) {
1565             // We need to go ahead and set our explicit page height if one exists, so that we can
1566             // avoid doing two layout passes.
1567             updateLogicalHeight();
1568             LayoutUnit columnHeight = isRenderView() ? view()->pageOrViewLogicalHeight() : contentLogicalHeight();
1569             if (columnHeight > 0) {
1570                 pageLogicalHeight = columnHeight;
1571                 hasSpecifiedPageLogicalHeight = true;
1572             }
1573             setLogicalHeight(0);
1574         }
1575
1576         if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout())
1577             pageLogicalHeightChanged = true;
1578
1579         colInfo->setColumnHeight(pageLogicalHeight);
1580         
1581         if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
1582             colInfo->clearForcedBreaks();
1583
1584         colInfo->setPaginationUnit(paginationUnit());
1585     } else if (isRenderFlowThread()) {
1586         pageLogicalHeight = 1; // This is just a hack to always make sure we have a page logical height.
1587         pageLogicalHeightChanged = toRenderFlowThread(this)->pageLogicalSizeChanged();
1588     }
1589 }
1590
1591 bool RenderBlock::relayoutToAvoidWidows(LayoutStateMaintainer& statePusher)
1592 {
1593     if (!shouldBreakAtLineToAvoidWidow())
1594         return false;
1595
1596     statePusher.pop();
1597     setEverHadLayout(true);
1598     layoutBlock(false);
1599     return true;
1600 }
1601
1602 void RenderBlock::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
1603 {
1604     ASSERT(needsLayout());
1605
1606     if (isInline() && !isInlineBlockOrInlineTable()) // Inline <form>s inside various table elements can
1607         return;                                      // cause us to come in here.  Just bail.
1608
1609     if (!relayoutChildren && simplifiedLayout())
1610         return;
1611
1612     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
1613
1614     if (updateLogicalWidthAndColumnWidth())
1615         relayoutChildren = true;
1616
1617     clearFloats();
1618
1619     LayoutUnit previousHeight = logicalHeight();
1620     // FIXME: should this start out as borderAndPaddingLogicalHeight() + scrollbarLogicalHeight(),
1621     // for consistency with other render classes?
1622     setLogicalHeight(0);
1623
1624     bool pageLogicalHeightChanged = false;
1625     bool hasSpecifiedPageLogicalHeight = false;
1626     checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
1627
1628     RenderView* renderView = view();
1629     RenderStyle* styleToUse = style();
1630     LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
1631
1632     // Regions changing widths can force us to relayout our children.
1633     RenderFlowThread* flowThread = flowThreadContainingBlock();
1634     if (logicalWidthChangedInRegions(flowThread))
1635         relayoutChildren = true;
1636     if (updateShapesBeforeBlockLayout())
1637         relayoutChildren = true;
1638
1639     // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
1640     // our current maximal positive and negative margins.  These values are used when we
1641     // are collapsed with adjacent blocks, so for example, if you have block A and B
1642     // collapsing together, then you'd take the maximal positive margin from both A and B
1643     // and subtract it from the maximal negative margin from both A and B to get the
1644     // true collapsed margin.  This algorithm is recursive, so when we finish layout()
1645     // our block knows its current maximal positive/negative values.
1646     //
1647     // Start out by setting our margin values to our current margins.  Table cells have
1648     // no margins, so we don't fill in the values for table cells.
1649     bool isCell = isTableCell();
1650     if (!isCell) {
1651         initMaxMarginValues();
1652         
1653         setHasMarginBeforeQuirk(styleToUse->hasMarginBeforeQuirk());
1654         setHasMarginAfterQuirk(styleToUse->hasMarginAfterQuirk());
1655         setPaginationStrut(0);
1656     }
1657
1658     LayoutUnit repaintLogicalTop = 0;
1659     LayoutUnit repaintLogicalBottom = 0;
1660     LayoutUnit maxFloatLogicalBottom = 0;
1661     if (!firstChild() && !isAnonymousBlock())
1662         setChildrenInline(true);
1663     if (childrenInline())
1664         layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
1665     else
1666         layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
1667
1668     // Expand our intrinsic height to encompass floats.
1669     LayoutUnit toAdd = borderAndPaddingAfter() + scrollbarLogicalHeight();
1670     if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
1671         setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
1672     
1673     if (relayoutForPagination(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher) || relayoutToAvoidWidows(statePusher)) {
1674         ASSERT(!shouldBreakAtLineToAvoidWidow());
1675         return;
1676     }
1677
1678     // Calculate our new height.
1679     LayoutUnit oldHeight = logicalHeight();
1680     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
1681
1682     // Before updating the final size of the flow thread make sure a forced break is applied after the content.
1683     // This ensures the size information is correctly computed for the last auto-height region receiving content.
1684     if (isRenderFlowThread())
1685         toRenderFlowThread(this)->applyBreakAfterContent(oldClientAfterEdge);
1686
1687     updateLogicalHeight();
1688     LayoutUnit newHeight = logicalHeight();
1689     if (oldHeight != newHeight) {
1690         if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
1691             // One of our children's floats may have become an overhanging float for us. We need to look for it.
1692             for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1693                 if (child->isBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
1694                     RenderBlock* block = toRenderBlock(child);
1695                     if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
1696                         addOverhangingFloats(block, false);
1697                 }
1698             }
1699         }
1700     }
1701
1702     bool heightChanged = (previousHeight != newHeight);
1703     if (heightChanged)
1704         relayoutChildren = true;
1705
1706     layoutPositionedObjects(relayoutChildren || isRoot());
1707
1708     updateShapesAfterBlockLayout(heightChanged);
1709
1710     // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
1711     computeOverflow(oldClientAfterEdge);
1712     
1713     statePusher.pop();
1714
1715     fitBorderToLinesIfNeeded();
1716
1717     if (renderView->layoutState()->m_pageLogicalHeight)
1718         setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(this, logicalTop()));
1719
1720     updateLayerTransform();
1721
1722     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
1723     // we overflow or not.
1724     updateScrollInfoAfterLayout();
1725
1726     // FIXME: This repaint logic should be moved into a separate helper function!
1727     // Repaint with our new bounds if they are different from our old bounds.
1728     bool didFullRepaint = repainter.repaintAfterLayout();
1729     if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
1730         // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
1731         // it had to lay out.  We wouldn't need the hasOverflowClip() hack in that case either.
1732         LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
1733         LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
1734         if (hasOverflowClip()) {
1735             // If we have clipped overflow, we should use layout overflow as well, since visual overflow from lines didn't propagate to our block's overflow.
1736             // Note the old code did this as well but even for overflow:visible.  The addition of hasOverflowClip() at least tightens up the hack a bit.
1737             // layoutInlineChildren should be patched to compute the entire repaint rect.
1738             repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
1739             repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
1740         }
1741         
1742         LayoutRect repaintRect;
1743         if (isHorizontalWritingMode())
1744             repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
1745         else
1746             repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
1747
1748         // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
1749         adjustRectForColumns(repaintRect);
1750
1751         repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
1752         
1753         if (hasOverflowClip()) {
1754             // Adjust repaint rect for scroll offset
1755             repaintRect.move(-scrolledContentOffset());
1756
1757             // Don't allow this rect to spill out of our overflow box.
1758             repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
1759         }
1760
1761         // Make sure the rect is still non-empty after intersecting for overflow above
1762         if (!repaintRect.isEmpty()) {
1763             repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
1764             if (hasReflection())
1765                 repaintRectangle(reflectedRect(repaintRect));
1766         }
1767     }
1768
1769     setNeedsLayout(false);
1770 }
1771
1772 void RenderBlock::addOverflowFromChildren()
1773 {
1774     if (!hasColumns()) {
1775         if (childrenInline())
1776             addOverflowFromInlineChildren();
1777         else
1778             addOverflowFromBlockChildren();
1779     } else {
1780         ColumnInfo* colInfo = columnInfo();
1781         if (columnCount(colInfo)) {
1782             LayoutRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1);
1783             addLayoutOverflow(lastRect);
1784             if (!hasOverflowClip())
1785                 addVisualOverflow(lastRect);
1786         }
1787     }
1788 }
1789
1790 void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
1791 {
1792     m_overflow.clear();
1793
1794     // Add overflow from children.
1795     addOverflowFromChildren();
1796
1797     if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
1798         addOverflowFromFloats();
1799
1800     // Add in the overflow from positioned objects.
1801     addOverflowFromPositionedObjects();
1802
1803     if (hasOverflowClip()) {
1804         // When we have overflow clip, propagate the original spillout since it will include collapsed bottom margins
1805         // and bottom padding.  Set the axis we don't care about to be 1, since we want this overflow to always
1806         // be considered reachable.
1807         LayoutRect clientRect(clientBoxRect());
1808         LayoutRect rectToApply;
1809         if (isHorizontalWritingMode())
1810             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), 1, max<LayoutUnit>(0, oldClientAfterEdge - clientRect.y()));
1811         else
1812             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), max<LayoutUnit>(0, oldClientAfterEdge - clientRect.x()), 1);
1813         addLayoutOverflow(rectToApply);
1814         if (hasRenderOverflow())
1815             m_overflow->setLayoutClientAfterEdge(oldClientAfterEdge);
1816     }
1817         
1818     // Allow our overflow to catch cases where the caret in an empty editable element with negative text indent needs to get painted.
1819     LayoutUnit textIndent = textIndentOffset();
1820     if (textIndent < 0) {
1821         LayoutRect clientRect(clientBoxRect());
1822         LayoutRect rectToApply = LayoutRect(clientRect.x() + min<LayoutUnit>(0, textIndent), clientRect.y(), clientRect.width() - min<LayoutUnit>(0, textIndent), clientRect.height());
1823         addVisualOverflow(rectToApply);
1824     }
1825
1826     // Add visual overflow from box-shadow and border-image-outset.
1827     addVisualEffectOverflow();
1828
1829     // Add visual overflow from theme.
1830     addVisualOverflowFromTheme();
1831
1832     if (isRenderNamedFlowThread())
1833         toRenderNamedFlowThread(this)->computeOversetStateForRegions(oldClientAfterEdge);
1834 }
1835
1836 void RenderBlock::clearLayoutOverflow()
1837 {
1838     if (!m_overflow)
1839         return;
1840     
1841     if (visualOverflowRect() == borderBoxRect()) {
1842         m_overflow.clear();
1843         return;
1844     }
1845     
1846     m_overflow->setLayoutOverflow(borderBoxRect());
1847 }
1848
1849 void RenderBlock::addOverflowFromBlockChildren()
1850 {
1851     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1852         if (!child->isFloatingOrOutOfFlowPositioned())
1853             addOverflowFromChild(child);
1854     }
1855 }
1856
1857 void RenderBlock::addOverflowFromFloats()
1858 {
1859     if (!m_floatingObjects)
1860         return;
1861
1862     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1863     FloatingObjectSetIterator end = floatingObjectSet.end();
1864     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1865         FloatingObject* r = *it;
1866         if (r->isDescendant())
1867             addOverflowFromChild(r->renderer(), IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
1868     }
1869 }
1870
1871 void RenderBlock::addOverflowFromPositionedObjects()
1872 {
1873     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
1874     if (!positionedDescendants)
1875         return;
1876
1877     RenderBox* positionedObject;
1878     TrackedRendererListHashSet::iterator end = positionedDescendants->end();
1879     for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
1880         positionedObject = *it;
1881         
1882         // Fixed positioned elements don't contribute to layout overflow, since they don't scroll with the content.
1883         if (positionedObject->style()->position() != FixedPosition) {
1884             LayoutUnit x = positionedObject->x();
1885             if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1886                 x -= verticalScrollbarWidth();
1887             addOverflowFromChild(positionedObject, LayoutSize(x, positionedObject->y()));
1888         }
1889     }
1890 }
1891
1892 void RenderBlock::addVisualOverflowFromTheme()
1893 {
1894     if (!style()->hasAppearance())
1895         return;
1896
1897     IntRect inflatedRect = pixelSnappedBorderBoxRect();
1898     theme()->adjustRepaintRect(this, inflatedRect);
1899     addVisualOverflow(inflatedRect);
1900 }
1901
1902 bool RenderBlock::expandsToEncloseOverhangingFloats() const
1903 {
1904     return isInlineBlockOrInlineTable() || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || (parent() && parent()->isFlexibleBoxIncludingDeprecated())
1905            || hasColumns() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot();
1906 }
1907
1908 void RenderBlock::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
1909 {
1910     bool isHorizontal = isHorizontalWritingMode();
1911     bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
1912     
1913     LayoutUnit logicalTop = logicalHeight();
1914     updateStaticInlinePositionForChild(child, logicalTop);
1915
1916     if (!marginInfo.canCollapseWithMarginBefore()) {
1917         // Positioned blocks don't collapse margins, so add the margin provided by
1918         // the container now. The child's own margin is added later when calculating its logical top.
1919         LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
1920         LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
1921         logicalTop += collapsedBeforePos - collapsedBeforeNeg;
1922     }
1923     
1924     RenderLayer* childLayer = child->layer();
1925     if (childLayer->staticBlockPosition() != logicalTop) {
1926         childLayer->setStaticBlockPosition(logicalTop);
1927         if (hasStaticBlockPosition)
1928             child->setChildNeedsLayout(true, MarkOnlyThis);
1929     }
1930 }
1931
1932 void RenderBlock::adjustFloatingBlock(const MarginInfo& marginInfo)
1933 {
1934     // The float should be positioned taking into account the bottom margin
1935     // of the previous flow.  We add that margin into the height, get the
1936     // float positioned properly, and then subtract the margin out of the
1937     // height again.  In the case of self-collapsing blocks, we always just
1938     // use the top margins, since the self-collapsing block collapsed its
1939     // own bottom margin into its top margin.
1940     //
1941     // Note also that the previous flow may collapse its margin into the top of
1942     // our block.  If this is the case, then we do not add the margin in to our
1943     // height when computing the position of the float.   This condition can be tested
1944     // for by simply calling canCollapseWithMarginBefore.  See
1945     // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
1946     // an example of this scenario.
1947     LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1948     setLogicalHeight(logicalHeight() + marginOffset);
1949     positionNewFloats();
1950     setLogicalHeight(logicalHeight() - marginOffset);
1951 }
1952
1953 static void destroyRunIn(RenderBoxModelObject* runIn)
1954 {
1955     ASSERT(runIn->isRunIn());
1956     ASSERT(!runIn->firstChild());
1957
1958     // Delete our line box tree. This is needed as our children got moved
1959     // and our line box tree is no longer valid.
1960     if (runIn->isRenderBlock())
1961         toRenderBlock(runIn)->deleteLineBoxTree();
1962     else if (runIn->isRenderInline())
1963         toRenderInline(runIn)->deleteLineBoxTree();
1964     else
1965         ASSERT_NOT_REACHED();
1966
1967     runIn->destroy();
1968 }
1969
1970 void RenderBlock::placeRunInIfNeeded(RenderObject* newChild)
1971 {
1972     if (newChild->isRunIn())
1973         moveRunInUnderSiblingBlockIfNeeded(newChild);
1974     else if (RenderObject* prevSibling = newChild->previousSibling()) {
1975         if (prevSibling->isRunIn())
1976             moveRunInUnderSiblingBlockIfNeeded(prevSibling);
1977     }
1978 }
1979
1980 RenderBoxModelObject* RenderBlock::createReplacementRunIn(RenderBoxModelObject* runIn)
1981 {
1982     ASSERT(runIn->isRunIn());
1983     ASSERT(runIn->node());
1984
1985     RenderBoxModelObject* newRunIn = 0;
1986     if (!runIn->isRenderBlock())
1987         newRunIn = new (renderArena()) RenderBlock(runIn->node());
1988     else
1989         newRunIn = new (renderArena()) RenderInline(toElement(runIn->node()));
1990
1991     runIn->node()->setRenderer(newRunIn);
1992     newRunIn->setStyle(runIn->style());
1993
1994     runIn->moveAllChildrenTo(newRunIn, true);
1995
1996     return newRunIn;
1997 }
1998
1999 void RenderBlock::moveRunInUnderSiblingBlockIfNeeded(RenderObject* runIn)
2000 {
2001     ASSERT(runIn->isRunIn());
2002
2003     // See if we have inline children. If the children aren't inline,
2004     // then just treat the run-in as a normal block.
2005     if (!runIn->childrenInline())
2006         return;
2007
2008     // FIXME: We don't handle non-block elements with run-in for now.
2009     if (!runIn->isRenderBlock())
2010         return;
2011
2012     // FIXME: We don't support run-ins with or as part of a continuation
2013     // as it makes the back-and-forth placing complex.
2014     if (runIn->isElementContinuation() || runIn->virtualContinuation())
2015         return;
2016
2017     // Check if this node is allowed to run-in. E.g. <select> expects its renderer to
2018     // be a RenderListBox or RenderMenuList, and hence cannot be a RenderInline run-in.
2019     if (!runIn->canBeReplacedWithInlineRunIn())
2020         return;
2021
2022     RenderObject* curr = runIn->nextSibling();
2023     if (!curr || !curr->isRenderBlock() || !curr->childrenInline())
2024         return;
2025
2026     if (toRenderBlock(curr)->beingDestroyed())
2027         return;
2028
2029     // Per CSS3, "A run-in cannot run in to a block that already starts with a
2030     // run-in or that itself is a run-in".
2031     if (curr->isRunIn() || (curr->firstChild() && curr->firstChild()->isRunIn()))
2032         return;
2033
2034     if (curr->isAnonymous() || curr->isFloatingOrOutOfFlowPositioned())
2035         return;
2036
2037     RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
2038     RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
2039     destroyRunIn(oldRunIn);
2040
2041     // Now insert the new child under |curr| block. Use addChild instead of insertChildNode
2042     // since it handles correct placement of the children, especially where we cannot insert
2043     // anything before the first child. e.g. details tag. See https://bugs.webkit.org/show_bug.cgi?id=58228.
2044     curr->addChild(newRunIn, curr->firstChild());
2045
2046     // Make sure that |this| get a layout since its run-in child moved.
2047     curr->setNeedsLayoutAndPrefWidthsRecalc();
2048 }
2049
2050 bool RenderBlock::runInIsPlacedIntoSiblingBlock(RenderObject* runIn)
2051 {
2052     ASSERT(runIn->isRunIn());
2053
2054     // If we don't have a parent, we can't be moved into our sibling block.
2055     if (!parent())
2056         return false;
2057
2058     // An intruded run-in needs to be an inline.
2059     if (!runIn->isRenderInline())
2060         return false;
2061
2062     return true;
2063 }
2064
2065 void RenderBlock::moveRunInToOriginalPosition(RenderObject* runIn)
2066 {
2067     ASSERT(runIn->isRunIn());
2068
2069     if (!runInIsPlacedIntoSiblingBlock(runIn))
2070         return;
2071
2072     // FIXME: Run-in that are now placed in sibling block can break up into continuation
2073     // chains when new children are added to it. We cannot easily send them back to their
2074     // original place since that requires writing integration logic with RenderInline::addChild
2075     // and all other places that might cause continuations to be created (without blowing away
2076     // |this|). Disabling this feature for now to prevent crashes.
2077     if (runIn->isElementContinuation() || runIn->virtualContinuation())
2078         return;
2079
2080     RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
2081     RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
2082     destroyRunIn(oldRunIn);
2083
2084     // Add the run-in block as our previous sibling.
2085     parent()->addChild(newRunIn, this);
2086
2087     // Make sure that the parent holding the new run-in gets layout.
2088     parent()->setNeedsLayoutAndPrefWidthsRecalc();
2089 }
2090
2091 LayoutUnit RenderBlock::collapseMargins(RenderBox* child, MarginInfo& marginInfo)
2092 {
2093     bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
2094     bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
2095     bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
2096
2097     // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
2098     childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
2099
2100     // Get the four margin values for the child and cache them.
2101     const MarginValues childMargins = marginValuesForChild(child);
2102
2103     // Get our max pos and neg top margins.
2104     LayoutUnit posTop = childMargins.positiveMarginBefore();
2105     LayoutUnit negTop = childMargins.negativeMarginBefore();
2106
2107     // For self-collapsing blocks, collapse our bottom margins into our
2108     // top to get new posTop and negTop values.
2109     if (childIsSelfCollapsing) {
2110         posTop = max(posTop, childMargins.positiveMarginAfter());
2111         negTop = max(negTop, childMargins.negativeMarginAfter());
2112     }
2113     
2114     // See if the top margin is quirky. We only care if this child has
2115     // margins that will collapse with us.
2116     bool topQuirk = hasMarginBeforeQuirk(child);
2117
2118     if (marginInfo.canCollapseWithMarginBefore()) {
2119         if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
2120             // This child is collapsing with the top of the
2121             // block. If it has larger margin values, then we need to update
2122             // our own maximal values.
2123             if (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
2124                 setMaxMarginBeforeValues(max(posTop, maxPositiveMarginBefore()), max(negTop, maxNegativeMarginBefore()));
2125
2126             // The minute any of the margins involved isn't a quirk, don't
2127             // collapse it away, even if the margin is smaller (www.webreference.com
2128             // has an example of this, a <dt> with 0.8em author-specified inside
2129             // a <dl> inside a <td>.
2130             if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
2131                 setHasMarginBeforeQuirk(false);
2132                 marginInfo.setDeterminedMarginBeforeQuirk(true);
2133             }
2134
2135             if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore())
2136                 // We have no top margin and our top child has a quirky margin.
2137                 // We will pick up this quirky margin and pass it through.
2138                 // This deals with the <td><div><p> case.
2139                 // Don't do this for a block that split two inlines though. You do
2140                 // still apply margins in this case.
2141                 setHasMarginBeforeQuirk(true);
2142         } else
2143             // The before margin of the container will also discard all the margins it is collapsing with.
2144             setMustDiscardMarginBefore();
2145     }
2146
2147     // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard. 
2148     if (childDiscardMarginBefore) {
2149         marginInfo.setDiscardMargin(true);
2150         marginInfo.clearMargin();
2151     }
2152
2153     if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
2154         marginInfo.setHasMarginBeforeQuirk(topQuirk);
2155
2156     LayoutUnit beforeCollapseLogicalTop = logicalHeight();
2157     LayoutUnit logicalTop = beforeCollapseLogicalTop;
2158     if (childIsSelfCollapsing) {
2159         // For a self collapsing block both the before and after margins get discarded. The block doesn't contribute anything to the height of the block.
2160         // Also, the child's top position equals the logical height of the container.
2161         if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
2162             // This child has no height. We need to compute our
2163             // position before we collapse the child's margins together,
2164             // so that we can get an accurate position for the zero-height block.
2165             LayoutUnit collapsedBeforePos = max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
2166             LayoutUnit collapsedBeforeNeg = max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
2167             marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
2168             
2169             // Now collapse the child's margins together, which means examining our
2170             // bottom margin values as well. 
2171             marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
2172             marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
2173
2174             if (!marginInfo.canCollapseWithMarginBefore())
2175                 // We need to make sure that the position of the self-collapsing block
2176                 // is correct, since it could have overflowing content
2177                 // that needs to be positioned correctly (e.g., a block that
2178                 // had a specified height of 0 but that actually had subcontent).
2179                 logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
2180         }
2181     } else {
2182         if (mustSeparateMarginBeforeForChild(child)) {
2183             ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
2184             // If we are at the before side of the block and we collapse, ignore the computed margin
2185             // and just add the child margin to the container height. This will correctly position
2186             // the child inside the container.
2187             LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit(0);
2188             setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(child));
2189             logicalTop = logicalHeight();
2190         } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
2191             || (!marginInfo.canCollapseMarginBeforeWithChildren()
2192             && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
2193             // We're collapsing with a previous sibling's margins and not
2194             // with the top of the block.
2195             setLogicalHeight(logicalHeight() + max(marginInfo.positiveMargin(), posTop) - max(marginInfo.negativeMargin(), negTop));
2196             logicalTop = logicalHeight();
2197         }
2198
2199         marginInfo.setDiscardMargin(childDiscardMarginAfter);
2200         
2201         if (!marginInfo.discardMargin()) {
2202             marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
2203             marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
2204         } else
2205             marginInfo.clearMargin();
2206
2207         if (marginInfo.margin())
2208             marginInfo.setHasMarginAfterQuirk(hasMarginAfterQuirk(child));
2209     }
2210     
2211     // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
2212     // collapsed into the page edge.
2213     LayoutState* layoutState = view()->layoutState();
2214     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
2215         && hasNextPage(beforeCollapseLogicalTop)) {
2216         LayoutUnit oldLogicalTop = logicalTop;
2217         logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
2218         setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
2219     }
2220
2221     // If we have collapsed into a previous sibling and so reduced the height of the parent, ensure any floats that now
2222     // overhang from the previous sibling are added to our parent. If the child's previous sibling itself is a float the child will avoid
2223     // or clear it anyway, so don't worry about any floating children it may contain.
2224     LayoutUnit oldLogicalHeight = logicalHeight();
2225     setLogicalHeight(logicalTop);
2226     RenderObject* prev = child->previousSibling();
2227     if (prev && prev->isBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
2228         RenderBlock* block = toRenderBlock(prev);
2229         if (block->containsFloats() && !block->avoidsFloats() && (block->logicalTop() + block->lowestFloatLogicalBottom()) > logicalTop) 
2230             addOverhangingFloats(block, false);
2231     }
2232     setLogicalHeight(oldLogicalHeight);
2233
2234     return logicalTop;
2235 }
2236
2237 LayoutUnit RenderBlock::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
2238 {
2239     LayoutUnit heightIncrease = getClearDelta(child, yPos);
2240     if (!heightIncrease)
2241         return yPos;
2242
2243     if (child->isSelfCollapsingBlock()) {
2244         bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
2245
2246         // For self-collapsing blocks that clear, they can still collapse their
2247         // margins with following siblings.  Reset the current margins to represent
2248         // the self-collapsing block's margins only.
2249         // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
2250         if (!childDiscardMargin) {
2251             MarginValues childMargins = marginValuesForChild(child);
2252             marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
2253             marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
2254         } else
2255             marginInfo.clearMargin();
2256         marginInfo.setDiscardMargin(childDiscardMargin);
2257
2258         // CSS2.1 states:
2259         // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with 
2260         // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
2261         // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Check subsequent siblings
2262         // for a block with height - if none is found then don't allow the margins to collapse with the parent.
2263         bool wouldCollapseMarginsWithParent = marginInfo.canCollapseMarginAfterWithChildren();
2264         for (RenderBox* curr = child->nextSiblingBox(); curr && wouldCollapseMarginsWithParent; curr = curr->nextSiblingBox()) {
2265             if (!curr->isFloatingOrOutOfFlowPositioned() && !curr->isSelfCollapsingBlock())
2266                 wouldCollapseMarginsWithParent = false;
2267         }
2268         if (wouldCollapseMarginsWithParent)
2269             marginInfo.setCanCollapseMarginAfterWithChildren(false);
2270
2271         // CSS2.1: "the amount of clearance is set so that clearance + margin-top = [height of float], i.e., clearance = [height of float] - margin-top"
2272         // Move the top of the child box to the bottom of the float ignoring the child's top margin.
2273         LayoutUnit collapsedMargin = collapsedMarginBeforeForChild(child);
2274         setLogicalHeight(child->logicalTop() - collapsedMargin);
2275         // A negative collapsed margin-top value cancels itself out as it has already been factored into |yPos| above.
2276         heightIncrease -= max(LayoutUnit(), collapsedMargin);
2277     } else
2278         // Increase our height by the amount we had to clear.
2279         setLogicalHeight(logicalHeight() + heightIncrease);
2280     
2281     if (marginInfo.canCollapseWithMarginBefore()) {
2282         // We can no longer collapse with the top of the block since a clear
2283         // occurred.  The empty blocks collapse into the cleared block.
2284         // FIXME: This isn't quite correct.  Need clarification for what to do
2285         // if the height the cleared block is offset by is smaller than the
2286         // margins involved.
2287         setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
2288         marginInfo.setAtBeforeSideOfBlock(false);
2289
2290         // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
2291         setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MDISCARD);
2292     }
2293
2294     LayoutUnit logicalTop = yPos + heightIncrease;
2295     // After margin collapsing, one of our floats may now intrude into the child. If the child doesn't contain floats of its own it
2296     // won't get picked up for relayout even though the logical top estimate was wrong - so add the newly intruding float now.
2297     if (containsFloats() && child->isRenderBlock() && !toRenderBlock(child)->containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
2298         toRenderBlock(child)->addIntrudingFloats(this, logicalLeftOffsetForContent(), logicalTop);
2299
2300     return logicalTop;
2301 }
2302
2303 void RenderBlock::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
2304 {
2305     // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
2306     // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
2307     // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
2308     if ((document()->inQuirksMode() && hasMarginAfterQuirk(child) && (isTableCell() || isBody())) || child->style()->marginBeforeCollapse() == MSEPARATE)
2309         return;
2310
2311     // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
2312     // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
2313     if (child->style()->marginBeforeCollapse() == MDISCARD) {
2314         positiveMarginBefore = 0;
2315         negativeMarginBefore = 0;
2316         discardMarginBefore = true;
2317         return;
2318     }
2319
2320     LayoutUnit beforeChildMargin = marginBeforeForChild(child);
2321     positiveMarginBefore = max(positiveMarginBefore, beforeChildMargin);
2322     negativeMarginBefore = max(negativeMarginBefore, -beforeChildMargin);
2323
2324     if (!child->isRenderBlock())
2325         return;
2326     
2327     RenderBlock* childBlock = toRenderBlock(child);
2328     if (childBlock->childrenInline() || childBlock->isWritingModeRoot())
2329         return;
2330
2331     MarginInfo childMarginInfo(childBlock, childBlock->borderAndPaddingBefore(), childBlock->borderAndPaddingAfter());
2332     if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
2333         return;
2334
2335     RenderBox* grandchildBox = childBlock->firstChildBox();
2336     for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
2337         if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
2338             break;
2339     }
2340     
2341     // Give up if there is clearance on the box, since it probably won't collapse into us.
2342     if (!grandchildBox || grandchildBox->style()->clear() != CNONE)
2343         return;
2344
2345     // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
2346     if (grandchildBox->needsLayout()) {
2347         grandchildBox->computeAndSetBlockDirectionMargins(this);
2348         if (grandchildBox->isRenderBlock()) {
2349             RenderBlock* grandchildBlock = toRenderBlock(grandchildBox);
2350             grandchildBlock->setHasMarginBeforeQuirk(grandchildBox->style()->hasMarginBeforeQuirk());
2351             grandchildBlock->setHasMarginAfterQuirk(grandchildBox->style()->hasMarginAfterQuirk());
2352         }
2353     }
2354
2355     // Collapse the margin of the grandchild box with our own to produce an estimate.
2356     childBlock->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
2357 }
2358
2359 LayoutUnit RenderBlock::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
2360 {
2361     // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
2362     // relayout if there are intruding floats.
2363     LayoutUnit logicalTopEstimate = logicalHeight();
2364     if (!marginInfo.canCollapseWithMarginBefore()) {
2365         LayoutUnit positiveMarginBefore = 0;
2366         LayoutUnit negativeMarginBefore = 0;
2367         bool discardMarginBefore = false;
2368         if (child->selfNeedsLayout()) {
2369             // Try to do a basic estimation of how the collapse is going to go.
2370             marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
2371         } else {
2372             // Use the cached collapsed margin values from a previous layout. Most of the time they
2373             // will be right.
2374             MarginValues marginValues = marginValuesForChild(child);
2375             positiveMarginBefore = max(positiveMarginBefore, marginValues.positiveMarginBefore());
2376             negativeMarginBefore = max(negativeMarginBefore, marginValues.negativeMarginBefore());
2377             discardMarginBefore = mustDiscardMarginBeforeForChild(child);
2378         }
2379
2380         // Collapse the result with our current margins.
2381         if (!discardMarginBefore)
2382             logicalTopEstimate += max(marginInfo.positiveMargin(), positiveMarginBefore) - max(marginInfo.negativeMargin(), negativeMarginBefore);
2383     }
2384
2385     // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
2386     // page.
2387     LayoutState* layoutState = view()->layoutState();
2388     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
2389         && hasNextPage(logicalHeight()))
2390         logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
2391
2392     logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
2393     
2394     estimateWithoutPagination = logicalTopEstimate;
2395
2396     if (layoutState->isPaginated()) {
2397         // If the object has a page or column break value of "before", then we should shift to the top of the next page.
2398         logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
2399     
2400         // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
2401         logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
2402         
2403         if (!child->selfNeedsLayout() && child->isRenderBlock())
2404             logicalTopEstimate += toRenderBlock(child)->paginationStrut();
2405     }
2406
2407     return logicalTopEstimate;
2408 }
2409
2410 LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* region)
2411 {
2412     LayoutUnit startPosition = startOffsetForContent(region);
2413
2414     // Add in our start margin.
2415     LayoutUnit oldPosition = startPosition + childMarginStart;
2416     LayoutUnit newPosition = oldPosition;
2417
2418     LayoutUnit blockOffset = logicalTopForChild(child);
2419     if (region)
2420         blockOffset = max(blockOffset, blockOffset + (region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage()));
2421
2422     LayoutUnit startOff = startOffsetForLine(blockOffset, false, region, logicalHeightForChild(child));
2423
2424     if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
2425         if (childMarginStart < 0)
2426             startOff += childMarginStart;
2427         newPosition = max(newPosition, startOff); // Let the float sit in the child's margin if it can fit.
2428     } else if (startOff != startPosition)
2429         newPosition = startOff + childMarginStart;
2430
2431     return newPosition - oldPosition;
2432 }
2433
2434 void RenderBlock::determineLogicalLeftPositionForChild(RenderBox* child, ApplyLayoutDeltaMode applyDelta)
2435 {
2436     LayoutUnit startPosition = borderStart() + paddingStart();
2437     if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2438         startPosition -= verticalScrollbarWidth();
2439     LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
2440
2441     // Add in our start margin.
2442     LayoutUnit childMarginStart = marginStartForChild(child);
2443     LayoutUnit newPosition = startPosition + childMarginStart;
2444         
2445     // Some objects (e.g., tables, horizontal rules, overflow:auto blocks) avoid floats.  They need
2446     // to shift over as necessary to dodge any floats that might get in the way.
2447     if (child->avoidsFloats() && containsFloats() && !flowThreadContainingBlock())
2448         newPosition += computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child));
2449
2450     setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), applyDelta);
2451 }
2452
2453 void RenderBlock::setCollapsedBottomMargin(const MarginInfo& marginInfo)
2454 {
2455     if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
2456         // Update the after side margin of the container to discard if the after margin of the last child also discards and we collapse with it.
2457         // Don't update the max margin values because we won't need them anyway.
2458         if (marginInfo.discardMargin()) {
2459             setMustDiscardMarginAfter();
2460             return;
2461         }
2462
2463         // Update our max pos/neg bottom margins, since we collapsed our bottom margins
2464         // with our children.
2465         setMaxMarginAfterValues(max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
2466
2467         if (!marginInfo.hasMarginAfterQuirk())
2468             setHasMarginAfterQuirk(false);
2469
2470         if (marginInfo.hasMarginAfterQuirk() && !marginAfter())
2471             // We have no bottom margin and our last child has a quirky margin.
2472             // We will pick up this quirky margin and pass it through.
2473             // This deals with the <td><div><p> case.
2474             setHasMarginAfterQuirk(true);
2475     }
2476 }
2477
2478 void RenderBlock::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
2479 {
2480     marginInfo.setAtAfterSideOfBlock(true);
2481
2482     // If we can't collapse with children then go ahead and add in the bottom margin.
2483     if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
2484         && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
2485         setLogicalHeight(logicalHeight() + marginInfo.margin());
2486         
2487     // Now add in our bottom border/padding.
2488     setLogicalHeight(logicalHeight() + afterSide);
2489
2490     // Negative margins can cause our height to shrink below our minimal height (border/padding).
2491     // If this happens, ensure that the computed height is increased to the minimal height.
2492     setLogicalHeight(max(logicalHeight(), beforeSide + afterSide));
2493
2494     // Update our bottom collapsed margin info.
2495     setCollapsedBottomMargin(marginInfo);
2496 }
2497
2498 void RenderBlock::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
2499 {
2500     if (isHorizontalWritingMode()) {
2501         if (applyDelta == ApplyLayoutDelta)
2502             view()->addLayoutDelta(LayoutSize(child->x() - logicalLeft, 0));
2503         child->setX(logicalLeft);
2504     } else {
2505         if (applyDelta == ApplyLayoutDelta)
2506             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalLeft));
2507         child->setY(logicalLeft);
2508     }
2509 }
2510
2511 void RenderBlock::setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
2512 {
2513     if (isHorizontalWritingMode()) {
2514         if (applyDelta == ApplyLayoutDelta)
2515             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalTop));
2516         child->setY(logicalTop);
2517     } else {
2518         if (applyDelta == ApplyLayoutDelta)
2519             view()->addLayoutDelta(LayoutSize(child->x() - logicalTop, 0));
2520         child->setX(logicalTop);
2521     }
2522 }
2523
2524 void RenderBlock::updateBlockChildDirtyBitsBeforeLayout(bool relayoutChildren, RenderBox* child)
2525 {
2526     // FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
2527     // an auto value. Add a method to determine this, so that we can avoid the relayout.
2528     if (relayoutChildren || (child->hasRelativeLogicalHeight() && !isRenderView()) || child->hasViewportPercentageLogicalHeight())
2529         child->setChildNeedsLayout(true, MarkOnlyThis);
2530
2531     // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2532     if (relayoutChildren && child->needsPreferredWidthsRecalculation())
2533         child->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
2534 }
2535
2536 void RenderBlock::dirtyForLayoutFromPercentageHeightDescendants()
2537 {
2538     if (!gPercentHeightDescendantsMap)
2539         return;
2540
2541     TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this);
2542     if (!descendants)
2543         return;
2544     
2545     TrackedRendererListHashSet::iterator end = descendants->end();
2546     for (TrackedRendererListHashSet::iterator it = descendants->begin(); it != end; ++it) {
2547         RenderBox* box = *it;
2548         while (box != this) {
2549             if (box->normalChildNeedsLayout())
2550                 break;
2551             box->setChildNeedsLayout(true, MarkOnlyThis);
2552             
2553             // If the width of an image is affected by the height of a child (e.g., an image with an aspect ratio),
2554             // then we have to dirty preferred widths, since even enclosing blocks can become dirty as a result.
2555             // (A horizontal flexbox that contains an inline image wrapped in an anonymous block for example.)
2556             if (box->hasAspectRatio()) 
2557                 box->setPreferredLogicalWidthsDirty(true);
2558             
2559             box = box->containingBlock();
2560             ASSERT(box);
2561             if (!box)
2562                 break;
2563         }
2564     }
2565 }
2566
2567 void RenderBlock::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
2568 {
2569     dirtyForLayoutFromPercentageHeightDescendants();
2570
2571     LayoutUnit beforeEdge = borderAndPaddingBefore();
2572     LayoutUnit afterEdge = borderAndPaddingAfter() + scrollbarLogicalHeight();
2573
2574     setLogicalHeight(beforeEdge);
2575     
2576     // Lay out our hypothetical grid line as though it occurs at the top of the block.
2577     if (view()->layoutState()->lineGrid() == this)
2578         layoutLineGridBox();
2579
2580     // The margin struct caches all our current margin collapsing state.  The compact struct caches state when we encounter compacts,
2581     MarginInfo marginInfo(this, beforeEdge, afterEdge);
2582
2583     // Fieldsets need to find their legend and position it inside the border of the object.
2584     // The legend then gets skipped during normal layout.  The same is true for ruby text.
2585     // It doesn't get included in the normal layout process but is instead skipped.
2586     RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren);
2587
2588     LayoutUnit previousFloatLogicalBottom = 0;
2589     maxFloatLogicalBottom = 0;
2590
2591     RenderBox* next = firstChildBox();
2592
2593     while (next) {
2594         RenderBox* child = next;
2595         next = child->nextSiblingBox();
2596
2597         if (childToExclude == child)
2598             continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
2599
2600         updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
2601
2602         if (child->isOutOfFlowPositioned()) {
2603             child->containingBlock()->insertPositionedObject(child);
2604             adjustPositionedBlock(child, marginInfo);
2605             continue;
2606         }
2607         if (child->isFloating()) {
2608             insertFloatingObject(child);
2609             adjustFloatingBlock(marginInfo);
2610             continue;
2611         }
2612
2613         // Lay out the child.
2614         layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
2615     }
2616     
2617     // Now do the handling of the bottom of the block, adding in our bottom border/padding and
2618     // determining the correct collapsed bottom margin information.
2619     handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
2620 }
2621
2622 void RenderBlock::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
2623 {
2624     LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
2625     LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
2626
2627     // The child is a normal flow object.  Compute the margins we will use for collapsing now.
2628     child->computeAndSetBlockDirectionMargins(this);
2629
2630     // Try to guess our correct logical top position.  In most cases this guess will
2631     // be correct.  Only if we're wrong (when we compute the real logical top position)
2632     // will we have to potentially relayout.
2633     LayoutUnit estimateWithoutPagination;
2634     LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
2635
2636     // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
2637     LayoutRect oldRect = child->frameRect();
2638     LayoutUnit oldLogicalTop = logicalTopForChild(child);
2639
2640 #if !ASSERT_DISABLED
2641     LayoutSize oldLayoutDelta = view()->layoutDelta();
2642 #endif
2643     // Go ahead and position the child as though it didn't collapse with the top.
2644     setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
2645     estimateRegionRangeForBoxChild(child);
2646
2647     RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
2648     bool markDescendantsWithFloats = false;
2649     if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats())
2650         markDescendantsWithFloats = true;
2651 #if ENABLE(SUBPIXEL_LAYOUT)
2652     else if (UNLIKELY(logicalTopEstimate.mightBeSaturated()))
2653         // logicalTopEstimate, returned by estimateLogicalTopPosition, might be saturated for
2654         // very large elements. If it does the comparison with oldLogicalTop might yield a
2655         // false negative as adding and removing margins, borders etc from a saturated number
2656         // might yield incorrect results. If this is the case always mark for layout.
2657         markDescendantsWithFloats = true;
2658 #endif
2659     else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
2660         // If an element might be affected by the presence of floats, then always mark it for
2661         // layout.
2662         LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
2663         if (fb > logicalTopEstimate)
2664             markDescendantsWithFloats = true;
2665     }
2666
2667     if (childRenderBlock) {
2668         if (markDescendantsWithFloats)
2669             childRenderBlock->markAllDescendantsWithFloatsForLayout();
2670         if (!child->isWritingModeRoot())
2671             previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottom());
2672     }
2673
2674     if (!child->needsLayout())
2675         child->markForPaginationRelayoutIfNeeded();
2676
2677     bool childHadLayout = child->everHadLayout();
2678     bool childNeededLayout = child->needsLayout();
2679     if (childNeededLayout)
2680         child->layout();
2681
2682     // Cache if we are at the top of the block right now.
2683     bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
2684
2685     // Now determine the correct ypos based off examination of collapsing margin
2686     // values.
2687     LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
2688
2689     // Now check for clear.
2690     LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
2691     
2692     bool paginated = view()->layoutState()->isPaginated();
2693     if (paginated)
2694         logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
2695             atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
2696
2697     setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
2698
2699     // Now we have a final top position.  See if it really does end up being different from our estimate.
2700     // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
2701     // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
2702     if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout() || (paginated && childRenderBlock && childRenderBlock->shouldBreakAtLineToAvoidWidow())) {
2703         if (child->shrinkToAvoidFloats()) {
2704             // The child's width depends on the line width.
2705             // When the child shifts to clear an item, its width can
2706             // change (because it has more available line width).
2707             // So go ahead and mark the item as dirty.
2708             child->setChildNeedsLayout(true, MarkOnlyThis);
2709         }
2710         
2711         if (childRenderBlock) {
2712             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
2713                 childRenderBlock->markAllDescendantsWithFloatsForLayout();
2714             if (!child->needsLayout())
2715                 child->markForPaginationRelayoutIfNeeded();
2716         }
2717
2718         // Our guess was wrong. Make the child lay itself out again.
2719         child->layoutIfNeeded();
2720     }
2721
2722     if (updateRegionRangeForBoxChild(child)) {
2723         child->setNeedsLayout(true, MarkOnlyThis);
2724         child->layoutIfNeeded();
2725     }
2726
2727     // We are no longer at the top of the block if we encounter a non-empty child.  
2728     // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
2729     if (marginInfo.atBeforeSideOfBlock() && !child->isSelfCollapsingBlock())
2730         marginInfo.setAtBeforeSideOfBlock(false);
2731
2732     // Now place the child in the correct left position
2733     determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
2734
2735     // Update our height now that the child has been placed in the correct position.
2736     setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
2737     if (mustSeparateMarginAfterForChild(child)) {
2738         setLogicalHeight(logicalHeight() + marginAfterForChild(child));
2739         marginInfo.clearMargin();
2740     }
2741     // If the child has overhanging floats that intrude into following siblings (or possibly out
2742     // of this block), then the parent gets notified of the floats now.
2743     if (childRenderBlock && childRenderBlock->containsFloats())
2744         maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
2745
2746     LayoutSize childOffset = child->location() - oldRect.location();
2747     if (childOffset.width() || childOffset.height()) {
2748         view()->addLayoutDelta(childOffset);
2749
2750         // If the child moved, we have to repaint it as well as any floating/positioned
2751         // descendants.  An exception is if we need a layout.  In this case, we know we're going to
2752         // repaint ourselves (and the child) anyway.
2753         if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
2754             child->repaintDuringLayoutIfMoved(oldRect);
2755     }
2756
2757     if (!childHadLayout && child->checkForRepaintDuringLayout()) {
2758         child->repaint();
2759         child->repaintOverhangingFloats(true);
2760     }
2761
2762     if (paginated) {
2763         // Check for an after page/column break.
2764         LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
2765         if (newHeight != height())
2766             setLogicalHeight(newHeight);
2767     }
2768
2769     ASSERT(view()->layoutDeltaMatches(oldLayoutDelta));
2770 }
2771
2772 void RenderBlock::simplifiedNormalFlowLayout()
2773 {
2774     if (childrenInline()) {
2775         ListHashSet<RootInlineBox*> lineBoxes;
2776         for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
2777             RenderObject* o = walker.current();
2778             if (!o->isOutOfFlowPositioned() && (o->isReplaced() || o->isFloating())) {
2779                 o->layoutIfNeeded();
2780                 if (toRenderBox(o)->inlineBoxWrapper()) {
2781                     RootInlineBox* box = toRenderBox(o)->inlineBoxWrapper()->root();
2782                     lineBoxes.add(box);
2783                 }
2784             } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline()))
2785                 o->setNeedsLayout(false);
2786         }
2787
2788         // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
2789         // FIXME: Find a way to invalidate the knownToHaveNoOverflow flag on the InlineBoxes.
2790         GlyphOverflowAndFallbackFontsMap textBoxDataMap;                  
2791         for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
2792             RootInlineBox* box = *it;
2793             box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
2794         }
2795     } else {
2796         for (RenderBox* box = firstChildBox(); box; box = box->nextSiblingBox()) {
2797             if (!box->isOutOfFlowPositioned())
2798                 box->layoutIfNeeded();
2799         }
2800     }
2801 }
2802
2803 bool RenderBlock::simplifiedLayout()
2804 {
2805     if ((!posChildNeedsLayout() && !needsSimplifiedNormalFlowLayout()) || normalChildNeedsLayout() || selfNeedsLayout())
2806         return false;
2807
2808     LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
2809     
2810     if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
2811         return false;
2812
2813     // Lay out positioned descendants or objects that just need to recompute overflow.
2814     if (needsSimplifiedNormalFlowLayout())
2815         simplifiedNormalFlowLayout();
2816
2817     // Make sure a forced break is applied after the content if we are a flow thread in a simplified layout.
2818     // This ensures the size information is correctly computed for the last auto-height region receiving content.
2819     if (isRenderFlowThread())
2820         toRenderFlowThread(this)->applyBreakAfterContent(clientLogicalBottom());
2821
2822     // Lay out our positioned objects if our positioned child bit is set.
2823     // Also, if an absolute position element inside a relative positioned container moves, and the absolute element has a fixed position
2824     // child, neither the fixed element nor its container learn of the movement since posChildNeedsLayout() is only marked as far as the 
2825     // relative positioned container. So if we can have fixed pos objects in our positioned objects list check if any of them
2826     // are statically positioned and thus need to move with their absolute ancestors.
2827     bool canContainFixedPosObjects = canContainFixedPositionObjects();
2828     if (posChildNeedsLayout() || canContainFixedPosObjects)
2829         layoutPositionedObjects(false, !posChildNeedsLayout() && canContainFixedPosObjects);
2830
2831     // Recompute our overflow information.
2832     // FIXME: We could do better here by computing a temporary overflow object from layoutPositionedObjects and only
2833     // updating our overflow if we either used to have overflow or if the new temporary object has overflow.
2834     // For now just always recompute overflow.  This is no worse performance-wise than the old code that called rightmostPosition and
2835     // lowestPosition on every relayout so it's not a regression.
2836     // computeOverflow expects the bottom edge before we clamp our height. Since this information isn't available during
2837     // simplifiedLayout, we cache the value in m_overflow.
2838     LayoutUnit oldClientAfterEdge = hasRenderOverflow() ? m_overflow->layoutClientAfterEdge() : clientLogicalBottom();
2839     computeOverflow(oldClientAfterEdge, true);
2840
2841     statePusher.pop();
2842     
2843     updateLayerTransform();
2844
2845     updateScrollInfoAfterLayout();
2846
2847     setNeedsLayout(false);
2848     return true;
2849 }
2850
2851 void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject* child)
2852 {
2853     if (child->style()->position() != FixedPosition)
2854         return;
2855
2856     bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontalWritingMode());
2857     bool hasStaticInlinePosition = child->style()->hasStaticInlinePosition(isHorizontalWritingMode());
2858     if (!hasStaticBlockPosition && !hasStaticInlinePosition)
2859         return;
2860
2861     RenderObject* o = child->parent();
2862     while (o && !o->isRenderView() && o->style()->position() != AbsolutePosition)
2863         o = o->parent();
2864     if (o->style()->position() != AbsolutePosition)
2865         return;
2866
2867     RenderBox* box = toRenderBox(child);
2868     if (hasStaticInlinePosition) {
2869         LogicalExtentComputedValues computedValues;
2870         box->computeLogicalWidthInRegion(computedValues);
2871         LayoutUnit newLeft = computedValues.m_position;
2872         if (newLeft != box->logicalLeft())
2873             child->setChildNeedsLayout(true, MarkOnlyThis);
2874     } else if (hasStaticBlockPosition) {
2875         LayoutUnit oldTop = box->logicalTop();
2876         box->updateLogicalHeight();
2877         if (box->logicalTop() != oldTop)
2878             child->setChildNeedsLayout(true, MarkOnlyThis);
2879     }
2880 }
2881
2882 void RenderBlock::layoutPositionedObjects(bool relayoutChildren, bool fixedPositionObjectsOnly)
2883 {
2884     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
2885     if (!positionedDescendants)
2886         return;
2887         
2888     if (hasColumns())
2889         view()->layoutState()->clearPaginationInformation(); // Positioned objects are not part of the column flow, so they don't paginate with the columns.
2890
2891     RenderBox* r;
2892     TrackedRendererListHashSet::iterator end = positionedDescendants->end();
2893     for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
2894         r = *it;
2895         
2896         estimateRegionRangeForBoxChild(r);
2897
2898         // A fixed position element with an absolute positioned ancestor has no way of knowing if the latter has changed position. So
2899         // if this is a fixed position element, mark it for layout if it has an abspos ancestor and needs to move with that ancestor, i.e. 
2900         // it has static position.
2901         markFixedPositionObjectForLayoutIfNeeded(r);
2902         if (fixedPositionObjectsOnly) {
2903             r->layoutIfNeeded();
2904             continue;
2905         }
2906
2907         // When a non-positioned block element moves, it may have positioned children that are implicitly positioned relative to the
2908         // non-positioned block.  Rather than trying to detect all of these movement cases, we just always lay out positioned
2909         // objects that are positioned implicitly like this.  Such objects are rare, and so in typical DHTML menu usage (where everything is
2910         // positioned explicitly) this should not incur a performance penalty.
2911         if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
2912             r->setChildNeedsLayout(true, MarkOnlyThis);
2913             
2914         // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2915         if (relayoutChildren && r->needsPreferredWidthsRecalculation())
2916             r->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
2917         
2918         if (!r->needsLayout())
2919             r->markForPaginationRelayoutIfNeeded();
2920         
2921         // We don't have to do a full layout.  We just have to update our position. Try that first. If we have shrink-to-fit width
2922         // and we hit the available width constraint, the layoutIfNeeded() will catch it and do a full layout.
2923         if (r->needsPositionedMovementLayoutOnly() && r->tryLayoutDoingPositionedMovementOnly())
2924             r->setNeedsLayout(false);
2925             
2926         // If we are paginated or in a line grid, go ahead and compute a vertical position for our object now.
2927         // If it's wrong we'll lay out again.
2928         LayoutUnit oldLogicalTop = 0;
2929         bool needsBlockDirectionLocationSetBeforeLayout = r->needsLayout() && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout(); 
2930         if (needsBlockDirectionLocationSetBeforeLayout) {
2931             if (isHorizontalWritingMode() == r->isHorizontalWritingMode())
2932                 r->updateLogicalHeight();
2933             else
2934                 r->updateLogicalWidth();
2935             oldLogicalTop = logicalTopForChild(r);
2936         }
2937
2938         r->layoutIfNeeded();
2939
2940         // Lay out again if our estimate was wrong.
2941         if (needsBlockDirectionLocationSetBeforeLayout && logicalTopForChild(r) != oldLogicalTop) {
2942             r->setChildNeedsLayout(true, MarkOnlyThis);
2943             r->layoutIfNeeded();
2944         }
2945
2946         if (updateRegionRangeForBoxChild(r)) {
2947             r->setNeedsLayout(true, MarkOnlyThis);
2948             r->layoutIfNeeded();
2949         }
2950     }
2951     
2952     if (hasColumns())
2953         view()->layoutState()->m_columnInfo = columnInfo(); // FIXME: Kind of gross. We just put this back into the layout state so that pop() will work.
2954 }
2955
2956 void RenderBlock::markPositionedObjectsForLayout()
2957 {
2958     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
2959     if (positionedDescendants) {
2960         RenderBox* r;
2961         TrackedRendererListHashSet::iterator end = positionedDescendants->end();
2962         for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
2963             r = *it;
2964             r->setChildNeedsLayout(true);
2965         }
2966     }
2967 }
2968
2969 void RenderBlock::markForPaginationRelayoutIfNeeded()
2970 {
2971     ASSERT(!needsLayout());
2972     if (needsLayout())
2973         return;
2974
2975     if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()))
2976         setChildNeedsLayout(true, MarkOnlyThis);
2977 }
2978
2979 void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
2980 {
2981     // Repaint any overhanging floats (if we know we're the one to paint them).
2982     // Otherwise, bail out.
2983     if (!hasOverhangingFloats())
2984         return;
2985
2986     // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
2987     // in this block. Better yet would be to push extra state for the containers of other floats.
2988     LayoutStateDisabler layoutStateDisabler(view());
2989     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2990     FloatingObjectSetIterator end = floatingObjectSet.end();
2991     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2992         FloatingObject* r = *it;
2993         // Only repaint the object if it is overhanging, is not in its own layer, and
2994         // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
2995         // condition is replaced with being a descendant of us.
2996         if (logicalBottomForFloat(r) > logicalHeight() && ((paintAllDescendants && r->renderer()->isDescendantOf(this)) || r->shouldPaint()) && !r->renderer()->hasSelfPaintingLayer()) {
2997             r->renderer()->repaint();
2998             r->renderer()->repaintOverhangingFloats(false);
2999         }
3000     }
3001 }
3002  
3003 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3004 {
3005     LayoutPoint adjustedPaintOffset = paintOffset + location();
3006     
3007     PaintPhase phase = paintInfo.phase;
3008
3009     // Check if we need to do anything at all.
3010     // FIXME: Could eliminate the isRoot() check if we fix background painting so that the RenderView
3011     // paints the root's background.
3012     if (!isRoot()) {
3013         LayoutRect overflowBox = overflowRectForPaintRejection();
3014         flipForWritingMode(overflowBox);
3015         overflowBox.inflate(maximalOutlineSize(paintInfo.phase));
3016         overflowBox.moveBy(adjustedPaintOffset);
3017         if (!overflowBox.intersects(paintInfo.rect))
3018             return;
3019     }
3020
3021     bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
3022     paintObject(paintInfo, adjustedPaintOffset);
3023     if (pushedClip)
3024         popContentsClip(paintInfo, phase, adjustedPaintOffset);
3025
3026     // Our scrollbar widgets paint exactly when we tell them to, so that they work properly with
3027     // z-index.  We paint after we painted the background/border, so that the scrollbars will
3028     // sit above the background/border.
3029     if (hasOverflowClip() && style()->visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && paintInfo.shouldPaintWithinRoot(this) && !paintInfo.paintRootBackgroundOnly())
3030         layer()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
3031 }
3032
3033 void RenderBlock::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3034 {
3035     if (paintInfo.context->paintingDisabled())
3036         return;
3037
3038     const Color& ruleColor = style()->visitedDependentColor(CSSPropertyWebkitColumnRuleColor);
3039     bool ruleTransparent = style()->columnRuleIsTransparent();
3040     EBorderStyle ruleStyle = style()->columnRuleStyle();
3041     LayoutUnit ruleThickness = style()->columnRuleWidth();
3042     LayoutUnit colGap = columnGap();
3043     bool renderRule = ruleStyle > BHIDDEN && !ruleTransparent;
3044     if (!renderRule)
3045         return;
3046
3047     ColumnInfo* colInfo = columnInfo();
3048     unsigned colCount = columnCount(colInfo);
3049
3050     bool antialias = shouldAntialiasLines(paintInfo.context);
3051
3052     if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
3053         bool leftToRight = style()->isLeftToRightDirection() ^ colInfo->progressionIsReversed();
3054         LayoutUnit currLogicalLeftOffset = leftToRight ? LayoutUnit() : contentLogicalWidth();
3055         LayoutUnit ruleAdd = logicalLeftOffsetForContent();
3056         LayoutUnit ruleLogicalLeft = leftToRight ? LayoutUnit() : contentLogicalWidth();
3057         LayoutUnit inlineDirectionSize = colInfo->desiredColumnWidth();
3058         BoxSide boxSide = isHorizontalWritingMode()
3059             ? leftToRight ? BSLeft : BSRight
3060             : leftToRight ? BSTop : BSBottom;
3061
3062         for (unsigned i = 0; i < colCount; i++) {
3063             // Move to the next position.
3064             if (leftToRight) {
3065                 ruleLogicalLeft += inlineDirectionSize + colGap / 2;
3066                 currLogicalLeftOffset += inlineDirectionSize + colGap;
3067             } else {
3068                 ruleLogicalLeft -= (inlineDirectionSize + colGap / 2);
3069                 currLogicalLeftOffset -= (inlineDirectionSize + colGap);
3070             }
3071            
3072             // Now paint the column rule.
3073             if (i < colCount - 1) {
3074                 LayoutUnit ruleLeft = isHorizontalWritingMode() ? paintOffset.x() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd : paintOffset.x() + borderLeft() + paddingLeft();
3075                 LayoutUnit ruleRight = isHorizontalWritingMode() ? ruleLeft + ruleThickness : ruleLeft + contentWidth();
3076                 LayoutUnit ruleTop = isHorizontalWritingMode() ? paintOffset.y() + borderTop() + paddingTop() : paintOffset.y() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd;
3077                 LayoutUnit ruleBottom = isHorizontalWritingMode() ? ruleTop + contentHeight() : ruleTop + ruleThickness;
3078                 IntRect pixelSnappedRuleRect = pixelSnappedIntRectFromEdges(ruleLeft, ruleTop, ruleRight, ruleBottom);
3079                 drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
3080             }
3081             
3082             ruleLogicalLeft = currLogicalLeftOffset;
3083         }
3084     } else {
3085         bool topToBottom = !style()->isFlippedBlocksWritingMode() ^ colInfo->progressionIsReversed();
3086         LayoutUnit ruleLeft = isHorizontalWritingMode()
3087             ? borderLeft() + paddingLeft()
3088             : colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderAndPaddingBefore() : borderAndPaddingAfter());
3089         LayoutUnit ruleWidth = isHorizontalWritingMode() ? contentWidth() : ruleThickness;
3090         LayoutUnit ruleTop = isHorizontalWritingMode()
3091             ? colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderAndPaddingBefore() : borderAndPaddingAfter())
3092             : borderStart() + paddingStart();
3093         LayoutUnit ruleHeight = isHorizontalWritingMode() ? ruleThickness : contentHeight();
3094         LayoutRect ruleRect(ruleLeft, ruleTop, ruleWidth, ruleHeight);
3095
3096         if (!topToBottom) {
3097             if (isHorizontalWritingMode())
3098                 ruleRect.setY(height() - ruleRect.maxY());
3099             else
3100                 ruleRect.setX(width() - ruleRect.maxX());
3101         }
3102
3103         ruleRect.moveBy(paintOffset);
3104
3105         BoxSide boxSide = isHorizontalWritingMode()
3106             ? topToBottom ? BSTop : BSBottom
3107             : topToBottom ? BSLeft : BSRight;
3108
3109         LayoutSize step(0, topToBottom ? colInfo->columnHeight() + colGap : -(colInfo->columnHeight() + colGap));
3110         if (!isHorizontalWritingMode())
3111             step = step.transposedSize();
3112
3113         for (unsigned i = 1; i < colCount; i++) {
3114             ruleRect.move(step);
3115             IntRect pixelSnappedRuleRect = pixelSnappedIntRect(ruleRect);
3116             drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
3117         }
3118     }
3119 }
3120
3121 LayoutUnit RenderBlock::initialBlockOffsetForPainting() const
3122 {
3123     ColumnInfo* colInfo = columnInfo();
3124     LayoutUnit result = 0;
3125     if (colInfo->progressionAxis() == ColumnInfo::BlockAxis && colInfo->progressionIsReversed()) {
3126         LayoutRect colRect = columnRectAt(colInfo, 0);
3127         result = isHorizontalWritingMode() ? colRect.y() : colRect.x();
3128         result -= borderAndPaddingBefore();
3129         if (style()->isFlippedBlocksWritingMode())
3130             result = -result;
3131     }
3132     return result;
3133 }
3134     
3135 LayoutUnit RenderBlock::blockDeltaForPaintingNextColumn() const
3136 {
3137     ColumnInfo* colInfo = columnInfo();
3138     LayoutUnit blockDelta = -colInfo->columnHeight();
3139     LayoutUnit colGap = columnGap();
3140     if (colInfo->progressionAxis() == ColumnInfo::BlockAxis) {
3141         if (!colInfo->progressionIsReversed())
3142             blockDelta = colGap;
3143         else
3144             blockDelta -= (colInfo->columnHeight() + colGap);
3145     }
3146     if (style()->isFlippedBlocksWritingMode())
3147         blockDelta = -blockDelta;
3148     return blockDelta;
3149 }
3150
3151 void RenderBlock::paintColumnContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool paintingFloats)
3152 {
3153     // We need to do multiple passes, breaking up our child painting into strips.
3154     GraphicsContext* context = paintInfo.context;
3155     ColumnInfo* colInfo = columnInfo();
3156     unsigned colCount = columnCount(colInfo);
3157     if (!colCount)
3158         return;
3159     LayoutUnit colGap = columnGap();
3160     LayoutUnit currLogicalTopOffset = initialBlockOffsetForPainting();
3161     LayoutUnit blockDelta = blockDeltaForPaintingNextColumn();
3162     for (unsigned i = 0; i < colCount; i++) {
3163         // For each rect, we clip to the rect, and then we adjust our coords.
3164         LayoutRect colRect = columnRectAt(colInfo, i);
3165         flipForWritingMode(colRect);
3166         
3167         LayoutUnit logicalLeftOffset = (isHorizontalWritingMode() ? colRect.x() : colRect.y()) - logicalLeftOffsetForContent();
3168         LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(logicalLeftOffset, currLogicalTopOffset) : LayoutSize(currLogicalTopOffset, logicalLeftOffset);
3169         colRect.moveBy(paintOffset);
3170         PaintInfo info(paintInfo);
3171         info.rect.intersect(pixelSnappedIntRect(colRect));
3172         
3173         if (!info.rect.isEmpty()) {
3174             GraphicsContextStateSaver stateSaver(*context);
3175             LayoutRect clipRect(colRect);
3176             
3177             if (i < colCount - 1) {
3178                 if (isHorizontalWritingMode())
3179                     clipRect.expand(colGap / 2, 0);
3180                 else
3181                     clipRect.expand(0, colGap / 2);
3182             }
3183             // Each strip pushes a clip, since column boxes are specified as being
3184             // like overflow:hidden.
3185             // FIXME: Content and column rules that extend outside column boxes at the edges of the multi-column element
3186             // are clipped according to the 'overflow' property.
3187             context->clip(pixelSnappedIntRect(clipRect));
3188
3189             // Adjust our x and y when painting.
3190             LayoutPoint adjustedPaintOffset = paintOffset + offset;
3191             if (paintingFloats)
3192                 paintFloats(info, adjustedPaintOffset, paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip);
3193             else
3194                 paintContents(info, adjustedPaintOffset);
3195         }
3196         currLogicalTopOffset += blockDelta;
3197     }
3198 }
3199
3200 void RenderBlock::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3201 {
3202     // Avoid painting descendants of the root element when stylesheets haven't loaded.  This eliminates FOUC.
3203     // It's ok not to draw, because later on, when all the stylesheets do load, styleResolverChanged() on the Document
3204     // will do a full repaint.
3205     if (document()->didLayoutWithPendingStylesheets() && !isRenderView())
3206         return;
3207
3208     if (childrenInline())
3209         m_lineBoxes.paint(this, paintInfo, paintOffset);
3210     else {
3211         PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
3212         newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
3213
3214         // We don't paint our own background, but we do let the kids paint their backgrounds.
3215         PaintInfo paintInfoForChild(paintInfo);
3216         paintInfoForChild.phase = newPhase;
3217         paintInfoForChild.updateSubtreePaintRootForChildren(this);
3218
3219         // FIXME: Paint-time pagination is obsolete and is now only used by embedded WebViews inside AppKit
3220         // NSViews. Do not add any more code for this.
3221         bool usePrintRect = !view()->printRect().isEmpty();
3222         paintChildren(paintInfo, paintOffset, paintInfoForChild, usePrintRect);
3223     }
3224 }
3225
3226 void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
3227 {
3228     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
3229         if (!paintChild(child, paintInfo, paintOffset, paintInfoForChild, usePrintRect))
3230             return;
3231     }
3232 }
3233
3234 bool RenderBlock::paintChild(RenderBox* child, PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
3235 {
3236     // Check for page-break-before: always, and if it's set, break and bail.
3237     bool checkBeforeAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakBefore() == PBALWAYS);
3238     LayoutUnit absoluteChildY = paintOffset.y() + child->y();
3239     if (checkBeforeAlways
3240         && absoluteChildY > paintInfo.rect.y()
3241         && absoluteChildY < paintInfo.rect.maxY()) {
3242         view()->setBestTruncatedAt(absoluteChildY, this, true);
3243         return false;
3244     }
3245
3246     RenderView* renderView = view();
3247     if (!child->isFloating() && child->isReplaced() && usePrintRect && child->height() <= renderView->printRect().height()) {
3248         // Paginate block-level replaced elements.
3249         if (absoluteChildY + child->height() > renderView->printRect().maxY()) {
3250             if (absoluteChildY < renderView->truncatedAt())
3251                 renderView->setBestTruncatedAt(absoluteChildY, child);
3252             // If we were able to truncate, don't paint.
3253             if (absoluteChildY >= renderView->truncatedAt())
3254                 return false;
3255         }
3256     }
3257
3258     LayoutPoint childPoint = flipForWritingModeForChild(child, paintOffset);
3259     if (!child->hasSelfPaintingLayer() && !child->isFloating())
3260         child->paint(paintInfoForChild, childPoint);
3261
3262     // Check for page-break-after: always, and if it's set, break and bail.
3263     bool checkAfterAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakAfter() == PBALWAYS);
3264     if (checkAfterAlways
3265         && (absoluteChildY + child->height()) > paintInfo.rect.y()
3266         && (absoluteChildY + child->height()) < paintInfo.rect.maxY()) {
3267         view()->setBestTruncatedAt(absoluteChildY + child->height() + max<LayoutUnit>(0, child->collapsedMarginAfter()), this, true);
3268         return false;
3269     }
3270     return true;
3271 }
3272
3273
3274 void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
3275 {
3276     // Paint the caret if the FrameSelection says so or if caret browsing is enabled
3277     bool caretBrowsing = frame()->settings().caretBrowsingEnabled();
3278     RenderObject* caretPainter;
3279     bool isContentEditable;
3280     if (type == CursorCaret) {
3281         caretPainter = frame()->selection().caretRenderer();
3282         isContentEditable = frame()->selection().rendererIsEditable();
3283     } else {
3284         caretPainter = frame()->page()->dragCaretController().caretRenderer();
3285         isContentEditable = frame()->page()->dragCaretController().isContentEditable();
3286     }
3287
3288     if (caretPainter == this && (isContentEditable || caretBrowsing)) {
3289         if (type == CursorCaret)
3290             frame()->selection().paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
3291         else
3292             frame()->page()->dragCaretController().paintDragCaret(frame(), paintInfo.context, paintOffset, paintInfo.rect);
3293     }
3294 }
3295
3296 void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3297 {
3298     PaintPhase paintPhase = paintInfo.phase;
3299
3300     // 1. paint background, borders etc
3301     if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style()->visibility() == VISIBLE) {
3302         if (hasBoxDecorations())
3303             paintBoxDecorations(paintInfo, paintOffset);
3304         if (hasColumns() && !paintInfo.paintRootBackgroundOnly())
3305             paintColumnRules(paintInfo, paintOffset);
3306     }
3307
3308     if (paintPhase == PaintPhaseMask && style()->visibility() == VISIBLE) {
3309         paintMask(paintInfo, paintOffset);
3310         return;
3311     }
3312
3313     // We're done.  We don't bother painting any children.
3314     if (paintPhase == PaintPhaseBlockBackground || paintInfo.paintRootBackgroundOnly())
3315         return;
3316
3317     // Adjust our painting position if we're inside a scrolled layer (e.g., an overflow:auto div).
3318     LayoutPoint scrolledOffset = paintOffset;
3319     if (hasOverflowClip())
3320         scrolledOffset.move(-scrolledContentOffset());
3321
3322     // 2. paint contents
3323     if (paintPhase != PaintPhaseSelfOutline) {
3324         if (hasColumns())
3325             paintColumnContents(paintInfo, scrolledOffset);
3326         else
3327             paintContents(paintInfo, scrolledOffset);
3328     }
3329
3330     // 3. paint selection
3331     // FIXME: Make this work with multi column layouts.  For now don't fill gaps.
3332     bool isPrinting = document()->printing();
3333     if (!isPrinting && !hasColumns())
3334         paintSelection(paintInfo, scrolledOffset); // Fill in gaps in selection on lines and between blocks.
3335
3336     // 4. paint floats.
3337     if (paintPhase == PaintPhaseFloat || paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip) {
3338         if (hasColumns())
3339             paintColumnContents(paintInfo, scrolledOffset, true);
3340         else
3341             paintFloats(paintInfo, scrolledOffset, paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip);
3342     }
3343
3344     // 5. paint outline.
3345     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseSelfOutline) && hasOutline() && style()->visibility() == VISIBLE)
3346         paintOutline(paintInfo, LayoutRect(paintOffset, size()));
3347
3348     // 6. paint continuation outlines.
3349     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseChildOutlines)) {
3350         RenderInline* inlineCont = inlineElementContinuation();
3351         if (inlineCont && inlineCont->hasOutline() && inlineCont->style()->visibility() == VISIBLE) {
3352             RenderInline* inlineRenderer = toRenderInline(inlineCont->node()->renderer());
3353             RenderBlock* cb = containingBlock();
3354
3355             bool inlineEnclosedInSelfPaintingLayer = false;
3356             for (RenderBoxModelObject* box = inlineRenderer; box != cb; box = box->parent()->enclosingBoxModelObject()) {
3357                 if (box->hasSelfPaintingLayer()) {
3358                     inlineEnclosedInSelfPaintingLayer = true;
3359                     break;
3360                 }
3361             }
3362
3363             // Do not add continuations for outline painting by our containing block if we are a relative positioned
3364             // anonymous block (i.e. have our own layer), paint them straightaway instead. This is because a block depends on renderers in its continuation table being
3365             // in the same layer. 
3366             if (!inlineEnclosedInSelfPaintingLayer && !hasLayer())
3367                 cb->addContinuationWithOutline(inlineRenderer);
3368             else if (!inlineRenderer->firstLineBox() || (!inlineEnclosedInSelfPaintingLayer && hasLayer()))
3369                 inlineRenderer->paintOutline(paintInfo, paintOffset - locationOffset() + inlineRenderer->containingBlock()->location());
3370         }
3371         paintContinuationOutlines(paintInfo, paintOffset);
3372     }
3373
3374     // 7. paint caret.
3375     // If the caret's node's render object's containing block is this block, and the paint action is PaintPhaseForeground,
3376     // then paint the caret.
3377     if (paintPhase == PaintPhaseForeground) {        
3378         paintCaret(paintInfo, paintOffset, CursorCaret);
3379         paintCaret(paintInfo, paintOffset, DragCaret);
3380     }
3381 }
3382
3383 LayoutPoint RenderBlock::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
3384 {
3385     if (!style()->isFlippedBlocksWritingMode())
3386         return point;
3387     
3388     // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
3389     // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
3390     // case.
3391     if (isHorizontalWritingMode())
3392         return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
3393     return LayoutPoint(point.x() + width() - child->renderer()->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
3394 }
3395
3396 void RenderBlock::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
3397 {
3398     if (!m_floatingObjects)
3399         return;
3400
3401     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
3402     FloatingObjectSetIterator end = floatingObjectSet.end();
3403     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
3404         FloatingObject* r = *it;
3405         // Only paint the object if our m_shouldPaint flag is set.
3406         if (r->shouldPaint() && !r->renderer()->hasSelfPaintingLayer()) {
3407             PaintInfo currentPaintInfo(paintInfo);
3408             currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
3409             // FIXME: LayoutPoint version of xPositionForFloatIncludingMargin would make this much cleaner.
3410             LayoutPoint childPoint = flipFloatForWritingModeForChild(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->renderer()->x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->renderer()->y()));
3411             r->renderer()->paint(currentPaintInfo, childPoint);
3412             if (!preservePhase) {
3413                 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
3414                 r->renderer()->paint(currentPaintInfo, childPoint);
3415                 currentPaintInfo.phase = PaintPhaseFloat;
3416                 r->renderer()->paint(currentPaintInfo, childPoint);
3417                 currentPaintInfo.phase = PaintPhaseForeground;
3418                 r->renderer()->paint(currentPaintInfo, childPoint);
3419                 currentPaintInfo.phase = PaintPhaseOutline;
3420                 r->renderer()->paint(currentPaintInfo, childPoint);
3421             }
3422         }
3423     }
3424 }
3425
3426 RenderInline* RenderBlock::inlineElementContinuation() const
3427
3428     RenderBoxModelObject* continuation = this->continuation();
3429     return continuation && continuation->isInline() ? toRenderInline(continuation) : 0;
3430 }
3431
3432 RenderBlock* RenderBlock::blockElementContinuation() const
3433 {
3434     RenderBoxModelObject* currentContinuation = continuation();
3435     if (!currentContinuation || currentContinuation->isInline())
3436         return 0;
3437     RenderBlock* nextContinuation = toRenderBlock(currentContinuation);
3438     if (nextContinuation->isAnonymousBlock())
3439         return nextContinuation->blockElementContinuation();
3440     return nextContinuation;
3441 }
3442     
3443 static ContinuationOutlineTableMap* continuationOutlineTable()
3444 {
3445     DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
3446     return &table;
3447 }
3448
3449 void RenderBlock::addContinuationWithOutline(RenderInline* flow)
3450 {
3451     // We can't make this work if the inline is in a layer.  We'll just rely on the broken
3452     // way of painting.
3453     ASSERT(!flow->layer() && !flow->isInlineElementContinuation());
3454     
3455     ContinuationOutlineTableMap* table = continuationOutlineTable();
3456     ListHashSet<RenderInline*>* continuations = table->get(this);
3457     if (!continuations) {
3458         continuations = new ListHashSet<RenderInline*>;
3459         table->set(this, adoptPtr(continuations));
3460     }
3461     
3462     continuations->add(flow);
3463 }
3464
3465 bool RenderBlock::paintsContinuationOutline(RenderInline* flow)
3466 {
3467     ContinuationOutlineTableMap* table = continuationOutlineTable();
3468     if (table->isEmpty())
3469         return false;
3470         
3471     ListHashSet<RenderInline*>* continuations = table->get(this);
3472     if (!continuations)
3473         return false;
3474
3475     return continuations->contains(flow);
3476 }
3477
3478 void RenderBlock::paintContinuationOutlines(PaintInfo& info, const LayoutPoint& paintOffset)
3479 {
3480     ContinuationOutlineTableMap* table = continuationOutlineTable();
3481     if (table->isEmpty())
3482         return;
3483         
3484     OwnPtr<ListHashSet<RenderInline*> > continuations = table->take(this);
3485     if (!continuations)
3486         return;
3487
3488     LayoutPoint accumulatedPaintOffset = paintOffset;
3489     // Paint each continuation outline.
3490     ListHashSet<RenderInline*>::iterator end = continuations->end();
3491     for (ListHashSet<RenderInline*>::iterator it = continuations->begin(); it != end; ++it) {
3492         // Need to add in the coordinates of the intervening blocks.
3493         RenderInline* flow = *it;
3494         RenderBlock* block = flow->containingBlock();
3495         for ( ; block && block != this; block = block->containingBlock())
3496             accumulatedPaintOffset.moveBy(block->location());
3497         ASSERT(block);   
3498         flow->paintOutline(info, accumulatedPaintOffset);
3499     }
3500 }
3501
3502 bool RenderBlock::shouldPaintSelectionGaps() const
3503 {
3504     return selectionState() != SelectionNone && style()->visibility() == VISIBLE && isSelectionRoot();
3505 }
3506
3507 bool RenderBlock::isSelectionRoot() const
3508 {
3509     if (isPseudoElement())
3510         return false;
3511     ASSERT(node() || isAnonymous());
3512         
3513     // FIXME: Eventually tables should have to learn how to fill gaps between cells, at least in simple non-spanning cases.
3514     if (isTable())
3515         return false;
3516         
3517     if (isBody() || isRoot() || hasOverflowClip()
3518         || isPositioned() || isFloating()
3519         || isTableCell() || isInlineBlockOrInlineTable()
3520         || hasTransform() || hasReflection() || hasMask() || isWritingModeRoot()
3521         || isRenderFlowThread())
3522         return true;
3523     
3524     if (view() && view()->selectionStart()) {
3525         Node* startElement = view()->selectionStart()->node();
3526         if (startElement && startElement->rootEditableElement() == node())
3527             return true;
3528     }
3529     
3530     return false;
3531 }
3532
3533 GapRects RenderBlock::selectionGapRectsForRepaint(const RenderLayerModelObject* repaintContainer)
3534 {
3535     ASSERT(!needsLayout());
3536
3537     if (!shouldPaintSelectionGaps())
3538         return GapRects();
3539
3540     TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
3541     mapLocalToContainer(repaintContainer, transformState, ApplyContainerFlip | UseTransforms);
3542     LayoutPoint offsetFromRepaintContainer = roundedLayoutPoint(transformState.mappedPoint());
3543
3544     if (hasOverflowClip())
3545         offsetFromRepaintContainer -= scrolledContentOffset();
3546
3547     LogicalSelectionOffsetCaches cache(this);
3548     LayoutUnit lastTop = 0;
3549     LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop, cache);
3550     LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop, cache);
3551     
3552     return selectionGaps(this, offsetFromRepaintContainer, IntSize(), lastTop, lastLeft, lastRight, cache);
3553 }
3554
3555 void RenderBlock::paintSelection(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3556 {
3557     if (shouldPaintSelectionGaps() && paintInfo.phase == PaintPhaseForeground) {
3558         LogicalSelectionOffsetCaches cache(this);
3559         LayoutUnit lastTop = 0;
3560         LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop, cache);
3561         LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop, cache);
3562         GraphicsContextStateSaver stateSaver(*paintInfo.context);
3563
3564         LayoutRect gapRectsBounds = selectionGaps(this, paintOffset, LayoutSize(), lastTop, lastLeft, lastRight, cache, &paintInfo);
3565         if (!gapRectsBounds.isEmpty()) {
3566             if (RenderLayer* layer = enclosingLayer()) {
3567                 gapRectsBounds.moveBy(-paintOffset);
3568                 if (!hasLayer()) {
3569                     LayoutRect localBounds(gapRectsBounds);
3570                     flipForWritingMode(localBounds);
3571                     gapRectsBounds = localToContainerQuad(FloatRect(localBounds), layer->renderer()).enclosingBoundingBox();
3572                     if (layer->renderer()->hasOverflowClip())
3573                         gapRectsBounds.move(layer->renderBox()->scrolledContentOffset());
3574                 }
3575                 layer->addBlockSelectionGapsBounds(gapRectsBounds);
3576             }
3577         }
3578     }
3579 }
3580
3581 static void clipOutPositionedObjects(const PaintInfo* paintInfo, const LayoutPoint& offset, TrackedRendererListHashSet* positionedObjects)
3582 {
3583     if (!positionedObjects)
3584         return;
3585     
3586     TrackedRendererListHashSet::const_iterator end = positionedObjects->end();
3587     for (TrackedRendererListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
3588         RenderBox* r = *it;
3589         paintInfo->context->clipOut(IntRect(offset.x() + r->x(), offset.y() + r->y(), r->width(), r->height()));
3590     }
3591 }
3592
3593 static LayoutUnit blockDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
3594 {
3595     return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
3596 }
3597
3598 static LayoutUnit inlineDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
3599 {
3600     return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.width() : offsetFromRootBlock.height();
3601 }
3602
3603 LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect)
3604 {
3605     LayoutRect result;
3606     if (isHorizontalWritingMode())
3607         result = logicalRect;
3608     else
3609         result = LayoutRect(logicalRect.y(), logicalRect.x(), logicalRect.height(), logicalRect.width());
3610     flipForWritingMode(result);
3611     result.moveBy(rootBlockPhysicalPosition);
3612     return result;
3613 }
3614
3615 GapRects RenderBlock::selectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3616     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
3617 {
3618     // IMPORTANT: Callers of this method that intend for painting to happen need to do a save/restore.
3619     // Clip out floating and positioned objects when painting selection gaps.
3620     if (paintInfo) {
3621         // Note that we don't clip out overflow for positioned objects.  We just stick to the border box.
3622         LayoutRect flippedBlockRect(offsetFromRootBlock.width(), offsetFromRootBlock.height(), width(), height());
3623         rootBlock->flipForWritingMode(flippedBlockRect);
3624         flippedBlockRect.moveBy(rootBlockPhysicalPosition);
3625         clipOutPositionedObjects(paintInfo, flippedBlockRect.location(), positionedObjects());
3626         if (isBody() || isRoot()) // The <body> must make sure to examine its containingBlock's positioned objects.
3627             for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
3628                 clipOutPositionedObjects(paintInfo, LayoutPoint(cb->x(), cb->y()), cb->positionedObjects()); // FIXME: Not right for flipped writing modes.
3629         if (m_floatingObjects) {
3630             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
3631             FloatingObjectSetIterator end = floatingObjectSet.end();
3632             for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
3633                 FloatingObject* r = *it;
3634                 LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(r),
3635                                     offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(r),
3636                                     r->renderer()->width(), r->renderer()->height());
3637                 rootBlock->flipForWritingMode(floatBox);
3638                 floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
3639                 paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
3640             }
3641         }
3642     }
3643
3644     // FIXME: overflow: auto/scroll regions need more math here, since painting in the border box is different from painting in the padding box (one is scrolled, the other is
3645     // fixed).
3646     GapRects result;
3647     if (!isBlockFlow()) // FIXME: Make multi-column selection gap filling work someday.
3648         return result;
3649
3650     if (hasColumns() || hasTransform() || style()->columnSpan()) {
3651         // FIXME: We should learn how to gap fill multiple columns and transforms eventually.
3652         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
3653         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight(), cache);
3654         lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight(), cache);
3655         return result;
3656     }
3657
3658     if (childrenInline())
3659         result = inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, cache, paintInfo);
3660     else
3661         result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, cache, paintInfo);
3662
3663     // Go ahead and fill the vertical gap all the way to the bottom of our block if the selection extends past our block.
3664     if (rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd)) {
3665         result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock,
3666             lastLogicalTop, lastLogicalLeft, lastLogicalRight, logicalHeight(), cache, paintInfo));
3667     }
3668
3669     return result;
3670 }
3671
3672 GapRects RenderBlock::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3673     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
3674 {
3675     GapRects result;
3676
3677     bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
3678
3679     if (!firstLineBox()) {
3680         if (containsStart) {
3681             // Go ahead and update our lastLogicalTop to be the bottom of the block.  <hr>s or empty blocks with height can trip this
3682             // case.
3683             lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
3684             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight(), cache);
3685             lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight(), cache);
3686         }
3687         return result;
3688     }
3689
3690     RootInlineBox* lastSelectedLine = 0;
3691     RootInlineBox* curr;
3692     for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
3693
3694     // Now paint the gaps for the lines.
3695     for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
3696         LayoutUnit selTop =  curr->selectionTopAdjustedForPrecedingBlock();
3697         LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
3698
3699         if (!containsStart && !lastSelectedLine &&
3700             selectionState() != SelectionStart && selectionState() != SelectionBoth)
3701             result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, selTop, cache, paintInfo));
3702         
3703         LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
3704         logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
3705         LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
3706         if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
3707             || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
3708             result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, cache, paintInfo));
3709
3710         lastSelectedLine = curr;
3711     }
3712
3713     if (containsStart && !lastSelectedLine)
3714         // VisibleSelection must start just after our last line.
3715         lastSelectedLine = lastRootBox();
3716
3717     if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
3718         // Go ahead and update our lastY to be the bottom of the last selected line.
3719         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + lastSelectedLine->selectionBottom();
3720         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom(), cache);
3721         lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom(), cache);
3722     }
3723     return result;
3724 }
3725
3726 GapRects RenderBlock::blockSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3727     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
3728 {
3729     GapRects result;
3730
3731     // Go ahead and jump right to the first block child that contains some selected objects.
3732     RenderBox* curr;
3733     for (curr = firstChildBox(); curr && curr->selectionState() == SelectionNone; curr = curr->nextSiblingBox()) { }
3734     
3735     if (!curr)
3736         return result;
3737
3738     LogicalSelectionOffsetCaches childCache(this, cache);
3739
3740     for (bool sawSelectionEnd = false; curr && !sawSelectionEnd; curr = curr->nextSiblingBox()) {
3741         SelectionState childState = curr->selectionState();
3742         if (childState == SelectionBoth || childState == SelectionEnd)
3743             sawSelectionEnd = true;
3744
3745         if (curr->isFloatingOrOutOfFlowPositioned())
3746             continue; // We must be a normal flow object in order to even be considered.
3747
3748         if (curr->isInFlowPositioned() && curr->hasLayer()) {
3749             // If the relposition offset is anything other than 0, then treat this just like an absolute posi