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