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