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