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