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