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