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