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