Remove overflow: scroll handling in block flow layout methods
[WebKit.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->isOutOfFlowPositioned()
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 ? !isFloatingOrOutOfFlowPositioned() && !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() && !isOutOfFlowPositioned() && (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 = !isFloatingOrOutOfFlowPositioned() && !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->isFloatingOrOutOfFlowPositioned()) {
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->isFloatingOrOutOfFlowPositioned()) {
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->isFloatingOrOutOfFlowPositioned() || 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     // Now take all of the children from beforeChild to the end and remove
572     // them from |this| and place them in the clone.
573     moveChildrenTo(cloneBlock, beforeChild, 0, true);
574     
575     // Hook |clone| up as the continuation of the middle block.
576     if (!cloneBlock->isAnonymousBlock())
577         middleBlock->setContinuation(cloneBlock);
578
579     // We have been reparented and are now under the fromBlock.  We need
580     // to walk up our block parent chain until we hit the containing anonymous columns block.
581     // Once we hit the anonymous columns block we're done.
582     RenderBoxModelObject* curr = toRenderBoxModelObject(parent());
583     RenderBoxModelObject* currChild = this;
584     RenderObject* currChildNextSibling = currChild->nextSibling();
585     bool documentUsesBeforeAfterRules = document()->usesBeforeAfterRules(); 
586
587     // Note: |this| can be destroyed inside this loop if it is an empty anonymous
588     // block and we try to call updateBeforeAfterContent inside which removes the
589     // generated content and additionally cleans up |this| empty anonymous block.
590     // See RenderBlock::removeChild(). DO NOT reference any local variables to |this|
591     // after this point.
592     while (curr && curr != fromBlock) {
593         ASSERT(curr->isRenderBlock());
594         
595         RenderBlock* blockCurr = toRenderBlock(curr);
596         
597         // Create a new clone.
598         RenderBlock* cloneChild = cloneBlock;
599         cloneBlock = blockCurr->clone();
600
601         // Insert our child clone as the first child.
602         cloneBlock->addChildIgnoringContinuation(cloneChild, 0);
603
604         // Hook the clone up as a continuation of |curr|.  Note we do encounter
605         // anonymous blocks possibly as we walk up the block chain.  When we split an
606         // anonymous block, there's no need to do any continuation hookup, since we haven't
607         // actually split a real element.
608         if (!blockCurr->isAnonymousBlock()) {
609             oldCont = blockCurr->continuation();
610             blockCurr->setContinuation(cloneBlock);
611             cloneBlock->setContinuation(oldCont);
612         }
613
614         // Someone may have indirectly caused a <q> to split.  When this happens, the :after content
615         // has to move into the inline continuation.  Call updateBeforeAfterContent to ensure that the inline's :after
616         // content gets properly destroyed.
617         bool isLastChild = (currChildNextSibling == blockCurr->lastChild());
618         if (documentUsesBeforeAfterRules)
619             blockCurr->children()->updateBeforeAfterContent(blockCurr, AFTER);
620         if (isLastChild && currChildNextSibling != blockCurr->lastChild())
621             currChildNextSibling = 0; // We destroyed the last child, so now we need to update
622                                       // the value of currChildNextSibling.
623
624         // Now we need to take all of the children starting from the first child
625         // *after* currChild and append them all to the clone.
626         blockCurr->moveChildrenTo(cloneBlock, currChildNextSibling, 0, true);
627
628         // Keep walking up the chain.
629         currChild = curr;
630         currChildNextSibling = currChild->nextSibling();
631         curr = toRenderBoxModelObject(curr->parent());
632     }
633
634     // Now we are at the columns block level. We need to put the clone into the toBlock.
635     toBlock->children()->appendChildNode(toBlock, cloneBlock);
636
637     // Now take all the children after currChild and remove them from the fromBlock
638     // and put them in the toBlock.
639     fromBlock->moveChildrenTo(toBlock, currChildNextSibling, 0, true);
640 }
641
642 void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
643                             RenderObject* newChild, RenderBoxModelObject* oldCont)
644 {
645     RenderBlock* pre = 0;
646     RenderBlock* block = containingColumnsBlock();
647     
648     // Delete our line boxes before we do the inline split into continuations.
649     block->deleteLineBoxTree();
650     
651     bool madeNewBeforeBlock = false;
652     if (block->isAnonymousColumnsBlock()) {
653         // We can reuse this block and make it the preBlock of the next continuation.
654         pre = block;
655         pre->removePositionedObjects(0);
656         block = toRenderBlock(block->parent());
657     } else {
658         // No anonymous block available for use.  Make one.
659         pre = block->createAnonymousColumnsBlock();
660         pre->setChildrenInline(false);
661         madeNewBeforeBlock = true;
662     }
663
664     RenderBlock* post = block->createAnonymousColumnsBlock();
665     post->setChildrenInline(false);
666
667     RenderObject* boxFirst = madeNewBeforeBlock ? block->firstChild() : pre->nextSibling();
668     if (madeNewBeforeBlock)
669         block->children()->insertChildNode(block, pre, boxFirst);
670     block->children()->insertChildNode(block, newBlockBox, boxFirst);
671     block->children()->insertChildNode(block, post, boxFirst);
672     block->setChildrenInline(false);
673     
674     if (madeNewBeforeBlock)
675         block->moveChildrenTo(pre, boxFirst, 0, true);
676
677     splitBlocks(pre, post, newBlockBox, beforeChild, oldCont);
678
679     // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
680     // time in makeChildrenNonInline by just setting this explicitly up front.
681     newBlockBox->setChildrenInline(false);
682
683     // We delayed adding the newChild until now so that the |newBlockBox| would be fully
684     // connected, thus allowing newChild access to a renderArena should it need
685     // to wrap itself in additional boxes (e.g., table construction).
686     newBlockBox->addChild(newChild);
687
688     // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
689     // get deleted properly.  Because objects moves from the pre block into the post block, we want to
690     // make new line boxes instead of leaving the old line boxes around.
691     pre->setNeedsLayoutAndPrefWidthsRecalc();
692     block->setNeedsLayoutAndPrefWidthsRecalc();
693     post->setNeedsLayoutAndPrefWidthsRecalc();
694 }
695
696 void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlock* newBlockBox, RenderObject* newChild)
697 {
698     RenderBlock* pre = 0;
699     RenderBlock* post = 0;
700     RenderBlock* block = this; // Eventually block will not just be |this|, but will also be a block nested inside |this|.  Assign to a variable
701                                // so that we don't have to patch all of the rest of the code later on.
702     
703     // Delete the block's line boxes before we do the split.
704     block->deleteLineBoxTree();
705
706     if (beforeChild && beforeChild->parent() != this)
707         beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
708
709     if (beforeChild != firstChild()) {
710         pre = block->createAnonymousColumnsBlock();
711         pre->setChildrenInline(block->childrenInline());
712     }
713
714     if (beforeChild) {
715         post = block->createAnonymousColumnsBlock();
716         post->setChildrenInline(block->childrenInline());
717     }
718
719     RenderObject* boxFirst = block->firstChild();
720     if (pre)
721         block->children()->insertChildNode(block, pre, boxFirst);
722     block->children()->insertChildNode(block, newBlockBox, boxFirst);
723     if (post)
724         block->children()->insertChildNode(block, post, boxFirst);
725     block->setChildrenInline(false);
726     
727     // 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).
728     block->moveChildrenTo(pre, boxFirst, beforeChild, true);
729     block->moveChildrenTo(post, beforeChild, 0, true);
730
731     // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
732     // time in makeChildrenNonInline by just setting this explicitly up front.
733     newBlockBox->setChildrenInline(false);
734
735     // We delayed adding the newChild until now so that the |newBlockBox| would be fully
736     // connected, thus allowing newChild access to a renderArena should it need
737     // to wrap itself in additional boxes (e.g., table construction).
738     newBlockBox->addChild(newChild);
739
740     // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
741     // get deleted properly.  Because objects moved from the pre block into the post block, we want to
742     // make new line boxes instead of leaving the old line boxes around.
743     if (pre)
744         pre->setNeedsLayoutAndPrefWidthsRecalc();
745     block->setNeedsLayoutAndPrefWidthsRecalc();
746     if (post)
747         post->setNeedsLayoutAndPrefWidthsRecalc();
748 }
749
750 RenderBlock* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
751 {
752     // FIXME: This function is the gateway for the addition of column-span support.  It will
753     // be added to in three stages:
754     // (1) Immediate children of a multi-column block can span.
755     // (2) Nested block-level children with only block-level ancestors between them and the multi-column block can span.
756     // (3) Nested children with block or inline ancestors between them and the multi-column block can span (this is when we
757     // cross the streams and have to cope with both types of continuations mixed together).
758     // This function currently supports (1) and (2).
759     RenderBlock* columnsBlockAncestor = 0;
760     if (!newChild->isText() && newChild->style()->columnSpan() && !newChild->isBeforeOrAfterContent()
761         && !newChild->isFloatingOrOutOfFlowPositioned() && !newChild->isInline() && !isAnonymousColumnSpanBlock()) {
762         columnsBlockAncestor = containingColumnsBlock(false);
763         if (columnsBlockAncestor) {
764             // Make sure that none of the parent ancestors have a continuation.
765             // If yes, we do not want split the block into continuations.
766             RenderObject* curr = this;
767             while (curr && curr != columnsBlockAncestor) {
768                 if (curr->isRenderBlock() && toRenderBlock(curr)->continuation()) {
769                     columnsBlockAncestor = 0;
770                     break;
771                 }
772                 curr = curr->parent();
773             }
774         }
775     }
776     return columnsBlockAncestor;
777 }
778
779 void RenderBlock::addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
780 {
781     // Make sure we don't append things after :after-generated content if we have it.
782     if (!beforeChild)
783         beforeChild = afterPseudoElementRenderer();
784
785     if (beforeChild && beforeChild->parent() != this) {
786         RenderObject* beforeChildContainer = beforeChild->parent();
787         while (beforeChildContainer->parent() != this)
788             beforeChildContainer = beforeChildContainer->parent();
789         ASSERT(beforeChildContainer);
790
791         if (beforeChildContainer->isAnonymous()) {
792             // If the requested beforeChild is not one of our children, then this is because
793             // there is an anonymous container within this object that contains the beforeChild.
794             RenderObject* beforeChildAnonymousContainer = beforeChildContainer;
795             if (beforeChildAnonymousContainer->isAnonymousBlock()
796 #if ENABLE(FULLSCREEN_API)
797                 // Full screen renderers and full screen placeholders act as anonymous blocks, not tables:
798                 || beforeChildAnonymousContainer->isRenderFullScreen()
799                 || beforeChildAnonymousContainer->isRenderFullScreenPlaceholder()
800 #endif
801                 ) {
802                 // Insert the child into the anonymous block box instead of here.
803                 if (newChild->isInline() || beforeChild->parent()->firstChild() != beforeChild)
804                     beforeChild->parent()->addChild(newChild, beforeChild);
805                 else
806                     addChild(newChild, beforeChild->parent());
807                 return;
808             }
809
810             ASSERT(beforeChildAnonymousContainer->isTable());
811             if (newChild->isTablePart()) {
812                 // Insert into the anonymous table.
813                 beforeChildAnonymousContainer->addChild(newChild, beforeChild);
814                 return;
815             }
816
817             beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
818
819             ASSERT(beforeChild->parent() == this);
820             if (beforeChild->parent() != this) {
821                 // We should never reach here. If we do, we need to use the
822                 // safe fallback to use the topmost beforeChild container.
823                 beforeChild = beforeChildContainer;
824             }
825         } else {
826             // We will reach here when beforeChild is a run-in element.
827             // If run-in element precedes a block-level element, it becomes the
828             // the first inline child of that block level element. The insertion
829             // point will be before that block-level element.
830             ASSERT(beforeChild->isRunIn());
831             beforeChild = beforeChildContainer;
832         }
833     }
834
835     // Nothing goes before the intruded run-in.
836     if (beforeChild && beforeChild->isRunIn() && runInIsPlacedIntoSiblingBlock(beforeChild))
837         beforeChild = beforeChild->nextSibling();
838
839     // Check for a spanning element in columns.
840     RenderBlock* columnsBlockAncestor = columnsBlockForSpanningElement(newChild);
841     if (columnsBlockAncestor) {
842         // We are placing a column-span element inside a block. 
843         RenderBlock* newBox = createAnonymousColumnSpanBlock();
844         
845         if (columnsBlockAncestor != this) {
846             // We are nested inside a multi-column element and are being split by the span.  We have to break up
847             // our block into continuations.
848             RenderBoxModelObject* oldContinuation = continuation();
849
850             // When we split an anonymous block, there's no need to do any continuation hookup,
851             // since we haven't actually split a real element.
852             if (!isAnonymousBlock())
853                 setContinuation(newBox);
854
855             // Someone may have put a <p> inside a <q>, causing a split.  When this happens, the :after content
856             // has to move into the inline continuation.  Call updateBeforeAfterContent to ensure that our :after
857             // content gets properly destroyed.
858             bool isFirstChild = (beforeChild == firstChild());
859             bool isLastChild = (beforeChild == lastChild());
860             if (document()->usesBeforeAfterRules())
861                 children()->updateBeforeAfterContent(this, AFTER);
862             if (isLastChild && beforeChild != lastChild()) {
863                 // We destroyed the last child, so now we need to update our insertion
864                 // point to be 0. It's just a straight append now.
865                 beforeChild = 0;
866             } else if (isFirstChild && beforeChild != firstChild()) {
867                 // If beforeChild was the last anonymous block that collapsed,
868                 // then we need to update its value.
869                 beforeChild = firstChild();
870             }
871
872             splitFlow(beforeChild, newBox, newChild, oldContinuation);
873             return;
874         }
875
876         // We have to perform a split of this block's children.  This involves creating an anonymous block box to hold
877         // the column-spanning |newChild|.  We take all of the children from before |newChild| and put them into
878         // one anonymous columns block, and all of the children after |newChild| go into another anonymous block.
879         makeChildrenAnonymousColumnBlocks(beforeChild, newBox, newChild);
880         return;
881     }
882
883     bool madeBoxesNonInline = false;
884
885     // A block has to either have all of its children inline, or all of its children as blocks.
886     // So, if our children are currently inline and a block child has to be inserted, we move all our
887     // inline children into anonymous block boxes.
888     if (childrenInline() && !newChild->isInline() && !newChild->isFloatingOrOutOfFlowPositioned()) {
889         // This is a block with inline content. Wrap the inline content in anonymous blocks.
890         makeChildrenNonInline(beforeChild);
891         madeBoxesNonInline = true;
892
893         if (beforeChild && beforeChild->parent() != this) {
894             beforeChild = beforeChild->parent();
895             ASSERT(beforeChild->isAnonymousBlock());
896             ASSERT(beforeChild->parent() == this);
897         }
898     } else if (!childrenInline() && (newChild->isFloatingOrOutOfFlowPositioned() || newChild->isInline())) {
899         // If we're inserting an inline child but all of our children are blocks, then we have to make sure
900         // it is put into an anomyous block box. We try to use an existing anonymous box if possible, otherwise
901         // a new one is created and inserted into our list of children in the appropriate position.
902         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : lastChild();
903
904         if (afterChild && afterChild->isAnonymousBlock()) {
905             afterChild->addChild(newChild);
906             return;
907         }
908
909         if (newChild->isInline()) {
910             // No suitable existing anonymous box - create a new one.
911             RenderBlock* newBox = createAnonymousBlock();
912             RenderBox::addChild(newBox, beforeChild);
913             newBox->addChild(newChild);
914             return;
915         }
916     }
917
918     RenderBox::addChild(newChild, beforeChild);
919  
920     // Handle placement of run-ins.
921     placeRunInIfNeeded(newChild, DoNotPlaceGeneratedRunIn);
922
923     if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
924         toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
925     // this object may be dead here
926 }
927
928 void RenderBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
929 {
930     if (continuation() && !isAnonymousBlock())
931         addChildToContinuation(newChild, beforeChild);
932     else
933         addChildIgnoringContinuation(newChild, beforeChild);
934 }
935
936 void RenderBlock::addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild)
937 {
938     if (!isAnonymousBlock() && firstChild() && (firstChild()->isAnonymousColumnsBlock() || firstChild()->isAnonymousColumnSpanBlock()))
939         addChildToAnonymousColumnBlocks(newChild, beforeChild);
940     else
941         addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
942 }
943
944 static void getInlineRun(RenderObject* start, RenderObject* boundary,
945                          RenderObject*& inlineRunStart,
946                          RenderObject*& inlineRunEnd)
947 {
948     // Beginning at |start| we find the largest contiguous run of inlines that
949     // we can.  We denote the run with start and end points, |inlineRunStart|
950     // and |inlineRunEnd|.  Note that these two values may be the same if
951     // we encounter only one inline.
952     //
953     // We skip any non-inlines we encounter as long as we haven't found any
954     // inlines yet.
955     //
956     // |boundary| indicates a non-inclusive boundary point.  Regardless of whether |boundary|
957     // is inline or not, we will not include it in a run with inlines before it.  It's as though we encountered
958     // a non-inline.
959     
960     // Start by skipping as many non-inlines as we can.
961     RenderObject * curr = start;
962     bool sawInline;
963     do {
964         while (curr && !(curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()))
965             curr = curr->nextSibling();
966         
967         inlineRunStart = inlineRunEnd = curr;
968         
969         if (!curr)
970             return; // No more inline children to be found.
971         
972         sawInline = curr->isInline();
973         
974         curr = curr->nextSibling();
975         while (curr && (curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()) && (curr != boundary)) {
976             inlineRunEnd = curr;
977             if (curr->isInline())
978                 sawInline = true;
979             curr = curr->nextSibling();
980         }
981     } while (!sawInline);
982 }
983
984 void RenderBlock::deleteLineBoxTree()
985 {
986     if (containsFloats()) {
987         // Clear references to originating lines, since the lines are being deleted
988         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
989         FloatingObjectSetIterator end = floatingObjectSet.end();
990         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
991             ASSERT(!((*it)->m_originatingLine) || (*it)->m_originatingLine->renderer() == this);
992             (*it)->m_originatingLine = 0;
993         }
994     }
995     m_lineBoxes.deleteLineBoxTree(renderArena());
996 }
997
998 RootInlineBox* RenderBlock::createRootInlineBox() 
999 {
1000     return new (renderArena()) RootInlineBox(this);
1001 }
1002
1003 RootInlineBox* RenderBlock::createAndAppendRootInlineBox()
1004 {
1005     RootInlineBox* rootBox = createRootInlineBox();
1006     m_lineBoxes.appendLineBox(rootBox);
1007     return rootBox;
1008 }
1009
1010 void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
1011 {    
1012     // makeChildrenNonInline takes a block whose children are *all* inline and it
1013     // makes sure that inline children are coalesced under anonymous
1014     // blocks.  If |insertionPoint| is defined, then it represents the insertion point for
1015     // the new block child that is causing us to have to wrap all the inlines.  This
1016     // means that we cannot coalesce inlines before |insertionPoint| with inlines following
1017     // |insertionPoint|, because the new child is going to be inserted in between the inlines,
1018     // splitting them.
1019     ASSERT(isInlineBlockOrInlineTable() || !isInline());
1020     ASSERT(!insertionPoint || insertionPoint->parent() == this);
1021
1022     setChildrenInline(false);
1023
1024     RenderObject *child = firstChild();
1025     if (!child)
1026         return;
1027
1028     deleteLineBoxTree();
1029
1030     // Since we are going to have block children, we have to move
1031     // back the run-in to its original place.
1032     if (child->isRunIn()) {
1033         moveRunInToOriginalPosition(child);
1034         child = firstChild();
1035     }
1036
1037     while (child) {
1038         RenderObject *inlineRunStart, *inlineRunEnd;
1039         getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
1040
1041         if (!inlineRunStart)
1042             break;
1043
1044         child = inlineRunEnd->nextSibling();
1045
1046         RenderBlock* block = createAnonymousBlock();
1047         children()->insertChildNode(this, block, inlineRunStart);
1048         moveChildrenTo(block, inlineRunStart, child);
1049     }
1050
1051 #ifndef NDEBUG
1052     for (RenderObject *c = firstChild(); c; c = c->nextSibling())
1053         ASSERT(!c->isInline());
1054 #endif
1055
1056     repaint();
1057 }
1058
1059 void RenderBlock::removeLeftoverAnonymousBlock(RenderBlock* child)
1060 {
1061     ASSERT(child->isAnonymousBlock());
1062     ASSERT(!child->childrenInline());
1063     
1064     if (child->continuation() || (child->firstChild() && (child->isAnonymousColumnSpanBlock() || child->isAnonymousColumnsBlock())))
1065         return;
1066     
1067     RenderObject* firstAnChild = child->m_children.firstChild();
1068     RenderObject* lastAnChild = child->m_children.lastChild();
1069     if (firstAnChild) {
1070         RenderObject* o = firstAnChild;
1071         while (o) {
1072             o->setParent(this);
1073             o = o->nextSibling();
1074         }
1075         firstAnChild->setPreviousSibling(child->previousSibling());
1076         lastAnChild->setNextSibling(child->nextSibling());
1077         if (child->previousSibling())
1078             child->previousSibling()->setNextSibling(firstAnChild);
1079         if (child->nextSibling())
1080             child->nextSibling()->setPreviousSibling(lastAnChild);
1081             
1082         if (child == m_children.firstChild())
1083             m_children.setFirstChild(firstAnChild);
1084         if (child == m_children.lastChild())
1085             m_children.setLastChild(lastAnChild);
1086     } else {
1087         if (child == m_children.firstChild())
1088             m_children.setFirstChild(child->nextSibling());
1089         if (child == m_children.lastChild())
1090             m_children.setLastChild(child->previousSibling());
1091
1092         if (child->previousSibling())
1093             child->previousSibling()->setNextSibling(child->nextSibling());
1094         if (child->nextSibling())
1095             child->nextSibling()->setPreviousSibling(child->previousSibling());
1096     }
1097     child->setParent(0);
1098     child->setPreviousSibling(0);
1099     child->setNextSibling(0);
1100     
1101     child->children()->setFirstChild(0);
1102     child->m_next = 0;
1103
1104     child->destroy();
1105 }
1106
1107 static bool canMergeContiguousAnonymousBlocks(RenderObject* oldChild, RenderObject* prev, RenderObject* next)
1108 {
1109     if (oldChild->documentBeingDestroyed() || oldChild->isInline() || oldChild->virtualContinuation())
1110         return false;
1111
1112     if ((prev && (!prev->isAnonymousBlock() || toRenderBlock(prev)->continuation() || toRenderBlock(prev)->beingDestroyed()))
1113         || (next && (!next->isAnonymousBlock() || toRenderBlock(next)->continuation() || toRenderBlock(next)->beingDestroyed())))
1114         return false;
1115
1116     // FIXME: This check isn't required when inline run-ins can't be split into continuations.
1117     if (prev && prev->firstChild() && prev->firstChild()->isInline() && prev->firstChild()->isRunIn())
1118         return false;
1119
1120     if ((prev && (prev->isRubyRun() || prev->isRubyBase()))
1121         || (next && (next->isRubyRun() || next->isRubyBase())))
1122         return false;
1123
1124     if (!prev || !next)
1125         return true;
1126
1127     // Make sure the types of the anonymous blocks match up.
1128     return prev->isAnonymousColumnsBlock() == next->isAnonymousColumnsBlock()
1129            && prev->isAnonymousColumnSpanBlock() == next->isAnonymousColumnSpanBlock();
1130 }
1131
1132 void RenderBlock::collapseAnonymousBoxChild(RenderBlock* parent, RenderObject* child)
1133 {
1134     parent->setNeedsLayoutAndPrefWidthsRecalc();
1135     parent->setChildrenInline(child->childrenInline());
1136     RenderObject* nextSibling = child->nextSibling();
1137
1138     RenderFlowThread* childFlowThread = child->enclosingRenderFlowThread();
1139     RenderBlock* anonBlock = toRenderBlock(parent->children()->removeChildNode(parent, child, child->hasLayer()));
1140     anonBlock->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
1141     // Delete the now-empty block's lines and nuke it.
1142     if (!parent->documentBeingDestroyed())
1143         anonBlock->deleteLineBoxTree();
1144     if (!parent->documentBeingDestroyed() && childFlowThread && childFlowThread->isRenderNamedFlowThread())
1145         toRenderNamedFlowThread(childFlowThread)->removeFlowChildInfo(anonBlock);
1146     anonBlock->destroy();
1147 }
1148
1149 void RenderBlock::removeChild(RenderObject* oldChild)
1150 {
1151     // If this child is a block, and if our previous and next siblings are
1152     // both anonymous blocks with inline content, then we can go ahead and
1153     // fold the inline content back together.
1154     RenderObject* prev = oldChild->previousSibling();
1155     RenderObject* next = oldChild->nextSibling();
1156     bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
1157     if (canMergeAnonymousBlocks && prev && next) {
1158         prev->setNeedsLayoutAndPrefWidthsRecalc();
1159         RenderBlock* nextBlock = toRenderBlock(next);
1160         RenderBlock* prevBlock = toRenderBlock(prev);
1161        
1162         if (prev->childrenInline() != next->childrenInline()) {
1163             RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
1164             RenderBlock* blockChildrenBlock = prev->childrenInline() ? nextBlock : prevBlock;
1165             
1166             // Place the inline children block inside of the block children block instead of deleting it.
1167             // In order to reuse it, we have to reset it to just be a generic anonymous block.  Make sure
1168             // to clear out inherited column properties by just making a new style, and to also clear the
1169             // column span flag if it is set.
1170             ASSERT(!inlineChildrenBlock->continuation());
1171             RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK);
1172             children()->removeChildNode(this, inlineChildrenBlock, inlineChildrenBlock->hasLayer());
1173             inlineChildrenBlock->setStyle(newStyle);
1174             
1175             // Now just put the inlineChildrenBlock inside the blockChildrenBlock.
1176             blockChildrenBlock->children()->insertChildNode(blockChildrenBlock, inlineChildrenBlock, prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : 0,
1177                                                             inlineChildrenBlock->hasLayer() || blockChildrenBlock->hasLayer());
1178             next->setNeedsLayoutAndPrefWidthsRecalc();
1179             
1180             // inlineChildrenBlock got reparented to blockChildrenBlock, so it is no longer a child
1181             // of "this". we null out prev or next so that is not used later in the function.
1182             if (inlineChildrenBlock == prevBlock)
1183                 prev = 0;
1184             else
1185                 next = 0;
1186         } else {
1187             // Take all the children out of the |next| block and put them in
1188             // the |prev| block.
1189             nextBlock->moveAllChildrenTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());        
1190             
1191             // Delete the now-empty block's lines and nuke it.
1192             nextBlock->deleteLineBoxTree();
1193             nextBlock->destroy();
1194             next = 0;
1195         }
1196     }
1197
1198     RenderBox::removeChild(oldChild);
1199
1200     RenderObject* child = prev ? prev : next;
1201     if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && !isFlexibleBoxIncludingDeprecated()) {
1202         // The removal has knocked us down to containing only a single anonymous
1203         // box.  We can go ahead and pull the content right back up into our
1204         // box.
1205         collapseAnonymousBoxChild(this, child);
1206     } else if (((prev && prev->isAnonymousBlock()) || (next && next->isAnonymousBlock())) && !isFlexibleBoxIncludingDeprecated()) {
1207         // It's possible that the removal has knocked us down to a single anonymous
1208         // block with pseudo-style element siblings (e.g. first-letter). If these
1209         // are floating, then we need to pull the content up also.
1210         RenderBlock* anonBlock = toRenderBlock((prev && prev->isAnonymousBlock()) ? prev : next);
1211         if ((anonBlock->previousSibling() || anonBlock->nextSibling())
1212             && (!anonBlock->previousSibling() || (anonBlock->previousSibling()->style()->styleType() != NOPSEUDO && anonBlock->previousSibling()->isFloating() && !anonBlock->previousSibling()->previousSibling()))
1213             && (!anonBlock->nextSibling() || (anonBlock->nextSibling()->style()->styleType() != NOPSEUDO && anonBlock->nextSibling()->isFloating() && !anonBlock->nextSibling()->nextSibling()))) {
1214             collapseAnonymousBoxChild(this, anonBlock);
1215         }
1216     }
1217
1218     if (!firstChild() && !documentBeingDestroyed()) {
1219         // If this was our last child be sure to clear out our line boxes.
1220         if (childrenInline())
1221             deleteLineBoxTree();
1222
1223         // If we are an empty anonymous block in the continuation chain,
1224         // we need to remove ourself and fix the continuation chain.
1225         if (!beingDestroyed() && isAnonymousBlockContinuation()) {
1226             RenderObject* containingBlockIgnoringAnonymous = containingBlock();
1227             while (containingBlockIgnoringAnonymous && containingBlockIgnoringAnonymous->isAnonymousBlock())
1228                 containingBlockIgnoringAnonymous = containingBlockIgnoringAnonymous->containingBlock();
1229             for (RenderObject* curr = this; curr; curr = curr->previousInPreOrder(containingBlockIgnoringAnonymous)) {
1230                 if (curr->virtualContinuation() != this)
1231                     continue;
1232
1233                 // Found our previous continuation. We just need to point it to
1234                 // |this|'s next continuation.
1235                 RenderBoxModelObject* nextContinuation = continuation();
1236                 if (curr->isRenderInline())
1237                     toRenderInline(curr)->setContinuation(nextContinuation);
1238                 else if (curr->isRenderBlock())
1239                     toRenderBlock(curr)->setContinuation(nextContinuation);
1240                 else
1241                     ASSERT_NOT_REACHED();
1242
1243                 break;
1244             }
1245             setContinuation(0);
1246             destroy();
1247         }
1248     }
1249 }
1250
1251 bool RenderBlock::isSelfCollapsingBlock() const
1252 {
1253     // We are not self-collapsing if we
1254     // (a) have a non-zero height according to layout (an optimization to avoid wasting time)
1255     // (b) are a table,
1256     // (c) have border/padding,
1257     // (d) have a min-height
1258     // (e) have specified that one of our margins can't collapse using a CSS extension
1259     if (logicalHeight() > ZERO_LAYOUT_UNIT
1260         || isTable() || borderAndPaddingLogicalHeight()
1261         || style()->logicalMinHeight().isPositive()
1262         || style()->marginBeforeCollapse() == MSEPARATE || style()->marginAfterCollapse() == MSEPARATE)
1263         return false;
1264
1265     Length logicalHeightLength = style()->logicalHeight();
1266     bool hasAutoHeight = logicalHeightLength.isAuto();
1267     if (logicalHeightLength.isPercent() && !document()->inQuirksMode()) {
1268         hasAutoHeight = true;
1269         for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
1270             if (cb->style()->logicalHeight().isFixed() || cb->isTableCell())
1271                 hasAutoHeight = false;
1272         }
1273     }
1274
1275     // If the height is 0 or auto, then whether or not we are a self-collapsing block depends
1276     // on whether we have content that is all self-collapsing or not.
1277     if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
1278         // If the block has inline children, see if we generated any line boxes.  If we have any
1279         // line boxes, then we can't be self-collapsing, since we have content.
1280         if (childrenInline())
1281             return !firstLineBox();
1282         
1283         // Whether or not we collapse is dependent on whether all our normal flow children
1284         // are also self-collapsing.
1285         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1286             if (child->isFloatingOrOutOfFlowPositioned())
1287                 continue;
1288             if (!child->isSelfCollapsingBlock())
1289                 return false;
1290         }
1291         return true;
1292     }
1293     return false;
1294 }
1295
1296 void RenderBlock::startDelayUpdateScrollInfo()
1297 {
1298     if (gDelayUpdateScrollInfo == 0) {
1299         ASSERT(!gDelayedUpdateScrollInfoSet);
1300         gDelayedUpdateScrollInfoSet = new DelayedUpdateScrollInfoSet;
1301     }
1302     ASSERT(gDelayedUpdateScrollInfoSet);
1303     ++gDelayUpdateScrollInfo;
1304 }
1305
1306 void RenderBlock::finishDelayUpdateScrollInfo()
1307 {
1308     --gDelayUpdateScrollInfo;
1309     ASSERT(gDelayUpdateScrollInfo >= 0);
1310     if (gDelayUpdateScrollInfo == 0) {
1311         ASSERT(gDelayedUpdateScrollInfoSet);
1312
1313         OwnPtr<DelayedUpdateScrollInfoSet> infoSet(adoptPtr(gDelayedUpdateScrollInfoSet));
1314         gDelayedUpdateScrollInfoSet = 0;
1315
1316         for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
1317             RenderBlock* block = *it;
1318             if (block->hasOverflowClip()) {
1319                 block->layer()->updateScrollInfoAfterLayout();
1320             }
1321         }
1322     }
1323 }
1324
1325 void RenderBlock::updateScrollInfoAfterLayout()
1326 {
1327     if (hasOverflowClip()) {
1328         if (gDelayUpdateScrollInfo)
1329             gDelayedUpdateScrollInfoSet->add(this);
1330         else
1331             layer()->updateScrollInfoAfterLayout();
1332     }
1333 }
1334
1335 void RenderBlock::layout()
1336 {
1337     OverflowEventDispatcher dispatcher(this);
1338
1339     // Update our first letter info now.
1340     updateFirstLetter();
1341
1342     // Table cells call layoutBlock directly, so don't add any logic here.  Put code into
1343     // layoutBlock().
1344     layoutBlock(false);
1345     
1346     // It's safe to check for control clip here, since controls can never be table cells.
1347     // If we have a lightweight clip, there can never be any overflow from children.
1348     if (hasControlClip() && m_overflow)
1349         clearLayoutOverflow();
1350 }
1351
1352 void RenderBlock::computeInitialRegionRangeForBlock()
1353 {
1354     if (inRenderFlowThread()) {
1355         // Set our start and end regions. No regions above or below us will be considered by our children. They are
1356         // effectively clamped to our region range.
1357         LayoutUnit oldHeight =  logicalHeight();
1358         LayoutUnit oldLogicalTop = logicalTop();
1359         setLogicalHeight(MAX_LAYOUT_UNIT / 2);
1360         computeLogicalHeight();
1361         enclosingRenderFlowThread()->setRegionRangeForBox(this, offsetFromLogicalTopOfFirstPage());
1362         setLogicalHeight(oldHeight);
1363         setLogicalTop(oldLogicalTop);
1364     }
1365 }
1366
1367 void RenderBlock::computeRegionRangeForBlock()
1368 {
1369     if (inRenderFlowThread())
1370         enclosingRenderFlowThread()->setRegionRangeForBox(this, offsetFromLogicalTopOfFirstPage());
1371 }
1372
1373 bool RenderBlock::recomputeLogicalWidth()
1374 {
1375     LayoutUnit oldWidth = logicalWidth();
1376     LayoutUnit oldColumnWidth = desiredColumnWidth();
1377
1378     computeLogicalWidth();
1379     calcColumnWidth();
1380
1381     return oldWidth != logicalWidth() || oldColumnWidth != desiredColumnWidth();
1382 }
1383
1384 void RenderBlock::checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight)
1385 {
1386     ColumnInfo* colInfo = columnInfo();
1387     if (hasColumns()) {
1388         if (!pageLogicalHeight) {
1389             // We need to go ahead and set our explicit page height if one exists, so that we can
1390             // avoid doing two layout passes.
1391             computeLogicalHeight();
1392             LayoutUnit columnHeight = contentLogicalHeight();
1393             if (columnHeight > ZERO_LAYOUT_UNIT) {
1394                 pageLogicalHeight = columnHeight;
1395                 hasSpecifiedPageLogicalHeight = true;
1396             }
1397             setLogicalHeight(ZERO_LAYOUT_UNIT);
1398         }
1399         if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout()) {
1400             colInfo->setColumnHeight(pageLogicalHeight);
1401             pageLogicalHeightChanged = true;
1402         }
1403         
1404         if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
1405             colInfo->clearForcedBreaks();
1406
1407         colInfo->setPaginationUnit(paginationUnit());
1408     }
1409 }
1410
1411 void RenderBlock::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
1412 {
1413     ASSERT(needsLayout());
1414
1415     if (isInline() && !isInlineBlockOrInlineTable()) // Inline <form>s inside various table elements can
1416         return;                                      // cause us to come in here.  Just bail.
1417
1418     if (!relayoutChildren && simplifiedLayout())
1419         return;
1420
1421     LayoutRepainter repainter(*this, everHadLayout() && checkForRepaintDuringLayout());
1422
1423     if (recomputeLogicalWidth())
1424         relayoutChildren = true;
1425
1426     m_overflow.clear();
1427
1428     clearFloats();
1429
1430     LayoutUnit previousHeight = logicalHeight();
1431     setLogicalHeight(ZERO_LAYOUT_UNIT);
1432
1433     bool pageLogicalHeightChanged = false;
1434     bool hasSpecifiedPageLogicalHeight = false;
1435     checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
1436
1437     RenderView* renderView = view();
1438     RenderStyle* styleToUse = style();
1439     LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
1440
1441     if (inRenderFlowThread()) {
1442         // Regions changing widths can force us to relayout our children.
1443         if (logicalWidthChangedInRegions())
1444             relayoutChildren = true;
1445     }
1446     computeInitialRegionRangeForBlock();
1447
1448     // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
1449     // our current maximal positive and negative margins.  These values are used when we
1450     // are collapsed with adjacent blocks, so for example, if you have block A and B
1451     // collapsing together, then you'd take the maximal positive margin from both A and B
1452     // and subtract it from the maximal negative margin from both A and B to get the
1453     // true collapsed margin.  This algorithm is recursive, so when we finish layout()
1454     // our block knows its current maximal positive/negative values.
1455     //
1456     // Start out by setting our margin values to our current margins.  Table cells have
1457     // no margins, so we don't fill in the values for table cells.
1458     bool isCell = isTableCell();
1459     if (!isCell) {
1460         initMaxMarginValues();
1461         
1462         setMarginBeforeQuirk(styleToUse->marginBefore().quirk());
1463         setMarginAfterQuirk(styleToUse->marginAfter().quirk());
1464
1465         Node* n = node();
1466         if (n && n->hasTagName(formTag) && static_cast<HTMLFormElement*>(n)->isMalformed()) {
1467             // See if this form is malformed (i.e., unclosed). If so, don't give the form
1468             // a bottom margin.
1469             setMaxMarginAfterValues(0, 0);
1470         }
1471         
1472         setPaginationStrut(0);
1473     }
1474
1475     LayoutUnit repaintLogicalTop = ZERO_LAYOUT_UNIT;
1476     LayoutUnit repaintLogicalBottom = ZERO_LAYOUT_UNIT;
1477     LayoutUnit maxFloatLogicalBottom = ZERO_LAYOUT_UNIT;
1478     if (!firstChild() && !isAnonymousBlock())
1479         setChildrenInline(true);
1480     if (childrenInline())
1481         layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
1482     else
1483         layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
1484
1485     // Expand our intrinsic height to encompass floats.
1486     LayoutUnit toAdd = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
1487     if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
1488         setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
1489     
1490     if (relayoutForPagination(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher))
1491         return;
1492  
1493     // Calculate our new height.
1494     LayoutUnit oldHeight = logicalHeight();
1495     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
1496     computeLogicalHeight();
1497     LayoutUnit newHeight = logicalHeight();
1498     if (oldHeight != newHeight) {
1499         if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
1500             // One of our children's floats may have become an overhanging float for us. We need to look for it.
1501             for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1502                 if (child->isBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
1503                     RenderBlock* block = toRenderBlock(child);
1504                     if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
1505                         addOverhangingFloats(block, false);
1506                 }
1507             }
1508         }
1509     }
1510
1511     if (previousHeight != newHeight)
1512         relayoutChildren = true;
1513
1514     layoutPositionedObjects(relayoutChildren || isRoot());
1515
1516     computeRegionRangeForBlock();
1517
1518     // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
1519     computeOverflow(oldClientAfterEdge);
1520     
1521     statePusher.pop();
1522
1523     if (renderView->layoutState()->m_pageLogicalHeight)
1524         setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(this, logicalTop()));
1525
1526     updateLayerTransform();
1527
1528     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
1529     // we overflow or not.
1530     updateScrollInfoAfterLayout();
1531
1532     // FIXME: This repaint logic should be moved into a separate helper function!
1533     // Repaint with our new bounds if they are different from our old bounds.
1534     bool didFullRepaint = repainter.repaintAfterLayout();
1535     if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
1536         // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
1537         // it had to lay out.  We wouldn't need the hasOverflowClip() hack in that case either.
1538         LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
1539         LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
1540         if (hasOverflowClip()) {
1541             // 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.
1542             // 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.
1543             // layoutInlineChildren should be patched to compute the entire repaint rect.
1544             repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
1545             repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
1546         }
1547         
1548         LayoutRect repaintRect;
1549         if (isHorizontalWritingMode())
1550             repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
1551         else
1552             repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
1553
1554         // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
1555         adjustRectForColumns(repaintRect);
1556
1557         repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
1558         
1559         if (hasOverflowClip()) {
1560             // Adjust repaint rect for scroll offset
1561             repaintRect.move(-scrolledContentOffset());
1562
1563             // Don't allow this rect to spill out of our overflow box.
1564             repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
1565         }
1566
1567         // Make sure the rect is still non-empty after intersecting for overflow above
1568         if (!repaintRect.isEmpty()) {
1569             repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
1570             if (hasReflection())
1571                 repaintRectangle(reflectedRect(repaintRect));
1572         }
1573     }
1574     
1575     setNeedsLayout(false);
1576 }
1577
1578 void RenderBlock::addOverflowFromChildren()
1579 {
1580     if (!hasColumns()) {
1581         if (childrenInline())
1582             addOverflowFromInlineChildren();
1583         else
1584             addOverflowFromBlockChildren();
1585     } else {
1586         ColumnInfo* colInfo = columnInfo();
1587         if (columnCount(colInfo)) {
1588             LayoutRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1);
1589             addLayoutOverflow(lastRect);
1590             if (!hasOverflowClip())
1591                 addVisualOverflow(lastRect);
1592         }
1593     }
1594 }
1595
1596 void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
1597 {
1598     // Add overflow from children.
1599     addOverflowFromChildren();
1600
1601     if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
1602         addOverflowFromFloats();
1603
1604     // Add in the overflow from positioned objects.
1605     addOverflowFromPositionedObjects();
1606
1607     if (hasOverflowClip()) {
1608         // When we have overflow clip, propagate the original spillout since it will include collapsed bottom margins
1609         // and bottom padding.  Set the axis we don't care about to be 1, since we want this overflow to always
1610         // be considered reachable.
1611         LayoutRect clientRect(clientBoxRect());
1612         LayoutRect rectToApply;
1613         if (isHorizontalWritingMode())
1614             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), 1, max(ZERO_LAYOUT_UNIT, oldClientAfterEdge - clientRect.y()));
1615         else
1616             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), max(ZERO_LAYOUT_UNIT, oldClientAfterEdge - clientRect.x()), 1);
1617         addLayoutOverflow(rectToApply);
1618     }
1619         
1620     // Add visual overflow from box-shadow and border-image-outset.
1621     addVisualEffectOverflow();
1622
1623     // Add visual overflow from theme.
1624     addVisualOverflowFromTheme();
1625
1626     if (isRenderFlowThread())
1627         enclosingRenderFlowThread()->computeOverflowStateForRegions(oldClientAfterEdge);
1628 }
1629
1630 void RenderBlock::addOverflowFromBlockChildren()
1631 {
1632     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1633         if (!child->isFloatingOrOutOfFlowPositioned())
1634             addOverflowFromChild(child);
1635     }
1636 }
1637
1638 void RenderBlock::addOverflowFromFloats()
1639 {
1640     if (!m_floatingObjects)
1641         return;
1642
1643     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1644     FloatingObjectSetIterator end = floatingObjectSet.end();
1645     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1646         FloatingObject* r = *it;
1647         if (r->isDescendant())
1648             addOverflowFromChild(r->m_renderer, IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
1649     }
1650     return;
1651 }
1652
1653 void RenderBlock::addOverflowFromPositionedObjects()
1654 {
1655     if (!m_positionedObjects)
1656         return;
1657
1658     RenderBox* positionedObject;
1659     Iterator end = m_positionedObjects->end();
1660     for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
1661         positionedObject = *it;
1662         
1663         // Fixed positioned elements don't contribute to layout overflow, since they don't scroll with the content.
1664         if (positionedObject->style()->position() != FixedPosition)
1665             addOverflowFromChild(positionedObject, IntSize(positionedObject->x(), positionedObject->y()));
1666     }
1667 }
1668
1669 void RenderBlock::addVisualOverflowFromTheme()
1670 {
1671     if (!style()->hasAppearance())
1672         return;
1673
1674     IntRect inflatedRect = pixelSnappedBorderBoxRect();
1675     theme()->adjustRepaintRect(this, inflatedRect);
1676     addVisualOverflow(inflatedRect);
1677 }
1678
1679 bool RenderBlock::expandsToEncloseOverhangingFloats() const
1680 {
1681     return isInlineBlockOrInlineTable() || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || (parent() && parent()->isDeprecatedFlexibleBox())
1682            || hasColumns() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot();
1683 }
1684
1685 void RenderBlock::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
1686 {
1687     bool isHorizontal = isHorizontalWritingMode();
1688     bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
1689     
1690     LayoutUnit logicalTop = logicalHeight();
1691     setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent(logicalTop));
1692
1693     if (!marginInfo.canCollapseWithMarginBefore()) {
1694         child->computeBlockDirectionMargins(this);
1695         LayoutUnit marginBefore = marginBeforeForChild(child);
1696         LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
1697         LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
1698         if (marginBefore > 0) {
1699             if (marginBefore > collapsedBeforePos)
1700                 collapsedBeforePos = marginBefore;
1701         } else {
1702             if (-marginBefore > collapsedBeforeNeg)
1703                 collapsedBeforeNeg = -marginBefore;
1704         }
1705         logicalTop += (collapsedBeforePos - collapsedBeforeNeg) - marginBefore;
1706     }
1707     
1708     RenderLayer* childLayer = child->layer();
1709     if (childLayer->staticBlockPosition() != logicalTop) {
1710         childLayer->setStaticBlockPosition(logicalTop);
1711         if (hasStaticBlockPosition)
1712             child->setChildNeedsLayout(true, MarkOnlyThis);
1713     }
1714 }
1715
1716 void RenderBlock::adjustFloatingBlock(const MarginInfo& marginInfo)
1717 {
1718     // The float should be positioned taking into account the bottom margin
1719     // of the previous flow.  We add that margin into the height, get the
1720     // float positioned properly, and then subtract the margin out of the
1721     // height again.  In the case of self-collapsing blocks, we always just
1722     // use the top margins, since the self-collapsing block collapsed its
1723     // own bottom margin into its top margin.
1724     //
1725     // Note also that the previous flow may collapse its margin into the top of
1726     // our block.  If this is the case, then we do not add the margin in to our
1727     // height when computing the position of the float.   This condition can be tested
1728     // for by simply calling canCollapseWithMarginBefore.  See
1729     // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
1730     // an example of this scenario.
1731     LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? ZERO_LAYOUT_UNIT : marginInfo.margin();
1732     setLogicalHeight(logicalHeight() + marginOffset);
1733     positionNewFloats();
1734     setLogicalHeight(logicalHeight() - marginOffset);
1735 }
1736
1737 bool RenderBlock::handleSpecialChild(RenderBox* child, const MarginInfo& marginInfo)
1738 {
1739     // Handle in the given order
1740     return handlePositionedChild(child, marginInfo)
1741         || handleFloatingChild(child, marginInfo);
1742 }
1743
1744
1745 bool RenderBlock::handlePositionedChild(RenderBox* child, const MarginInfo& marginInfo)
1746 {
1747     if (child->isOutOfFlowPositioned()) {
1748         child->containingBlock()->insertPositionedObject(child);
1749         adjustPositionedBlock(child, marginInfo);
1750         return true;
1751     }
1752     return false;
1753 }
1754
1755 bool RenderBlock::handleFloatingChild(RenderBox* child, const MarginInfo& marginInfo)
1756 {
1757     if (child->isFloating()) {
1758         insertFloatingObject(child);
1759         adjustFloatingBlock(marginInfo);
1760         return true;
1761     }
1762     return false;
1763 }
1764
1765 static void destroyRunIn(RenderBoxModelObject* runIn)
1766 {
1767     ASSERT(runIn->isRunIn());
1768     ASSERT(!runIn->firstChild());
1769
1770     // Delete our line box tree. This is needed as our children got moved
1771     // and our line box tree is no longer valid.
1772     if (runIn->isRenderBlock())
1773         toRenderBlock(runIn)->deleteLineBoxTree();
1774     else if (runIn->isRenderInline())
1775         toRenderInline(runIn)->deleteLineBoxTree();
1776     else
1777         ASSERT_NOT_REACHED();
1778
1779     runIn->destroy();
1780 }
1781
1782 void RenderBlock::placeRunInIfNeeded(RenderObject* newChild, PlaceGeneratedRunInFlag flag)
1783 {
1784     if (newChild->isRunIn() && (flag == PlaceGeneratedRunIn || !newChild->isBeforeOrAfterContent()))
1785         moveRunInUnderSiblingBlockIfNeeded(newChild);
1786     else if (RenderObject* prevSibling = newChild->previousSibling()) {
1787         if (prevSibling->isRunIn() && (flag == PlaceGeneratedRunIn || !newChild->isBeforeOrAfterContent()))
1788             moveRunInUnderSiblingBlockIfNeeded(prevSibling);
1789     }
1790 }
1791
1792 RenderBoxModelObject* RenderBlock::createReplacementRunIn(RenderBoxModelObject* runIn)
1793 {
1794     ASSERT(runIn->isRunIn());
1795
1796     // First we destroy any :before/:after content. It will be regenerated by the new run-in.
1797     // Exception is if the run-in itself is generated.
1798     if (runIn->style()->styleType() != BEFORE && runIn->style()->styleType() != AFTER) {
1799         RenderObject* generatedContent;
1800         if (runIn->getCachedPseudoStyle(BEFORE) && (generatedContent = runIn->beforePseudoElementRenderer()))
1801             generatedContent->destroy();
1802         if (runIn->getCachedPseudoStyle(AFTER) && (generatedContent = runIn->afterPseudoElementRenderer()))
1803             generatedContent->destroy();
1804     }
1805
1806     bool newRunInShouldBeBlock = !runIn->isRenderBlock();
1807     Node* runInNode = runIn->node();
1808     RenderBoxModelObject* newRunIn = 0;
1809     if (newRunInShouldBeBlock)
1810         newRunIn = new (renderArena()) RenderBlock(runInNode ? runInNode : document());
1811     else
1812         newRunIn = new (renderArena()) RenderInline(runInNode ? runInNode : document());
1813     newRunIn->setStyle(runIn->style());
1814  
1815     runIn->moveAllChildrenTo(newRunIn, true);
1816
1817     // If the run-in had an element, we need to set the new renderer.
1818     if (runInNode)
1819         runInNode->setRenderer(newRunIn);
1820
1821     return newRunIn;
1822 }
1823
1824 void RenderBlock::moveRunInUnderSiblingBlockIfNeeded(RenderObject* runIn)
1825 {
1826     ASSERT(runIn->isRunIn());
1827
1828     // See if we have inline children. If the children aren't inline,
1829     // then just treat the run-in as a normal block.
1830     if (!runIn->childrenInline())
1831         return;
1832
1833     // FIXME: We don't handle non-block elements with run-in for now.
1834     if (!runIn->isRenderBlock())
1835         return;
1836
1837     // FIXME: We don't support run-ins with or as part of a continuation
1838     // as it makes the back-and-forth placing complex.
1839     if (runIn->isElementContinuation() || runIn->virtualContinuation())
1840         return;
1841
1842     // Check if this node is allowed to run-in. E.g. <select> expects its renderer to
1843     // be a RenderListBox or RenderMenuList, and hence cannot be a RenderInline run-in.
1844     Node* runInNode = runIn->node();
1845     if (runInNode && runInNode->hasTagName(selectTag))
1846         return;
1847
1848     if (runInNode && runInNode->hasTagName(progressTag))
1849         return;
1850
1851     RenderObject* curr = runIn->nextSibling();
1852     if (!curr || !curr->isRenderBlock() || !curr->childrenInline())
1853         return;
1854
1855     // Per CSS3, "A run-in cannot run in to a block that already starts with a
1856     // run-in or that itself is a run-in".
1857     if (curr->isRunIn() || (curr->firstChild() && curr->firstChild()->isRunIn()))
1858         return;
1859
1860     if (curr->isAnonymous() || curr->isFloatingOrOutOfFlowPositioned())
1861         return;
1862
1863     RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
1864     RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
1865     destroyRunIn(oldRunIn);
1866
1867     // Now insert the new child under |curr| block. Use addChild instead of insertChildNode
1868     // since it handles correct placement of the children, especially where we cannot insert
1869     // anything before the first child. e.g. details tag. See https://bugs.webkit.org/show_bug.cgi?id=58228.
1870     curr->addChild(newRunIn, curr->firstChild());
1871
1872     // Make sure that |this| get a layout since its run-in child moved.
1873     curr->setNeedsLayoutAndPrefWidthsRecalc();
1874 }
1875
1876 bool RenderBlock::runInIsPlacedIntoSiblingBlock(RenderObject* runIn)
1877 {
1878     ASSERT(runIn->isRunIn());
1879
1880     // If we don't have a parent, we can't be moved into our sibling block.
1881     if (!parent())
1882         return false;
1883
1884     // An intruded run-in needs to be an inline.
1885     if (!runIn->isRenderInline())
1886         return false;
1887
1888     return true;
1889 }
1890
1891 void RenderBlock::moveRunInToOriginalPosition(RenderObject* runIn)
1892 {
1893     ASSERT(runIn->isRunIn());
1894
1895     if (!runInIsPlacedIntoSiblingBlock(runIn))
1896         return;
1897
1898     // FIXME: Run-in that are now placed in sibling block can break up into continuation
1899     // chains when new children are added to it. We cannot easily send them back to their
1900     // original place since that requires writing integration logic with RenderInline::addChild
1901     // and all other places that might cause continuations to be created (without blowing away
1902     // |this|). Disabling this feature for now to prevent crashes.
1903     if (runIn->isElementContinuation() || runIn->virtualContinuation())
1904         return;
1905
1906     RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
1907     RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
1908     destroyRunIn(oldRunIn);
1909
1910     // Add the run-in block as our previous sibling.
1911     parent()->addChild(newRunIn, this);
1912
1913     // Make sure that the parent holding the new run-in gets layout.
1914     parent()->setNeedsLayoutAndPrefWidthsRecalc();
1915 }
1916
1917 LayoutUnit RenderBlock::collapseMargins(RenderBox* child, MarginInfo& marginInfo)
1918 {
1919     // Get the four margin values for the child and cache them.
1920     const MarginValues childMargins = marginValuesForChild(child);
1921
1922     // Get our max pos and neg top margins.
1923     LayoutUnit posTop = childMargins.positiveMarginBefore();
1924     LayoutUnit negTop = childMargins.negativeMarginBefore();
1925
1926     // For self-collapsing blocks, collapse our bottom margins into our
1927     // top to get new posTop and negTop values.
1928     if (child->isSelfCollapsingBlock()) {
1929         posTop = max(posTop, childMargins.positiveMarginAfter());
1930         negTop = max(negTop, childMargins.negativeMarginAfter());
1931     }
1932     
1933     // See if the top margin is quirky. We only care if this child has
1934     // margins that will collapse with us.
1935     bool topQuirk = child->isMarginBeforeQuirk() || style()->marginBeforeCollapse() == MDISCARD;
1936
1937     if (marginInfo.canCollapseWithMarginBefore()) {
1938         // This child is collapsing with the top of the
1939         // block.  If it has larger margin values, then we need to update
1940         // our own maximal values.
1941         if (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
1942             setMaxMarginBeforeValues(max(posTop, maxPositiveMarginBefore()), max(negTop, maxNegativeMarginBefore()));
1943
1944         // The minute any of the margins involved isn't a quirk, don't
1945         // collapse it away, even if the margin is smaller (www.webreference.com
1946         // has an example of this, a <dt> with 0.8em author-specified inside
1947         // a <dl> inside a <td>.
1948         if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
1949             setMarginBeforeQuirk(false);
1950             marginInfo.setDeterminedMarginBeforeQuirk(true);
1951         }
1952
1953         if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore())
1954             // We have no top margin and our top child has a quirky margin.
1955             // We will pick up this quirky margin and pass it through.
1956             // This deals with the <td><div><p> case.
1957             // Don't do this for a block that split two inlines though.  You do
1958             // still apply margins in this case.
1959             setMarginBeforeQuirk(true);
1960     }
1961
1962     if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
1963         marginInfo.setMarginBeforeQuirk(topQuirk);
1964
1965     LayoutUnit beforeCollapseLogicalTop = logicalHeight();
1966     LayoutUnit logicalTop = beforeCollapseLogicalTop;
1967     if (child->isSelfCollapsingBlock()) {
1968         // This child has no height.  We need to compute our
1969         // position before we collapse the child's margins together,
1970         // so that we can get an accurate position for the zero-height block.
1971         LayoutUnit collapsedBeforePos = max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
1972         LayoutUnit collapsedBeforeNeg = max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
1973         marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
1974         
1975         // Now collapse the child's margins together, which means examining our
1976         // bottom margin values as well. 
1977         marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
1978         marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
1979
1980         if (!marginInfo.canCollapseWithMarginBefore())
1981             // We need to make sure that the position of the self-collapsing block
1982             // is correct, since it could have overflowing content
1983             // that needs to be positioned correctly (e.g., a block that
1984             // had a specified height of 0 but that actually had subcontent).
1985             logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
1986     }
1987     else {
1988         if (child->style()->marginBeforeCollapse() == MSEPARATE) {
1989             setLogicalHeight(logicalHeight() + marginInfo.margin() + marginBeforeForChild(child));
1990             logicalTop = logicalHeight();
1991         }
1992         else if (!marginInfo.atBeforeSideOfBlock() ||
1993             (!marginInfo.canCollapseMarginBeforeWithChildren()
1994              && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.marginBeforeQuirk()))) {
1995             // We're collapsing with a previous sibling's margins and not
1996             // with the top of the block.
1997             setLogicalHeight(logicalHeight() + max(marginInfo.positiveMargin(), posTop) - max(marginInfo.negativeMargin(), negTop));
1998             logicalTop = logicalHeight();
1999         }
2000
2001         marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
2002         marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
2003
2004         if (marginInfo.margin())
2005             marginInfo.setMarginAfterQuirk(child->isMarginAfterQuirk() || style()->marginAfterCollapse() == MDISCARD);
2006     }
2007     
2008     // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
2009     // collapsed into the page edge.
2010     LayoutState* layoutState = view()->layoutState();
2011     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
2012         && hasNextPage(beforeCollapseLogicalTop)) {
2013         LayoutUnit oldLogicalTop = logicalTop;
2014         logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
2015         setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
2016     }
2017
2018     // If we have collapsed into a previous sibling and so reduced the height of the parent, ensure any floats that now
2019     // overhang from the previous sibling are added to our parent. If the child's previous sibling itself is a float the child will avoid
2020     // or clear it anyway, so don't worry about any floating children it may contain.
2021     RenderObject* prev = child->previousSibling();
2022     if (prev && prev->isBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
2023         RenderBlock* block = toRenderBlock(prev);
2024         if (block->containsFloats() && !block->avoidsFloats() && (block->logicalTop() + block->lowestFloatLogicalBottom()) > logicalTop) 
2025             addOverhangingFloats(block, false);
2026     }
2027
2028     return logicalTop;
2029 }
2030
2031 LayoutUnit RenderBlock::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
2032 {
2033     LayoutUnit heightIncrease = getClearDelta(child, yPos);
2034     if (!heightIncrease)
2035         return yPos;
2036
2037     if (child->isSelfCollapsingBlock()) {
2038         // For self-collapsing blocks that clear, they can still collapse their
2039         // margins with following siblings.  Reset the current margins to represent
2040         // the self-collapsing block's margins only.
2041         // CSS2.1 states:
2042         // "An element that has had clearance applied to it never collapses its top margin with its parent block's bottom margin.
2043         // Therefore if we are at the bottom of the block, let's go ahead and reset margins to only include the
2044         // self-collapsing block's bottom margin.
2045         bool atBottomOfBlock = true;
2046         for (RenderBox* curr = child->nextSiblingBox(); curr && atBottomOfBlock; curr = curr->nextSiblingBox()) {
2047             if (!curr->isFloatingOrOutOfFlowPositioned())
2048                 atBottomOfBlock = false;
2049         }
2050         
2051         MarginValues childMargins = marginValuesForChild(child);
2052         if (atBottomOfBlock) {
2053             marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
2054             marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
2055         } else {
2056             marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
2057             marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
2058         }
2059         
2060         // Adjust our height such that we are ready to be collapsed with subsequent siblings (or the bottom
2061         // of the parent block).
2062         setLogicalHeight(child->logicalTop() - max(ZERO_LAYOUT_UNIT, marginInfo.margin()));
2063     } else
2064         // Increase our height by the amount we had to clear.
2065         setLogicalHeight(logicalHeight() + heightIncrease);
2066     
2067     if (marginInfo.canCollapseWithMarginBefore()) {
2068         // We can no longer collapse with the top of the block since a clear
2069         // occurred.  The empty blocks collapse into the cleared block.
2070         // FIXME: This isn't quite correct.  Need clarification for what to do
2071         // if the height the cleared block is offset by is smaller than the
2072         // margins involved.
2073         setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
2074         marginInfo.setAtBeforeSideOfBlock(false);
2075     }
2076     
2077     return yPos + heightIncrease;
2078 }
2079
2080 void RenderBlock::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore) const
2081 {
2082     // FIXME: We should deal with the margin-collapse-* style extensions that prevent collapsing and that discard margins.
2083     // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
2084     if (document()->inQuirksMode() && child->isMarginBeforeQuirk() && (isTableCell() || isBody()))
2085         return;
2086
2087     LayoutUnit beforeChildMargin = marginBeforeForChild(child);
2088     positiveMarginBefore = max(positiveMarginBefore, beforeChildMargin);
2089     negativeMarginBefore = max(negativeMarginBefore, -beforeChildMargin);
2090
2091     if (!child->isRenderBlock())
2092         return;
2093     
2094     RenderBlock* childBlock = toRenderBlock(child);
2095     if (childBlock->childrenInline() || childBlock->isWritingModeRoot())
2096         return;
2097
2098     MarginInfo childMarginInfo(childBlock, childBlock->borderBefore() + childBlock->paddingBefore(), childBlock->borderAfter() + childBlock->paddingAfter());
2099     if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
2100         return;
2101
2102     RenderBox* grandchildBox = childBlock->firstChildBox();
2103     for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
2104         if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
2105             break;
2106     }
2107     
2108     // Give up if there is clearance on the box, since it probably won't collapse into us.
2109     if (!grandchildBox || grandchildBox->style()->clear() != CNONE)
2110         return;
2111
2112     // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
2113     if (grandchildBox->needsLayout()) {
2114         grandchildBox->computeBlockDirectionMargins(this); 
2115         grandchildBox->setMarginBeforeQuirk(grandchildBox->style()->marginBefore().quirk());
2116         grandchildBox->setMarginAfterQuirk(grandchildBox->style()->marginAfter().quirk());
2117     }
2118
2119     // Collapse the margin of the grandchild box with our own to produce an estimate.
2120     childBlock->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore);
2121 }
2122
2123 LayoutUnit RenderBlock::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
2124 {
2125     // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
2126     // relayout if there are intruding floats.
2127     LayoutUnit logicalTopEstimate = logicalHeight();
2128     if (!marginInfo.canCollapseWithMarginBefore()) {
2129         LayoutUnit positiveMarginBefore = ZERO_LAYOUT_UNIT;
2130         LayoutUnit negativeMarginBefore = ZERO_LAYOUT_UNIT;
2131         if (child->selfNeedsLayout()) {
2132             // Try to do a basic estimation of how the collapse is going to go.
2133             marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore);
2134         } else {
2135             // Use the cached collapsed margin values from a previous layout. Most of the time they
2136             // will be right.
2137             MarginValues marginValues = marginValuesForChild(child);
2138             positiveMarginBefore = max(positiveMarginBefore, marginValues.positiveMarginBefore());
2139             negativeMarginBefore = max(negativeMarginBefore, marginValues.negativeMarginBefore());
2140         }
2141
2142         // Collapse the result with our current margins.
2143         logicalTopEstimate += max(marginInfo.positiveMargin(), positiveMarginBefore) - max(marginInfo.negativeMargin(), negativeMarginBefore);
2144     }
2145
2146     // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
2147     // page.
2148     LayoutState* layoutState = view()->layoutState();
2149     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
2150         && hasNextPage(logicalHeight()))
2151         logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
2152
2153     logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
2154     
2155     estimateWithoutPagination = logicalTopEstimate;
2156
2157     if (layoutState->isPaginated()) {
2158         // If the object has a page or column break value of "before", then we should shift to the top of the next page.
2159         logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
2160     
2161         // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
2162         logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
2163         
2164         if (!child->selfNeedsLayout() && child->isRenderBlock())
2165             logicalTopEstimate += toRenderBlock(child)->paginationStrut();
2166     }
2167
2168     return logicalTopEstimate;
2169 }
2170
2171 LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart,
2172     RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
2173 {
2174     LayoutUnit startPosition = startOffsetForContent(region, offsetFromLogicalTopOfFirstPage);
2175
2176     // Add in our start margin.
2177     LayoutUnit oldPosition = startPosition + childMarginStart;
2178     LayoutUnit newPosition = oldPosition;
2179
2180     LayoutUnit blockOffset = logicalTopForChild(child);
2181     if (region)
2182         blockOffset = max(blockOffset, blockOffset + (region->offsetFromLogicalTopOfFirstPage() - offsetFromLogicalTopOfFirstPage));
2183
2184     LayoutUnit startOff = startOffsetForLine(blockOffset, false, region, offsetFromLogicalTopOfFirstPage, logicalHeightForChild(child));
2185
2186     if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
2187         if (childMarginStart < 0)
2188             startOff += childMarginStart;
2189         newPosition = max(newPosition, startOff); // Let the float sit in the child's margin if it can fit.
2190     } else if (startOff != startPosition)
2191         newPosition = startOff + childMarginStart;
2192
2193     return newPosition - oldPosition;
2194 }
2195
2196 void RenderBlock::determineLogicalLeftPositionForChild(RenderBox* child)
2197 {
2198     LayoutUnit startPosition = borderStart() + paddingStart();
2199     LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
2200
2201     // Add in our start margin.
2202     LayoutUnit childMarginStart = marginStartForChild(child);
2203     LayoutUnit newPosition = startPosition + childMarginStart;
2204         
2205     // Some objects (e.g., tables, horizontal rules, overflow:auto blocks) avoid floats.  They need
2206     // to shift over as necessary to dodge any floats that might get in the way.
2207     if (child->avoidsFloats() && containsFloats() && !inRenderFlowThread())
2208         newPosition += computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child));
2209
2210     setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), ApplyLayoutDelta);
2211 }
2212
2213 void RenderBlock::setCollapsedBottomMargin(const MarginInfo& marginInfo)
2214 {
2215     if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
2216         // Update our max pos/neg bottom margins, since we collapsed our bottom margins
2217         // with our children.
2218         setMaxMarginAfterValues(max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
2219
2220         if (!marginInfo.marginAfterQuirk())
2221             setMarginAfterQuirk(false);
2222
2223         if (marginInfo.marginAfterQuirk() && marginAfter() == 0)
2224             // We have no bottom margin and our last child has a quirky margin.
2225             // We will pick up this quirky margin and pass it through.
2226             // This deals with the <td><div><p> case.
2227             setMarginAfterQuirk(true);
2228     }
2229 }
2230
2231 void RenderBlock::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
2232 {
2233     marginInfo.setAtAfterSideOfBlock(true);
2234
2235     // If we can't collapse with children then go ahead and add in the bottom margin.
2236     if (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
2237         && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.marginAfterQuirk()))
2238         setLogicalHeight(logicalHeight() + marginInfo.margin());
2239         
2240     // Now add in our bottom border/padding.
2241     setLogicalHeight(logicalHeight() + afterSide);
2242
2243     // Negative margins can cause our height to shrink below our minimal height (border/padding).
2244     // If this happens, ensure that the computed height is increased to the minimal height.
2245     setLogicalHeight(max(logicalHeight(), beforeSide + afterSide));
2246
2247     // Update our bottom collapsed margin info.
2248     setCollapsedBottomMargin(marginInfo);
2249 }
2250
2251 void RenderBlock::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
2252 {
2253     if (isHorizontalWritingMode()) {
2254         if (applyDelta == ApplyLayoutDelta)
2255             view()->addLayoutDelta(LayoutSize(child->x() - logicalLeft, 0));
2256         child->setX(logicalLeft);
2257     } else {
2258         if (applyDelta == ApplyLayoutDelta)
2259             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalLeft));
2260         child->setY(logicalLeft);
2261     }
2262 }
2263
2264 void RenderBlock::setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
2265 {
2266     if (isHorizontalWritingMode()) {
2267         if (applyDelta == ApplyLayoutDelta)
2268             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalTop));
2269         child->setY(logicalTop);
2270     } else {
2271         if (applyDelta == ApplyLayoutDelta)
2272             view()->addLayoutDelta(LayoutSize(child->x() - logicalTop, 0));
2273         child->setX(logicalTop);
2274     }
2275 }
2276
2277 void RenderBlock::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
2278 {
2279     if (gPercentHeightDescendantsMap) {
2280         if (HashSet<RenderBox*>* descendants = gPercentHeightDescendantsMap->get(this)) {
2281             HashSet<RenderBox*>::iterator end = descendants->end();
2282             for (HashSet<RenderBox*>::iterator it = descendants->begin(); it != end; ++it) {
2283                 RenderBox* box = *it;
2284                 while (box != this) {
2285                     if (box->normalChildNeedsLayout())
2286                         break;
2287                     box->setChildNeedsLayout(true, MarkOnlyThis);
2288                     box = box->containingBlock();
2289                     ASSERT(box);
2290                     if (!box)
2291                         break;
2292                 }
2293             }
2294         }
2295     }
2296
2297     LayoutUnit beforeEdge = borderBefore() + paddingBefore();
2298     LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
2299
2300     setLogicalHeight(beforeEdge);
2301     
2302     // Lay out our hypothetical grid line as though it occurs at the top of the block.
2303     if (view()->layoutState()->lineGrid() == this)
2304         layoutLineGridBox();
2305
2306     // The margin struct caches all our current margin collapsing state.  The compact struct caches state when we encounter compacts,
2307     MarginInfo marginInfo(this, beforeEdge, afterEdge);
2308
2309     // Fieldsets need to find their legend and position it inside the border of the object.
2310     // The legend then gets skipped during normal layout.  The same is true for ruby text.
2311     // It doesn't get included in the normal layout process but is instead skipped.
2312     RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren);
2313
2314     LayoutUnit previousFloatLogicalBottom = 0;
2315     maxFloatLogicalBottom = 0;
2316
2317     RenderBox* next = firstChildBox();
2318
2319     while (next) {
2320         RenderBox* child = next;
2321         next = child->nextSiblingBox();
2322
2323         if (childToExclude == child)
2324             continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
2325
2326         // Make sure we layout children if they need it.
2327         // FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
2328         // an auto value.  Add a method to determine this, so that we can avoid the relayout.
2329         if (relayoutChildren || (child->hasRelativeLogicalHeight() && !isRenderView()))
2330             child->setChildNeedsLayout(true, MarkOnlyThis);
2331
2332         // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2333         if (relayoutChildren && child->needsPreferredWidthsRecalculation())
2334             child->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
2335
2336         // Handle the four types of special elements first.  These include positioned content, floating content, compacts and
2337         // run-ins.  When we encounter these four types of objects, we don't actually lay them out as normal flow blocks.
2338         if (handleSpecialChild(child, marginInfo))
2339             continue;
2340
2341         // Lay out the child.
2342         layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
2343     }
2344     
2345     // Now do the handling of the bottom of the block, adding in our bottom border/padding and
2346     // determining the correct collapsed bottom margin information.
2347     handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
2348 }
2349
2350 void RenderBlock::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
2351 {
2352     LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
2353     LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
2354
2355     // The child is a normal flow object.  Compute the margins we will use for collapsing now.
2356     child->computeBlockDirectionMargins(this);
2357
2358     // Do not allow a collapse if the margin-before-collapse style is set to SEPARATE.
2359     RenderStyle* childStyle = child->style();
2360     if (childStyle->marginBeforeCollapse() == MSEPARATE) {
2361         marginInfo.setAtBeforeSideOfBlock(false);
2362         marginInfo.clearMargin();
2363     }
2364
2365     // Try to guess our correct logical top position.  In most cases this guess will
2366     // be correct.  Only if we're wrong (when we compute the real logical top position)
2367     // will we have to potentially relayout.
2368     LayoutUnit estimateWithoutPagination;
2369     LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
2370
2371     // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
2372     LayoutRect oldRect = child->frameRect();
2373     LayoutUnit oldLogicalTop = logicalTopForChild(child);
2374
2375 #if !ASSERT_DISABLED
2376     LayoutSize oldLayoutDelta = view()->layoutDelta();
2377 #endif
2378     // Go ahead and position the child as though it didn't collapse with the top.
2379     setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
2380
2381     RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
2382     bool markDescendantsWithFloats = false;
2383     if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats())
2384         markDescendantsWithFloats = true;
2385     else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
2386         // If an element might be affected by the presence of floats, then always mark it for
2387         // layout.
2388         LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
2389         if (fb > logicalTopEstimate)
2390             markDescendantsWithFloats = true;
2391     }
2392
2393     if (childRenderBlock) {
2394         if (markDescendantsWithFloats)
2395             childRenderBlock->markAllDescendantsWithFloatsForLayout();
2396         if (!child->isWritingModeRoot())
2397             previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottom());
2398     }
2399
2400     if (!child->needsLayout())
2401         child->markForPaginationRelayoutIfNeeded();
2402
2403     bool childHadLayout = child->everHadLayout();
2404     bool childNeededLayout = child->needsLayout();
2405     if (childNeededLayout)
2406         child->layout();
2407
2408     // Cache if we are at the top of the block right now.
2409     bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
2410
2411     // Now determine the correct ypos based off examination of collapsing margin
2412     // values.
2413     LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
2414
2415     // Now check for clear.
2416     LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
2417     
2418     bool paginated = view()->layoutState()->isPaginated();
2419     if (paginated)
2420         logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
2421             atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
2422
2423     setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
2424
2425     // Now we have a final top position.  See if it really does end up being different from our estimate.
2426     // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
2427     // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
2428     if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout()) {
2429         if (child->shrinkToAvoidFloats()) {
2430             // The child's width depends on the line width.
2431             // When the child shifts to clear an item, its width can
2432             // change (because it has more available line width).
2433             // So go ahead and mark the item as dirty.
2434             child->setChildNeedsLayout(true, MarkOnlyThis);
2435         }
2436         
2437         if (childRenderBlock) {
2438             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
2439                 childRenderBlock->markAllDescendantsWithFloatsForLayout();
2440             if (!child->needsLayout())
2441                 child->markForPaginationRelayoutIfNeeded();
2442         }
2443
2444         // Our guess was wrong. Make the child lay itself out again.
2445         child->layoutIfNeeded();
2446     }
2447
2448     // We are no longer at the top of the block if we encounter a non-empty child.  
2449     // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
2450     if (marginInfo.atBeforeSideOfBlock() && !child->isSelfCollapsingBlock())
2451         marginInfo.setAtBeforeSideOfBlock(false);
2452
2453     // Now place the child in the correct left position
2454     determineLogicalLeftPositionForChild(child);
2455
2456     // Update our height now that the child has been placed in the correct position.
2457     setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
2458     if (childStyle->marginAfterCollapse() == MSEPARATE) {
2459         setLogicalHeight(logicalHeight() + marginAfterForChild(child));
2460         marginInfo.clearMargin();
2461     }
2462     // If the child has overhanging floats that intrude into following siblings (or possibly out
2463     // of this block), then the parent gets notified of the floats now.
2464     if (childRenderBlock && childRenderBlock->containsFloats())
2465         maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
2466
2467     LayoutSize childOffset = child->location() - oldRect.location();
2468     if (childOffset.width() || childOffset.height()) {
2469         view()->addLayoutDelta(childOffset);
2470
2471         // If the child moved, we have to repaint it as well as any floating/positioned
2472         // descendants.  An exception is if we need a layout.  In this case, we know we're going to
2473         // repaint ourselves (and the child) anyway.
2474         if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
2475             child->repaintDuringLayoutIfMoved(oldRect);
2476     }
2477
2478     if (!childHadLayout && child->checkForRepaintDuringLayout()) {
2479         child->repaint();
2480         child->repaintOverhangingFloats(true);
2481     }
2482
2483     if (paginated) {
2484         // Check for an after page/column break.
2485         LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
2486         if (newHeight != height())
2487             setLogicalHeight(newHeight);
2488     }
2489
2490     ASSERT(oldLayoutDelta == view()->layoutDelta());
2491 }
2492
2493 void RenderBlock::simplifiedNormalFlowLayout()
2494 {
2495     if (childrenInline()) {
2496         ListHashSet<RootInlineBox*> lineBoxes;
2497         for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
2498             RenderObject* o = walker.current();
2499             if (!o->isOutOfFlowPositioned() && (o->isReplaced() || o->isFloating())) {
2500                 o->layoutIfNeeded();
2501                 if (toRenderBox(o)->inlineBoxWrapper()) {
2502                     RootInlineBox* box = toRenderBox(o)->inlineBoxWrapper()->root();
2503                     lineBoxes.add(box);
2504                 }
2505             } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline()))
2506                 o->setNeedsLayout(false);
2507         }
2508
2509         // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
2510         GlyphOverflowAndFallbackFontsMap textBoxDataMap;                  
2511         for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
2512             RootInlineBox* box = *it;
2513             box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
2514         }
2515     } else {
2516         for (RenderBox* box = firstChildBox(); box; box = box->nextSiblingBox()) {
2517             if (!box->isOutOfFlowPositioned())
2518                 box->layoutIfNeeded();
2519         }
2520     }
2521 }
2522
2523 bool RenderBlock::simplifiedLayout()
2524 {
2525     if ((!posChildNeedsLayout() && !needsSimplifiedNormalFlowLayout()) || normalChildNeedsLayout() || selfNeedsLayout())
2526         return false;
2527
2528     LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
2529     
2530     if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
2531         return false;
2532
2533     // Lay out positioned descendants or objects that just need to recompute overflow.
2534     if (needsSimplifiedNormalFlowLayout())
2535         simplifiedNormalFlowLayout();
2536
2537     // Lay out our positioned objects if our positioned child bit is set.
2538     if (posChildNeedsLayout())
2539         layoutPositionedObjects(false);
2540
2541     // Recompute our overflow information.
2542     // FIXME: We could do better here by computing a temporary overflow object from layoutPositionedObjects and only
2543     // updating our overflow if we either used to have overflow or if the new temporary object has overflow.
2544     // For now just always recompute overflow.  This is no worse performance-wise than the old code that called rightmostPosition and
2545     // lowestPosition on every relayout so it's not a regression.
2546     m_overflow.clear();
2547     computeOverflow(clientLogicalBottom(), true);
2548
2549     statePusher.pop();
2550     
2551     updateLayerTransform();
2552
2553     updateScrollInfoAfterLayout();
2554
2555     setNeedsLayout(false);
2556     return true;
2557 }
2558
2559 void RenderBlock::layoutPositionedObjects(bool relayoutChildren)
2560 {
2561     if (!m_positionedObjects)
2562         return;
2563         
2564     if (hasColumns())
2565         view()->layoutState()->clearPaginationInformation(); // Positioned objects are not part of the column flow, so they don't paginate with the columns.
2566
2567     RenderBox* r;
2568     Iterator end = m_positionedObjects->end();
2569     for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
2570         r = *it;
2571         // When a non-positioned block element moves, it may have positioned children that are implicitly positioned relative to the
2572         // non-positioned block.  Rather than trying to detect all of these movement cases, we just always lay out positioned
2573         // objects that are positioned implicitly like this.  Such objects are rare, and so in typical DHTML menu usage (where everything is
2574         // positioned explicitly) this should not incur a performance penalty.
2575         if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
2576             r->setChildNeedsLayout(true, MarkOnlyThis);
2577             
2578         // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2579         if (relayoutChildren && r->needsPreferredWidthsRecalculation())
2580             r->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
2581         
2582         if (!r->needsLayout())
2583             r->markForPaginationRelayoutIfNeeded();
2584         
2585         // 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
2586         // and we hit the available width constraint, the layoutIfNeeded() will catch it and do a full layout.
2587         if (r->needsPositionedMovementLayoutOnly() && r->tryLayoutDoingPositionedMovementOnly())
2588             r->setNeedsLayout(false);
2589             
2590         // If we are paginated or in a line grid, go ahead and compute a vertical position for our object now.
2591         // If it's wrong we'll lay out again.
2592         LayoutUnit oldLogicalTop = 0;
2593         bool needsBlockDirectionLocationSetBeforeLayout = r->needsLayout() && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout(); 
2594         if (needsBlockDirectionLocationSetBeforeLayout) {
2595             if (isHorizontalWritingMode() == r->isHorizontalWritingMode())
2596                 r->computeLogicalHeight();
2597             else
2598                 r->computeLogicalWidth();
2599             oldLogicalTop = logicalTopForChild(r);
2600         }
2601         
2602         r->layoutIfNeeded();
2603
2604         // Adjust the static position of a center-aligned inline positioned object with a block child now that the child's width has been computed.
2605         if (!r->parent()->isRenderView() && r->parent()->isRenderBlock() && r->firstChild() && r->style()->position() == AbsolutePosition
2606             && r->style()->isOriginalDisplayInlineType() && (r->style()->textAlign() == CENTER || r->style()->textAlign() == WEBKIT_CENTER)) {
2607             RenderBlock* block = toRenderBlock(r->parent());
2608             LayoutUnit blockHeight = block->logicalHeight();
2609             block->setStaticInlinePositionForChild(r, blockHeight, block->startAlignedOffsetForLine(r, blockHeight, false));
2610         }
2611
2612         // Lay out again if our estimate was wrong.
2613         if (needsBlockDirectionLocationSetBeforeLayout && logicalTopForChild(r) != oldLogicalTop) {
2614             r->setChildNeedsLayout(true, MarkOnlyThis);
2615             r->layoutIfNeeded();
2616         }
2617     }
2618     
2619     if (hasColumns())
2620         view()->layoutState()->m_columnInfo = columnInfo(); // FIXME: Kind of gross. We just put this back into the layout state so that pop() will work.
2621 }
2622
2623 void RenderBlock::markPositionedObjectsForLayout()
2624 {
2625     if (m_positionedObjects) {
2626         RenderBox* r;
2627         Iterator end = m_positionedObjects->end();
2628         for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
2629             r = *it;
2630             r->setChildNeedsLayout(true);
2631         }
2632     }
2633 }
2634
2635 void RenderBlock::markForPaginationRelayoutIfNeeded()
2636 {
2637     ASSERT(!needsLayout());
2638     if (needsLayout())
2639         return;
2640
2641     if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()))
2642         setChildNeedsLayout(true, MarkOnlyThis);
2643 }
2644
2645 void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
2646 {
2647     // Repaint any overhanging floats (if we know we're the one to paint them).
2648     // Otherwise, bail out.
2649     if (!hasOverhangingFloats())
2650         return;
2651
2652     // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
2653     // in this block. Better yet would be to push extra state for the containers of other floats.
2654     LayoutStateDisabler layoutStateDisabler(view());
2655     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2656     FloatingObjectSetIterator end = floatingObjectSet.end();
2657     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2658         FloatingObject* r = *it;
2659         // Only repaint the object if it is overhanging, is not in its own layer, and
2660         // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
2661         // condition is replaced with being a descendant of us.
2662         if (logicalBottomForFloat(r) > logicalHeight() && ((paintAllDescendants && r->m_renderer->isDescendantOf(this)) || r->shouldPaint()) && !r->m_renderer->hasSelfPaintingLayer()) {
2663             r->m_renderer->repaint();
2664             r->m_renderer->repaintOverhangingFloats();
2665         }
2666     }
2667 }
2668  
2669 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2670 {
2671     LayoutPoint adjustedPaintOffset = paintOffset + location();
2672     
2673     PaintPhase phase = paintInfo.phase;
2674
2675     // Check if we need to do anything at all.
2676     // FIXME: Could eliminate the isRoot() check if we fix background painting so that the RenderView
2677     // paints the root's background.
2678     if (!isRoot()) {
2679         LayoutRect overflowBox = visualOverflowRect();
2680         flipForWritingMode(overflowBox);
2681         overflowBox.inflate(maximalOutlineSize(paintInfo.phase));
2682         overflowBox.moveBy(adjustedPaintOffset);
2683         if (!overflowBox.intersects(paintInfo.rect))
2684             return;
2685     }
2686
2687     bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
2688     paintObject(paintInfo, adjustedPaintOffset);
2689     if (pushedClip)
2690         popContentsClip(paintInfo, phase, adjustedPaintOffset);
2691
2692     // Our scrollbar widgets paint exactly when we tell them to, so that they work properly with
2693     // z-index.  We paint after we painted the background/border, so that the scrollbars will
2694     // sit above the background/border.
2695     if (hasOverflowClip() && style()->visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && paintInfo.shouldPaintWithinRoot(this))
2696         layer()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
2697 }
2698
2699 void RenderBlock::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2700 {
2701     if (paintInfo.context->paintingDisabled())
2702         return;
2703
2704     const Color& ruleColor = style()->visitedDependentColor(CSSPropertyWebkitColumnRuleColor);
2705     bool ruleTransparent = style()->columnRuleIsTransparent();
2706     EBorderStyle ruleStyle = style()->columnRuleStyle();
2707     LayoutUnit ruleThickness = style()->columnRuleWidth();
2708     LayoutUnit colGap = columnGap();
2709     bool renderRule = ruleStyle > BHIDDEN && !ruleTransparent && ruleThickness <= colGap;
2710     if (!renderRule)
2711         return;
2712
2713     ColumnInfo* colInfo = columnInfo();
2714     unsigned colCount = columnCount(colInfo);
2715
2716     bool antialias = shouldAntialiasLines(paintInfo.context);
2717
2718     if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
2719         bool leftToRight = style()->isLeftToRightDirection() ^ colInfo->progressionIsReversed();
2720         LayoutUnit currLogicalLeftOffset = leftToRight ? ZERO_LAYOUT_UNIT : contentLogicalWidth();
2721         LayoutUnit ruleAdd = logicalLeftOffsetForContent();
2722         LayoutUnit ruleLogicalLeft = leftToRight ? ZERO_LAYOUT_UNIT : contentLogicalWidth();
2723         LayoutUnit inlineDirectionSize = colInfo->desiredColumnWidth();
2724         BoxSide boxSide = isHorizontalWritingMode()
2725             ? leftToRight ? BSLeft : BSRight
2726             : leftToRight ? BSTop : BSBottom;
2727
2728         for (unsigned i = 0; i < colCount; i++) {
2729             // Move to the next position.
2730             if (leftToRight) {
2731                 ruleLogicalLeft += inlineDirectionSize + colGap / 2;
2732                 currLogicalLeftOffset += inlineDirectionSize + colGap;
2733             } else {
2734                 ruleLogicalLeft -= (inlineDirectionSize + colGap / 2);
2735                 currLogicalLeftOffset -= (inlineDirectionSize + colGap);
2736             }
2737            
2738             // Now paint the column rule.
2739             if (i < colCount - 1) {
2740                 LayoutUnit ruleLeft = isHorizontalWritingMode() ? paintOffset.x() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd : paintOffset.x() + borderLeft() + paddingLeft();
2741                 LayoutUnit ruleRight = isHorizontalWritingMode() ? ruleLeft + ruleThickness : ruleLeft + contentWidth();
2742                 LayoutUnit ruleTop = isHorizontalWritingMode() ? paintOffset.y() + borderTop() + paddingTop() : paintOffset.y() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd;
2743                 LayoutUnit ruleBottom = isHorizontalWritingMode() ? ruleTop + contentHeight() : ruleTop + ruleThickness;
2744                 IntRect pixelSnappedRuleRect = pixelSnappedIntRectFromEdges(ruleLeft, ruleTop, ruleRight, ruleBottom);
2745                 drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
2746             }
2747             
2748             ruleLogicalLeft = currLogicalLeftOffset;
2749         }
2750     } else {
2751         bool topToBottom = !style()->isFlippedBlocksWritingMode() ^ colInfo->progressionIsReversed();
2752         LayoutUnit ruleLeft = isHorizontalWritingMode()
2753             ? borderLeft() + paddingLeft()
2754             : colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderBefore() + paddingBefore() : borderAfter() + paddingAfter());
2755         LayoutUnit ruleWidth = isHorizontalWritingMode() ? contentWidth() : ruleThickness;
2756         LayoutUnit ruleTop = isHorizontalWritingMode()
2757             ? colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderBefore() + paddingBefore() : borderAfter() + paddingAfter())
2758             : borderStart() + paddingStart();
2759         LayoutUnit ruleHeight = isHorizontalWritingMode() ? ruleThickness : contentHeight();
2760         LayoutRect ruleRect(ruleLeft, ruleTop, ruleWidth, ruleHeight);
2761
2762         if (!topToBottom) {
2763             if (isHorizontalWritingMode())
2764                 ruleRect.setY(height() - ruleRect.maxY());
2765             else
2766                 ruleRect.setX(width() - ruleRect.maxX());
2767         }
2768
2769         ruleRect.moveBy(paintOffset);
2770
2771         BoxSide boxSide = isHorizontalWritingMode()
2772             ? topToBottom ? BSTop : BSBottom
2773             : topToBottom ? BSLeft : BSRight;
2774
2775         LayoutSize step(0, topToBottom ? colInfo->columnHeight() + colGap : -(colInfo->columnHeight() + colGap));
2776         if (!isHorizontalWritingMode())
2777             step = step.transposedSize();
2778
2779         for (unsigned i = 1; i < colCount; i++) {
2780             ruleRect.move(step);
2781             IntRect pixelSnappedRuleRect = pixelSnappedIntRect(ruleRect);
2782             drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
2783         }
2784     }
2785 }
2786
2787 void RenderBlock::paintColumnContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool paintingFloats)
2788 {
2789     // We need to do multiple passes, breaking up our child painting into strips.
2790     GraphicsContext* context = paintInfo.context;
2791     ColumnInfo* colInfo = columnInfo();
2792     unsigned colCount = columnCount(colInfo);
2793     if (!colCount)
2794         return;
2795     LayoutUnit currLogicalTopOffset = 0;
2796     LayoutUnit colGap = columnGap();
2797     for (unsigned i = 0; i < colCount; i++) {
2798         // For each rect, we clip to the rect, and then we adjust our coords.
2799         LayoutRect colRect = columnRectAt(colInfo, i);
2800         flipForWritingMode(colRect);
2801         LayoutUnit logicalLeftOffset = (isHorizontalWritingMode() ? colRect.x() : colRect.y()) - logicalLeftOffsetForContent();
2802         LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(logicalLeftOffset, currLogicalTopOffset) : LayoutSize(currLogicalTopOffset, logicalLeftOffset);
2803         if (colInfo->progressionAxis() == ColumnInfo::BlockAxis) {
2804             if (isHorizontalWritingMode())
2805                 offset.expand(0, colRect.y() - borderTop() - paddingTop());
2806             else
2807                 offset.expand(colRect.x() - borderLeft() - paddingLeft(), 0);
2808         }
2809         colRect.moveBy(paintOffset);
2810         PaintInfo info(paintInfo);
2811         info.rect.intersect(pixelSnappedIntRect(colRect));
2812         
2813         if (!info.rect.isEmpty()) {
2814             GraphicsContextStateSaver stateSaver(*context);
2815             LayoutRect clipRect(colRect);
2816             
2817             if (i < colCount - 1) {
2818                 if (isHorizontalWritingMode())
2819                     clipRect.expand(colGap / 2, 0);
2820                 else
2821                     clipRect.expand(0, colGap / 2);
2822             }
2823             // Each strip pushes a clip, since column boxes are specified as being
2824             // like overflow:hidden.
2825             // FIXME: Content and column rules that extend outside column boxes at the edges of the multi-column element
2826             // are clipped according to the 'overflow' property.
2827             context->clip(pixelSnappedIntRect(clipRect));
2828
2829             // Adjust our x and y when painting.
2830             LayoutPoint adjustedPaintOffset = paintOffset + offset;
2831             if (paintingFloats)
2832                 paintFloats(info, adjustedPaintOffset, paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip);
2833             else
2834                 paintContents(info, adjustedPaintOffset);
2835         }
2836
2837         LayoutUnit blockDelta = (isHorizontalWritingMode() ? colRect.height() : colRect.width());
2838         if (style()->isFlippedBlocksWritingMode())
2839             currLogicalTopOffset += blockDelta;
2840         else
2841             currLogicalTopOffset -= blockDelta;
2842     }
2843 }
2844
2845 void RenderBlock::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2846 {
2847     // Avoid painting descendants of the root element when stylesheets haven't loaded.  This eliminates FOUC.
2848     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
2849     // will do a full repaint().
2850     if (document()->didLayoutWithPendingStylesheets() && !isRenderView())
2851         return;
2852
2853     if (childrenInline())
2854         m_lineBoxes.paint(this, paintInfo, paintOffset);
2855     else {
2856         PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
2857         newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
2858
2859         // We don't paint our own background, but we do let the kids paint their backgrounds.
2860         PaintInfo paintInfoForChild(paintInfo);
2861         paintInfoForChild.phase = newPhase;
2862         paintInfoForChild.updatePaintingRootForChildren(this);
2863
2864         // FIXME: Paint-time pagination is obsolete and is now only used by embedded WebViews inside AppKit
2865         // NSViews. Do not add any more code for this.
2866         bool usePrintRect = !view()->printRect().isEmpty();
2867         paintChildren(paintInfo, paintOffset, paintInfoForChild, usePrintRect);
2868     }
2869 }
2870
2871 void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
2872 {
2873     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
2874         if (!paintChild(child, paintInfo, paintOffset, paintInfoForChild, usePrintRect))
2875             return;
2876     }
2877 }
2878
2879 bool RenderBlock::paintChild(RenderBox* child, PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
2880 {
2881     // Check for page-break-before: always, and if it's set, break and bail.
2882     bool checkBeforeAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakBefore() == PBALWAYS);
2883     LayoutUnit absoluteChildY = paintOffset.y() + child->y();
2884     if (checkBeforeAlways
2885         && absoluteChildY > paintInfo.rect.y()
2886         && absoluteChildY < paintInfo.rect.maxY()) {
2887         view()->setBestTruncatedAt(absoluteChildY, this, true);
2888         return false;
2889     }
2890
2891     RenderView* renderView = view();
2892     if (!child->isFloating() && child->isReplaced() && usePrintRect && child->height() <= renderView->printRect().height()) {
2893         // Paginate block-level replaced elements.
2894         if (absoluteChildY + child->height() > renderView->printRect().maxY()) {
2895             if (absoluteChildY < renderView->truncatedAt())
2896                 renderView->setBestTruncatedAt(absoluteChildY, child);
2897             // If we were able to truncate, don't paint.
2898             if (absoluteChildY >= renderView->truncatedAt())
2899                 return false;
2900         }
2901     }
2902
2903     LayoutPoint childPoint = flipForWritingModeForChild(child, paintOffset);
2904     if (!child->hasSelfPaintingLayer() && !child->isFloating())
2905         child->paint(paintInfoForChild, childPoint);
2906
2907     // Check for page-break-after: always, and if it's set, break and bail.
2908     bool checkAfterAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakAfter() == PBALWAYS);
2909     if (checkAfterAlways
2910         && (absoluteChildY + child->height()) > paintInfo.rect.y()
2911         && (absoluteChildY + child->height()) < paintInfo.rect.maxY()) {
2912         view()->setBestTruncatedAt(absoluteChildY + child->height() + max(ZERO_LAYOUT_UNIT, child->collapsedMarginAfter()), this, true);
2913         return false;
2914     }
2915     return true;
2916 }
2917
2918
2919 void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
2920 {
2921     // Paint the caret if the FrameSelection says so or if caret browsing is enabled
2922     bool caretBrowsing = frame()->settings() && frame()->settings()->caretBrowsingEnabled();
2923     RenderObject* caretPainter;
2924     bool isContentEditable;
2925     if (type == CursorCaret) {
2926         caretPainter = frame()->selection()->caretRenderer();
2927         isContentEditable = frame()->selection()->rendererIsEditable();
2928     } else {
2929         caretPainter = frame()->page()->dragCaretController()->caretRenderer();
2930         isContentEditable = frame()->page()->dragCaretController()->isContentEditable();
2931     }
2932
2933     if (caretPainter == this && (isContentEditable || caretBrowsing)) {
2934         if (type == CursorCaret)
2935             frame()->selection()->paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
2936         else
2937             frame()->page()->dragCaretController()->paintDragCaret(frame(), paintInfo.context, paintOffset, paintInfo.rect);
2938     }
2939 }
2940
2941 void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2942 {
2943     PaintPhase paintPhase = paintInfo.phase;
2944
2945     // 1. paint background, borders etc
2946     if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style()->visibility() == VISIBLE) {
2947         if (hasBoxDecorations())
2948             paintBoxDecorations(paintInfo, paintOffset);
2949         if (hasColumns())
2950             paintColumnRules(paintInfo, paintOffset);
2951     }
2952
2953     if (paintPhase == PaintPhaseMask && style()->visibility() == VISIBLE) {
2954         paintMask(paintInfo, paintOffset);
2955         return;
2956     }
2957
2958     // We're done.  We don't bother painting any children.
2959     if (paintPhase == PaintPhaseBlockBackground)
2960         return;
2961
2962     // Adjust our painting position if we're inside a scrolled layer (e.g., an overflow:auto div).
2963     LayoutPoint scrolledOffset = paintOffset;
2964     if (hasOverflowClip()) {
2965         scrolledOffset.move(-scrolledContentOffset());
2966         if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2967             scrolledOffset.move(verticalScrollbarWidth(), 0);
2968     }
2969
2970     // 2. paint contents
2971     if (paintPhase != PaintPhaseSelfOutline) {
2972         if (hasColumns())
2973             paintColumnContents(paintInfo, scrolledOffset);
2974         else
2975             paintContents(paintInfo, scrolledOffset);
2976     }
2977
2978     // 3. paint selection
2979     // FIXME: Make this work with multi column layouts.  For now don't fill gaps.
2980     bool isPrinting = document()->printing();
2981     if (!isPrinting && !hasColumns())
2982         paintSelection(paintInfo, scrolledOffset); // Fill in gaps in selection on lines and between blocks.
2983
2984     // 4. paint floats.
2985     if (paintPhase == PaintPhaseFloat || paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip) {
2986         if (hasColumns())
2987             paintColumnContents(paintInfo, scrolledOffset, true);
2988         else
2989             paintFloats(paintInfo, scrolledOffset, paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip);
2990     }
2991
2992     // 5. paint outline.
2993     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseSelfOutline) && hasOutline() && style()->visibility() == VISIBLE)
2994         paintOutline(paintInfo.context, LayoutRect(paintOffset, size()));
2995
2996     // 6. paint continuation outlines.
2997     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseChildOutlines)) {
2998         RenderInline* inlineCont = inlineElementContinuation();
2999         // FIXME: For now, do not add continuations for outline painting by our containing block if we are a relative positioned
3000         // anonymous block (i.e. have our own layer). This is because a block depends on renderers in its continuation table being
3001         // in the same layer. 
3002         if (inlineCont && inlineCont->hasOutline() && inlineCont->style()->visibility() == VISIBLE && !hasLayer()) {
3003             RenderInline* inlineRenderer = toRenderInline(inlineCont->node()->renderer());
3004             RenderBlock* cb = containingBlock();
3005
3006             bool inlineEnclosedInSelfPaintingLayer = false;
3007             for (RenderBoxModelObject* box = inlineRenderer; box != cb; box = box->parent()->enclosingBoxModelObject()) {
3008                 if (box->hasSelfPaintingLayer()) {
3009                     inlineEnclosedInSelfPaintingLayer = true;
3010                     break;
3011                 }
3012             }
3013
3014             if (!inlineEnclosedInSelfPaintingLayer)
3015                 cb->addContinuationWithOutline(inlineRenderer);
3016             else if (!inlineRenderer->firstLineBox())
3017                 inlineRenderer->paintOutline(paintInfo.context, paintOffset - locationOffset() + inlineRenderer->containingBlock()->location());
3018         }
3019         paintContinuationOutlines(paintInfo, paintOffset);
3020     }
3021
3022     // 7. paint caret.
3023     // If the caret's node's render object's containing block is this block, and the paint action is PaintPhaseForeground,
3024     // then paint the caret.
3025     if (paintPhase == PaintPhaseForeground) {        
3026         paintCaret(paintInfo, paintOffset, CursorCaret);
3027         paintCaret(paintInfo, paintOffset, DragCaret);
3028     }
3029 }
3030
3031 LayoutPoint RenderBlock::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
3032 {
3033     if (!style()->isFlippedBlocksWritingMode())
3034         return point;
3035     
3036     // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
3037     // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
3038     // case.
3039     if (isHorizontalWritingMode())
3040         return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
3041     return LayoutPoint(point.x() + width() - child->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
3042 }
3043
3044 void RenderBlock::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
3045 {
3046     if (!m_floatingObjects)
3047         return;
3048
3049     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
3050     FloatingObjectSetIterator end = floatingObjectSet.end();
3051     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
3052         FloatingObject* r = *it;
3053         // Only paint the object if our m_shouldPaint flag is set.
3054         if (r->shouldPaint() && !r->m_renderer->hasSelfPaintingLayer()) {
3055             PaintInfo currentPaintInfo(paintInfo);
3056             currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
3057             LayoutPoint childPoint = flipFloatForWritingModeForChild(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->m_renderer->x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->m_renderer->y()));
3058             r->m_renderer->paint(currentPaintInfo, childPoint);
3059             if (!preservePhase) {
3060                 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
3061                 r->m_renderer->paint(currentPaintInfo, childPoint);
3062                 currentPaintInfo.phase = PaintPhaseFloat;
3063                 r->m_renderer->paint(currentPaintInfo, childPoint);
3064                 currentPaintInfo.phase = PaintPhaseForeground;
3065                 r->m_renderer->paint(currentPaintInfo, childPoint);
3066                 currentPaintInfo.phase = PaintPhaseOutline;
3067                 r->m_renderer->paint(currentPaintInfo, childPoint);
3068             }
3069         }
3070     }
3071 }
3072
3073 void RenderBlock::paintEllipsisBoxes(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3074 {
3075     if (!paintInfo.shouldPaintWithinRoot(this) || !firstLineBox())
3076         return;
3077
3078     if (style()->visibility() == VISIBLE && paintInfo.phase == PaintPhaseForeground) {
3079         // We can check the first box and last box and avoid painting if we don't
3080         // intersect.
3081         LayoutUnit yPos = paintOffset.y() + firstLineBox()->y();
3082         LayoutUnit h = lastLineBox()->y() + lastLineBox()->logicalHeight() - firstLineBox()->y();
3083         if (yPos >= paintInfo.rect.maxY() || yPos + h <= paintInfo.rect.y())
3084             return;
3085
3086         // See if our boxes intersect with the dirty rect.  If so, then we paint
3087         // them.  Note that boxes can easily overlap, so we can't make any assumptions
3088         // based off positions of our first line box or our last line box.
3089         for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
3090             yPos = paintOffset.y() + curr->y();
3091             h = curr->logicalHeight();
3092             if (curr->ellipsisBox() && yPos < paintInfo.rect.maxY() && yPos + h > paintInfo.rect.y())
3093                 curr->paintEllipsisBox(paintInfo, paintOffset, curr->lineTop(), curr->lineBottom());
3094         }
3095     }
3096 }
3097
3098 RenderInline* RenderBlock::inlineElementContinuation() const
3099
3100     RenderBoxModelObject* continuation = this->continuation();
3101     return continuation && continuation->isInline() ? toRenderInline(continuation) : 0;
3102 }
3103
3104 RenderBlock* RenderBlock::blockElementContinuation() const
3105 {
3106     RenderBoxModelObject* currentContinuation = continuation();
3107     if (!currentContinuation || currentContinuation->isInline())
3108         return 0;
3109     RenderBlock* nextContinuation = toRenderBlock(currentContinuation);
3110     if (nextContinuation->isAnonymousBlock())
3111         return nextContinuation->blockElementContinuation();
3112     return nextContinuation;
3113 }
3114     
3115 static ContinuationOutlineTableMap* continuationOutlineTable()
3116 {
3117     DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
3118     return &table;
3119 }
3120
3121 void RenderBlock::addContinuationWithOutline(RenderInline* flow)
3122 {
3123     // We can't make this work if the inline is in a layer.  We'll just rely on the broken
3124     // way of painting.
3125     ASSERT(!flow->layer() && !flow->isInlineElementContinuation());
3126     
3127     ContinuationOutlineTableMap* table = continuationOutlineTable();
3128     ListHashSet<RenderInline*>* continuations = table->get(this);
3129     if (!continuations) {
3130         continuations = new ListHashSet<RenderInline*>;
3131         table->set(this, continuations);
3132     }
3133     
3134     continuations->add(flow);
3135 }
3136
3137 bool RenderBlock::paintsContinuationOutline(RenderInline* flow)
3138 {
3139     ContinuationOutlineTableMap* table = continuationOutlineTable();
3140     if (table->isEmpty())
3141         return false;
3142         
3143     ListHashSet<RenderInline*>* continuations = table->get(this);
3144     if (!continuations)
3145         return false;
3146
3147     return continuations->contains(flow);
3148 }
3149
3150 void RenderBlock::paintContinuationOutlines(PaintInfo& info, const LayoutPoint& paintOffset)
3151 {
3152     ContinuationOutlineTableMap* table = continuationOutlineTable();
3153     if (table->isEmpty())
3154         return;
3155         
3156     ListHashSet<RenderInline*>* continuations = table->get(this);
3157     if (!continuations)
3158         return;
3159
3160     LayoutPoint accumulatedPaintOffset = paintOffset;
3161     // Paint each continuation outline.
3162     ListHashSet<RenderInline*>::iterator end = continuations->end();
3163     for (ListHashSet<RenderInline*>::iterator it = continuations->begin(); it != end; ++it) {
3164         // Need to add in the coordinates of the intervening blocks.
3165         RenderInline* flow = *it;
3166         RenderBlock* block = flow->containingBlock();
3167         for ( ; block && block != this; block = block->containingBlock())
3168             accumulatedPaintOffset.moveBy(block->location());
3169         ASSERT(block);   
3170         flow->paintOutline(info.context, accumulatedPaintOffset);
3171     }
3172     
3173     // Delete
3174     delete continuations;
3175     table->remove(this);
3176 }
3177
3178 bool RenderBlock::shouldPaintSelectionGaps() const
3179 {
3180     return selectionState() != SelectionNone && style()->visibility() == VISIBLE && isSelectionRoot();
3181 }
3182
3183 bool RenderBlock::isSelectionRoot() const
3184 {
3185     if (!node())
3186         return false;
3187         
3188     // FIXME: Eventually tables should have to learn how to fill gaps between cells, at least in simple non-spanning cases.
3189     if (isTable())
3190         return false;
3191         
3192     if (isBody() || isRoot() || hasOverflowClip() || isRelPositioned()
3193         || isFloatingOrOutOfFlowPositioned() || isTableCell() || isInlineBlockOrInlineTable() || hasTransform()
3194         || hasReflection() || hasMask() || isWritingModeRoot())
3195         return true;
3196     
3197     if (view() && view()->selectionStart()) {
3198         Node* startElement = view()->selectionStart()->node();
3199         if (startElement && startElement->rootEditableElement() == node())
3200             return true;
3201     }
3202     
3203     return false;
3204 }
3205
3206 GapRects RenderBlock::selectionGapRectsForRepaint(RenderBoxModelObject* repaintContainer)
3207 {
3208     ASSERT(!needsLayout());
3209
3210     if (!shouldPaintSelectionGaps())
3211         return GapRects();
3212
3213     // FIXME: this is broken with transforms
3214     TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
3215     mapLocalToContainer(repaintContainer, false, false, transformState);
3216     LayoutPoint offsetFromRepaintContainer = roundedLayoutPoint(transformState.mappedPoint());
3217
3218     if (hasOverflowClip())
3219         offsetFromRepaintContainer -= scrolledContentOffset();
3220
3221     LayoutUnit lastTop = 0;
3222     LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop);
3223     LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop);
3224     
3225     return selectionGaps(this, offsetFromRepaintContainer, IntSize(), lastTop, lastLeft, lastRight);
3226 }
3227
3228 void RenderBlock::paintSelection(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3229 {
3230     if (shouldPaintSelectionGaps() && paintInfo.phase == PaintPhaseForeground) {
3231         LayoutUnit lastTop = 0;
3232         LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop);
3233         LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop);
3234         GraphicsContextStateSaver stateSaver(*paintInfo.context);
3235
3236         LayoutRect gapRectsBounds = selectionGaps(this, paintOffset, LayoutSize(), lastTop, lastLeft, lastRight, &paintInfo);
3237         if (!gapRectsBounds.isEmpty()) {
3238             if (RenderLayer* layer = enclosingLayer()) {
3239                 gapRectsBounds.moveBy(-paintOffset);
3240                 if (!hasLayer()) {
3241                     LayoutRect localBounds(gapRectsBounds);
3242                     flipForWritingMode(localBounds);
3243                     gapRectsBounds = localToContainerQuad(FloatRect(localBounds), layer->renderer()).enclosingBoundingBox();
3244                     if (layer->renderer()->hasOverflowClip())
3245                         gapRectsBounds.move(layer->renderBox()->scrolledContentOffset());
3246                 }
3247                 layer->addBlockSelectionGapsBounds(gapRectsBounds);
3248             }
3249         }
3250     }
3251 }
3252
3253 static void clipOutPositionedObjects(const PaintInfo* paintInfo, const LayoutPoint& offset, RenderBlock::PositionedObjectsListHashSet* positionedObjects)
3254 {
3255     if (!positionedObjects)
3256         return;
3257     
3258     RenderBlock::PositionedObjectsListHashSet::const_iterator end = positionedObjects->end();
3259     for (RenderBlock::PositionedObjectsListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
3260         RenderBox* r = *it;
3261         paintInfo->context->clipOut(IntRect(offset.x() + r->x(), offset.y() + r->y(), r->width(), r->height()));
3262     }
3263 }
3264
3265 static LayoutUnit blockDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
3266 {
3267     return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
3268 }
3269
3270 static LayoutUnit inlineDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
3271 {
3272     return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.width() : offsetFromRootBlock.height();
3273 }
3274
3275 LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect)
3276 {
3277     LayoutRect result;
3278     if (isHorizontalWritingMode())
3279         result = logicalRect;
3280     else
3281         result = LayoutRect(logicalRect.y(), logicalRect.x(), logicalRect.height(), logicalRect.width());
3282     flipForWritingMode(result);
3283     result.moveBy(rootBlockPhysicalPosition);
3284     return result;
3285 }
3286
3287 GapRects RenderBlock::selectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3288                                     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
3289 {
3290     // IMPORTANT: Callers of this method that intend for painting to happen need to do a save/restore.
3291     // Clip out floating and positioned objects when painting selection gaps.
3292     if (paintInfo) {