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