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