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