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