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