Replace PassRef with Ref/Ref&& across the board.
[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() ? 0 : 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(0)
100     , m_selectionUnsplitEnd(0)
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(0)
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().isPercent()
337                 || box.style().logicalMinHeight().isPercent()
338                 || box.style().logicalMaxHeight().isPercent()
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 0 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 0 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 0;
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     if (auto ownerElement = document().ownerElement()) {
623         RenderBox* ownerBox = ownerElement->renderBox();
624         if (!ownerBox)
625             return;
626         LayoutRect viewRect = this->viewRect();
627 #if PLATFORM(IOS)
628         // Don't clip using the visible rect since clipping is handled at a higher level on iPhone.
629         LayoutRect adjustedRect = repaintRect;
630 #else
631         LayoutRect adjustedRect = intersection(repaintRect, viewRect);
632 #endif
633         adjustedRect.moveBy(-viewRect.location());
634         adjustedRect.moveBy(ownerBox->contentBoxRect().location());
635         ownerBox->repaintRectangle(adjustedRect);
636         return;
637     }
638
639     frameView().addTrackedRepaintRect(snapRectToDevicePixels(repaintRect, document().deviceScaleFactor()));
640
641     // FIXME: convert all repaint rect dependencies to FloatRect.
642     IntRect enclosingRect = enclosingIntRect(repaintRect);
643     if (!m_accumulatedRepaintRegion) {
644         frameView().repaintContentRectangle(enclosingRect);
645         return;
646     }
647     m_accumulatedRepaintRegion->unite(enclosingRect);
648
649     // Region will get slow if it gets too complex. Merge all rects so far to bounds if this happens.
650     // FIXME: Maybe there should be a region type that does this automatically.
651     static const unsigned maximumRepaintRegionGridSize = 16 * 16;
652     if (m_accumulatedRepaintRegion->gridSize() > maximumRepaintRegionGridSize)
653         m_accumulatedRepaintRegion = std::make_unique<Region>(m_accumulatedRepaintRegion->bounds());
654 }
655
656 void RenderView::flushAccumulatedRepaintRegion() const
657 {
658     ASSERT(!document().ownerElement());
659     ASSERT(m_accumulatedRepaintRegion);
660     auto repaintRects = m_accumulatedRepaintRegion->rects();
661     for (auto& rect : repaintRects)
662         frameView().repaintContentRectangle(rect);
663     m_accumulatedRepaintRegion = nullptr;
664 }
665
666 void RenderView::repaintViewAndCompositedLayers()
667 {
668     repaintRootContents();
669
670     RenderLayerCompositor& compositor = this->compositor();
671     if (compositor.inCompositingMode())
672         compositor.repaintCompositedLayers();
673 }
674
675 LayoutRect RenderView::visualOverflowRect() const
676 {
677     if (frameView().paintsEntireContents())
678         return layoutOverflowRect();
679
680     return RenderBlockFlow::visualOverflowRect();
681 }
682
683 void RenderView::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
684 {
685     // If a container was specified, and was not 0 or the RenderView,
686     // then we should have found it by now.
687     ASSERT_ARG(repaintContainer, !repaintContainer || repaintContainer == this);
688
689     if (printing())
690         return;
691
692     if (style().isFlippedBlocksWritingMode()) {
693         // We have to flip by hand since the view's logical height has not been determined.  We
694         // can use the viewport width and height.
695         if (style().isHorizontalWritingMode())
696             rect.setY(viewHeight() - rect.maxY());
697         else
698             rect.setX(viewWidth() - rect.maxX());
699     }
700
701     if (fixed) {
702 #if PLATFORM(IOS)
703         rect.move(fixedPositionOffset(frameView()));
704 #else
705         rect.move(frameView().scrollOffsetForFixedPosition());
706 #endif
707     }
708         
709     // Apply our transform if we have one (because of full page zooming).
710     if (!repaintContainer && layer() && layer()->transform())
711         rect = LayoutRect(layer()->transform()->mapRect(snapRectToDevicePixels(rect, document().deviceScaleFactor())));
712 }
713
714 bool RenderView::isScrollableOrRubberbandableBox() const
715 {
716     // The main frame might be allowed to rubber-band even if there is no content to scroll to. This is unique to
717     // the main frame; subframes and overflow areas have to have content that can be scrolled to in order to rubber-band.
718     FrameView::Scrollability defineScrollable = frame().ownerElement() ? FrameView::Scrollability::Scrollable : FrameView::Scrollability::ScrollableOrRubberbandable;
719     return frameView().isScrollable(defineScrollable);
720 }
721
722 void RenderView::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
723 {
724     rects.append(snappedIntRect(accumulatedOffset, layer()->size()));
725 }
726
727 void RenderView::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
728 {
729     if (wasFixed)
730         *wasFixed = false;
731     quads.append(FloatRect(FloatPoint(), layer()->size()));
732 }
733
734 static RenderObject* rendererAfterPosition(RenderObject* object, unsigned offset)
735 {
736     if (!object)
737         return 0;
738
739     RenderObject* child = object->childAt(offset);
740     return child ? child : object->nextInPreOrderAfterChildren();
741 }
742
743 IntRect RenderView::selectionBounds(bool clipToVisibleContent) const
744 {
745     LayoutRect selRect = subtreeSelectionBounds(*this, clipToVisibleContent);
746
747     if (hasRenderNamedFlowThreads()) {
748         for (auto* namedFlowThread : *m_flowThreadController->renderNamedFlowThreadList()) {
749             LayoutRect currRect = subtreeSelectionBounds(*namedFlowThread, clipToVisibleContent);
750             selRect.unite(currRect);
751         }
752     }
753
754     return snappedIntRect(selRect);
755 }
756
757 LayoutRect RenderView::subtreeSelectionBounds(const SelectionSubtreeRoot& root, bool clipToVisibleContent) const
758 {
759     typedef HashMap<RenderObject*, std::unique_ptr<RenderSelectionInfo>> SelectionMap;
760     SelectionMap selectedObjects;
761
762     RenderObject* os = root.selectionData().selectionStart();
763     RenderObject* stop = rendererAfterPosition(root.selectionData().selectionEnd(), root.selectionData().selectionEndPos());
764     SelectionIterator selectionIterator(os);
765     while (os && os != stop) {
766         if ((os->canBeSelectionLeaf() || os == root.selectionData().selectionStart() || os == root.selectionData().selectionEnd()) && os->selectionState() != SelectionNone) {
767             // Blocks are responsible for painting line gaps and margin gaps. They must be examined as well.
768             selectedObjects.set(os, std::make_unique<RenderSelectionInfo>(*os, clipToVisibleContent));
769             RenderBlock* cb = os->containingBlock();
770             while (cb && !cb->isRenderView()) {
771                 std::unique_ptr<RenderSelectionInfo>& blockInfo = selectedObjects.add(cb, nullptr).iterator->value;
772                 if (blockInfo)
773                     break;
774                 blockInfo = std::make_unique<RenderSelectionInfo>(*cb, clipToVisibleContent);
775                 cb = cb->containingBlock();
776             }
777         }
778
779         os = selectionIterator.next();
780     }
781
782     // Now create a single bounding box rect that encloses the whole selection.
783     LayoutRect selRect;
784     SelectionMap::iterator end = selectedObjects.end();
785     for (SelectionMap::iterator i = selectedObjects.begin(); i != end; ++i) {
786         RenderSelectionInfo* info = i->value.get();
787         // RenderSelectionInfo::rect() is in the coordinates of the repaintContainer, so map to page coordinates.
788         LayoutRect currRect = info->rect();
789         if (RenderLayerModelObject* repaintContainer = info->repaintContainer()) {
790             FloatQuad absQuad = repaintContainer->localToAbsoluteQuad(FloatRect(currRect));
791             currRect = absQuad.enclosingBoundingBox(); 
792         }
793         selRect.unite(currRect);
794     }
795     return selRect;
796 }
797
798 void RenderView::repaintSelection() const
799 {
800     repaintSubtreeSelection(*this);
801
802     if (hasRenderNamedFlowThreads()) {
803         for (auto* namedFlowThread : *m_flowThreadController->renderNamedFlowThreadList())
804             repaintSubtreeSelection(*namedFlowThread);
805     }
806 }
807
808 void RenderView::repaintSubtreeSelection(const SelectionSubtreeRoot& root) const
809 {
810     HashSet<RenderBlock*> processedBlocks;
811
812     RenderObject* end = rendererAfterPosition(root.selectionData().selectionEnd(), root.selectionData().selectionEndPos());
813     SelectionIterator selectionIterator(root.selectionData().selectionStart());
814     for (RenderObject* o = selectionIterator.current(); o && o != end; o = selectionIterator.next()) {
815         if (!o->canBeSelectionLeaf() && o != root.selectionData().selectionStart() && o != root.selectionData().selectionEnd())
816             continue;
817         if (o->selectionState() == SelectionNone)
818             continue;
819
820         RenderSelectionInfo(*o, true).repaint();
821
822         // Blocks are responsible for painting line gaps and margin gaps. They must be examined as well.
823         for (RenderBlock* block = o->containingBlock(); block && !block->isRenderView(); block = block->containingBlock()) {
824             if (!processedBlocks.add(block).isNewEntry)
825                 break;
826             RenderSelectionInfo(*block, true).repaint();
827         }
828     }
829 }
830
831 // Compositing layer dimensions take outline size into account, so we have to recompute layer
832 // bounds when it changes.
833 // FIXME: This is ugly; it would be nice to have a better way to do this.
834 void RenderView::setMaximalOutlineSize(int o)
835 {
836     if (o != m_maximalOutlineSize) {
837         m_maximalOutlineSize = o;
838
839         // maximalOutlineSize affects compositing layer dimensions.
840         compositor().setCompositingLayersNeedRebuild();    // FIXME: this really just needs to be a geometry update.
841     }
842 }
843
844 void RenderView::setSelection(RenderObject* start, int startPos, RenderObject* end, int endPos, SelectionRepaintMode blockRepaintMode)
845 {
846     // Make sure both our start and end objects are defined.
847     // Check www.msnbc.com and try clicking around to find the case where this happened.
848     if ((start && !end) || (end && !start))
849         return;
850
851     bool caretChanged = m_selectionWasCaret != frame().selection().isCaret();
852     m_selectionWasCaret = frame().selection().isCaret();
853     // Just return if the selection hasn't changed.
854     if (m_selectionUnsplitStart == start && m_selectionUnsplitStartPos == startPos
855         && m_selectionUnsplitEnd == end && m_selectionUnsplitEndPos == endPos && !caretChanged) {
856         return;
857     }
858
859 #if ENABLE(SERVICE_CONTROLS)
860     // Clear the current rects and create a notifier for the new rects we are about to gather.
861     // The Notifier updates the Editor when it goes out of scope and is destroyed.
862     std::unique_ptr<SelectionRectGatherer::Notifier> rectNotifier = m_selectionRectGatherer.clearAndCreateNotifier();
863 #endif // ENABLE(SERVICE_CONTROLS)
864     // Set global positions for new selection.
865     m_selectionUnsplitStart = start;
866     m_selectionUnsplitStartPos = startPos;
867     m_selectionUnsplitEnd = end;
868     m_selectionUnsplitEndPos = endPos;
869
870     // If there is no RenderNamedFlowThreads we follow the regular selection.
871     if (!hasRenderNamedFlowThreads()) {
872         RenderSubtreesMap singleSubtreeMap;
873         singleSubtreeMap.set(this, SelectionSubtreeData(start, startPos, end, endPos));
874         updateSelectionForSubtrees(singleSubtreeMap, blockRepaintMode);
875         return;
876     }
877
878     splitSelectionBetweenSubtrees(start, startPos, end, endPos, blockRepaintMode);
879 }
880
881 void RenderView::splitSelectionBetweenSubtrees(const RenderObject* start, int startPos, const RenderObject* end, int endPos, SelectionRepaintMode blockRepaintMode)
882 {
883     // Compute the visible selection end points for each of the subtrees.
884     RenderSubtreesMap renderSubtreesMap;
885
886     SelectionSubtreeData initialSelection;
887     renderSubtreesMap.set(this, initialSelection);
888     for (auto* namedFlowThread : *flowThreadController().renderNamedFlowThreadList())
889         renderSubtreesMap.set(namedFlowThread, initialSelection);
890
891     if (start && end) {
892         Node* startNode = start->node();
893         Node* endNode = end->node();
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 void RenderView::clearSubtreeSelection(const SelectionSubtreeRoot& root, SelectionRepaintMode blockRepaintMode, OldSelectionData& oldSelectionData) const
947 {
948     // Record the old selected objects.  These will be used later
949     // when we compare against the new selected objects.
950     oldSelectionData.selectionStartPos = root.selectionData().selectionStartPos();
951     oldSelectionData.selectionEndPos = root.selectionData().selectionEndPos();
952     
953     // Blocks contain selected objects and fill gaps between them, either on the left, right, or in between lines and blocks.
954     // In order to get the repaint rect right, we have to examine left, middle, and right rects individually, since otherwise
955     // the union of those rects might remain the same even when changes have occurred.
956
957     RenderObject* os = root.selectionData().selectionStart();
958     RenderObject* stop = rendererAfterPosition(root.selectionData().selectionEnd(), root.selectionData().selectionEndPos());
959     SelectionIterator selectionIterator(os);
960     while (os && os != stop) {
961         if ((os->canBeSelectionLeaf() || os == root.selectionData().selectionStart() || os == root.selectionData().selectionEnd())
962             && os->selectionState() != SelectionNone) {
963             // Blocks are responsible for painting line gaps and margin gaps.  They must be examined as well.
964             oldSelectionData.selectedObjects.set(os, std::make_unique<RenderSelectionInfo>(*os, true));
965             if (blockRepaintMode == RepaintNewXOROld) {
966                 RenderBlock* cb = os->containingBlock();
967                 while (cb && !cb->isRenderView()) {
968                     std::unique_ptr<RenderBlockSelectionInfo>& blockInfo = oldSelectionData.selectedBlocks.add(cb, nullptr).iterator->value;
969                     if (blockInfo)
970                         break;
971                     blockInfo = std::make_unique<RenderBlockSelectionInfo>(*cb);
972                     cb = cb->containingBlock();
973                 }
974             }
975         }
976
977         os = selectionIterator.next();
978     }
979
980     for (auto* selectedObject : oldSelectionData.selectedObjects.keys())
981         selectedObject->setSelectionStateIfNeeded(SelectionNone);
982 }
983
984 void RenderView::applySubtreeSelection(const SelectionSubtreeRoot& root, SelectionRepaintMode blockRepaintMode, const OldSelectionData& oldSelectionData)
985 {
986     // Update the selection status of all objects between selectionStart and selectionEnd
987     if (root.selectionData().selectionStart() && root.selectionData().selectionStart() == root.selectionData().selectionEnd())
988         root.selectionData().selectionStart()->setSelectionStateIfNeeded(SelectionBoth);
989     else {
990         if (root.selectionData().selectionStart())
991             root.selectionData().selectionStart()->setSelectionStateIfNeeded(SelectionStart);
992         if (root.selectionData().selectionEnd())
993             root.selectionData().selectionEnd()->setSelectionStateIfNeeded(SelectionEnd);
994     }
995
996     RenderObject* o = root.selectionData().selectionStart();
997     RenderObject* stop = rendererAfterPosition(root.selectionData().selectionEnd(), root.selectionData().selectionEndPos());
998     SelectionIterator selectionIterator(o);
999     
1000     while (o && o != stop) {
1001         if (o != root.selectionData().selectionStart() && o != root.selectionData().selectionEnd() && o->canBeSelectionLeaf())
1002             o->setSelectionStateIfNeeded(SelectionInside);
1003         o = selectionIterator.next();
1004     }
1005
1006     if (blockRepaintMode != RepaintNothing)
1007         layer()->clearBlockSelectionGapsBounds();
1008
1009     // Now that the selection state has been updated for the new objects, walk them again and
1010     // put them in the new objects list.
1011     SelectedObjectMap newSelectedObjects;
1012     SelectedBlockMap newSelectedBlocks;
1013     o = root.selectionData().selectionStart();
1014     selectionIterator = SelectionIterator(o);
1015     while (o && o != stop) {
1016         if ((o->canBeSelectionLeaf() || o == root.selectionData().selectionStart() || o == root.selectionData().selectionEnd()) && o->selectionState() != SelectionNone) {
1017             std::unique_ptr<RenderSelectionInfo> selectionInfo = std::make_unique<RenderSelectionInfo>(*o, true);
1018
1019 #if ENABLE(SERVICE_CONTROLS)
1020             for (auto& rect : selectionInfo->collectedSelectionRects())
1021                 m_selectionRectGatherer.addRect(selectionInfo->repaintContainer(), rect);
1022             if (!o->isTextOrLineBreak())
1023                 m_selectionRectGatherer.setTextOnly(false);
1024 #endif
1025
1026             newSelectedObjects.set(o, WTF::move(selectionInfo));
1027
1028             RenderBlock* cb = o->containingBlock();
1029             while (cb && !cb->isRenderView()) {
1030                 std::unique_ptr<RenderBlockSelectionInfo>& blockInfo = newSelectedBlocks.add(cb, nullptr).iterator->value;
1031                 if (blockInfo)
1032                     break;
1033                 blockInfo = std::make_unique<RenderBlockSelectionInfo>(*cb);
1034                 cb = cb->containingBlock();
1035
1036 #if ENABLE(SERVICE_CONTROLS)
1037                 m_selectionRectGatherer.addGapRects(blockInfo->repaintContainer(), blockInfo->rects());
1038 #endif
1039             }
1040         }
1041
1042         o = selectionIterator.next();
1043     }
1044
1045     if (blockRepaintMode == RepaintNothing)
1046         return;
1047
1048     // Have any of the old selected objects changed compared to the new selection?
1049     for (const auto& selectedObjectInfo : oldSelectionData.selectedObjects) {
1050         RenderObject* obj = selectedObjectInfo.key;
1051         RenderSelectionInfo* newInfo = newSelectedObjects.get(obj);
1052         RenderSelectionInfo* oldInfo = selectedObjectInfo.value.get();
1053         if (!newInfo || oldInfo->rect() != newInfo->rect() || oldInfo->state() != newInfo->state()
1054             || (root.selectionData().selectionStart() == obj && oldSelectionData.selectionStartPos != root.selectionData().selectionStartPos())
1055             || (root.selectionData().selectionEnd() == obj && oldSelectionData.selectionEndPos != root.selectionData().selectionEndPos())) {
1056             oldInfo->repaint();
1057             if (newInfo) {
1058                 newInfo->repaint();
1059                 newSelectedObjects.remove(obj);
1060             }
1061         }
1062     }
1063
1064     // Any new objects that remain were not found in the old objects dict, and so they need to be updated.
1065     for (const auto& selectedObjectInfo : newSelectedObjects)
1066         selectedObjectInfo.value->repaint();
1067
1068     // Have any of the old blocks changed?
1069     for (const auto& selectedBlockInfo : oldSelectionData.selectedBlocks) {
1070         const RenderBlock* block = selectedBlockInfo.key;
1071         RenderBlockSelectionInfo* newInfo = newSelectedBlocks.get(block);
1072         RenderBlockSelectionInfo* oldInfo = selectedBlockInfo.value.get();
1073         if (!newInfo || oldInfo->rects() != newInfo->rects() || oldInfo->state() != newInfo->state()) {
1074             oldInfo->repaint();
1075             if (newInfo) {
1076                 newInfo->repaint();
1077                 newSelectedBlocks.remove(block);
1078             }
1079         }
1080     }
1081
1082     // Any new blocks that remain were not found in the old blocks dict, and so they need to be updated.
1083     for (const auto& selectedBlockInfo : newSelectedBlocks)
1084         selectedBlockInfo.value->repaint();
1085 }
1086
1087 void RenderView::getSelection(RenderObject*& startRenderer, int& startOffset, RenderObject*& endRenderer, int& endOffset) const
1088 {
1089     startRenderer = m_selectionUnsplitStart;
1090     startOffset = m_selectionUnsplitStartPos;
1091     endRenderer = m_selectionUnsplitEnd;
1092     endOffset = m_selectionUnsplitEndPos;
1093 }
1094
1095 void RenderView::clearSelection()
1096 {
1097     layer()->repaintBlockSelectionGaps();
1098     setSelection(0, -1, 0, -1, RepaintNewMinusOld);
1099 }
1100
1101 bool RenderView::printing() const
1102 {
1103     return document().printing();
1104 }
1105
1106 bool RenderView::shouldUsePrintingLayout() const
1107 {
1108     if (!printing())
1109         return false;
1110     return frameView().frame().shouldUsePrintingLayout();
1111 }
1112
1113 LayoutRect RenderView::viewRect() const
1114 {
1115     if (shouldUsePrintingLayout())
1116         return LayoutRect(LayoutPoint(), size());
1117     return frameView().visibleContentRect(ScrollableArea::LegacyIOSDocumentVisibleRect);
1118 }
1119
1120 IntRect RenderView::unscaledDocumentRect() const
1121 {
1122     LayoutRect overflowRect(layoutOverflowRect());
1123     flipForWritingMode(overflowRect);
1124     return snappedIntRect(overflowRect);
1125 }
1126
1127 bool RenderView::rootBackgroundIsEntirelyFixed() const
1128 {
1129     RenderElement* rootObject = document().documentElement() ? document().documentElement()->renderer() : 0;
1130     if (!rootObject)
1131         return false;
1132
1133     return rootObject->rendererForRootBackground().hasEntirelyFixedBackground();
1134 }
1135     
1136 LayoutRect RenderView::unextendedBackgroundRect(RenderBox*) const
1137 {
1138     // FIXME: What is this? Need to patch for new columns?
1139     return unscaledDocumentRect();
1140 }
1141     
1142 LayoutRect RenderView::backgroundRect(RenderBox* backgroundRenderer) const
1143 {
1144     // FIXME: New columns care about this?
1145     if (frameView().hasExtendedBackgroundRectForPainting())
1146         return frameView().extendedBackgroundRectForPainting();
1147
1148     return unextendedBackgroundRect(backgroundRenderer);
1149 }
1150
1151 IntRect RenderView::documentRect() const
1152 {
1153     FloatRect overflowRect(unscaledDocumentRect());
1154     if (hasTransform())
1155         overflowRect = layer()->currentTransform().mapRect(overflowRect);
1156     return IntRect(overflowRect);
1157 }
1158
1159 int RenderView::viewHeight() const
1160 {
1161     int height = 0;
1162     if (!shouldUsePrintingLayout()) {
1163         height = frameView().layoutHeight();
1164         height = frameView().useFixedLayout() ? ceilf(style().effectiveZoom() * float(height)) : height;
1165     }
1166     return height;
1167 }
1168
1169 int RenderView::viewWidth() const
1170 {
1171     int width = 0;
1172     if (!shouldUsePrintingLayout()) {
1173         width = frameView().layoutWidth();
1174         width = frameView().useFixedLayout() ? ceilf(style().effectiveZoom() * float(width)) : width;
1175     }
1176     return width;
1177 }
1178
1179 int RenderView::viewLogicalHeight() const
1180 {
1181     int height = style().isHorizontalWritingMode() ? viewHeight() : viewWidth();
1182     return height;
1183 }
1184
1185 float RenderView::zoomFactor() const
1186 {
1187     return frameView().frame().pageZoomFactor();
1188 }
1189
1190 void RenderView::pushLayoutState(RenderObject& root)
1191 {
1192     ASSERT(m_layoutStateDisableCount == 0);
1193     ASSERT(m_layoutState == 0);
1194
1195     m_layoutState = std::make_unique<LayoutState>(root);
1196     pushLayoutStateForCurrentFlowThread(root);
1197 }
1198
1199 bool RenderView::shouldDisableLayoutStateForSubtree(RenderObject* renderer) const
1200 {
1201     RenderObject* o = renderer;
1202     while (o) {
1203         if (o->hasTransform() || o->hasReflection())
1204             return true;
1205         o = o->container();
1206     }
1207     return false;
1208 }
1209
1210 IntSize RenderView::viewportSizeForCSSViewportUnits() const
1211 {
1212     return frameView().viewportSizeForCSSViewportUnits();
1213 }
1214
1215 void RenderView::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
1216 {
1217     if (result.innerNode())
1218         return;
1219
1220     Node* node = document().documentElement();
1221     if (node) {
1222         result.setInnerNode(node);
1223         if (!result.innerNonSharedNode())
1224             result.setInnerNonSharedNode(node);
1225
1226         LayoutPoint adjustedPoint = point;
1227         offsetForContents(adjustedPoint);
1228
1229         result.setLocalPoint(adjustedPoint);
1230     }
1231 }
1232
1233 // FIXME: This function is obsolete and only used by embedded WebViews inside AppKit NSViews.
1234 // Do not add callers of this function!
1235 // The idea here is to take into account what object is moving the pagination point, and
1236 // thus choose the best place to chop it.
1237 void RenderView::setBestTruncatedAt(int y, RenderBoxModelObject* forRenderer, bool forcedBreak)
1238 {
1239     // Nobody else can set a page break once we have a forced break.
1240     if (m_legacyPrinting.m_forcedPageBreak)
1241         return;
1242
1243     // Forced breaks always win over unforced breaks.
1244     if (forcedBreak) {
1245         m_legacyPrinting.m_forcedPageBreak = true;
1246         m_legacyPrinting.m_bestTruncatedAt = y;
1247         return;
1248     }
1249
1250     // Prefer the widest object that tries to move the pagination point
1251     IntRect boundingBox = forRenderer->borderBoundingBox();
1252     if (boundingBox.width() > m_legacyPrinting.m_truncatorWidth) {
1253         m_legacyPrinting.m_truncatorWidth = boundingBox.width();
1254         m_legacyPrinting.m_bestTruncatedAt = y;
1255     }
1256 }
1257
1258 bool RenderView::usesCompositing() const
1259 {
1260     return m_compositor && m_compositor->inCompositingMode();
1261 }
1262
1263 RenderLayerCompositor& RenderView::compositor()
1264 {
1265     if (!m_compositor)
1266         m_compositor = std::make_unique<RenderLayerCompositor>(*this);
1267
1268     return *m_compositor;
1269 }
1270
1271 void RenderView::setIsInWindow(bool isInWindow)
1272 {
1273     if (m_compositor)
1274         m_compositor->setIsInWindow(isInWindow);
1275 }
1276
1277 void RenderView::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1278 {
1279     RenderBlockFlow::styleDidChange(diff, oldStyle);
1280     if (hasRenderNamedFlowThreads())
1281         flowThreadController().styleDidChange();
1282
1283     frameView().styleDidChange();
1284 }
1285
1286 bool RenderView::hasRenderNamedFlowThreads() const
1287 {
1288     return m_flowThreadController && m_flowThreadController->hasRenderNamedFlowThreads();
1289 }
1290
1291 bool RenderView::checkTwoPassLayoutForAutoHeightRegions() const
1292 {
1293     return hasRenderNamedFlowThreads() && m_flowThreadController->hasFlowThreadsWithAutoLogicalHeightRegions();
1294 }
1295
1296 FlowThreadController& RenderView::flowThreadController()
1297 {
1298     if (!m_flowThreadController)
1299         m_flowThreadController = std::make_unique<FlowThreadController>(this);
1300
1301     return *m_flowThreadController;
1302 }
1303
1304 void RenderView::pushLayoutStateForCurrentFlowThread(const RenderObject& object)
1305 {
1306     if (!m_flowThreadController)
1307         return;
1308
1309     RenderFlowThread* currentFlowThread = object.flowThreadContainingBlock();
1310     if (!currentFlowThread)
1311         return;
1312
1313     m_layoutState->setCurrentRenderFlowThread(currentFlowThread);
1314
1315     currentFlowThread->pushFlowThreadLayoutState(object);
1316 }
1317
1318 void RenderView::popLayoutStateForCurrentFlowThread()
1319 {
1320     if (!m_flowThreadController)
1321         return;
1322
1323     RenderFlowThread* currentFlowThread = m_layoutState->currentRenderFlowThread();
1324     if (!currentFlowThread)
1325         return;
1326
1327     currentFlowThread->popFlowThreadLayoutState();
1328 }
1329
1330 ImageQualityController& RenderView::imageQualityController()
1331 {
1332     if (!m_imageQualityController)
1333         m_imageQualityController = std::make_unique<ImageQualityController>(*this);
1334     return *m_imageQualityController;
1335 }
1336
1337 void RenderView::addRendererWithPausedImageAnimations(RenderElement& renderer)
1338 {
1339     if (renderer.hasPausedImageAnimations()) {
1340         ASSERT(m_renderersWithPausedImageAnimation.contains(&renderer));
1341         return;
1342     }
1343     renderer.setHasPausedImageAnimations(true);
1344     m_renderersWithPausedImageAnimation.add(&renderer);
1345 }
1346
1347 void RenderView::removeRendererWithPausedImageAnimations(RenderElement& renderer)
1348 {
1349     ASSERT(renderer.hasPausedImageAnimations());
1350     ASSERT(m_renderersWithPausedImageAnimation.contains(&renderer));
1351
1352     renderer.setHasPausedImageAnimations(false);
1353     m_renderersWithPausedImageAnimation.remove(&renderer);
1354 }
1355
1356 void RenderView::resumePausedImageAnimationsIfNeeded()
1357 {
1358     auto visibleRect = frameView().windowToContents(frameView().windowClipRect());
1359     Vector<RenderElement*, 10> toRemove;
1360     for (auto* renderer : m_renderersWithPausedImageAnimation) {
1361         if (renderer->repaintForPausedImageAnimationsIfNeeded(visibleRect))
1362             toRemove.append(renderer);
1363     }
1364     for (auto& renderer : toRemove)
1365         removeRendererWithPausedImageAnimations(*renderer);
1366 }
1367
1368 RenderView::RepaintRegionAccumulator::RepaintRegionAccumulator(RenderView* view)
1369     : m_rootView(view ? view->document().topDocument().renderView() : nullptr)
1370 {
1371     if (!m_rootView)
1372         return;
1373     m_wasAccumulatingRepaintRegion = !!m_rootView->m_accumulatedRepaintRegion;
1374     if (!m_wasAccumulatingRepaintRegion)
1375         m_rootView->m_accumulatedRepaintRegion = std::make_unique<Region>();
1376 }
1377
1378 RenderView::RepaintRegionAccumulator::~RepaintRegionAccumulator()
1379 {
1380     if (!m_rootView)
1381         return;
1382     if (m_wasAccumulatingRepaintRegion)
1383         return;
1384     m_rootView->flushAccumulatedRepaintRegion();
1385 }
1386
1387 unsigned RenderView::pageNumberForBlockProgressionOffset(int offset) const
1388 {
1389     int columnNumber = 0;
1390     const Pagination& pagination = frameView().frame().page()->pagination();
1391     if (pagination.mode == Pagination::Unpaginated)
1392         return columnNumber;
1393     
1394     bool progressionIsInline = false;
1395     bool progressionIsReversed = false;
1396     
1397     if (multiColumnFlowThread()) {
1398         progressionIsInline = multiColumnFlowThread()->progressionIsInline();
1399         progressionIsReversed = multiColumnFlowThread()->progressionIsReversed();
1400     } else
1401         return columnNumber;
1402     
1403     if (!progressionIsInline) {
1404         if (!progressionIsReversed)
1405             columnNumber = (pagination.pageLength + pagination.gap - offset) / (pagination.pageLength + pagination.gap);
1406         else
1407             columnNumber = offset / (pagination.pageLength + pagination.gap);
1408     }
1409
1410     return columnNumber;
1411 }
1412
1413 unsigned RenderView::pageCount() const
1414 {
1415     const Pagination& pagination = frameView().frame().page()->pagination();
1416     if (pagination.mode == Pagination::Unpaginated)
1417         return 0;
1418     
1419     if (multiColumnFlowThread() && multiColumnFlowThread()->firstMultiColumnSet())
1420         return multiColumnFlowThread()->firstMultiColumnSet()->columnCount();
1421
1422     return 0;
1423 }
1424
1425 } // namespace WebCore