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