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