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