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