[WTF] Import std::optional reference implementation as WTF::Optional
[WebKit-https.git] / Source / WebCore / rendering / RenderView.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public License
16  * along with this library; see the file COPYING.LIB.  If not, write to
17  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #include "config.h"
22 #include "RenderView.h"
23
24 #include "Document.h"
25 #include "Element.h"
26 #include "FloatQuad.h"
27 #include "FloatingObjects.h"
28 #include "FlowThreadController.h"
29 #include "Frame.h"
30 #include "FrameSelection.h"
31 #include "FrameView.h"
32 #include "GraphicsContext.h"
33 #include "HTMLFrameOwnerElement.h"
34 #include "HTMLIFrameElement.h"
35 #include "HitTestResult.h"
36 #include "ImageQualityController.h"
37 #include "NodeTraversal.h"
38 #include "Page.h"
39 #include "RenderGeometryMap.h"
40 #include "RenderIterator.h"
41 #include "RenderLayer.h"
42 #include "RenderLayerBacking.h"
43 #include "RenderLayerCompositor.h"
44 #include "RenderMultiColumnFlowThread.h"
45 #include "RenderMultiColumnSet.h"
46 #include "RenderMultiColumnSpannerPlaceholder.h"
47 #include "RenderNamedFlowThread.h"
48 #include "RenderSelectionInfo.h"
49 #include "RenderWidget.h"
50 #include "ScrollbarTheme.h"
51 #include "Settings.h"
52 #include "StyleInheritedData.h"
53 #include "TransformState.h"
54 #include <wtf/SetForScope.h>
55 #include <wtf/StackStats.h>
56
57 namespace WebCore {
58
59 struct FrameFlatteningLayoutDisallower {
60     FrameFlatteningLayoutDisallower(FrameView& frameView)
61         : m_frameView(frameView)
62         , m_disallowLayout(frameView.frame().settings().frameFlatteningEnabled())
63     {
64         if (m_disallowLayout)
65             m_frameView.startDisallowingLayout();
66     }
67
68     ~FrameFlatteningLayoutDisallower()
69     {
70         if (m_disallowLayout)
71             m_frameView.endDisallowingLayout();
72     }
73
74 private:
75     FrameView& m_frameView;
76     bool m_disallowLayout { false };
77 };
78
79 struct SelectionIterator {
80     SelectionIterator(RenderObject* start)
81         : m_current(start)
82     {
83         checkForSpanner();
84     }
85     
86     RenderObject* current() const
87     {
88         return m_current;
89     }
90     
91     RenderObject* next()
92     {
93         RenderObject* currentSpan = m_spannerStack.isEmpty() ? nullptr : m_spannerStack.last()->spanner();
94         m_current = m_current->nextInPreOrder(currentSpan);
95         checkForSpanner();
96         if (!m_current && currentSpan) {
97             RenderObject* placeholder = m_spannerStack.last();
98             m_spannerStack.removeLast();
99             m_current = placeholder->nextInPreOrder();
100             checkForSpanner();
101         }
102         return m_current;
103     }
104
105 private:
106     void checkForSpanner()
107     {
108         if (!is<RenderMultiColumnSpannerPlaceholder>(m_current))
109             return;
110         auto& placeholder = downcast<RenderMultiColumnSpannerPlaceholder>(*m_current);
111         m_spannerStack.append(&placeholder);
112         m_current = placeholder.spanner();
113     }
114
115     RenderObject* m_current { nullptr };
116     Vector<RenderMultiColumnSpannerPlaceholder*> m_spannerStack;
117 };
118
119 RenderView::RenderView(Document& document, RenderStyle&& style)
120     : RenderBlockFlow(document, WTFMove(style))
121     , m_frameView(*document.view())
122     , m_lazyRepaintTimer(*this, &RenderView::lazyRepaintTimerFired)
123 #if ENABLE(SERVICE_CONTROLS)
124     , m_selectionRectGatherer(*this)
125 #endif
126 {
127     setIsRenderView();
128
129     // FIXME: We should find a way to enforce this at compile time.
130     ASSERT(document.view());
131
132     // init RenderObject attributes
133     setInline(false);
134     
135     m_minPreferredLogicalWidth = 0;
136     m_maxPreferredLogicalWidth = 0;
137
138     setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
139     
140     setPositionState(AbsolutePosition); // to 0,0 :)
141 }
142
143 RenderView::~RenderView()
144 {
145 }
146
147 void RenderView::scheduleLazyRepaint(RenderBox& renderer)
148 {
149     if (renderer.renderBoxNeedsLazyRepaint())
150         return;
151     renderer.setRenderBoxNeedsLazyRepaint(true);
152     m_renderersNeedingLazyRepaint.add(&renderer);
153     if (!m_lazyRepaintTimer.isActive())
154         m_lazyRepaintTimer.startOneShot(0);
155 }
156
157 void RenderView::unscheduleLazyRepaint(RenderBox& renderer)
158 {
159     if (!renderer.renderBoxNeedsLazyRepaint())
160         return;
161     renderer.setRenderBoxNeedsLazyRepaint(false);
162     m_renderersNeedingLazyRepaint.remove(&renderer);
163     if (m_renderersNeedingLazyRepaint.isEmpty())
164         m_lazyRepaintTimer.stop();
165 }
166
167 void RenderView::lazyRepaintTimerFired()
168 {
169     bool shouldRepaint = document().pageCacheState() == Document::NotInPageCache;
170
171     for (auto& renderer : m_renderersNeedingLazyRepaint) {
172         if (shouldRepaint)
173             renderer->repaint();
174         renderer->setRenderBoxNeedsLazyRepaint(false);
175     }
176     m_renderersNeedingLazyRepaint.clear();
177 }
178
179 bool RenderView::hitTest(const HitTestRequest& request, HitTestResult& result)
180 {
181     return hitTest(request, result.hitTestLocation(), result);
182 }
183
184 bool RenderView::hitTest(const HitTestRequest& request, const HitTestLocation& location, HitTestResult& result)
185 {
186     document().updateLayout();
187     
188 #if !ASSERT_DISABLED
189     SetForScope<bool> hitTestRestorer { m_inHitTesting, true };
190 #endif
191
192     FrameFlatteningLayoutDisallower disallower(frameView());
193
194     bool resultLayer = layer()->hitTest(request, location, result);
195
196     // ScrollView scrollbars are not the same as RenderLayer scrollbars tested by RenderLayer::hitTestOverflowControls,
197     // so we need to test ScrollView scrollbars separately here. In case of using overlay scrollbars, the layer hit test
198     // will always work so we need to check the ScrollView scrollbars in that case too.
199     if (!resultLayer || ScrollbarTheme::theme().usesOverlayScrollbars()) {
200         // FIXME: Consider if this test should be done unconditionally.
201         if (request.allowsFrameScrollbars()) {
202             IntPoint windowPoint = frameView().contentsToWindow(location.roundedPoint());
203             if (Scrollbar* frameScrollbar = frameView().scrollbarAtPoint(windowPoint)) {
204                 result.setScrollbar(frameScrollbar);
205                 return true;
206             }
207         }
208     }
209
210     return resultLayer;
211 }
212
213 void RenderView::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit, LogicalExtentComputedValues& computedValues) const
214 {
215     computedValues.m_extent = !shouldUsePrintingLayout() ? LayoutUnit(viewLogicalHeight()) : logicalHeight;
216 }
217
218 void RenderView::updateLogicalWidth()
219 {
220     if (!shouldUsePrintingLayout())
221         setLogicalWidth(viewLogicalWidth());
222 }
223
224 LayoutUnit RenderView::availableLogicalHeight(AvailableLogicalHeightType) const
225 {
226     // Make sure block progression pagination for percentages uses the column extent and
227     // not the view's extent. See https://bugs.webkit.org/show_bug.cgi?id=135204.
228     if (multiColumnFlowThread() && multiColumnFlowThread()->firstMultiColumnSet())
229         return multiColumnFlowThread()->firstMultiColumnSet()->computedColumnHeight();
230
231 #if PLATFORM(IOS)
232     // Workaround for <rdar://problem/7166808>.
233     if (document().isPluginDocument() && frameView().useFixedLayout())
234         return frameView().fixedLayoutSize().height();
235 #endif
236     return isHorizontalWritingMode() ? frameView().visibleHeight() : frameView().visibleWidth();
237 }
238
239 bool RenderView::isChildAllowed(const RenderObject& child, const RenderStyle&) const
240 {
241     return child.isBox();
242 }
243
244 void RenderView::layoutContent(const LayoutState& state)
245 {
246     UNUSED_PARAM(state);
247     ASSERT(needsLayout());
248
249     RenderBlockFlow::layout();
250     if (hasRenderNamedFlowThreads())
251         flowThreadController().layoutRenderNamedFlowThreads();
252 #ifndef NDEBUG
253     checkLayoutState(state);
254 #endif
255 }
256
257 #ifndef NDEBUG
258 void RenderView::checkLayoutState(const LayoutState& state)
259 {
260     ASSERT(layoutDeltaMatches(LayoutSize()));
261     ASSERT(!m_layoutStateDisableCount);
262     ASSERT(m_layoutState.get() == &state);
263 }
264 #endif
265
266 void RenderView::initializeLayoutState(LayoutState& state)
267 {
268     // FIXME: May be better to push a clip and avoid issuing offscreen repaints.
269     state.m_clipped = false;
270
271     state.m_pageLogicalHeight = m_pageLogicalHeight;
272     state.m_pageLogicalHeightChanged = m_pageLogicalHeightChanged;
273     ASSERT(state.m_pageLogicalHeight >= 0);
274     state.m_isPaginated = state.m_pageLogicalHeight > 0;
275 }
276
277 // The algorithm below assumes this is a full layout. In case there are previously computed values for regions, supplemental steps are taken
278 // to ensure the results are the same as those obtained from a full layout (i.e. the auto-height regions from all the flows are marked as needing
279 // layout).
280 // 1. The flows are laid out from the outer flow to the inner flow. This successfully computes the outer non-auto-height regions size so the 
281 // inner flows have the necessary information to correctly fragment the content.
282 // 2. The flows are laid out from the inner flow to the outer flow. After an inner flow is laid out it goes into the constrained layout phase
283 // and marks the auto-height regions they need layout. This means the outer flows will relayout if they depend on regions with auto-height regions
284 // belonging to inner flows. This step will correctly set the computedAutoHeight for the auto-height regions. It's possible for non-auto-height
285 // regions to relayout if they depend on auto-height regions. This will invalidate the inner flow threads and mark them as needing layout.
286 // 3. The last step is to do one last layout if there are pathological dependencies between non-auto-height regions and auto-height regions
287 // as detected in the previous step.
288 void RenderView::layoutContentInAutoLogicalHeightRegions(const LayoutState& state)
289 {
290     // We need to invalidate all the flows with auto-height regions if one such flow needs layout.
291     // If none is found we do a layout a check back again afterwards.
292     if (!flowThreadController().updateFlowThreadsNeedingLayout()) {
293         // Do a first layout of the content. In some cases more layouts are not needed (e.g. only flows with non-auto-height regions have changed).
294         layoutContent(state);
295
296         // If we find no named flow needing a two step layout after the first layout, exit early.
297         // Otherwise, initiate the two step layout algorithm and recompute all the flows.
298         if (!flowThreadController().updateFlowThreadsNeedingTwoStepLayout())
299             return;
300     }
301
302     // Layout to recompute all the named flows with auto-height regions.
303     layoutContent(state);
304
305     // Propagate the computed auto-height values upwards.
306     // Non-auto-height regions may invalidate the flow thread because they depended on auto-height regions, but that's ok.
307     flowThreadController().updateFlowThreadsIntoConstrainedPhase();
308
309     // Do one last layout that should update the auto-height regions found in the main flow
310     // and solve pathological dependencies between regions (e.g. a non-auto-height region depending
311     // on an auto-height one).
312     if (needsLayout())
313         layoutContent(state);
314 }
315
316 void RenderView::layoutContentToComputeOverflowInRegions(const LayoutState& state)
317 {
318     if (!hasRenderNamedFlowThreads())
319         return;
320
321     // First pass through the flow threads and mark the regions as needing a simple layout.
322     // The regions extract the overflow from the flow thread and pass it to their containg
323     // block chain.
324     flowThreadController().updateFlowThreadsIntoOverflowPhase();
325     if (needsLayout())
326         layoutContent(state);
327
328     // In case scrollbars resized the regions a new pass is necessary to update the flow threads
329     // and recompute the overflow on regions. This is the final state of the flow threads.
330     flowThreadController().updateFlowThreadsIntoFinalPhase();
331     if (needsLayout())
332         layoutContent(state);
333
334     // Finally reset the layout state of the flow threads.
335     flowThreadController().updateFlowThreadsIntoMeasureContentPhase();
336 }
337
338 void RenderView::layout()
339 {
340     StackStats::LayoutCheckPoint layoutCheckPoint;
341     if (!document().paginated())
342         setPageLogicalHeight(0);
343
344     if (shouldUsePrintingLayout())
345         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = logicalWidth();
346
347     // Use calcWidth/Height to get the new width/height, since this will take the full page zoom factor into account.
348     bool relayoutChildren = !shouldUsePrintingLayout() && (width() != viewWidth() || height() != viewHeight());
349     if (relayoutChildren) {
350         setChildNeedsLayout(MarkOnlyThis);
351
352         for (auto& box : childrenOfType<RenderBox>(*this)) {
353             if (box.hasRelativeLogicalHeight()
354                 || box.style().logicalHeight().isPercentOrCalculated()
355                 || box.style().logicalMinHeight().isPercentOrCalculated()
356                 || box.style().logicalMaxHeight().isPercentOrCalculated()
357                 || box.isSVGRoot()
358                 )
359                 box.setChildNeedsLayout(MarkOnlyThis);
360         }
361     }
362
363     ASSERT(!m_layoutState);
364     if (!needsLayout())
365         return;
366
367     m_layoutState = std::make_unique<LayoutState>();
368     initializeLayoutState(*m_layoutState);
369
370     m_pageLogicalHeightChanged = false;
371
372     if (checkTwoPassLayoutForAutoHeightRegions())
373         layoutContentInAutoLogicalHeightRegions(*m_layoutState);
374     else
375         layoutContent(*m_layoutState);
376
377     layoutContentToComputeOverflowInRegions(*m_layoutState);
378
379 #ifndef NDEBUG
380     checkLayoutState(*m_layoutState);
381 #endif
382     m_layoutState = nullptr;
383     clearNeedsLayout();
384 }
385
386 LayoutUnit RenderView::pageOrViewLogicalHeight() const
387 {
388     if (document().printing())
389         return pageLogicalHeight();
390     
391     if (multiColumnFlowThread() && !style().hasInlineColumnAxis()) {
392         if (int pageLength = frameView().pagination().pageLength)
393             return pageLength;
394     }
395
396     return viewLogicalHeight();
397 }
398
399 LayoutUnit RenderView::clientLogicalWidthForFixedPosition() const
400 {
401     // FIXME: If the FrameView's fixedVisibleContentRect() is not empty, perhaps it should be consulted here too?
402     if (frameView().fixedElementsLayoutRelativeToFrame())
403         return (isHorizontalWritingMode() ? frameView().visibleWidth() : frameView().visibleHeight()) / frameView().frame().frameScaleFactor();
404
405 #if PLATFORM(IOS)
406     if (frameView().useCustomFixedPositionLayoutRect())
407         return isHorizontalWritingMode() ? frameView().customFixedPositionLayoutRect().width() : frameView().customFixedPositionLayoutRect().height();
408 #endif
409
410     if (frameView().frame().settings().visualViewportEnabled())
411         return isHorizontalWritingMode() ? frameView().layoutViewportRect().width() : frameView().layoutViewportRect().height();
412
413     return clientLogicalWidth();
414 }
415
416 LayoutUnit RenderView::clientLogicalHeightForFixedPosition() const
417 {
418     // FIXME: If the FrameView's fixedVisibleContentRect() is not empty, perhaps it should be consulted here too?
419     if (frameView().fixedElementsLayoutRelativeToFrame())
420         return (isHorizontalWritingMode() ? frameView().visibleHeight() : frameView().visibleWidth()) / frameView().frame().frameScaleFactor();
421
422 #if PLATFORM(IOS)
423     if (frameView().useCustomFixedPositionLayoutRect())
424         return isHorizontalWritingMode() ? frameView().customFixedPositionLayoutRect().height() : frameView().customFixedPositionLayoutRect().width();
425 #endif
426
427     if (frameView().frame().settings().visualViewportEnabled())
428         return isHorizontalWritingMode() ? frameView().layoutViewportRect().height() : frameView().layoutViewportRect().width();
429
430     return clientLogicalHeight();
431 }
432
433 void RenderView::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
434 {
435     // If a container was specified, and was not nullptr or the RenderView,
436     // then we should have found it by now.
437     ASSERT_ARG(repaintContainer, !repaintContainer || repaintContainer == this);
438     ASSERT_UNUSED(wasFixed, !wasFixed || *wasFixed == (mode & IsFixed));
439
440     if (!repaintContainer && mode & UseTransforms && shouldUseTransformFromContainer(nullptr)) {
441         TransformationMatrix t;
442         getTransformFromContainer(nullptr, LayoutSize(), t);
443         transformState.applyTransform(t);
444     }
445     
446     if (mode & IsFixed)
447         transformState.move(toLayoutSize(frameView().scrollPositionRespectingCustomFixedPosition()));
448 }
449
450 const RenderObject* RenderView::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
451 {
452     // If a container was specified, and was not nullptr or the RenderView,
453     // then we should have found it by now.
454     ASSERT_ARG(ancestorToStopAt, !ancestorToStopAt || ancestorToStopAt == this);
455
456     LayoutPoint scrollPosition = frameView().scrollPositionRespectingCustomFixedPosition();
457
458     if (!ancestorToStopAt && shouldUseTransformFromContainer(nullptr)) {
459         TransformationMatrix t;
460         getTransformFromContainer(nullptr, LayoutSize(), t);
461         geometryMap.pushView(this, toLayoutSize(scrollPosition), &t);
462     } else
463         geometryMap.pushView(this, toLayoutSize(scrollPosition));
464
465     return nullptr;
466 }
467
468 void RenderView::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
469 {
470     if (mode & IsFixed)
471         transformState.move(toLayoutSize(frameView().scrollPositionRespectingCustomFixedPosition()));
472
473     if (mode & UseTransforms && shouldUseTransformFromContainer(nullptr)) {
474         TransformationMatrix t;
475         getTransformFromContainer(nullptr, LayoutSize(), t);
476         transformState.applyTransform(t);
477     }
478 }
479
480 bool RenderView::requiresColumns(int) const
481 {
482     return frameView().pagination().mode != Pagination::Unpaginated;
483 }
484
485 void RenderView::computeColumnCountAndWidth()
486 {
487     int columnWidth = contentLogicalWidth();
488     if (style().hasInlineColumnAxis()) {
489         if (int pageLength = frameView().pagination().pageLength)
490             columnWidth = pageLength;
491     }
492     setComputedColumnCountAndWidth(1, columnWidth);
493 }
494
495 void RenderView::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
496 {
497     // If we ever require layout but receive a paint anyway, something has gone horribly wrong.
498     ASSERT(!needsLayout());
499     // RenderViews should never be called to paint with an offset not on device pixels.
500     ASSERT(LayoutPoint(IntPoint(paintOffset.x(), paintOffset.y())) == paintOffset);
501
502     // This avoids painting garbage between columns if there is a column gap.
503     if (frameView().pagination().mode != Pagination::Unpaginated && paintInfo.shouldPaintWithinRoot(*this))
504         paintInfo.context().fillRect(paintInfo.rect, frameView().baseBackgroundColor());
505
506     paintObject(paintInfo, paintOffset);
507 }
508
509 static inline bool rendererObscuresBackground(RenderElement* rootObject)
510 {
511     if (!rootObject)
512         return false;
513     
514     const RenderStyle& style = rootObject->style();
515     if (style.visibility() != VISIBLE
516         || style.opacity() != 1
517         || style.hasTransform())
518         return false;
519     
520     if (rootObject->isComposited())
521         return false;
522
523     if (rootObject->rendererForRootBackground().style().backgroundClip() == TextFillBox)
524         return false;
525
526     if (style.hasBorderRadius())
527         return false;
528
529     return true;
530 }
531
532 void RenderView::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint&)
533 {
534     if (!paintInfo.shouldPaintWithinRoot(*this))
535         return;
536
537     // Check to see if we are enclosed by a layer that requires complex painting rules.  If so, we cannot blit
538     // when scrolling, and we need to use slow repaints.  Examples of layers that require this are transparent layers,
539     // layers with reflections, or transformed layers.
540     // FIXME: This needs to be dynamic.  We should be able to go back to blitting if we ever stop being inside
541     // a transform, transparency layer, etc.
542     for (HTMLFrameOwnerElement* element = document().ownerElement(); element && element->renderer(); element = element->document().ownerElement()) {
543         RenderLayer* layer = element->renderer()->enclosingLayer();
544         if (layer->cannotBlitToWindow()) {
545             frameView().setCannotBlitToWindow();
546             break;
547         }
548
549         if (RenderLayer* compositingLayer = layer->enclosingCompositingLayerForRepaint()) {
550             if (!compositingLayer->backing()->paintsIntoWindow()) {
551                 frameView().setCannotBlitToWindow();
552                 break;
553             }
554         }
555     }
556
557     if (document().ownerElement())
558         return;
559
560     if (paintInfo.skipRootBackground())
561         return;
562
563     bool rootFillsViewport = false;
564     bool rootObscuresBackground = false;
565     Element* documentElement = document().documentElement();
566     if (RenderElement* rootRenderer = documentElement ? documentElement->renderer() : nullptr) {
567         // The document element's renderer is currently forced to be a block, but may not always be.
568         RenderBox* rootBox = is<RenderBox>(*rootRenderer) ? downcast<RenderBox>(rootRenderer) : nullptr;
569         rootFillsViewport = rootBox && !rootBox->x() && !rootBox->y() && rootBox->width() >= width() && rootBox->height() >= height();
570         rootObscuresBackground = rendererObscuresBackground(rootRenderer);
571     }
572
573     bool backgroundShouldExtendBeyondPage = frameView().frame().settings().backgroundShouldExtendBeyondPage();
574     compositor().setRootExtendedBackgroundColor(backgroundShouldExtendBeyondPage ? frameView().documentBackgroundColor() : Color());
575
576     Page* page = document().page();
577     float pageScaleFactor = page ? page->pageScaleFactor() : 1;
578
579     // If painting will entirely fill the view, no need to fill the background.
580     if (rootFillsViewport && rootObscuresBackground && pageScaleFactor >= 1)
581         return;
582
583     // This code typically only executes if the root element's visibility has been set to hidden,
584     // if there is a transform on the <html>, or if there is a page scale factor less than 1.
585     // Only fill with a background color (typically white) if we're the root document, 
586     // since iframes/frames with no background in the child document should show the parent's background.
587     // We use the base background color unless the backgroundShouldExtendBeyondPage setting is set,
588     // in which case we use the document's background color.
589     if (frameView().isTransparent()) // FIXME: This needs to be dynamic. We should be able to go back to blitting if we ever stop being transparent.
590         frameView().setCannotBlitToWindow(); // The parent must show behind the child.
591     else {
592         const Color& documentBackgroundColor = frameView().documentBackgroundColor();
593         const Color& backgroundColor = (backgroundShouldExtendBeyondPage && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView().baseBackgroundColor();
594         if (backgroundColor.isVisible()) {
595             CompositeOperator previousOperator = paintInfo.context().compositeOperation();
596             paintInfo.context().setCompositeOperation(CompositeCopy);
597             paintInfo.context().fillRect(paintInfo.rect, backgroundColor);
598             paintInfo.context().setCompositeOperation(previousOperator);
599         } else
600             paintInfo.context().clearRect(paintInfo.rect);
601     }
602 }
603
604 bool RenderView::shouldRepaint(const LayoutRect& rect) const
605 {
606     return !printing() && !rect.isEmpty();
607 }
608
609 void RenderView::repaintRootContents()
610 {
611     if (layer()->isComposited()) {
612         layer()->setBackingNeedsRepaint(GraphicsLayer::DoNotClipToLayer);
613         return;
614     }
615
616     // Always use layoutOverflowRect() to fix rdar://problem/27182267.
617     // This should be cleaned up via webkit.org/b/159913 and webkit.org/b/159914.
618     RenderLayerModelObject* repaintContainer = containerForRepaint();
619     repaintUsingContainer(repaintContainer, computeRectForRepaint(layoutOverflowRect(), repaintContainer));
620 }
621
622 void RenderView::repaintViewRectangle(const LayoutRect& repaintRect) const
623 {
624     if (!shouldRepaint(repaintRect))
625         return;
626
627     // FIXME: enclosingRect is needed as long as we integral snap ScrollView/FrameView/RenderWidget size/position.
628     IntRect enclosingRect = enclosingIntRect(repaintRect);
629     if (auto ownerElement = document().ownerElement()) {
630         RenderBox* ownerBox = ownerElement->renderBox();
631         if (!ownerBox)
632             return;
633         LayoutRect viewRect = this->viewRect();
634 #if PLATFORM(IOS)
635         // Don't clip using the visible rect since clipping is handled at a higher level on iPhone.
636         LayoutRect adjustedRect = enclosingRect;
637 #else
638         LayoutRect adjustedRect = intersection(enclosingRect, viewRect);
639 #endif
640         adjustedRect.moveBy(-viewRect.location());
641         adjustedRect.moveBy(ownerBox->contentBoxRect().location());
642
643         // A dirty rect in an iframe is relative to the contents of that iframe.
644         // When we traverse between parent frames and child frames, we need to make sure
645         // that the coordinate system is mapped appropriately between the iframe's contents
646         // and the Renderer that contains the iframe. This transformation must account for a
647         // left scrollbar (if one exists).
648         FrameView& frameView = this->frameView();
649         if (frameView.shouldPlaceBlockDirectionScrollbarOnLeft() && frameView.verticalScrollbar())
650             adjustedRect.move(LayoutSize(frameView.verticalScrollbar()->occupiedWidth(), 0));
651
652         ownerBox->repaintRectangle(adjustedRect);
653         return;
654     }
655
656     frameView().addTrackedRepaintRect(snapRectToDevicePixels(repaintRect, document().deviceScaleFactor()));
657     if (!m_accumulatedRepaintRegion) {
658         frameView().repaintContentRectangle(enclosingRect);
659         return;
660     }
661     m_accumulatedRepaintRegion->unite(enclosingRect);
662
663     // Region will get slow if it gets too complex. Merge all rects so far to bounds if this happens.
664     // FIXME: Maybe there should be a region type that does this automatically.
665     static const unsigned maximumRepaintRegionGridSize = 16 * 16;
666     if (m_accumulatedRepaintRegion->gridSize() > maximumRepaintRegionGridSize)
667         m_accumulatedRepaintRegion = std::make_unique<Region>(m_accumulatedRepaintRegion->bounds());
668 }
669
670 void RenderView::flushAccumulatedRepaintRegion() const
671 {
672     ASSERT(!document().ownerElement());
673     ASSERT(m_accumulatedRepaintRegion);
674     auto repaintRects = m_accumulatedRepaintRegion->rects();
675     for (auto& rect : repaintRects)
676         frameView().repaintContentRectangle(rect);
677     m_accumulatedRepaintRegion = nullptr;
678 }
679
680 void RenderView::repaintViewAndCompositedLayers()
681 {
682     repaintRootContents();
683
684     RenderLayerCompositor& compositor = this->compositor();
685     if (compositor.inCompositingMode())
686         compositor.repaintCompositedLayers();
687 }
688
689 LayoutRect RenderView::visualOverflowRect() const
690 {
691     if (frameView().paintsEntireContents())
692         return layoutOverflowRect();
693
694     return RenderBlockFlow::visualOverflowRect();
695 }
696
697 LayoutRect RenderView::computeRectForRepaint(const LayoutRect& rect, const RenderLayerModelObject* repaintContainer, RepaintContext context) const
698 {
699     // If a container was specified, and was not nullptr or the RenderView,
700     // then we should have found it by now.
701     ASSERT_ARG(repaintContainer, !repaintContainer || repaintContainer == this);
702
703     if (printing())
704         return rect;
705     
706     LayoutRect adjustedRect = rect;
707     if (style().isFlippedBlocksWritingMode()) {
708         // We have to flip by hand since the view's logical height has not been determined.  We
709         // can use the viewport width and height.
710         if (style().isHorizontalWritingMode())
711             adjustedRect.setY(viewHeight() - adjustedRect.maxY());
712         else
713             adjustedRect.setX(viewWidth() - adjustedRect.maxX());
714     }
715
716     if (context.m_hasPositionFixedDescendant)
717         adjustedRect.moveBy(frameView().scrollPositionRespectingCustomFixedPosition());
718     
719     // Apply our transform if we have one (because of full page zooming).
720     if (!repaintContainer && layer() && layer()->transform())
721         adjustedRect = LayoutRect(layer()->transform()->mapRect(snapRectToDevicePixels(adjustedRect, document().deviceScaleFactor())));
722     return adjustedRect;
723 }
724
725 bool RenderView::isScrollableOrRubberbandableBox() const
726 {
727     // The main frame might be allowed to rubber-band even if there is no content to scroll to. This is unique to
728     // the main frame; subframes and overflow areas have to have content that can be scrolled to in order to rubber-band.
729     FrameView::Scrollability defineScrollable = frame().ownerElement() ? FrameView::Scrollability::Scrollable : FrameView::Scrollability::ScrollableOrRubberbandable;
730     return frameView().isScrollable(defineScrollable);
731 }
732
733 void RenderView::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
734 {
735     rects.append(snappedIntRect(accumulatedOffset, layer()->size()));
736 }
737
738 void RenderView::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
739 {
740     if (wasFixed)
741         *wasFixed = false;
742     quads.append(FloatRect(FloatPoint(), layer()->size()));
743 }
744
745 static RenderObject* rendererAfterPosition(RenderObject* object, unsigned offset)
746 {
747     if (!object)
748         return nullptr;
749
750     RenderObject* child = object->childAt(offset);
751     return child ? child : object->nextInPreOrderAfterChildren();
752 }
753
754 IntRect RenderView::selectionBounds(bool clipToVisibleContent) const
755 {
756     LayoutRect selRect = subtreeSelectionBounds(*this, clipToVisibleContent);
757
758     if (hasRenderNamedFlowThreads()) {
759         for (auto* namedFlowThread : *m_flowThreadController->renderNamedFlowThreadList()) {
760             LayoutRect currRect = subtreeSelectionBounds(*namedFlowThread, clipToVisibleContent);
761             selRect.unite(currRect);
762         }
763     }
764
765     return snappedIntRect(selRect);
766 }
767
768 LayoutRect RenderView::subtreeSelectionBounds(const SelectionSubtreeRoot& root, bool clipToVisibleContent) const
769 {
770     typedef HashMap<RenderObject*, std::unique_ptr<RenderSelectionInfo>> SelectionMap;
771     SelectionMap selectedObjects;
772
773     RenderObject* os = root.selectionData().selectionStart();
774     auto* selectionEnd = root.selectionData().selectionEnd();
775     RenderObject* stop = nullptr;
776     if (selectionEnd)
777         stop = rendererAfterPosition(selectionEnd, root.selectionData().selectionEndPos().value());
778     SelectionIterator selectionIterator(os);
779     while (os && os != stop) {
780         if ((os->canBeSelectionLeaf() || os == root.selectionData().selectionStart() || os == root.selectionData().selectionEnd()) && os->selectionState() != SelectionNone) {
781             // Blocks are responsible for painting line gaps and margin gaps. They must be examined as well.
782             selectedObjects.set(os, std::make_unique<RenderSelectionInfo>(*os, clipToVisibleContent));
783             RenderBlock* cb = os->containingBlock();
784             while (cb && !is<RenderView>(*cb)) {
785                 std::unique_ptr<RenderSelectionInfo>& blockInfo = selectedObjects.add(cb, nullptr).iterator->value;
786                 if (blockInfo)
787                     break;
788                 blockInfo = std::make_unique<RenderSelectionInfo>(*cb, clipToVisibleContent);
789                 cb = cb->containingBlock();
790             }
791         }
792
793         os = selectionIterator.next();
794     }
795
796     // Now create a single bounding box rect that encloses the whole selection.
797     LayoutRect selRect;
798     SelectionMap::iterator end = selectedObjects.end();
799     for (SelectionMap::iterator i = selectedObjects.begin(); i != end; ++i) {
800         RenderSelectionInfo* info = i->value.get();
801         // RenderSelectionInfo::rect() is in the coordinates of the repaintContainer, so map to page coordinates.
802         LayoutRect currRect = info->rect();
803         if (RenderLayerModelObject* repaintContainer = info->repaintContainer()) {
804             FloatQuad absQuad = repaintContainer->localToAbsoluteQuad(FloatRect(currRect));
805             currRect = absQuad.enclosingBoundingBox(); 
806         }
807         selRect.unite(currRect);
808     }
809     return selRect;
810 }
811
812 void RenderView::repaintSelection() const
813 {
814     repaintSubtreeSelection(*this);
815
816     if (hasRenderNamedFlowThreads()) {
817         for (auto* namedFlowThread : *m_flowThreadController->renderNamedFlowThreadList())
818             repaintSubtreeSelection(*namedFlowThread);
819     }
820 }
821
822 void RenderView::repaintSubtreeSelection(const SelectionSubtreeRoot& root) const
823 {
824     HashSet<RenderBlock*> processedBlocks;
825
826     auto* selectionEnd = root.selectionData().selectionEnd();
827     RenderObject* end = nullptr;
828     if (selectionEnd)
829         end = rendererAfterPosition(selectionEnd, root.selectionData().selectionEndPos().value());
830     SelectionIterator selectionIterator(root.selectionData().selectionStart());
831     for (RenderObject* o = selectionIterator.current(); o && o != end; o = selectionIterator.next()) {
832         if (!o->canBeSelectionLeaf() && o != root.selectionData().selectionStart() && o != root.selectionData().selectionEnd())
833             continue;
834         if (o->selectionState() == SelectionNone)
835             continue;
836
837         RenderSelectionInfo(*o, true).repaint();
838
839         // Blocks are responsible for painting line gaps and margin gaps. They must be examined as well.
840         for (RenderBlock* block = o->containingBlock(); block && !is<RenderView>(*block); block = block->containingBlock()) {
841             if (!processedBlocks.add(block).isNewEntry)
842                 break;
843             RenderSelectionInfo(*block, true).repaint();
844         }
845     }
846 }
847
848 void RenderView::setSelection(RenderObject* start, std::optional<unsigned> startPos, RenderObject* end, std::optional<unsigned> endPos, SelectionRepaintMode blockRepaintMode)
849 {
850     // Make sure both our start and end objects are defined.
851     // Check www.msnbc.com and try clicking around to find the case where this happened.
852     if ((start && !end) || (end && !start))
853         return;
854
855     bool caretChanged = m_selectionWasCaret != frame().selection().isCaret();
856     m_selectionWasCaret = frame().selection().isCaret();
857     // Just return if the selection hasn't changed.
858     if (m_selectionUnsplitStart == start && m_selectionUnsplitStartPos == startPos
859         && m_selectionUnsplitEnd == end && m_selectionUnsplitEndPos == endPos && !caretChanged) {
860         return;
861     }
862
863 #if ENABLE(SERVICE_CONTROLS)
864     // Clear the current rects and create a notifier for the new rects we are about to gather.
865     // The Notifier updates the Editor when it goes out of scope and is destroyed.
866     std::unique_ptr<SelectionRectGatherer::Notifier> rectNotifier = m_selectionRectGatherer.clearAndCreateNotifier();
867 #endif // ENABLE(SERVICE_CONTROLS)
868     // Set global positions for new selection.
869     m_selectionUnsplitStart = start;
870     m_selectionUnsplitStartPos = startPos;
871     m_selectionUnsplitEnd = end;
872     m_selectionUnsplitEndPos = endPos;
873
874     // If there is no RenderNamedFlowThreads we follow the regular selection.
875     if (!hasRenderNamedFlowThreads()) {
876         RenderSubtreesMap singleSubtreeMap;
877         singleSubtreeMap.set(this, SelectionSubtreeData(start, startPos, end, endPos));
878         updateSelectionForSubtrees(singleSubtreeMap, blockRepaintMode);
879         return;
880     }
881
882     splitSelectionBetweenSubtrees(start, startPos, end, endPos, blockRepaintMode);
883 }
884
885 void RenderView::splitSelectionBetweenSubtrees(const RenderObject* start, std::optional<unsigned> startPos, const RenderObject* end, std::optional<unsigned> endPos, SelectionRepaintMode blockRepaintMode)
886 {
887     // Compute the visible selection end points for each of the subtrees.
888     RenderSubtreesMap renderSubtreesMap;
889
890     SelectionSubtreeData initialSelection;
891     renderSubtreesMap.set(this, initialSelection);
892     for (auto* namedFlowThread : *flowThreadController().renderNamedFlowThreadList())
893         renderSubtreesMap.set(namedFlowThread, initialSelection);
894
895     if (start && end) {
896         Node* startNode = start->node();
897         Node* endNode = end->node();
898         ASSERT(endNode);
899         Node* stopNode = NodeTraversal::nextSkippingChildren(*endNode);
900
901         for (Node* node = startNode; node != stopNode; node = NodeTraversal::next(*node)) {
902             RenderObject* renderer = node->renderer();
903             if (!renderer)
904                 continue;
905
906             SelectionSubtreeRoot& root = renderer->selectionRoot();
907             SelectionSubtreeData selectionData = renderSubtreesMap.get(&root);
908             if (selectionData.selectionClear()) {
909                 selectionData.setSelectionStart(node->renderer());
910                 selectionData.setSelectionStartPos(node == startNode ? startPos : std::optional<unsigned>(0));
911             }
912
913             selectionData.setSelectionEnd(node->renderer());
914             if (node == endNode)
915                 selectionData.setSelectionEndPos(endPos);
916             else {
917                 unsigned newEndPos = node->offsetInCharacters() ? node->maxCharacterOffset() : node->countChildNodes();
918                 selectionData.setSelectionEndPos(newEndPos);
919             }
920
921             renderSubtreesMap.set(&root, selectionData);
922         }
923     }
924     
925     updateSelectionForSubtrees(renderSubtreesMap, blockRepaintMode);
926 }
927
928 void RenderView::updateSelectionForSubtrees(RenderSubtreesMap& renderSubtreesMap, SelectionRepaintMode blockRepaintMode)
929 {
930     SubtreeOldSelectionDataMap oldSelectionDataMap;
931     for (auto& subtreeSelectionInfo : renderSubtreesMap) {
932         SelectionSubtreeRoot& root = *subtreeSelectionInfo.key;
933         std::unique_ptr<OldSelectionData> oldSelectionData = std::make_unique<OldSelectionData>();
934
935         clearSubtreeSelection(root, blockRepaintMode, *oldSelectionData);
936         oldSelectionDataMap.set(&root, WTFMove(oldSelectionData));
937
938         root.setSelectionData(subtreeSelectionInfo.value);
939         if (hasRenderNamedFlowThreads())
940             root.adjustForVisibleSelection(document());
941     }
942
943     // Update selection status for the objects inside the selection subtrees.
944     // This needs to be done after the previous loop updated the selectionStart/End
945     // parameters of all subtrees because we're going to be climbing up the containing
946     // block chain and we might end up in a different selection subtree.
947     for (const auto* subtreeSelectionRoot : renderSubtreesMap.keys()) {
948         OldSelectionData& oldSelectionData = *oldSelectionDataMap.get(subtreeSelectionRoot);
949         applySubtreeSelection(*subtreeSelectionRoot, blockRepaintMode, oldSelectionData);
950     }
951 }
952
953 static inline bool isValidObjectForNewSelection(const SelectionSubtreeRoot& root, const RenderObject& object)
954 {
955     return (object.canBeSelectionLeaf() || &object == root.selectionData().selectionStart() || &object == root.selectionData().selectionEnd()) && object.selectionState() != RenderObject::SelectionNone && object.containingBlock();
956 }
957
958 void RenderView::clearSubtreeSelection(const SelectionSubtreeRoot& root, SelectionRepaintMode blockRepaintMode, OldSelectionData& oldSelectionData) const
959 {
960     // Record the old selected objects.  These will be used later
961     // when we compare against the new selected objects.
962     oldSelectionData.selectionStartPos = root.selectionData().selectionStartPos();
963     oldSelectionData.selectionEndPos = root.selectionData().selectionEndPos();
964     
965     // Blocks contain selected objects and fill gaps between them, either on the left, right, or in between lines and blocks.
966     // In order to get the repaint rect right, we have to examine left, middle, and right rects individually, since otherwise
967     // the union of those rects might remain the same even when changes have occurred.
968
969     RenderObject* os = root.selectionData().selectionStart();
970     auto* selectionEnd = root.selectionData().selectionEnd();
971     RenderObject* stop = nullptr;
972     if (selectionEnd)
973         stop = rendererAfterPosition(selectionEnd, root.selectionData().selectionEndPos().value());
974     SelectionIterator selectionIterator(os);
975     while (os && os != stop) {
976         if (isValidObjectForNewSelection(root, *os)) {
977             // Blocks are responsible for painting line gaps and margin gaps.  They must be examined as well.
978             oldSelectionData.selectedObjects.set(os, std::make_unique<RenderSelectionInfo>(*os, true));
979             if (blockRepaintMode == RepaintNewXOROld) {
980                 RenderBlock* cb = os->containingBlock();
981                 while (cb && !is<RenderView>(*cb)) {
982                     std::unique_ptr<RenderBlockSelectionInfo>& blockInfo = oldSelectionData.selectedBlocks.add(cb, nullptr).iterator->value;
983                     if (blockInfo)
984                         break;
985                     blockInfo = std::make_unique<RenderBlockSelectionInfo>(*cb);
986                     cb = cb->containingBlock();
987                 }
988             }
989         }
990
991         os = selectionIterator.next();
992     }
993
994     for (auto* selectedObject : oldSelectionData.selectedObjects.keys())
995         selectedObject->setSelectionStateIfNeeded(SelectionNone);
996 }
997
998 void RenderView::applySubtreeSelection(const SelectionSubtreeRoot& root, SelectionRepaintMode blockRepaintMode, const OldSelectionData& oldSelectionData)
999 {
1000     // Update the selection status of all objects between selectionStart and selectionEnd
1001     if (root.selectionData().selectionStart() && root.selectionData().selectionStart() == root.selectionData().selectionEnd())
1002         root.selectionData().selectionStart()->setSelectionStateIfNeeded(SelectionBoth);
1003     else {
1004         if (root.selectionData().selectionStart())
1005             root.selectionData().selectionStart()->setSelectionStateIfNeeded(SelectionStart);
1006         if (root.selectionData().selectionEnd())
1007             root.selectionData().selectionEnd()->setSelectionStateIfNeeded(SelectionEnd);
1008     }
1009
1010     RenderObject* selectionStart = root.selectionData().selectionStart();
1011     auto* selectionDataEnd = root.selectionData().selectionEnd();
1012     RenderObject* selectionEnd = nullptr;
1013     if (selectionDataEnd)
1014         selectionEnd = rendererAfterPosition(selectionDataEnd, root.selectionData().selectionEndPos().value());
1015     SelectionIterator selectionIterator(selectionStart);
1016     for (RenderObject* currentRenderer = selectionStart; currentRenderer && currentRenderer != selectionEnd; currentRenderer = selectionIterator.next()) {
1017         if (currentRenderer == root.selectionData().selectionStart() || currentRenderer == root.selectionData().selectionEnd())
1018             continue;
1019         if (!currentRenderer->canBeSelectionLeaf())
1020             continue;
1021         // FIXME: Move this logic to SelectionIterator::next()
1022         if (&currentRenderer->selectionRoot() != &root)
1023             continue;
1024         currentRenderer->setSelectionStateIfNeeded(SelectionInside);
1025     }
1026
1027     if (blockRepaintMode != RepaintNothing)
1028         layer()->clearBlockSelectionGapsBounds();
1029
1030     // Now that the selection state has been updated for the new objects, walk them again and
1031     // put them in the new objects list.
1032     SelectedObjectMap newSelectedObjects;
1033     SelectedBlockMap newSelectedBlocks;
1034     selectionIterator = SelectionIterator(selectionStart);
1035     for (RenderObject* currentRenderer = selectionStart; currentRenderer && currentRenderer != selectionEnd; currentRenderer = selectionIterator.next()) {
1036         if (isValidObjectForNewSelection(root, *currentRenderer)) {
1037             std::unique_ptr<RenderSelectionInfo> selectionInfo = std::make_unique<RenderSelectionInfo>(*currentRenderer, true);
1038
1039 #if ENABLE(SERVICE_CONTROLS)
1040             for (auto& rect : selectionInfo->collectedSelectionRects())
1041                 m_selectionRectGatherer.addRect(selectionInfo->repaintContainer(), rect);
1042             if (!currentRenderer->isTextOrLineBreak())
1043                 m_selectionRectGatherer.setTextOnly(false);
1044 #endif
1045
1046             newSelectedObjects.set(currentRenderer, WTFMove(selectionInfo));
1047
1048             RenderBlock* containingBlock = currentRenderer->containingBlock();
1049             while (containingBlock && !is<RenderView>(*containingBlock)) {
1050                 std::unique_ptr<RenderBlockSelectionInfo>& blockInfo = newSelectedBlocks.add(containingBlock, nullptr).iterator->value;
1051                 if (blockInfo)
1052                     break;
1053                 blockInfo = std::make_unique<RenderBlockSelectionInfo>(*containingBlock);
1054                 containingBlock = containingBlock->containingBlock();
1055
1056 #if ENABLE(SERVICE_CONTROLS)
1057                 m_selectionRectGatherer.addGapRects(blockInfo->repaintContainer(), blockInfo->rects());
1058 #endif
1059             }
1060         }
1061     }
1062
1063     if (blockRepaintMode == RepaintNothing)
1064         return;
1065
1066     // Have any of the old selected objects changed compared to the new selection?
1067     for (const auto& selectedObjectInfo : oldSelectionData.selectedObjects) {
1068         RenderObject* obj = selectedObjectInfo.key;
1069         RenderSelectionInfo* newInfo = newSelectedObjects.get(obj);
1070         RenderSelectionInfo* oldInfo = selectedObjectInfo.value.get();
1071         if (!newInfo || oldInfo->rect() != newInfo->rect() || oldInfo->state() != newInfo->state()
1072             || (root.selectionData().selectionStart() == obj && oldSelectionData.selectionStartPos != root.selectionData().selectionStartPos())
1073             || (root.selectionData().selectionEnd() == obj && oldSelectionData.selectionEndPos != root.selectionData().selectionEndPos())) {
1074             oldInfo->repaint();
1075             if (newInfo) {
1076                 newInfo->repaint();
1077                 newSelectedObjects.remove(obj);
1078             }
1079         }
1080     }
1081
1082     // Any new objects that remain were not found in the old objects dict, and so they need to be updated.
1083     for (const auto& selectedObjectInfo : newSelectedObjects)
1084         selectedObjectInfo.value->repaint();
1085
1086     // Have any of the old blocks changed?
1087     for (const auto& selectedBlockInfo : oldSelectionData.selectedBlocks) {
1088         const RenderBlock* block = selectedBlockInfo.key;
1089         RenderBlockSelectionInfo* newInfo = newSelectedBlocks.get(block);
1090         RenderBlockSelectionInfo* oldInfo = selectedBlockInfo.value.get();
1091         if (!newInfo || oldInfo->rects() != newInfo->rects() || oldInfo->state() != newInfo->state()) {
1092             oldInfo->repaint();
1093             if (newInfo) {
1094                 newInfo->repaint();
1095                 newSelectedBlocks.remove(block);
1096             }
1097         }
1098     }
1099
1100     // Any new blocks that remain were not found in the old blocks dict, and so they need to be updated.
1101     for (const auto& selectedBlockInfo : newSelectedBlocks)
1102         selectedBlockInfo.value->repaint();
1103 }
1104
1105 void RenderView::getSelection(RenderObject*& startRenderer, std::optional<unsigned>& startOffset, RenderObject*& endRenderer, std::optional<unsigned>& endOffset) const
1106 {
1107     startRenderer = m_selectionUnsplitStart;
1108     startOffset = m_selectionUnsplitStartPos;
1109     endRenderer = m_selectionUnsplitEnd;
1110     endOffset = m_selectionUnsplitEndPos;
1111 }
1112
1113 void RenderView::clearSelection()
1114 {
1115     layer()->repaintBlockSelectionGaps();
1116     setSelection(nullptr, std::nullopt, nullptr, std::nullopt, RepaintNewMinusOld);
1117 }
1118
1119 bool RenderView::printing() const
1120 {
1121     return document().printing();
1122 }
1123
1124 bool RenderView::shouldUsePrintingLayout() const
1125 {
1126     if (!printing())
1127         return false;
1128     return frameView().frame().shouldUsePrintingLayout();
1129 }
1130
1131 LayoutRect RenderView::viewRect() const
1132 {
1133     if (shouldUsePrintingLayout())
1134         return LayoutRect(LayoutPoint(), size());
1135     return frameView().visibleContentRect(ScrollableArea::LegacyIOSDocumentVisibleRect);
1136 }
1137
1138 IntRect RenderView::unscaledDocumentRect() const
1139 {
1140     LayoutRect overflowRect(layoutOverflowRect());
1141     flipForWritingMode(overflowRect);
1142     return snappedIntRect(overflowRect);
1143 }
1144
1145 bool RenderView::rootBackgroundIsEntirelyFixed() const
1146 {
1147     RenderElement* rootObject = document().documentElement() ? document().documentElement()->renderer() : nullptr;
1148     if (!rootObject)
1149         return false;
1150
1151     return rootObject->rendererForRootBackground().style().hasEntirelyFixedBackground();
1152 }
1153     
1154 LayoutRect RenderView::unextendedBackgroundRect() const
1155 {
1156     // FIXME: What is this? Need to patch for new columns?
1157     return unscaledDocumentRect();
1158 }
1159     
1160 LayoutRect RenderView::backgroundRect() const
1161 {
1162     // FIXME: New columns care about this?
1163     if (frameView().hasExtendedBackgroundRectForPainting())
1164         return frameView().extendedBackgroundRectForPainting();
1165
1166     return unextendedBackgroundRect();
1167 }
1168
1169 IntRect RenderView::documentRect() const
1170 {
1171     FloatRect overflowRect(unscaledDocumentRect());
1172     if (hasTransform())
1173         overflowRect = layer()->currentTransform().mapRect(overflowRect);
1174     return IntRect(overflowRect);
1175 }
1176
1177 int RenderView::viewHeight() const
1178 {
1179     int height = 0;
1180     if (!shouldUsePrintingLayout()) {
1181         height = frameView().layoutHeight();
1182         height = frameView().useFixedLayout() ? ceilf(style().effectiveZoom() * float(height)) : height;
1183     }
1184     return height;
1185 }
1186
1187 int RenderView::viewWidth() const
1188 {
1189     int width = 0;
1190     if (!shouldUsePrintingLayout()) {
1191         width = frameView().layoutWidth();
1192         width = frameView().useFixedLayout() ? ceilf(style().effectiveZoom() * float(width)) : width;
1193     }
1194     return width;
1195 }
1196
1197 int RenderView::viewLogicalHeight() const
1198 {
1199     int height = style().isHorizontalWritingMode() ? viewHeight() : viewWidth();
1200     return height;
1201 }
1202
1203 float RenderView::zoomFactor() const
1204 {
1205     return frameView().frame().pageZoomFactor();
1206 }
1207
1208 void RenderView::pushLayoutState(RenderObject& root)
1209 {
1210     ASSERT(m_layoutStateDisableCount == 0);
1211     ASSERT(m_layoutState == 0);
1212
1213     m_layoutState = std::make_unique<LayoutState>(root);
1214     pushLayoutStateForCurrentFlowThread(root);
1215 }
1216
1217 IntSize RenderView::viewportSizeForCSSViewportUnits() const
1218 {
1219     return frameView().viewportSizeForCSSViewportUnits();
1220 }
1221
1222 void RenderView::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
1223 {
1224     if (result.innerNode())
1225         return;
1226
1227     if (multiColumnFlowThread() && multiColumnFlowThread()->firstMultiColumnSet())
1228         return multiColumnFlowThread()->firstMultiColumnSet()->updateHitTestResult(result, point);
1229
1230     Node* node = document().documentElement();
1231     if (node) {
1232         result.setInnerNode(node);
1233         if (!result.innerNonSharedNode())
1234             result.setInnerNonSharedNode(node);
1235
1236         LayoutPoint adjustedPoint = point;
1237         offsetForContents(adjustedPoint);
1238
1239         result.setLocalPoint(adjustedPoint);
1240     }
1241 }
1242
1243 // FIXME: This function is obsolete and only used by embedded WebViews inside AppKit NSViews.
1244 // Do not add callers of this function!
1245 // The idea here is to take into account what object is moving the pagination point, and
1246 // thus choose the best place to chop it.
1247 void RenderView::setBestTruncatedAt(int y, RenderBoxModelObject* forRenderer, bool forcedBreak)
1248 {
1249     // Nobody else can set a page break once we have a forced break.
1250     if (m_legacyPrinting.m_forcedPageBreak)
1251         return;
1252
1253     // Forced breaks always win over unforced breaks.
1254     if (forcedBreak) {
1255         m_legacyPrinting.m_forcedPageBreak = true;
1256         m_legacyPrinting.m_bestTruncatedAt = y;
1257         return;
1258     }
1259
1260     // Prefer the widest object that tries to move the pagination point
1261     LayoutRect boundingBox = forRenderer->borderBoundingBox();
1262     if (boundingBox.width() > m_legacyPrinting.m_truncatorWidth) {
1263         m_legacyPrinting.m_truncatorWidth = boundingBox.width();
1264         m_legacyPrinting.m_bestTruncatedAt = y;
1265     }
1266 }
1267
1268 bool RenderView::usesCompositing() const
1269 {
1270     return m_compositor && m_compositor->inCompositingMode();
1271 }
1272
1273 RenderLayerCompositor& RenderView::compositor()
1274 {
1275     if (!m_compositor)
1276         m_compositor = std::make_unique<RenderLayerCompositor>(*this);
1277
1278     return *m_compositor;
1279 }
1280
1281 void RenderView::setIsInWindow(bool isInWindow)
1282 {
1283     if (m_compositor)
1284         m_compositor->setIsInWindow(isInWindow);
1285 }
1286
1287 void RenderView::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1288 {
1289     RenderBlockFlow::styleDidChange(diff, oldStyle);
1290     if (hasRenderNamedFlowThreads())
1291         flowThreadController().styleDidChange();
1292
1293     frameView().styleDidChange();
1294 }
1295
1296 bool RenderView::hasRenderNamedFlowThreads() const
1297 {
1298     return m_flowThreadController && m_flowThreadController->hasRenderNamedFlowThreads();
1299 }
1300
1301 bool RenderView::checkTwoPassLayoutForAutoHeightRegions() const
1302 {
1303     return hasRenderNamedFlowThreads() && m_flowThreadController->hasFlowThreadsWithAutoLogicalHeightRegions();
1304 }
1305
1306 FlowThreadController& RenderView::flowThreadController()
1307 {
1308     if (!m_flowThreadController)
1309         m_flowThreadController = std::make_unique<FlowThreadController>(this);
1310
1311     return *m_flowThreadController;
1312 }
1313
1314 void RenderView::pushLayoutStateForCurrentFlowThread(const RenderObject& object)
1315 {
1316     if (!m_flowThreadController)
1317         return;
1318
1319     RenderFlowThread* currentFlowThread = object.flowThreadContainingBlock();
1320     if (!currentFlowThread)
1321         return;
1322
1323     m_layoutState->setCurrentRenderFlowThread(currentFlowThread);
1324
1325     currentFlowThread->pushFlowThreadLayoutState(object);
1326 }
1327
1328 void RenderView::popLayoutStateForCurrentFlowThread()
1329 {
1330     if (!m_flowThreadController)
1331         return;
1332
1333     RenderFlowThread* currentFlowThread = m_layoutState->currentRenderFlowThread();
1334     if (!currentFlowThread)
1335         return;
1336
1337     currentFlowThread->popFlowThreadLayoutState();
1338 }
1339
1340 ImageQualityController& RenderView::imageQualityController()
1341 {
1342     if (!m_imageQualityController)
1343         m_imageQualityController = std::make_unique<ImageQualityController>(*this);
1344     return *m_imageQualityController;
1345 }
1346
1347 void RenderView::registerForVisibleInViewportCallback(RenderElement& renderer)
1348 {
1349     ASSERT(!m_visibleInViewportRenderers.contains(&renderer));
1350     m_visibleInViewportRenderers.add(&renderer);
1351 }
1352
1353 void RenderView::unregisterForVisibleInViewportCallback(RenderElement& renderer)
1354 {
1355     ASSERT(m_visibleInViewportRenderers.contains(&renderer));
1356     m_visibleInViewportRenderers.remove(&renderer);
1357 }
1358
1359 void RenderView::updateVisibleViewportRect(const IntRect& visibleRect)
1360 {
1361     resumePausedImageAnimationsIfNeeded(visibleRect);
1362
1363     for (auto* renderer : m_visibleInViewportRenderers)
1364         renderer->visibleInViewportStateChanged(visibleRect.intersects(enclosingIntRect(renderer->absoluteClippedOverflowRect())) ? RenderElement::VisibleInViewport : RenderElement::NotVisibleInViewport);
1365 }
1366
1367 void RenderView::addRendererWithPausedImageAnimations(RenderElement& renderer)
1368 {
1369     if (renderer.hasPausedImageAnimations()) {
1370         ASSERT(m_renderersWithPausedImageAnimation.contains(&renderer));
1371         return;
1372     }
1373     renderer.setHasPausedImageAnimations(true);
1374     m_renderersWithPausedImageAnimation.add(&renderer);
1375 }
1376
1377 void RenderView::removeRendererWithPausedImageAnimations(RenderElement& renderer)
1378 {
1379     ASSERT(renderer.hasPausedImageAnimations());
1380     ASSERT(m_renderersWithPausedImageAnimation.contains(&renderer));
1381
1382     renderer.setHasPausedImageAnimations(false);
1383     m_renderersWithPausedImageAnimation.remove(&renderer);
1384 }
1385
1386 void RenderView::resumePausedImageAnimationsIfNeeded(IntRect visibleRect)
1387 {
1388     Vector<RenderElement*, 10> toRemove;
1389     for (auto* renderer : m_renderersWithPausedImageAnimation) {
1390         if (renderer->repaintForPausedImageAnimationsIfNeeded(visibleRect))
1391             toRemove.append(renderer);
1392     }
1393     for (auto& renderer : toRemove)
1394         removeRendererWithPausedImageAnimations(*renderer);
1395 }
1396
1397 RenderView::RepaintRegionAccumulator::RepaintRegionAccumulator(RenderView* view)
1398     : m_rootView(view ? view->document().topDocument().renderView() : nullptr)
1399 {
1400     if (!m_rootView)
1401         return;
1402     m_wasAccumulatingRepaintRegion = !!m_rootView->m_accumulatedRepaintRegion;
1403     if (!m_wasAccumulatingRepaintRegion)
1404         m_rootView->m_accumulatedRepaintRegion = std::make_unique<Region>();
1405 }
1406
1407 RenderView::RepaintRegionAccumulator::~RepaintRegionAccumulator()
1408 {
1409     if (!m_rootView)
1410         return;
1411     if (m_wasAccumulatingRepaintRegion)
1412         return;
1413     m_rootView->flushAccumulatedRepaintRegion();
1414 }
1415
1416 unsigned RenderView::pageNumberForBlockProgressionOffset(int offset) const
1417 {
1418     int columnNumber = 0;
1419     const Pagination& pagination = frameView().frame().page()->pagination();
1420     if (pagination.mode == Pagination::Unpaginated)
1421         return columnNumber;
1422     
1423     bool progressionIsInline = false;
1424     bool progressionIsReversed = false;
1425     
1426     if (multiColumnFlowThread()) {
1427         progressionIsInline = multiColumnFlowThread()->progressionIsInline();
1428         progressionIsReversed = multiColumnFlowThread()->progressionIsReversed();
1429     } else
1430         return columnNumber;
1431     
1432     if (!progressionIsInline) {
1433         if (!progressionIsReversed)
1434             columnNumber = (pagination.pageLength + pagination.gap - offset) / (pagination.pageLength + pagination.gap);
1435         else
1436             columnNumber = offset / (pagination.pageLength + pagination.gap);
1437     }
1438
1439     return columnNumber;
1440 }
1441
1442 unsigned RenderView::pageCount() const
1443 {
1444     const Pagination& pagination = frameView().frame().page()->pagination();
1445     if (pagination.mode == Pagination::Unpaginated)
1446         return 0;
1447     
1448     if (multiColumnFlowThread() && multiColumnFlowThread()->firstMultiColumnSet())
1449         return multiColumnFlowThread()->firstMultiColumnSet()->columnCount();
1450
1451     return 0;
1452 }
1453
1454 #if ENABLE(CSS_SCROLL_SNAP)
1455 void RenderView::registerBoxWithScrollSnapCoordinates(const RenderBox& box)
1456 {
1457     m_boxesWithScrollSnapCoordinates.add(&box);
1458 }
1459
1460 void RenderView::unregisterBoxWithScrollSnapCoordinates(const RenderBox& box)
1461 {
1462     m_boxesWithScrollSnapCoordinates.remove(&box);
1463 }
1464 #endif
1465
1466 } // namespace WebCore