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