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