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