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