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