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