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