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