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