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