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