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