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