5d68406491fc3579f8d80886efe20ad32219bbee
[WebKit-https.git] / Source / WebCore / page / FrameView.cpp
1 /*
2  * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
3  *                     1999 Lars Knoll <knoll@kde.org>
4  *                     1999 Antti Koivisto <koivisto@kde.org>
5  *                     2000 Dirk Mueller <mueller@kde.org>
6  * Copyright (C) 2004-2008, 2013-2015 Apple Inc. All rights reserved.
7  *           (C) 2006 Graham Dennis (graham.dennis@gmail.com)
8  *           (C) 2006 Alexey Proskuryakov (ap@nypop.com)
9  * Copyright (C) 2009 Google Inc. All rights reserved.
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Library General Public
13  * License as published by the Free Software Foundation; either
14  * version 2 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Library General Public License for more details.
20  *
21  * You should have received a copy of the GNU Library General Public License
22  * along with this library; see the file COPYING.LIB.  If not, write to
23  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24  * Boston, MA 02110-1301, USA.
25  */
26
27 #include "config.h"
28 #include "FrameView.h"
29
30 #include "AXObjectCache.h"
31 #include "AnimationController.h"
32 #include "BackForwardController.h"
33 #include "CachedImage.h"
34 #include "CachedResourceLoader.h"
35 #include "Chrome.h"
36 #include "ChromeClient.h"
37 #include "DOMWindow.h"
38 #include "DebugPageOverlays.h"
39 #include "DocumentMarkerController.h"
40 #include "EventHandler.h"
41 #include "FloatRect.h"
42 #include "FocusController.h"
43 #include "FontLoader.h"
44 #include "FrameLoader.h"
45 #include "FrameLoaderClient.h"
46 #include "FrameSelection.h"
47 #include "FrameTree.h"
48 #include "GraphicsContext.h"
49 #include "HTMLBodyElement.h"
50 #include "HTMLDocument.h"
51 #include "HTMLFrameElement.h"
52 #include "HTMLFrameSetElement.h"
53 #include "HTMLNames.h"
54 #include "HTMLPlugInImageElement.h"
55 #include "ImageDocument.h"
56 #include "InspectorClient.h"
57 #include "InspectorController.h"
58 #include "InspectorInstrumentation.h"
59 #include "Logging.h"
60 #include "MainFrame.h"
61 #include "MemoryCache.h"
62 #include "MemoryPressureHandler.h"
63 #include "OverflowEvent.h"
64 #include "PageOverlayController.h"
65 #include "ProgressTracker.h"
66 #include "RenderEmbeddedObject.h"
67 #include "RenderFullScreen.h"
68 #include "RenderIFrame.h"
69 #include "RenderInline.h"
70 #include "RenderLayer.h"
71 #include "RenderLayerBacking.h"
72 #include "RenderLayerCompositor.h"
73 #include "RenderSVGRoot.h"
74 #include "RenderScrollbar.h"
75 #include "RenderScrollbarPart.h"
76 #include "RenderStyle.h"
77 #include "RenderText.h"
78 #include "RenderTheme.h"
79 #include "RenderView.h"
80 #include "RenderWidget.h"
81 #include "SVGDocument.h"
82 #include "SVGSVGElement.h"
83 #include "ScriptedAnimationController.h"
84 #include "ScrollAnimator.h"
85 #include "ScrollingCoordinator.h"
86 #include "Settings.h"
87 #include "StyleResolver.h"
88 #include "TextResourceDecoder.h"
89 #include "TextStream.h"
90 #include "TiledBacking.h"
91 #include "WheelEventTestTrigger.h"
92
93 #include <wtf/CurrentTime.h>
94 #include <wtf/Ref.h>
95 #include <wtf/TemporaryChange.h>
96
97 #if USE(COORDINATED_GRAPHICS)
98 #include "TiledBackingStore.h"
99 #endif
100
101 #if ENABLE(TEXT_AUTOSIZING)
102 #include "TextAutosizer.h"
103 #endif
104
105 #if ENABLE(CSS_SCROLL_SNAP)
106 #include "AxisScrollSnapOffsets.h"
107 #endif
108
109 #if PLATFORM(IOS)
110 #include "DocumentLoader.h"
111 #include "LegacyTileCache.h"
112 #endif
113
114 namespace WebCore {
115
116 using namespace HTMLNames;
117
118 double FrameView::sCurrentPaintTimeStamp = 0.0;
119
120 // The maximum number of updateEmbeddedObjects iterations that should be done before returning.
121 static const unsigned maxUpdateEmbeddedObjectsIterations = 2;
122
123 static RenderLayer::UpdateLayerPositionsFlags updateLayerPositionFlags(RenderLayer* layer, bool isRelayoutingSubtree, bool didFullRepaint)
124 {
125     RenderLayer::UpdateLayerPositionsFlags flags = RenderLayer::defaultFlags;
126     if (didFullRepaint) {
127         flags &= ~RenderLayer::CheckForRepaint;
128         flags |= RenderLayer::NeedsFullRepaintInBacking;
129     }
130     if (isRelayoutingSubtree && layer->enclosingPaginationLayer(RenderLayer::IncludeCompositedPaginatedLayers))
131         flags |= RenderLayer::UpdatePagination;
132     return flags;
133 }
134
135 Pagination::Mode paginationModeForRenderStyle(const RenderStyle& style)
136 {
137     EOverflow overflow = style.overflowY();
138     if (overflow != OPAGEDX && overflow != OPAGEDY)
139         return Pagination::Unpaginated;
140
141     bool isHorizontalWritingMode = style.isHorizontalWritingMode();
142     TextDirection textDirection = style.direction();
143     WritingMode writingMode = style.writingMode();
144
145     // paged-x always corresponds to LeftToRightPaginated or RightToLeftPaginated. If the WritingMode
146     // is horizontal, then we use TextDirection to choose between those options. If the WritingMode
147     // is vertical, then the direction of the verticality dictates the choice.
148     if (overflow == OPAGEDX) {
149         if ((isHorizontalWritingMode && textDirection == LTR) || writingMode == LeftToRightWritingMode)
150             return Pagination::LeftToRightPaginated;
151         return Pagination::RightToLeftPaginated;
152     }
153
154     // paged-y always corresponds to TopToBottomPaginated or BottomToTopPaginated. If the WritingMode
155     // is horizontal, then the direction of the horizontality dictates the choice. If the WritingMode
156     // is vertical, then we use TextDirection to choose between those options. 
157     if (writingMode == TopToBottomWritingMode || (!isHorizontalWritingMode && textDirection == RTL))
158         return Pagination::TopToBottomPaginated;
159     return Pagination::BottomToTopPaginated;
160 }
161
162 FrameView::FrameView(Frame& frame)
163     : m_frame(frame)
164     , m_canHaveScrollbars(true)
165     , m_layoutTimer(*this, &FrameView::layoutTimerFired)
166     , m_layoutRoot(nullptr)
167     , m_layoutPhase(OutsideLayout)
168     , m_inSynchronousPostLayout(false)
169     , m_postLayoutTasksTimer(*this, &FrameView::postLayoutTimerFired)
170     , m_updateEmbeddedObjectsTimer(*this, &FrameView::updateEmbeddedObjectsTimerFired)
171     , m_isTransparent(false)
172     , m_baseBackgroundColor(Color::white)
173     , m_mediaType("screen")
174     , m_overflowStatusDirty(true)
175     , m_viewportRenderer(nullptr)
176     , m_wasScrolledByUser(false)
177     , m_inProgrammaticScroll(false)
178     , m_safeToPropagateScrollToParent(true)
179     , m_delayedScrollEventTimer(*this, &FrameView::delayedScrollEventTimerFired)
180     , m_isTrackingRepaints(false)
181     , m_shouldUpdateWhileOffscreen(true)
182     , m_exposedRect(FloatRect::infiniteRect())
183     , m_deferSetNeedsLayoutCount(0)
184     , m_setNeedsLayoutWasDeferred(false)
185     , m_speculativeTilingEnabled(false)
186     , m_speculativeTilingEnableTimer(*this, &FrameView::speculativeTilingEnableTimerFired)
187 #if PLATFORM(IOS)
188     , m_useCustomFixedPositionLayoutRect(false)
189     , m_useCustomSizeForResizeEvent(false)
190     , m_horizontalVelocity(0)
191     , m_verticalVelocity(0)
192     , m_scaleChangeRate(0)
193     , m_lastVelocityUpdateTime(0)
194 #endif
195     , m_hasOverrideViewportSize(false)
196     , m_shouldAutoSize(false)
197     , m_inAutoSize(false)
198     , m_didRunAutosize(false)
199     , m_autoSizeFixedMinimumHeight(0)
200     , m_headerHeight(0)
201     , m_footerHeight(0)
202     , m_milestonesPendingPaint(0)
203     , m_visualUpdatesAllowedByClient(true)
204     , m_hasFlippedBlockRenderers(false)
205     , m_scrollPinningBehavior(DoNotPin)
206 {
207     init();
208
209 #if ENABLE(RUBBER_BANDING)
210     ScrollElasticity verticalElasticity = ScrollElasticityNone;
211     ScrollElasticity horizontalElasticity = ScrollElasticityNone;
212     if (m_frame->isMainFrame()) {
213         verticalElasticity = m_frame->page() ? m_frame->page()->verticalScrollElasticity() : ScrollElasticityAllowed;
214         horizontalElasticity = m_frame->page() ? m_frame->page()->horizontalScrollElasticity() : ScrollElasticityAllowed;
215     } else if (m_frame->settings().rubberBandingForSubScrollableRegionsEnabled()) {
216         verticalElasticity = ScrollElasticityAutomatic;
217         horizontalElasticity = ScrollElasticityAutomatic;
218     }
219
220     ScrollableArea::setVerticalScrollElasticity(verticalElasticity);
221     ScrollableArea::setHorizontalScrollElasticity(horizontalElasticity);
222 #endif
223 }
224
225 Ref<FrameView> FrameView::create(Frame& frame)
226 {
227     Ref<FrameView> view = adoptRef(*new FrameView(frame));
228     view->show();
229     return view;
230 }
231
232 Ref<FrameView> FrameView::create(Frame& frame, const IntSize& initialSize)
233 {
234     Ref<FrameView> view = adoptRef(*new FrameView(frame));
235     view->Widget::setFrameRect(IntRect(view->location(), initialSize));
236     view->show();
237     return view;
238 }
239
240 FrameView::~FrameView()
241 {
242     if (m_postLayoutTasksTimer.isActive())
243         m_postLayoutTasksTimer.stop();
244     
245     removeFromAXObjectCache();
246     resetScrollbars();
247
248     // Custom scrollbars should already be destroyed at this point
249     ASSERT(!horizontalScrollbar() || !horizontalScrollbar()->isCustomScrollbar());
250     ASSERT(!verticalScrollbar() || !verticalScrollbar()->isCustomScrollbar());
251
252     setHasHorizontalScrollbar(false); // Remove native scrollbars now before we lose the connection to the HostWindow.
253     setHasVerticalScrollbar(false);
254     
255     ASSERT(!m_scrollCorner);
256
257     ASSERT(frame().view() != this || !frame().contentRenderer());
258 }
259
260 void FrameView::reset()
261 {
262     m_cannotBlitToWindow = false;
263     m_isOverlapped = false;
264     m_contentIsOpaque = false;
265     m_layoutTimer.stop();
266     m_layoutRoot = nullptr;
267     m_delayedLayout = false;
268     m_needsFullRepaint = true;
269     m_layoutSchedulingEnabled = true;
270     m_layoutPhase = OutsideLayout;
271     m_inSynchronousPostLayout = false;
272     m_layoutCount = 0;
273     m_nestedLayoutCount = 0;
274     m_postLayoutTasksTimer.stop();
275     m_updateEmbeddedObjectsTimer.stop();
276     m_firstLayout = true;
277     m_firstLayoutCallbackPending = false;
278     m_wasScrolledByUser = false;
279     m_safeToPropagateScrollToParent = true;
280     m_delayedScrollEventTimer.stop();
281     m_lastViewportSize = IntSize();
282     m_lastZoomFactor = 1.0f;
283     m_isTrackingRepaints = false;
284     m_trackedRepaintRects.clear();
285     m_lastPaintTime = 0;
286     m_paintBehavior = PaintBehaviorNormal;
287     m_isPainting = false;
288     m_visuallyNonEmptyCharacterCount = 0;
289     m_visuallyNonEmptyPixelCount = 0;
290     m_isVisuallyNonEmpty = false;
291     m_firstVisuallyNonEmptyLayoutCallbackPending = true;
292     m_maintainScrollPositionAnchor = nullptr;
293     m_throttledTimers.clear();
294 }
295
296 void FrameView::removeFromAXObjectCache()
297 {
298     if (AXObjectCache* cache = axObjectCache()) {
299         if (HTMLFrameOwnerElement* owner = frame().ownerElement())
300             cache->childrenChanged(owner->renderer());
301         cache->remove(this);
302     }
303 }
304
305 void FrameView::resetScrollbars()
306 {
307     // Reset the document's scrollbars back to our defaults before we yield the floor.
308     m_firstLayout = true;
309     setScrollbarsSuppressed(true);
310     if (m_canHaveScrollbars)
311         setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
312     else
313         setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
314     setScrollbarsSuppressed(false);
315 }
316
317 void FrameView::resetScrollbarsAndClearContentsSize()
318 {
319     resetScrollbars();
320
321     setScrollbarsSuppressed(true);
322     setContentsSize(IntSize());
323     setScrollbarsSuppressed(false);
324 }
325
326 void FrameView::init()
327 {
328     reset();
329
330     m_margins = LayoutSize(-1, -1); // undefined
331     m_size = LayoutSize();
332
333     // Propagate the marginwidth/height and scrolling modes to the view.
334     Element* ownerElement = frame().ownerElement();
335     if (is<HTMLFrameElementBase>(ownerElement)) {
336         HTMLFrameElementBase& frameElement = downcast<HTMLFrameElementBase>(*ownerElement);
337         if (frameElement.scrollingMode() == ScrollbarAlwaysOff)
338             setCanHaveScrollbars(false);
339         LayoutUnit marginWidth = frameElement.marginWidth();
340         LayoutUnit marginHeight = frameElement.marginHeight();
341         if (marginWidth != -1)
342             setMarginWidth(marginWidth);
343         if (marginHeight != -1)
344             setMarginHeight(marginHeight);
345     }
346
347     Page* page = frame().page();
348     if (page && page->chrome().client().shouldPaintEntireContents())
349         setPaintsEntireContents(true);
350 }
351     
352 void FrameView::prepareForDetach()
353 {
354     detachCustomScrollbars();
355     // When the view is no longer associated with a frame, it needs to be removed from the ax object cache
356     // right now, otherwise it won't be able to reach the topDocument()'s axObject cache later.
357     removeFromAXObjectCache();
358
359     if (frame().page()) {
360         if (ScrollingCoordinator* scrollingCoordinator = frame().page()->scrollingCoordinator())
361             scrollingCoordinator->willDestroyScrollableArea(*this);
362     }
363 }
364
365 void FrameView::detachCustomScrollbars()
366 {
367     Scrollbar* horizontalBar = horizontalScrollbar();
368     if (horizontalBar && horizontalBar->isCustomScrollbar())
369         setHasHorizontalScrollbar(false);
370
371     Scrollbar* verticalBar = verticalScrollbar();
372     if (verticalBar && verticalBar->isCustomScrollbar())
373         setHasVerticalScrollbar(false);
374
375     m_scrollCorner = nullptr;
376 }
377
378 void FrameView::recalculateScrollbarOverlayStyle()
379 {
380     ScrollbarOverlayStyle oldOverlayStyle = scrollbarOverlayStyle();
381     WTF::Optional<ScrollbarOverlayStyle> clientOverlayStyle = frame().page() ? frame().page()->chrome().client().preferredScrollbarOverlayStyle() : ScrollbarOverlayStyleDefault;
382     if (clientOverlayStyle) {
383         if (clientOverlayStyle.value() != oldOverlayStyle)
384             setScrollbarOverlayStyle(clientOverlayStyle.value());
385         return;
386     }
387
388     ScrollbarOverlayStyle computedOverlayStyle = ScrollbarOverlayStyleDefault;
389
390     Color backgroundColor = documentBackgroundColor();
391     if (backgroundColor.isValid()) {
392         // Reduce the background color from RGB to a lightness value
393         // and determine which scrollbar style to use based on a lightness
394         // heuristic.
395         double hue, saturation, lightness;
396         backgroundColor.getHSL(hue, saturation, lightness);
397         if (lightness <= .5 && backgroundColor.alpha() > 0)
398             computedOverlayStyle = ScrollbarOverlayStyleLight;
399     }
400
401     if (oldOverlayStyle != computedOverlayStyle)
402         setScrollbarOverlayStyle(computedOverlayStyle);
403 }
404
405 void FrameView::clear()
406 {
407     setCanBlitOnScroll(true);
408     
409     reset();
410
411     setScrollbarsSuppressed(true);
412
413 #if PLATFORM(IOS)
414     // To avoid flashes of white, disable tile updates immediately when view is cleared at the beginning of a page load.
415     // Tiling will be re-enabled from UIKit via [WAKWindow setTilingMode:] when we have content to draw.
416     if (LegacyTileCache* tileCache = legacyTileCache())
417         tileCache->setTilingMode(LegacyTileCache::Disabled);
418 #endif
419 }
420
421 bool FrameView::didFirstLayout() const
422 {
423     return !m_firstLayout;
424 }
425
426 void FrameView::invalidateRect(const IntRect& rect)
427 {
428     if (!parent()) {
429         if (HostWindow* window = hostWindow())
430             window->invalidateContentsAndRootView(rect);
431         return;
432     }
433
434     RenderWidget* renderer = frame().ownerRenderer();
435     if (!renderer)
436         return;
437
438     IntRect repaintRect = rect;
439     repaintRect.move(renderer->borderLeft() + renderer->paddingLeft(),
440                      renderer->borderTop() + renderer->paddingTop());
441     renderer->repaintRectangle(repaintRect);
442 }
443
444 void FrameView::setFrameRect(const IntRect& newRect)
445 {
446     IntRect oldRect = frameRect();
447     if (newRect == oldRect)
448         return;
449
450 #if ENABLE(TEXT_AUTOSIZING)
451     // Autosized font sizes depend on the width of the viewing area.
452     if (newRect.width() != oldRect.width()) {
453         if (frame().isMainFrame() && page->settings().textAutosizingEnabled()) {
454             for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext())
455                 frame().document()->textAutosizer()->recalculateMultipliers();
456         }
457     }
458 #endif
459
460     ScrollView::setFrameRect(newRect);
461
462     updateScrollableAreaSet();
463
464     if (RenderView* renderView = this->renderView()) {
465         if (renderView->usesCompositing())
466             renderView->compositor().frameViewDidChangeSize();
467     }
468
469     if (frame().isMainFrame())
470         frame().mainFrame().pageOverlayController().didChangeViewSize();
471
472     viewportContentsChanged();
473 }
474
475 #if ENABLE(REQUEST_ANIMATION_FRAME)
476 bool FrameView::scheduleAnimation()
477 {
478     if (HostWindow* window = hostWindow()) {
479         window->scheduleAnimation();
480         return true;
481     }
482     return false;
483 }
484 #endif
485
486 void FrameView::setMarginWidth(LayoutUnit w)
487 {
488     // make it update the rendering area when set
489     m_margins.setWidth(w);
490 }
491
492 void FrameView::setMarginHeight(LayoutUnit h)
493 {
494     // make it update the rendering area when set
495     m_margins.setHeight(h);
496 }
497
498 bool FrameView::frameFlatteningEnabled() const
499 {
500     return frame().settings().frameFlatteningEnabled();
501 }
502
503 bool FrameView::isFrameFlatteningValidForThisFrame() const
504 {
505     if (!frameFlatteningEnabled())
506         return false;
507
508     HTMLFrameOwnerElement* owner = frame().ownerElement();
509     if (!owner)
510         return false;
511
512     // Frame flattening is valid only for <frame> and <iframe>.
513     return owner->hasTagName(frameTag) || owner->hasTagName(iframeTag);
514 }
515
516 bool FrameView::avoidScrollbarCreation() const
517 {
518     // with frame flattening no subframe can have scrollbars
519     // but we also cannot turn scrollbars off as we determine
520     // our flattening policy using that.
521     return isFrameFlatteningValidForThisFrame();
522 }
523
524 void FrameView::setCanHaveScrollbars(bool canHaveScrollbars)
525 {
526     m_canHaveScrollbars = canHaveScrollbars;
527     ScrollView::setCanHaveScrollbars(canHaveScrollbars);
528 }
529
530 void FrameView::updateCanHaveScrollbars()
531 {
532     ScrollbarMode hMode;
533     ScrollbarMode vMode;
534     scrollbarModes(hMode, vMode);
535     if (hMode == ScrollbarAlwaysOff && vMode == ScrollbarAlwaysOff)
536         setCanHaveScrollbars(false);
537     else
538         setCanHaveScrollbars(true);
539 }
540
541 PassRefPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
542 {
543     if (!frame().settings().allowCustomScrollbarInMainFrame() && frame().isMainFrame())
544         return ScrollView::createScrollbar(orientation);
545
546     // FIXME: We need to update the scrollbar dynamically as documents change (or as doc elements and bodies get discovered that have custom styles).
547     Document* doc = frame().document();
548
549     // Try the <body> element first as a scrollbar source.
550     HTMLElement* body = doc ? doc->bodyOrFrameset() : nullptr;
551     if (body && body->renderer() && body->renderer()->style().hasPseudoStyle(SCROLLBAR))
552         return RenderScrollbar::createCustomScrollbar(*this, orientation, body);
553     
554     // If the <body> didn't have a custom style, then the root element might.
555     Element* docElement = doc ? doc->documentElement() : nullptr;
556     if (docElement && docElement->renderer() && docElement->renderer()->style().hasPseudoStyle(SCROLLBAR))
557         return RenderScrollbar::createCustomScrollbar(*this, orientation, docElement);
558         
559     // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
560     RenderWidget* frameRenderer = frame().ownerRenderer();
561     if (frameRenderer && frameRenderer->style().hasPseudoStyle(SCROLLBAR))
562         return RenderScrollbar::createCustomScrollbar(*this, orientation, nullptr, &frame());
563     
564     // Nobody set a custom style, so we just use a native scrollbar.
565     return ScrollView::createScrollbar(orientation);
566 }
567
568 void FrameView::setContentsSize(const IntSize& size)
569 {
570     if (size == contentsSize())
571         return;
572
573     m_deferSetNeedsLayoutCount++;
574
575     ScrollView::setContentsSize(size);
576     contentsResized();
577     
578     Page* page = frame().page();
579     if (!page)
580         return;
581
582     updateScrollableAreaSet();
583
584     page->chrome().contentsSizeChanged(&frame(), size); // Notify only.
585
586     if (frame().isMainFrame())
587         frame().mainFrame().pageOverlayController().didChangeDocumentSize();
588
589     ASSERT(m_deferSetNeedsLayoutCount);
590     m_deferSetNeedsLayoutCount--;
591     
592     if (!m_deferSetNeedsLayoutCount)
593         m_setNeedsLayoutWasDeferred = false; // FIXME: Find a way to make the deferred layout actually happen.
594 }
595
596 void FrameView::adjustViewSize()
597 {
598     RenderView* renderView = this->renderView();
599     if (!renderView)
600         return;
601
602     ASSERT(frame().view() == this);
603
604     const IntRect rect = renderView->documentRect();
605     const IntSize& size = rect.size();
606     ScrollView::setScrollOrigin(IntPoint(-rect.x(), -rect.y()), !frame().document()->printing(), size == contentsSize());
607
608     setContentsSize(size);
609 }
610
611 void FrameView::applyOverflowToViewport(RenderElement* renderer, ScrollbarMode& hMode, ScrollbarMode& vMode)
612 {
613     // Handle the overflow:hidden/scroll case for the body/html elements.  WinIE treats
614     // overflow:hidden and overflow:scroll on <body> as applying to the document's
615     // scrollbars.  The CSS2.1 draft states that HTML UAs should use the <html> or <body> element and XML/XHTML UAs should
616     // use the root element.
617
618     // To combat the inability to scroll on a page with overflow:hidden on the root when scaled, disregard hidden when
619     // there is a frameScaleFactor that is greater than one on the main frame. Also disregard hidden if there is a
620     // header or footer.
621
622     bool overrideHidden = frame().isMainFrame() && ((frame().frameScaleFactor() > 1) || headerHeight() || footerHeight());
623
624     EOverflow overflowX = renderer->style().overflowX();
625     EOverflow overflowY = renderer->style().overflowY();
626
627     if (is<RenderSVGRoot>(*renderer)) {
628         // FIXME: evaluate if we can allow overflow for these cases too.
629         // Overflow is always hidden when stand-alone SVG documents are embedded.
630         if (downcast<RenderSVGRoot>(*renderer).isEmbeddedThroughFrameContainingSVGDocument()) {
631             overflowX = OHIDDEN;
632             overflowY = OHIDDEN;
633         }
634     }
635
636     switch (overflowX) {
637         case OHIDDEN:
638             if (overrideHidden)
639                 hMode = ScrollbarAuto;
640             else
641                 hMode = ScrollbarAlwaysOff;
642             break;
643         case OSCROLL:
644             hMode = ScrollbarAlwaysOn;
645             break;
646         case OAUTO:
647             hMode = ScrollbarAuto;
648             break;
649         default:
650             // Don't set it at all.
651             ;
652     }
653     
654      switch (overflowY) {
655         case OHIDDEN:
656             if (overrideHidden)
657                 vMode = ScrollbarAuto;
658             else
659                 vMode = ScrollbarAlwaysOff;
660             break;
661         case OSCROLL:
662             vMode = ScrollbarAlwaysOn;
663             break;
664         case OAUTO:
665             vMode = ScrollbarAuto;
666             break;
667         default:
668             // Don't set it at all. Values of OPAGEDX and OPAGEDY are handled by applyPaginationToViewPort().
669             ;
670     }
671
672     m_viewportRenderer = renderer;
673 }
674
675 void FrameView::applyPaginationToViewport()
676 {
677     Document* document = frame().document();
678     auto documentElement = document->documentElement();
679     RenderElement* documentRenderer = documentElement ? documentElement->renderer() : nullptr;
680     RenderElement* documentOrBodyRenderer = documentRenderer;
681     auto* body = document->body();
682     if (body && body->renderer())
683         documentOrBodyRenderer = documentRenderer->style().overflowX() == OVISIBLE && is<HTMLHtmlElement>(*documentElement) ? body->renderer() : documentRenderer;
684
685     Pagination pagination;
686
687     if (!documentOrBodyRenderer) {
688         setPagination(pagination);
689         return;
690     }
691
692     EOverflow overflowY = documentOrBodyRenderer->style().overflowY();
693     if (overflowY == OPAGEDX || overflowY == OPAGEDY) {
694         pagination.mode = WebCore::paginationModeForRenderStyle(documentOrBodyRenderer->style());
695         pagination.gap = static_cast<unsigned>(documentOrBodyRenderer->style().columnGap());
696     }
697
698     setPagination(pagination);
699 }
700
701 void FrameView::calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy strategy)
702 {
703     m_viewportRenderer = nullptr;
704
705     const HTMLFrameOwnerElement* owner = frame().ownerElement();
706     if (owner && (owner->scrollingMode() == ScrollbarAlwaysOff)) {
707         hMode = ScrollbarAlwaysOff;
708         vMode = ScrollbarAlwaysOff;
709         return;
710     }  
711     
712     if (m_canHaveScrollbars || strategy == RulesFromWebContentOnly) {
713         hMode = ScrollbarAuto;
714         vMode = ScrollbarAuto;
715     } else {
716         hMode = ScrollbarAlwaysOff;
717         vMode = ScrollbarAlwaysOff;
718     }
719     
720     if (!m_layoutRoot) {
721         Document* document = frame().document();
722         auto documentElement = document->documentElement();
723         RenderElement* rootRenderer = documentElement ? documentElement->renderer() : nullptr;
724         auto* body = document->bodyOrFrameset();
725         if (body && body->renderer()) {
726             if (is<HTMLFrameSetElement>(*body) && !frameFlatteningEnabled()) {
727                 vMode = ScrollbarAlwaysOff;
728                 hMode = ScrollbarAlwaysOff;
729             } else if (is<HTMLBodyElement>(*body)) {
730                 // It's sufficient to just check the X overflow,
731                 // since it's illegal to have visible in only one direction.
732                 RenderElement* o = rootRenderer->style().overflowX() == OVISIBLE && is<HTMLHtmlElement>(*document->documentElement()) ? body->renderer() : rootRenderer;
733                 applyOverflowToViewport(o, hMode, vMode);
734             }
735         } else if (rootRenderer)
736             applyOverflowToViewport(rootRenderer, hMode, vMode);
737     }    
738 }
739
740 void FrameView::willRecalcStyle()
741 {
742     RenderView* renderView = this->renderView();
743     if (!renderView)
744         return;
745
746     renderView->compositor().willRecalcStyle();
747 }
748
749 void FrameView::updateCompositingLayersAfterStyleChange()
750 {
751     RenderView* renderView = this->renderView();
752     if (!renderView)
753         return;
754
755     // If we expect to update compositing after an incipient layout, don't do so here.
756     if (inPreLayoutStyleUpdate() || layoutPending() || renderView->needsLayout())
757         return;
758
759     renderView->compositor().didRecalcStyleWithNoPendingLayout();
760 }
761
762 void FrameView::updateCompositingLayersAfterLayout()
763 {
764     RenderView* renderView = this->renderView();
765     if (!renderView)
766         return;
767
768     // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
769     renderView->compositor().cacheAcceleratedCompositingFlags();
770     renderView->compositor().updateCompositingLayers(CompositingUpdateAfterLayout);
771 }
772
773 void FrameView::clearBackingStores()
774 {
775     RenderView* renderView = this->renderView();
776     if (!renderView)
777         return;
778
779     RenderLayerCompositor& compositor = renderView->compositor();
780     ASSERT(compositor.inCompositingMode());
781     compositor.enableCompositingMode(false);
782     compositor.clearBackingForAllLayers();
783 }
784
785 void FrameView::restoreBackingStores()
786 {
787     RenderView* renderView = this->renderView();
788     if (!renderView)
789         return;
790
791     RenderLayerCompositor& compositor = renderView->compositor();
792     compositor.enableCompositingMode(true);
793     compositor.updateCompositingLayers(CompositingUpdateAfterLayout);
794 }
795
796 GraphicsLayer* FrameView::layerForScrolling() const
797 {
798     RenderView* renderView = this->renderView();
799     if (!renderView)
800         return nullptr;
801     return renderView->compositor().scrollLayer();
802 }
803
804 GraphicsLayer* FrameView::layerForHorizontalScrollbar() const
805 {
806     RenderView* renderView = this->renderView();
807     if (!renderView)
808         return nullptr;
809     return renderView->compositor().layerForHorizontalScrollbar();
810 }
811
812 GraphicsLayer* FrameView::layerForVerticalScrollbar() const
813 {
814     RenderView* renderView = this->renderView();
815     if (!renderView)
816         return nullptr;
817     return renderView->compositor().layerForVerticalScrollbar();
818 }
819
820 GraphicsLayer* FrameView::layerForScrollCorner() const
821 {
822     RenderView* renderView = this->renderView();
823     if (!renderView)
824         return nullptr;
825     return renderView->compositor().layerForScrollCorner();
826 }
827
828 TiledBacking* FrameView::tiledBacking() const
829 {
830     RenderView* renderView = this->renderView();
831     if (!renderView)
832         return nullptr;
833
834     RenderLayerBacking* backing = renderView->layer()->backing();
835     if (!backing)
836         return nullptr;
837
838     return backing->graphicsLayer()->tiledBacking();
839 }
840
841 uint64_t FrameView::scrollLayerID() const
842 {
843     RenderView* renderView = this->renderView();
844     if (!renderView)
845         return 0;
846
847     RenderLayerBacking* backing = renderView->layer()->backing();
848     if (!backing)
849         return 0;
850
851     return backing->scrollingNodeIDForRole(Scrolling);
852 }
853
854 ScrollableArea* FrameView::scrollableAreaForScrollLayerID(uint64_t nodeID) const
855 {
856     RenderView* renderView = this->renderView();
857     if (!renderView)
858         return nullptr;
859
860     return renderView->compositor().scrollableAreaForScrollLayerID(nodeID);
861 }
862
863 #if ENABLE(RUBBER_BANDING)
864 GraphicsLayer* FrameView::layerForOverhangAreas() const
865 {
866     RenderView* renderView = this->renderView();
867     if (!renderView)
868         return nullptr;
869     return renderView->compositor().layerForOverhangAreas();
870 }
871
872 GraphicsLayer* FrameView::setWantsLayerForTopOverHangArea(bool wantsLayer) const
873 {
874     RenderView* renderView = this->renderView();
875     if (!renderView)
876         return nullptr;
877
878     return renderView->compositor().updateLayerForTopOverhangArea(wantsLayer);
879 }
880
881 GraphicsLayer* FrameView::setWantsLayerForBottomOverHangArea(bool wantsLayer) const
882 {
883     RenderView* renderView = this->renderView();
884     if (!renderView)
885         return nullptr;
886
887     return renderView->compositor().updateLayerForBottomOverhangArea(wantsLayer);
888 }
889
890 #endif // ENABLE(RUBBER_BANDING)
891
892 #if ENABLE(CSS_SCROLL_SNAP)
893 void FrameView::updateSnapOffsets()
894 {
895     if (!frame().document())
896         return;
897
898     // FIXME: Should we allow specifying snap points through <html> tags too?
899     HTMLElement* body = frame().document()->bodyOrFrameset();
900     if (!renderView() || !body || !body->renderer())
901         return;
902     
903     updateSnapOffsetsForScrollableArea(*this, *body, *renderView(), body->renderer()->style());
904 }
905 #endif
906
907 bool FrameView::flushCompositingStateForThisFrame(Frame* rootFrameForFlush)
908 {
909     RenderView* renderView = this->renderView();
910     if (!renderView)
911         return true; // We don't want to keep trying to update layers if we have no renderer.
912
913     ASSERT(frame().view() == this);
914
915     // If we sync compositing layers when a layout is pending, we may cause painting of compositing
916     // layer content to occur before layout has happened, which will cause paintContents() to bail.
917     if (needsLayout())
918         return false;
919
920 #if PLATFORM(IOS)
921     if (LegacyTileCache* tileCache = legacyTileCache())
922         tileCache->doPendingRepaints();
923 #endif
924
925     renderView->compositor().flushPendingLayerChanges(rootFrameForFlush == m_frame.ptr());
926
927     return true;
928 }
929
930 void FrameView::setNeedsOneShotDrawingSynchronization()
931 {
932     if (Page* page = frame().page())
933         page->chrome().client().setNeedsOneShotDrawingSynchronization();
934 }
935
936 GraphicsLayer* FrameView::graphicsLayerForPlatformWidget(PlatformWidget platformWidget)
937 {
938     // To find the Widget that corresponds with platformWidget we have to do a linear
939     // search of our child widgets.
940     Widget* foundWidget = nullptr;
941     for (auto& widget : children()) {
942         if (widget->platformWidget() != platformWidget)
943             continue;
944         foundWidget = widget.get();
945         break;
946     }
947
948     if (!foundWidget)
949         return nullptr;
950
951     auto* renderWidget = RenderWidget::find(foundWidget);
952     if (!renderWidget)
953         return nullptr;
954
955     RenderLayer* widgetLayer = renderWidget->layer();
956     if (!widgetLayer || !widgetLayer->isComposited())
957         return nullptr;
958
959     return widgetLayer->backing()->parentForSublayers();
960 }
961
962 void FrameView::scheduleLayerFlushAllowingThrottling()
963 {
964     RenderView* view = this->renderView();
965     if (!view)
966         return;
967     view->compositor().scheduleLayerFlush(true /* canThrottle */);
968 }
969
970 void FrameView::setHeaderHeight(int headerHeight)
971 {
972     if (frame().page())
973         ASSERT(frame().isMainFrame());
974     m_headerHeight = headerHeight;
975
976     if (RenderView* renderView = this->renderView())
977         renderView->setNeedsLayout();
978 }
979
980 void FrameView::setFooterHeight(int footerHeight)
981 {
982     if (frame().page())
983         ASSERT(frame().isMainFrame());
984     m_footerHeight = footerHeight;
985
986     if (RenderView* renderView = this->renderView())
987         renderView->setNeedsLayout();
988 }
989
990 float FrameView::topContentInset(TopContentInsetType contentInsetTypeToReturn) const
991 {
992     if (platformWidget() && contentInsetTypeToReturn == TopContentInsetType::WebCoreOrPlatformContentInset)
993         return platformTopContentInset();
994
995     if (!frame().isMainFrame())
996         return 0;
997     
998     Page* page = frame().page();
999     return page ? page->topContentInset() : 0;
1000 }
1001     
1002 void FrameView::topContentInsetDidChange(float newTopContentInset)
1003 {
1004     RenderView* renderView = this->renderView();
1005     if (!renderView)
1006         return;
1007
1008     if (platformWidget())
1009         platformSetTopContentInset(newTopContentInset);
1010     
1011     layout();
1012
1013     updateScrollbars(scrollOffset());
1014     if (renderView->usesCompositing())
1015         renderView->compositor().frameViewDidChangeSize();
1016
1017     if (TiledBacking* tiledBacking = this->tiledBacking())
1018         tiledBacking->setTopContentInset(newTopContentInset);
1019 }
1020     
1021 bool FrameView::hasCompositedContent() const
1022 {
1023     if (RenderView* renderView = this->renderView())
1024         return renderView->compositor().inCompositingMode();
1025     return false;
1026 }
1027
1028 // Sometimes (for plug-ins) we need to eagerly go into compositing mode.
1029 void FrameView::enterCompositingMode()
1030 {
1031     if (RenderView* renderView = this->renderView()) {
1032         renderView->compositor().enableCompositingMode();
1033         if (!needsLayout())
1034             renderView->compositor().scheduleCompositingLayerUpdate();
1035     }
1036 }
1037
1038 bool FrameView::isEnclosedInCompositingLayer() const
1039 {
1040     auto frameOwnerRenderer = frame().ownerRenderer();
1041     if (frameOwnerRenderer && frameOwnerRenderer->containerForRepaint())
1042         return true;
1043
1044     if (FrameView* parentView = parentFrameView())
1045         return parentView->isEnclosedInCompositingLayer();
1046     return false;
1047 }
1048
1049 bool FrameView::flushCompositingStateIncludingSubframes()
1050 {
1051     bool allFramesFlushed = flushCompositingStateForThisFrame(&frame());
1052
1053     for (Frame* child = frame().tree().firstRenderedChild(); child; child = child->tree().traverseNextRendered(m_frame.ptr())) {
1054         if (!child->view())
1055             continue;
1056         bool flushed = child->view()->flushCompositingStateForThisFrame(&frame());
1057         allFramesFlushed &= flushed;
1058     }
1059     return allFramesFlushed;
1060 }
1061
1062 bool FrameView::isSoftwareRenderable() const
1063 {
1064     RenderView* renderView = this->renderView();
1065     return !renderView || !renderView->compositor().has3DContent();
1066 }
1067
1068 void FrameView::setIsInWindow(bool isInWindow)
1069 {
1070     if (RenderView* renderView = this->renderView())
1071         renderView->setIsInWindow(isInWindow);
1072 }
1073
1074 RenderObject* FrameView::layoutRoot(bool onlyDuringLayout) const
1075 {
1076     return onlyDuringLayout && layoutPending() ? nullptr : m_layoutRoot;
1077 }
1078
1079 inline void FrameView::forceLayoutParentViewIfNeeded()
1080 {
1081     RenderWidget* ownerRenderer = frame().ownerRenderer();
1082     if (!ownerRenderer)
1083         return;
1084
1085     RenderBox* contentBox = embeddedContentBox();
1086     if (!contentBox)
1087         return;
1088
1089     auto& svgRoot = downcast<RenderSVGRoot>(*contentBox);
1090     if (svgRoot.everHadLayout() && !svgRoot.needsLayout())
1091         return;
1092
1093     // If the embedded SVG document appears the first time, the ownerRenderer has already finished
1094     // layout without knowing about the existence of the embedded SVG document, because RenderReplaced
1095     // embeddedContentBox() returns nullptr, as long as the embedded document isn't loaded yet. Before
1096     // bothering to lay out the SVG document, mark the ownerRenderer needing layout and ask its
1097     // FrameView for a layout. After that the RenderEmbeddedObject (ownerRenderer) carries the
1098     // correct size, which RenderSVGRoot::computeReplacedLogicalWidth/Height rely on, when laying
1099     // out for the first time, or when the RenderSVGRoot size has changed dynamically (eg. via <script>).
1100     Ref<FrameView> frameView(ownerRenderer->view().frameView());
1101
1102     // Mark the owner renderer as needing layout.
1103     ownerRenderer->setNeedsLayoutAndPrefWidthsRecalc();
1104
1105     // Synchronously enter layout, to layout the view containing the host object/embed/iframe.
1106     frameView->layout();
1107 }
1108
1109 void FrameView::layout(bool allowSubtree)
1110 {
1111     if (isInLayout())
1112         return;
1113
1114     // Protect the view from being deleted during layout (in recalcStyle).
1115     Ref<FrameView> protect(*this);
1116
1117     // Many of the tasks performed during layout can cause this function to be re-entered,
1118     // so save the layout phase now and restore it on exit.
1119     TemporaryChange<LayoutPhase> layoutPhaseRestorer(m_layoutPhase, InPreLayout);
1120
1121     // Every scroll that happens during layout is programmatic.
1122     TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
1123
1124     bool inChildFrameLayoutWithFrameFlattening = isInChildFrameWithFrameFlattening();
1125
1126     if (inChildFrameLayoutWithFrameFlattening) {
1127         startLayoutAtMainFrameViewIfNeeded(allowSubtree);
1128         RenderElement* root = m_layoutRoot ? m_layoutRoot : frame().document()->renderView();
1129         if (!root || !root->needsLayout())
1130             return;
1131     }
1132
1133 #if PLATFORM(IOS)
1134     if (updateFixedPositionLayoutRect())
1135         allowSubtree = false;
1136 #endif
1137
1138     m_layoutTimer.stop();
1139     m_delayedLayout = false;
1140     m_setNeedsLayoutWasDeferred = false;
1141     
1142     // we shouldn't enter layout() while painting
1143     ASSERT(!isPainting());
1144     if (isPainting())
1145         return;
1146
1147     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willLayout(frame());
1148     AnimationUpdateBlock animationUpdateBlock(&frame().animation());
1149     
1150     if (!allowSubtree && m_layoutRoot) {
1151         m_layoutRoot->markContainingBlocksForLayout(false);
1152         m_layoutRoot = nullptr;
1153     }
1154
1155     ASSERT(frame().view() == this);
1156     ASSERT(frame().document());
1157
1158     Document& document = *frame().document();
1159     ASSERT(!document.inPageCache());
1160
1161     bool subtree;
1162     RenderElement* root;
1163
1164     {
1165         TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
1166
1167         if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !inChildFrameLayoutWithFrameFlattening) {
1168             // This is a new top-level layout. If there are any remaining tasks from the previous
1169             // layout, finish them now.
1170             TemporaryChange<bool> inSynchronousPostLayoutChange(m_inSynchronousPostLayout, true);
1171             performPostLayoutTasks();
1172         }
1173
1174         m_layoutPhase = InPreLayoutStyleUpdate;
1175
1176         // Viewport-dependent media queries may cause us to need completely different style information.
1177         StyleResolver* styleResolver = document.styleResolverIfExists();
1178         if (!styleResolver || styleResolver->hasMediaQueriesAffectedByViewportChange()) {
1179             document.styleResolverChanged(DeferRecalcStyle);
1180             // FIXME: This instrumentation event is not strictly accurate since cached media query results do not persist across StyleResolver rebuilds.
1181             InspectorInstrumentation::mediaQueryResultChanged(document);
1182         } else
1183             document.evaluateMediaQueryList();
1184
1185         // If there is any pagination to apply, it will affect the RenderView's style, so we should
1186         // take care of that now.
1187         applyPaginationToViewport();
1188
1189         // Always ensure our style info is up-to-date. This can happen in situations where
1190         // the layout beats any sort of style recalc update that needs to occur.
1191         document.updateStyleIfNeeded();
1192         m_layoutPhase = InPreLayout;
1193
1194         subtree = m_layoutRoot;
1195
1196         // If there is only one ref to this view left, then its going to be destroyed as soon as we exit, 
1197         // so there's no point to continuing to layout
1198         if (hasOneRef())
1199             return;
1200
1201         root = subtree ? m_layoutRoot : document.renderView();
1202         if (!root) {
1203             // FIXME: Do we need to set m_size here?
1204             return;
1205         }
1206
1207         // Close block here so we can set up the font cache purge preventer, which we will still
1208         // want in scope even after we want m_layoutSchedulingEnabled to be restored again.
1209         // The next block sets m_layoutSchedulingEnabled back to false once again.
1210     }
1211
1212     RenderLayer* layer;
1213
1214     ++m_nestedLayoutCount;
1215
1216     {
1217         TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
1218
1219         if (!m_layoutRoot) {
1220             auto* body = document.bodyOrFrameset();
1221             if (body && body->renderer()) {
1222                 if (is<HTMLFrameSetElement>(*body) && !frameFlatteningEnabled()) {
1223                     body->renderer()->setChildNeedsLayout();
1224                 } else if (is<HTMLBodyElement>(*body)) {
1225                     if (!m_firstLayout && m_size.height() != layoutHeight() && body->renderer()->enclosingBox().stretchesToViewport())
1226                         body->renderer()->setChildNeedsLayout();
1227                 }
1228             }
1229
1230 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1231             if (m_firstLayout && !frame().ownerElement())
1232                 printf("Elapsed time before first layout: %lld\n", document.elapsedTime().count());
1233 #endif        
1234         }
1235
1236         autoSizeIfEnabled();
1237
1238         m_needsFullRepaint = !subtree && (m_firstLayout || downcast<RenderView>(*root).printing());
1239
1240         if (!subtree) {
1241             ScrollbarMode hMode;
1242             ScrollbarMode vMode;    
1243             calculateScrollbarModesForLayout(hMode, vMode);
1244
1245             if (m_firstLayout || (hMode != horizontalScrollbarMode() || vMode != verticalScrollbarMode())) {
1246                 if (m_firstLayout) {
1247                     setScrollbarsSuppressed(true);
1248
1249                     m_firstLayout = false;
1250                     m_firstLayoutCallbackPending = true;
1251                     m_lastViewportSize = sizeForResizeEvent();
1252                     m_lastZoomFactor = root->style().zoom();
1253
1254                     // Set the initial vMode to AlwaysOn if we're auto.
1255                     if (vMode == ScrollbarAuto)
1256                         setVerticalScrollbarMode(ScrollbarAlwaysOn); // This causes a vertical scrollbar to appear.
1257                     // Set the initial hMode to AlwaysOff if we're auto.
1258                     if (hMode == ScrollbarAuto)
1259                         setHorizontalScrollbarMode(ScrollbarAlwaysOff); // This causes a horizontal scrollbar to disappear.
1260                     Page* page = frame().page();
1261                     if (page && page->expectsWheelEventTriggers())
1262                         scrollAnimator().setWheelEventTestTrigger(page->testTrigger());
1263                     setScrollbarModes(hMode, vMode);
1264                     setScrollbarsSuppressed(false, true);
1265                 } else
1266                     setScrollbarModes(hMode, vMode);
1267             }
1268
1269             LayoutSize oldSize = m_size;
1270             m_size = layoutSize();
1271
1272             if (oldSize != m_size) {
1273                 m_needsFullRepaint = true;
1274                 if (!m_firstLayout) {
1275                     RenderBox* rootRenderer = document.documentElement() ? document.documentElement()->renderBox() : nullptr;
1276                     auto* body = document.bodyOrFrameset();
1277                     RenderBox* bodyRenderer = rootRenderer && body ? body->renderBox() : nullptr;
1278                     if (bodyRenderer && bodyRenderer->stretchesToViewport())
1279                         bodyRenderer->setChildNeedsLayout();
1280                     else if (rootRenderer && rootRenderer->stretchesToViewport())
1281                         rootRenderer->setChildNeedsLayout();
1282                 }
1283             }
1284
1285             m_layoutPhase = InPreLayout;
1286         }
1287
1288         layer = root->enclosingLayer();
1289
1290         bool disableLayoutState = false;
1291         if (subtree) {
1292             disableLayoutState = root->view().shouldDisableLayoutStateForSubtree(root);
1293             root->view().pushLayoutState(*root);
1294         }
1295         LayoutStateDisabler layoutStateDisabler(disableLayoutState ? &root->view() : nullptr);
1296         RenderView::RepaintRegionAccumulator repaintRegionAccumulator(&root->view());
1297
1298         ASSERT(m_layoutPhase == InPreLayout);
1299         m_layoutPhase = InLayout;
1300
1301         forceLayoutParentViewIfNeeded();
1302
1303         ASSERT(m_layoutPhase == InLayout);
1304
1305         root->layout();
1306 #if ENABLE(IOS_TEXT_AUTOSIZING)
1307         if (Page* page = frame().page()) {
1308             float minimumZoomFontSize = frame().settings().minimumZoomFontSize();
1309             float textAutosizingWidth = page->textAutosizingWidth();
1310             if (minimumZoomFontSize && textAutosizingWidth && !root->view().printing()) {
1311                 root->adjustComputedFontSizesOnBlocks(minimumZoomFontSize, textAutosizingWidth);
1312                 if (root->needsLayout())
1313                     root->layout();
1314             }
1315         }
1316 #endif
1317 #if ENABLE(TEXT_AUTOSIZING)
1318         if (document.textAutosizer()->processSubtree(root) && root->needsLayout())
1319             root->layout();
1320 #endif
1321
1322         ASSERT(m_layoutPhase == InLayout);
1323
1324         if (subtree)
1325             root->view().popLayoutState(*root);
1326
1327         m_layoutRoot = nullptr;
1328
1329         // Close block here to end the scope of changeSchedulingEnabled and layoutStateDisabler.
1330     }
1331
1332     m_layoutPhase = InViewSizeAdjust;
1333
1334     bool neededFullRepaint = m_needsFullRepaint;
1335
1336     if (!subtree && !downcast<RenderView>(*root).printing())
1337         adjustViewSize();
1338
1339     m_layoutPhase = InPostLayout;
1340
1341     m_needsFullRepaint = neededFullRepaint;
1342
1343     // Now update the positions of all layers.
1344     if (m_needsFullRepaint)
1345         root->view().repaintRootContents();
1346
1347     root->view().releaseProtectedRenderWidgets();
1348
1349     ASSERT(!root->needsLayout());
1350
1351     layer->updateLayerPositionsAfterLayout(renderView()->layer(), updateLayerPositionFlags(layer, subtree, m_needsFullRepaint));
1352
1353     updateCompositingLayersAfterLayout();
1354
1355     m_layoutPhase = InPostLayerPositionsUpdatedAfterLayout;
1356
1357     m_layoutCount++;
1358
1359 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
1360     if (AXObjectCache* cache = root->document().existingAXObjectCache())
1361         cache->postNotification(root, AXObjectCache::AXLayoutComplete);
1362 #endif
1363
1364 #if ENABLE(DASHBOARD_SUPPORT)
1365     updateAnnotatedRegions();
1366 #endif
1367
1368 #if ENABLE(IOS_TOUCH_EVENTS)
1369     document.dirtyTouchEventRects();
1370 #endif
1371
1372     updateCanBlitOnScrollRecursively();
1373
1374     handleDeferredScrollUpdateAfterContentSizeChange();
1375
1376     if (document.hasListenerType(Document::OVERFLOWCHANGED_LISTENER))
1377         updateOverflowStatus(layoutWidth() < contentsWidth(), layoutHeight() < contentsHeight());
1378
1379     if (!m_postLayoutTasksTimer.isActive()) {
1380         if (!m_inSynchronousPostLayout) {
1381             if (inChildFrameLayoutWithFrameFlattening)
1382                 updateWidgetPositions();
1383             else {
1384                 TemporaryChange<bool> inSynchronousPostLayoutChange(m_inSynchronousPostLayout, true);
1385                 performPostLayoutTasks(); // Calls resumeScheduledEvents().
1386             }
1387         }
1388
1389         if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || inChildFrameLayoutWithFrameFlattening)) {
1390             // If we need layout or are already in a synchronous call to postLayoutTasks(), 
1391             // defer widget updates and event dispatch until after we return. postLayoutTasks()
1392             // can make us need to update again, and we can get stuck in a nasty cycle unless
1393             // we call it through the timer here.
1394             m_postLayoutTasksTimer.startOneShot(0);
1395             if (needsLayout())
1396                 layout();
1397         }
1398     }
1399
1400     InspectorInstrumentation::didLayout(cookie, root);
1401     DebugPageOverlays::didLayout(frame());
1402
1403     --m_nestedLayoutCount;
1404 }
1405
1406 bool FrameView::shouldDeferScrollUpdateAfterContentSizeChange()
1407 {
1408     return (m_layoutPhase < InPostLayout) && (m_layoutPhase != OutsideLayout);
1409 }
1410
1411 RenderBox* FrameView::embeddedContentBox() const
1412 {
1413     RenderView* renderView = this->renderView();
1414     if (!renderView)
1415         return nullptr;
1416
1417     RenderObject* firstChild = renderView->firstChild();
1418
1419     // Curently only embedded SVG documents participate in the size-negotiation logic.
1420     if (is<RenderSVGRoot>(firstChild))
1421         return downcast<RenderSVGRoot>(firstChild);
1422
1423     return nullptr;
1424 }
1425
1426 void FrameView::addEmbeddedObjectToUpdate(RenderEmbeddedObject& embeddedObject)
1427 {
1428     if (!m_embeddedObjectsToUpdate)
1429         m_embeddedObjectsToUpdate = std::make_unique<ListHashSet<RenderEmbeddedObject*>>();
1430
1431     HTMLFrameOwnerElement& element = embeddedObject.frameOwnerElement();
1432     if (is<HTMLObjectElement>(element) || is<HTMLEmbedElement>(element)) {
1433         // Tell the DOM element that it needs a widget update.
1434         HTMLPlugInImageElement& pluginElement = downcast<HTMLPlugInImageElement>(element);
1435         if (!pluginElement.needsCheckForSizeChange())
1436             pluginElement.setNeedsWidgetUpdate(true);
1437     }
1438
1439     m_embeddedObjectsToUpdate->add(&embeddedObject);
1440 }
1441
1442 void FrameView::removeEmbeddedObjectToUpdate(RenderEmbeddedObject& embeddedObject)
1443 {
1444     if (!m_embeddedObjectsToUpdate)
1445         return;
1446
1447     m_embeddedObjectsToUpdate->remove(&embeddedObject);
1448 }
1449
1450 void FrameView::setMediaType(const String& mediaType)
1451 {
1452     m_mediaType = mediaType;
1453 }
1454
1455 String FrameView::mediaType() const
1456 {
1457     // See if we have an override type.
1458     String overrideType = frame().loader().client().overrideMediaType();
1459     InspectorInstrumentation::applyEmulatedMedia(frame(), overrideType);
1460     if (!overrideType.isNull())
1461         return overrideType;
1462     return m_mediaType;
1463 }
1464
1465 void FrameView::adjustMediaTypeForPrinting(bool printing)
1466 {
1467     if (printing) {
1468         if (m_mediaTypeWhenNotPrinting.isNull())
1469             m_mediaTypeWhenNotPrinting = mediaType();
1470             setMediaType("print");
1471     } else {
1472         if (!m_mediaTypeWhenNotPrinting.isNull())
1473             setMediaType(m_mediaTypeWhenNotPrinting);
1474         m_mediaTypeWhenNotPrinting = String();
1475     }
1476 }
1477
1478 bool FrameView::useSlowRepaints(bool considerOverlap) const
1479 {
1480     bool mustBeSlow = hasSlowRepaintObjects() || (platformWidget() && hasViewportConstrainedObjects());
1481
1482     // FIXME: WidgetMac.mm makes the assumption that useSlowRepaints ==
1483     // m_contentIsOpaque, so don't take the fast path for composited layers
1484     // if they are a platform widget in order to get painting correctness
1485     // for transparent layers. See the comment in WidgetMac::paint.
1486     if (usesCompositedScrolling() && !platformWidget())
1487         return mustBeSlow;
1488
1489     bool isOverlapped = m_isOverlapped && considerOverlap;
1490
1491     if (mustBeSlow || m_cannotBlitToWindow || isOverlapped || !m_contentIsOpaque)
1492         return true;
1493
1494     if (FrameView* parentView = parentFrameView())
1495         return parentView->useSlowRepaints(considerOverlap);
1496
1497     return false;
1498 }
1499
1500 bool FrameView::useSlowRepaintsIfNotOverlapped() const
1501 {
1502     return useSlowRepaints(false);
1503 }
1504
1505 void FrameView::updateCanBlitOnScrollRecursively()
1506 {
1507     for (auto* frame = m_frame.ptr(); frame; frame = frame->tree().traverseNext(m_frame.ptr())) {
1508         if (FrameView* view = frame->view())
1509             view->setCanBlitOnScroll(!view->useSlowRepaints());
1510     }
1511 }
1512
1513 bool FrameView::usesCompositedScrolling() const
1514 {
1515     RenderView* renderView = this->renderView();
1516     if (renderView && renderView->isComposited()) {
1517         GraphicsLayer* layer = renderView->layer()->backing()->graphicsLayer();
1518         if (layer && layer->drawsContent())
1519             return true;
1520     }
1521
1522     return false;
1523 }
1524
1525 bool FrameView::usesAsyncScrolling() const
1526 {
1527 #if ENABLE(ASYNC_SCROLLING)
1528     if (Page* page = frame().page()) {
1529         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1530             return scrollingCoordinator->coordinatesScrollingForFrameView(*this);
1531     }
1532 #endif
1533     return false;
1534 }
1535
1536 void FrameView::setCannotBlitToWindow()
1537 {
1538     m_cannotBlitToWindow = true;
1539     updateCanBlitOnScrollRecursively();
1540 }
1541
1542 void FrameView::addSlowRepaintObject(RenderElement* o)
1543 {
1544     bool hadSlowRepaintObjects = hasSlowRepaintObjects();
1545
1546     if (!m_slowRepaintObjects)
1547         m_slowRepaintObjects = std::make_unique<HashSet<RenderElement*>>();
1548
1549     m_slowRepaintObjects->add(o);
1550
1551     if (!hadSlowRepaintObjects) {
1552         updateCanBlitOnScrollRecursively();
1553
1554         if (Page* page = frame().page()) {
1555             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1556                 scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(*this);
1557         }
1558     }
1559 }
1560
1561 void FrameView::removeSlowRepaintObject(RenderElement* o)
1562 {
1563     if (!m_slowRepaintObjects)
1564         return;
1565
1566     m_slowRepaintObjects->remove(o);
1567     if (m_slowRepaintObjects->isEmpty()) {
1568         m_slowRepaintObjects = nullptr;
1569         updateCanBlitOnScrollRecursively();
1570
1571         if (Page* page = frame().page()) {
1572             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1573                 scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(*this);
1574         }
1575     }
1576 }
1577
1578 void FrameView::addViewportConstrainedObject(RenderElement* object)
1579 {
1580     if (!m_viewportConstrainedObjects)
1581         m_viewportConstrainedObjects = std::make_unique<ViewportConstrainedObjectSet>();
1582
1583     if (!m_viewportConstrainedObjects->contains(object)) {
1584         m_viewportConstrainedObjects->add(object);
1585         if (platformWidget())
1586             updateCanBlitOnScrollRecursively();
1587
1588         if (Page* page = frame().page()) {
1589             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1590                 scrollingCoordinator->frameViewFixedObjectsDidChange(*this);
1591         }
1592     }
1593 }
1594
1595 void FrameView::removeViewportConstrainedObject(RenderElement* object)
1596 {
1597     if (m_viewportConstrainedObjects && m_viewportConstrainedObjects->remove(object)) {
1598         if (Page* page = frame().page()) {
1599             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1600                 scrollingCoordinator->frameViewFixedObjectsDidChange(*this);
1601         }
1602
1603         // FIXME: In addFixedObject() we only call this if there's a platform widget,
1604         // why isn't the same check being made here?
1605         updateCanBlitOnScrollRecursively();
1606     }
1607 }
1608
1609 LayoutRect FrameView::viewportConstrainedVisibleContentRect() const
1610 {
1611 #if PLATFORM(IOS)
1612     if (useCustomFixedPositionLayoutRect())
1613         return customFixedPositionLayoutRect();
1614 #endif
1615     LayoutRect viewportRect = visibleContentRect();
1616
1617     viewportRect.setLocation(toLayoutPoint(scrollOffsetForFixedPosition()));
1618     return viewportRect;
1619 }
1620
1621 float FrameView::frameScaleFactor() const
1622 {
1623     return frame().frameScaleFactor();
1624 }
1625
1626 LayoutSize FrameView::scrollOffsetForFixedPosition(const LayoutRect& visibleContentRect, const LayoutSize& totalContentsSize, const LayoutPoint& scrollPosition, const LayoutPoint& scrollOrigin, float frameScaleFactor, bool fixedElementsLayoutRelativeToFrame, ScrollBehaviorForFixedElements behaviorForFixed, int headerHeight, int footerHeight)
1627 {
1628     LayoutPoint position;
1629     if (behaviorForFixed == StickToDocumentBounds)
1630         position = ScrollableArea::constrainScrollPositionForOverhang(visibleContentRect, totalContentsSize, scrollPosition, scrollOrigin, headerHeight, footerHeight);
1631     else {
1632         position = scrollPosition;
1633         position.setY(position.y() - headerHeight);
1634     }
1635
1636     LayoutSize maxSize = totalContentsSize - visibleContentRect.size();
1637
1638     float dragFactorX = (fixedElementsLayoutRelativeToFrame || !maxSize.width()) ? 1 : (totalContentsSize.width() - visibleContentRect.width() * frameScaleFactor) / maxSize.width();
1639     float dragFactorY = (fixedElementsLayoutRelativeToFrame || !maxSize.height()) ? 1 : (totalContentsSize.height() - visibleContentRect.height() * frameScaleFactor) / maxSize.height();
1640
1641     return LayoutSize(position.x() * dragFactorX / frameScaleFactor, position.y() * dragFactorY / frameScaleFactor);
1642 }
1643
1644 float FrameView::yPositionForInsetClipLayer(const FloatPoint& scrollPosition, float topContentInset)
1645 {
1646     if (!topContentInset)
1647         return 0;
1648
1649     // The insetClipLayer should not move for negative scroll values.
1650     float scrollY = std::max<float>(0, scrollPosition.y());
1651
1652     if (scrollY >= topContentInset)
1653         return 0;
1654
1655     return topContentInset - scrollY;
1656 }
1657
1658 float FrameView::yPositionForHeaderLayer(const FloatPoint& scrollPosition, float topContentInset)
1659 {
1660     if (!topContentInset)
1661         return 0;
1662
1663     float scrollY = std::max<float>(0, scrollPosition.y());
1664
1665     if (scrollY >= topContentInset)
1666         return topContentInset;
1667
1668     return scrollY;
1669 }
1670
1671 float FrameView::yPositionForRootContentLayer(const FloatPoint& scrollPosition, float topContentInset, float headerHeight)
1672 {
1673     return yPositionForHeaderLayer(scrollPosition, topContentInset) + headerHeight;
1674 }
1675
1676 float FrameView::yPositionForFooterLayer(const FloatPoint& scrollPosition, float topContentInset, float totalContentsHeight, float footerHeight)
1677 {
1678     return yPositionForHeaderLayer(scrollPosition, topContentInset) + totalContentsHeight - footerHeight;
1679 }
1680
1681 float FrameView::yPositionForRootContentLayer() const
1682 {
1683     return yPositionForRootContentLayer(scrollPosition(), topContentInset(), headerHeight());
1684 }
1685
1686 #if PLATFORM(IOS)
1687 LayoutRect FrameView::rectForViewportConstrainedObjects(const LayoutRect& visibleContentRect, const LayoutSize& totalContentsSize, float frameScaleFactor, bool fixedElementsLayoutRelativeToFrame, ScrollBehaviorForFixedElements scrollBehavior)
1688 {
1689     if (fixedElementsLayoutRelativeToFrame)
1690         return visibleContentRect;
1691     
1692     if (totalContentsSize.isEmpty())
1693         return visibleContentRect;
1694
1695     // We impose an lower limit on the size (so an upper limit on the scale) of
1696     // the rect used to position fixed objects so that they don't crowd into the
1697     // center of the screen at larger scales.
1698     const LayoutUnit maxContentWidthForZoomThreshold = LayoutUnit::fromPixel(1024);
1699     float zoomedOutScale = frameScaleFactor * visibleContentRect.width() / std::min(maxContentWidthForZoomThreshold, totalContentsSize.width());
1700     float constraintThresholdScale = 1.5 * zoomedOutScale;
1701     float maxPostionedObjectsRectScale = std::min(frameScaleFactor, constraintThresholdScale);
1702
1703     LayoutRect viewportConstrainedObjectsRect = visibleContentRect;
1704
1705     if (frameScaleFactor > constraintThresholdScale) {
1706         FloatRect contentRect(FloatPoint(), totalContentsSize);
1707         FloatRect viewportRect = visibleContentRect;
1708         
1709         // Scale the rect up from a point that is relative to its position in the viewport.
1710         FloatSize sizeDelta = contentRect.size() - viewportRect.size();
1711
1712         FloatPoint scaleOrigin;
1713         scaleOrigin.setX(contentRect.x() + sizeDelta.width() > 0 ? contentRect.width() * (viewportRect.x() - contentRect.x()) / sizeDelta.width() : 0);
1714         scaleOrigin.setY(contentRect.y() + sizeDelta.height() > 0 ? contentRect.height() * (viewportRect.y() - contentRect.y()) / sizeDelta.height() : 0);
1715         
1716         AffineTransform rescaleTransform = AffineTransform::translation(scaleOrigin.x(), scaleOrigin.y());
1717         rescaleTransform.scale(frameScaleFactor / maxPostionedObjectsRectScale, frameScaleFactor / maxPostionedObjectsRectScale);
1718         rescaleTransform = CGAffineTransformTranslate(rescaleTransform, -scaleOrigin.x(), -scaleOrigin.y());
1719
1720         viewportConstrainedObjectsRect = enclosingLayoutRect(rescaleTransform.mapRect(visibleContentRect));
1721     }
1722     
1723     if (scrollBehavior == StickToDocumentBounds) {
1724         LayoutRect documentBounds(LayoutPoint(), totalContentsSize);
1725         viewportConstrainedObjectsRect.intersect(documentBounds);
1726     }
1727
1728     return viewportConstrainedObjectsRect;
1729 }
1730     
1731 LayoutRect FrameView::viewportConstrainedObjectsRect() const
1732 {
1733     return rectForViewportConstrainedObjects(visibleContentRect(), totalContentsSize(), frame().frameScaleFactor(), fixedElementsLayoutRelativeToFrame(), scrollBehaviorForFixedElements());
1734 }
1735 #endif
1736     
1737 IntPoint FrameView::minimumScrollPosition() const
1738 {
1739     IntPoint minimumPosition(ScrollView::minimumScrollPosition());
1740
1741     if (frame().isMainFrame() && m_scrollPinningBehavior == PinToBottom)
1742         minimumPosition.setY(maximumScrollPosition().y());
1743     
1744     return minimumPosition;
1745 }
1746
1747 IntPoint FrameView::maximumScrollPosition() const
1748 {
1749     IntPoint maximumOffset(contentsWidth() - visibleWidth() - scrollOrigin().x(), totalContentsSize().height() - visibleHeight() - scrollOrigin().y());
1750
1751     maximumOffset.clampNegativeToZero();
1752
1753     if (frame().isMainFrame() && m_scrollPinningBehavior == PinToTop)
1754         maximumOffset.setY(minimumScrollPosition().y());
1755     
1756     return maximumOffset;
1757 }
1758
1759 void FrameView::delayedScrollEventTimerFired()
1760 {
1761     sendScrollEvent();
1762 }
1763
1764 void FrameView::viewportContentsChanged()
1765 {
1766     if (!frame().view()) {
1767         // The frame is being destroyed.
1768         return;
1769     }
1770
1771     // When the viewport contents changes (scroll, resize, style recalc, layout, ...),
1772     // check if we should resume animated images or unthrottle DOM timers.
1773     applyRecursivelyWithVisibleRect([] (FrameView& frameView, const IntRect& visibleRect) {
1774         frameView.resumeVisibleImageAnimations(visibleRect);
1775         frameView.updateThrottledDOMTimersState(visibleRect);
1776         frameView.updateScriptedAnimationsThrottlingState(visibleRect);
1777     });
1778 }
1779
1780 bool FrameView::fixedElementsLayoutRelativeToFrame() const
1781 {
1782     return frame().settings().fixedElementsLayoutRelativeToFrame();
1783 }
1784
1785 IntPoint FrameView::lastKnownMousePosition() const
1786 {
1787     return frame().eventHandler().lastKnownMousePosition();
1788 }
1789
1790 bool FrameView::isHandlingWheelEvent() const
1791 {
1792     return frame().eventHandler().isHandlingWheelEvent();
1793 }
1794
1795 bool FrameView::shouldSetCursor() const
1796 {
1797     Page* page = frame().page();
1798     return page && page->isVisible() && page->focusController().isActive();
1799 }
1800
1801 bool FrameView::scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect)
1802 {
1803     if (!m_viewportConstrainedObjects || m_viewportConstrainedObjects->isEmpty()) {
1804         hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1805         return true;
1806     }
1807
1808     const bool isCompositedContentLayer = usesCompositedScrolling();
1809
1810     // Get the rects of the fixed objects visible in the rectToScroll
1811     Region regionToUpdate;
1812     for (auto& renderer : *m_viewportConstrainedObjects) {
1813         if (!renderer->style().hasViewportConstrainedPosition())
1814             continue;
1815         if (renderer->isComposited())
1816             continue;
1817
1818         // Fixed items should always have layers.
1819         ASSERT(renderer->hasLayer());
1820         RenderLayer* layer = downcast<RenderBoxModelObject>(*renderer).layer();
1821
1822         if (layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForBoundsOutOfView
1823             || layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForNoVisibleContent) {
1824             // Don't invalidate for invisible fixed layers.
1825             continue;
1826         }
1827
1828         if (layer->hasAncestorWithFilterOutsets()) {
1829             // If the fixed layer has a blur/drop-shadow filter applied on at least one of its parents, we cannot 
1830             // scroll using the fast path, otherwise the outsets of the filter will be moved around the page.
1831             return false;
1832         }
1833
1834         // FIXME: use pixel snapping instead of enclosing when ScrollView has finished transitioning from IntRect to Float/LayoutRect.
1835         IntRect updateRect = enclosingIntRect(layer->repaintRectIncludingNonCompositingDescendants());
1836         updateRect = contentsToRootView(updateRect);
1837         if (!isCompositedContentLayer && clipsRepaints())
1838             updateRect.intersect(rectToScroll);
1839         if (!updateRect.isEmpty())
1840             regionToUpdate.unite(updateRect);
1841     }
1842
1843     // 1) scroll
1844     hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1845
1846     // 2) update the area of fixed objects that has been invalidated
1847     Vector<IntRect> subRectsToUpdate = regionToUpdate.rects();
1848     size_t viewportConstrainedObjectsCount = subRectsToUpdate.size();
1849     for (size_t i = 0; i < viewportConstrainedObjectsCount; ++i) {
1850         IntRect updateRect = subRectsToUpdate[i];
1851         IntRect scrolledRect = updateRect;
1852         scrolledRect.move(scrollDelta);
1853         updateRect.unite(scrolledRect);
1854         if (isCompositedContentLayer) {
1855             updateRect = rootViewToContents(updateRect);
1856             ASSERT(renderView());
1857             renderView()->layer()->setBackingNeedsRepaintInRect(updateRect);
1858             continue;
1859         }
1860         if (clipsRepaints())
1861             updateRect.intersect(rectToScroll);
1862         hostWindow()->invalidateContentsAndRootView(updateRect);
1863     }
1864
1865     return true;
1866 }
1867
1868 void FrameView::scrollContentsSlowPath(const IntRect& updateRect)
1869 {
1870     repaintSlowRepaintObjects();
1871
1872     if (!usesCompositedScrolling() && isEnclosedInCompositingLayer()) {
1873         if (RenderWidget* frameRenderer = frame().ownerRenderer()) {
1874             LayoutRect rect(frameRenderer->borderLeft() + frameRenderer->paddingLeft(), frameRenderer->borderTop() + frameRenderer->paddingTop(),
1875                 visibleWidth(), visibleHeight());
1876             frameRenderer->repaintRectangle(rect);
1877             return;
1878         }
1879     }
1880
1881     ScrollView::scrollContentsSlowPath(updateRect);
1882 }
1883
1884 void FrameView::repaintSlowRepaintObjects()
1885 {
1886     if (!m_slowRepaintObjects)
1887         return;
1888
1889     // Renderers with fixed backgrounds may be in compositing layers, so we need to explicitly
1890     // repaint them after scrolling.
1891     for (auto& renderer : *m_slowRepaintObjects)
1892         renderer->repaintSlowRepaintObject();
1893 }
1894
1895 // Note that this gets called at painting time.
1896 void FrameView::setIsOverlapped(bool isOverlapped)
1897 {
1898     if (isOverlapped == m_isOverlapped)
1899         return;
1900
1901     m_isOverlapped = isOverlapped;
1902     updateCanBlitOnScrollRecursively();
1903 }
1904
1905 bool FrameView::isOverlappedIncludingAncestors() const
1906 {
1907     if (isOverlapped())
1908         return true;
1909
1910     if (FrameView* parentView = parentFrameView()) {
1911         if (parentView->isOverlapped())
1912             return true;
1913     }
1914
1915     return false;
1916 }
1917
1918 void FrameView::setContentIsOpaque(bool contentIsOpaque)
1919 {
1920     if (contentIsOpaque == m_contentIsOpaque)
1921         return;
1922
1923     m_contentIsOpaque = contentIsOpaque;
1924     updateCanBlitOnScrollRecursively();
1925 }
1926
1927 void FrameView::restoreScrollbar()
1928 {
1929     setScrollbarsSuppressed(false);
1930 }
1931
1932 bool FrameView::scrollToFragment(const URL& url)
1933 {
1934     // If our URL has no ref, then we have no place we need to jump to.
1935     // OTOH If CSS target was set previously, we want to set it to 0, recalc
1936     // and possibly repaint because :target pseudo class may have been
1937     // set (see bug 11321).
1938     if (!url.hasFragmentIdentifier() && !frame().document()->cssTarget())
1939         return false;
1940
1941     String fragmentIdentifier = url.fragmentIdentifier();
1942     if (scrollToAnchor(fragmentIdentifier))
1943         return true;
1944
1945     // Try again after decoding the ref, based on the document's encoding.
1946     if (TextResourceDecoder* decoder = frame().document()->decoder())
1947         return scrollToAnchor(decodeURLEscapeSequences(fragmentIdentifier, decoder->encoding()));
1948
1949     return false;
1950 }
1951
1952 bool FrameView::scrollToAnchor(const String& name)
1953 {
1954     ASSERT(frame().document());
1955     auto& document = *frame().document();
1956
1957     if (!document.haveStylesheetsLoaded()) {
1958         document.setGotoAnchorNeededAfterStylesheetsLoad(true);
1959         return false;
1960     }
1961
1962     document.setGotoAnchorNeededAfterStylesheetsLoad(false);
1963
1964     Element* anchorElement = document.findAnchor(name);
1965
1966     // Setting to null will clear the current target.
1967     document.setCSSTarget(anchorElement);
1968
1969     if (is<SVGDocument>(document)) {
1970         if (auto* rootElement = downcast<SVGDocument>(document).rootElement()) {
1971             rootElement->scrollToAnchor(name, anchorElement);
1972             if (!anchorElement)
1973                 return true;
1974         }
1975     }
1976   
1977     // Implement the rule that "" and "top" both mean top of page as in other browsers.
1978     if (!anchorElement && !(name.isEmpty() || equalIgnoringCase(name, "top")))
1979         return false;
1980
1981     ContainerNode* scrollPositionAnchor = anchorElement;
1982     if (!scrollPositionAnchor)
1983         scrollPositionAnchor = frame().document();
1984     maintainScrollPositionAtAnchor(scrollPositionAnchor);
1985     
1986     // If the anchor accepts keyboard focus, move focus there to aid users relying on keyboard navigation.
1987     if (anchorElement && anchorElement->isFocusable())
1988         document.setFocusedElement(anchorElement);
1989     
1990     return true;
1991 }
1992
1993 void FrameView::maintainScrollPositionAtAnchor(ContainerNode* anchorNode)
1994 {
1995     m_maintainScrollPositionAnchor = anchorNode;
1996     if (!m_maintainScrollPositionAnchor)
1997         return;
1998
1999     // We need to update the layout before scrolling, otherwise we could
2000     // really mess things up if an anchor scroll comes at a bad moment.
2001     frame().document()->updateStyleIfNeeded();
2002     // Only do a layout if changes have occurred that make it necessary.
2003     RenderView* renderView = this->renderView();
2004     if (renderView && renderView->needsLayout())
2005         layout();
2006     else
2007         scrollToAnchor();
2008 }
2009
2010 void FrameView::scrollElementToRect(Element* element, const IntRect& rect)
2011 {
2012     frame().document()->updateLayoutIgnorePendingStylesheets();
2013
2014     LayoutRect bounds;
2015     if (RenderElement* renderer = element->renderer())
2016         bounds = renderer->anchorRect();
2017     int centeringOffsetX = (rect.width() - bounds.width()) / 2;
2018     int centeringOffsetY = (rect.height() - bounds.height()) / 2;
2019     setScrollPosition(IntPoint(bounds.x() - centeringOffsetX - rect.x(), bounds.y() - centeringOffsetY - rect.y()));
2020 }
2021
2022 void FrameView::setScrollPosition(const IntPoint& scrollPoint)
2023 {
2024     TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
2025     m_maintainScrollPositionAnchor = nullptr;
2026     Page* page = frame().page();
2027     if (page && page->expectsWheelEventTriggers())
2028         scrollAnimator().setWheelEventTestTrigger(page->testTrigger());
2029     ScrollView::setScrollPosition(scrollPoint);
2030 }
2031
2032 void FrameView::delegatesScrollingDidChange()
2033 {
2034     // When we switch to delgatesScrolling mode, we should destroy the scrolling/clipping layers in RenderLayerCompositor.
2035     if (hasCompositedContent())
2036         clearBackingStores();
2037 }
2038
2039 #if USE(COORDINATED_GRAPHICS)
2040 void FrameView::setFixedVisibleContentRect(const IntRect& visibleContentRect)
2041 {
2042     bool visibleContentSizeDidChange = false;
2043     if (visibleContentRect.size() != this->fixedVisibleContentRect().size()) {
2044         // When the viewport size changes or the content is scaled, we need to
2045         // reposition the fixed and sticky positioned elements.
2046         setViewportConstrainedObjectsNeedLayout();
2047         visibleContentSizeDidChange = true;
2048     }
2049
2050     IntSize offset = scrollOffset();
2051     IntPoint oldPosition = scrollPosition();
2052     ScrollView::setFixedVisibleContentRect(visibleContentRect);
2053     if (offset != scrollOffset()) {
2054         updateLayerPositionsAfterScrolling();
2055         if (frame().settings().acceleratedCompositingForFixedPositionEnabled())
2056             updateCompositingLayersAfterScrolling();
2057         IntPoint newPosition = scrollPosition();
2058         scrollAnimator().setCurrentPosition(scrollPosition());
2059         scrollPositionChanged(oldPosition, newPosition);
2060     }
2061     if (visibleContentSizeDidChange) {
2062         // Update the scroll-bars to calculate new page-step size.
2063         updateScrollbars(scrollOffset());
2064     }
2065     didChangeScrollOffset();
2066 }
2067 #endif
2068
2069 void FrameView::setViewportConstrainedObjectsNeedLayout()
2070 {
2071     if (!hasViewportConstrainedObjects())
2072         return;
2073
2074     for (auto& renderer : *m_viewportConstrainedObjects)
2075         renderer->setNeedsLayout();
2076 }
2077
2078 void FrameView::didChangeScrollOffset()
2079 {
2080     frame().mainFrame().pageOverlayController().didScrollFrame(frame());
2081     frame().loader().client().didChangeScrollOffset();
2082 }
2083
2084 void FrameView::scrollPositionChangedViaPlatformWidgetImpl(const IntPoint& oldPosition, const IntPoint& newPosition)
2085 {
2086     updateLayerPositionsAfterScrolling();
2087     updateCompositingLayersAfterScrolling();
2088     repaintSlowRepaintObjects();
2089     scrollPositionChanged(oldPosition, newPosition);
2090 }
2091
2092 void FrameView::scrollPositionChanged(const IntPoint& oldPosition, const IntPoint& newPosition)
2093 {
2094     Page* page = frame().page();
2095     auto throttlingDelay = page ? page->chrome().client().eventThrottlingDelay() : std::chrono::milliseconds::zero();
2096
2097     if (throttlingDelay == std::chrono::milliseconds::zero()) {
2098         m_delayedScrollEventTimer.stop();
2099         sendScrollEvent();
2100     } else if (!m_delayedScrollEventTimer.isActive())
2101         m_delayedScrollEventTimer.startOneShot(throttlingDelay);
2102
2103     if (Document* document = frame().document())
2104         document->sendWillRevealEdgeEventsIfNeeded(oldPosition, newPosition, visibleContentRect(), contentsSize());
2105
2106     if (RenderView* renderView = this->renderView()) {
2107         if (renderView->usesCompositing())
2108             renderView->compositor().frameViewDidScroll();
2109     }
2110
2111     viewportContentsChanged();
2112 }
2113
2114 void FrameView::applyRecursivelyWithVisibleRect(const std::function<void (FrameView& frameView, const IntRect& visibleRect)>& apply)
2115 {
2116     IntRect windowClipRect = this->windowClipRect();
2117     auto visibleRect = windowToContents(windowClipRect);
2118     apply(*this, visibleRect);
2119
2120     // Recursive call for subframes. We cache the current FrameView's windowClipRect to avoid recomputing it for every subframe.
2121     TemporaryChange<IntRect*> windowClipRectCache(m_cachedWindowClipRect, &windowClipRect);
2122     for (Frame* childFrame = frame().tree().firstChild(); childFrame; childFrame = childFrame->tree().nextSibling()) {
2123         if (auto* childView = childFrame->view())
2124             childView->applyRecursivelyWithVisibleRect(apply);
2125     }
2126 }
2127
2128 void FrameView::resumeVisibleImageAnimations(const IntRect& visibleRect)
2129 {
2130     if (visibleRect.isEmpty())
2131         return;
2132
2133     if (auto* renderView = frame().contentRenderer())
2134         renderView->resumePausedImageAnimationsIfNeeded(visibleRect);
2135 }
2136
2137 void FrameView::updateScriptedAnimationsThrottlingState(const IntRect& visibleRect)
2138 {
2139 #if ENABLE(REQUEST_ANIMATION_FRAME)
2140     if (frame().isMainFrame())
2141         return;
2142
2143     auto* document = frame().document();
2144     if (!document)
2145         return;
2146
2147     auto* scriptedAnimationController = document->scriptedAnimationController();
2148     if (!scriptedAnimationController)
2149         return;
2150
2151     // FIXME: This doesn't work for subframes of a "display: none" frame because
2152     // they have a non-null ownerRenderer.
2153     bool shouldThrottle = !frame().ownerRenderer() || visibleRect.isEmpty();
2154     scriptedAnimationController->setThrottled(shouldThrottle);
2155 #else
2156     UNUSED_PARAM(visibleRect);
2157 #endif
2158 }
2159
2160
2161 void FrameView::resumeVisibleImageAnimationsIncludingSubframes()
2162 {
2163     applyRecursivelyWithVisibleRect([] (FrameView& frameView, const IntRect& visibleRect) {
2164         frameView.resumeVisibleImageAnimations(visibleRect);
2165     });
2166 }
2167
2168 void FrameView::updateLayerPositionsAfterScrolling()
2169 {
2170     // If we're scrolling as a result of updating the view size after layout, we'll update widgets and layer positions soon anyway.
2171     if (m_layoutPhase == InViewSizeAdjust)
2172         return;
2173
2174     if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
2175         if (RenderView* renderView = this->renderView()) {
2176             updateWidgetPositions();
2177             renderView->layer()->updateLayerPositionsAfterDocumentScroll();
2178         }
2179     }
2180 }
2181
2182 bool FrameView::shouldUpdateCompositingLayersAfterScrolling() const
2183 {
2184 #if ENABLE(ASYNC_SCROLLING)
2185     // If the scrolling thread is updating the fixed elements, then the FrameView should not update them as well.
2186
2187     Page* page = frame().page();
2188     if (!page)
2189         return true;
2190
2191     if (&page->mainFrame() != m_frame.ptr())
2192         return true;
2193
2194     ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator();
2195     if (!scrollingCoordinator)
2196         return true;
2197
2198     if (!scrollingCoordinator->supportsFixedPositionLayers())
2199         return true;
2200
2201     if (scrollingCoordinator->shouldUpdateScrollLayerPositionSynchronously())
2202         return true;
2203
2204     if (inProgrammaticScroll())
2205         return true;
2206
2207     return false;
2208 #endif
2209     return true;
2210 }
2211
2212 void FrameView::updateCompositingLayersAfterScrolling()
2213 {
2214     ASSERT(m_layoutPhase >= InPostLayout || m_layoutPhase == OutsideLayout);
2215
2216     if (!shouldUpdateCompositingLayersAfterScrolling())
2217         return;
2218
2219     if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
2220         if (RenderView* renderView = this->renderView())
2221             renderView->compositor().updateCompositingLayers(CompositingUpdateOnScroll);
2222     }
2223 }
2224
2225 bool FrameView::isRubberBandInProgress() const
2226 {
2227     if (scrollbarsSuppressed())
2228         return false;
2229
2230     // If the scrolling thread updates the scroll position for this FrameView, then we should return
2231     // ScrollingCoordinator::isRubberBandInProgress().
2232     if (Page* page = frame().page()) {
2233         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator()) {
2234             if (!scrollingCoordinator->shouldUpdateScrollLayerPositionSynchronously())
2235                 return scrollingCoordinator->isRubberBandInProgress();
2236         }
2237     }
2238
2239     // If the main thread updates the scroll position for this FrameView, we should return
2240     // ScrollAnimator::isRubberBandInProgress().
2241     if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
2242         return scrollAnimator->isRubberBandInProgress();
2243
2244     return false;
2245 }
2246
2247 bool FrameView::requestScrollPositionUpdate(const IntPoint& position)
2248 {
2249 #if ENABLE(ASYNC_SCROLLING)
2250     if (TiledBacking* tiledBacking = this->tiledBacking())
2251         tiledBacking->prepopulateRect(FloatRect(position, visibleContentRect().size()));
2252 #endif
2253
2254 #if ENABLE(ASYNC_SCROLLING) || USE(COORDINATED_GRAPHICS)
2255     if (Page* page = frame().page()) {
2256         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
2257             return scrollingCoordinator->requestScrollPositionUpdate(*this, position);
2258     }
2259 #else
2260     UNUSED_PARAM(position);
2261 #endif
2262
2263     return false;
2264 }
2265
2266 HostWindow* FrameView::hostWindow() const
2267 {
2268     if (Page* page = frame().page())
2269         return &page->chrome();
2270     return nullptr;
2271 }
2272
2273 void FrameView::addTrackedRepaintRect(const FloatRect& r)
2274 {
2275     if (!m_isTrackingRepaints || r.isEmpty())
2276         return;
2277
2278     FloatRect repaintRect = r;
2279     repaintRect.move(-scrollOffset());
2280     m_trackedRepaintRects.append(repaintRect);
2281 }
2282
2283 void FrameView::repaintContentRectangle(const IntRect& r)
2284 {
2285     ASSERT(!frame().ownerElement());
2286
2287     if (!shouldUpdate())
2288         return;
2289
2290     ScrollView::repaintContentRectangle(r);
2291 }
2292
2293 static unsigned countRenderedCharactersInRenderObjectWithThreshold(const RenderElement& renderer, unsigned threshold)
2294 {
2295     unsigned count = 0;
2296     for (const RenderObject* descendant = &renderer; descendant; descendant = descendant->nextInPreOrder()) {
2297         if (is<RenderText>(*descendant)) {
2298             count += downcast<RenderText>(*descendant).text()->length();
2299             if (count >= threshold)
2300                 break;
2301         }
2302     }
2303     return count;
2304 }
2305
2306 bool FrameView::renderedCharactersExceed(unsigned threshold)
2307 {
2308     if (!frame().contentRenderer())
2309         return false;
2310     return countRenderedCharactersInRenderObjectWithThreshold(*frame().contentRenderer(), threshold) >= threshold;
2311 }
2312
2313 void FrameView::availableContentSizeChanged(AvailableSizeChangeReason reason)
2314 {
2315     if (Document* document = frame().document())
2316         document->updateViewportUnitsOnResize();
2317
2318     setNeedsLayout();
2319     ScrollView::availableContentSizeChanged(reason);
2320 }
2321
2322 bool FrameView::shouldLayoutAfterContentsResized() const
2323 {
2324     return !useFixedLayout() || useCustomFixedPositionLayoutRect();
2325 }
2326
2327 void FrameView::updateContentsSize()
2328 {
2329     // We check to make sure the view is attached to a frame() as this method can
2330     // be triggered before the view is attached by Frame::createView(...) setting
2331     // various values such as setScrollBarModes(...) for example.  An ASSERT is
2332     // triggered when a view is layout before being attached to a frame().
2333     if (!frame().view())
2334         return;
2335
2336 #if PLATFORM(IOS)
2337     if (RenderView* root = m_frame->contentRenderer()) {
2338         if (useCustomFixedPositionLayoutRect() && hasViewportConstrainedObjects()) {
2339             setViewportConstrainedObjectsNeedLayout();
2340             // We must eagerly enter compositing mode because fixed position elements
2341             // will not have been made compositing via a preceding style change before
2342             // m_useCustomFixedPositionLayoutRect was true.
2343             root->compositor().enableCompositingMode();
2344         }
2345     }
2346 #endif
2347
2348     if (shouldLayoutAfterContentsResized() && needsLayout())
2349         layout();
2350
2351     if (RenderView* renderView = this->renderView()) {
2352         if (renderView->usesCompositing())
2353             renderView->compositor().frameViewDidChangeSize();
2354     }
2355 }
2356
2357 void FrameView::addedOrRemovedScrollbar()
2358 {
2359     if (RenderView* renderView = this->renderView()) {
2360         if (renderView->usesCompositing())
2361             renderView->compositor().frameViewDidAddOrRemoveScrollbars();
2362     }
2363 }
2364
2365 static LayerFlushThrottleState::Flags determineLayerFlushThrottleState(Page& page)
2366 {
2367     // We only throttle when constantly receiving new data during the inital page load.
2368     if (!page.progress().isMainLoadProgressing())
2369         return 0;
2370     // Scrolling during page loading disables throttling.
2371     if (page.mainFrame().view()->wasScrolledByUser())
2372         return 0;
2373     // Disable for image documents so large GIF animations don't get throttled during loading.
2374     auto* document = page.mainFrame().document();
2375     if (!document || is<ImageDocument>(*document))
2376         return 0;
2377     return LayerFlushThrottleState::Enabled;
2378 }
2379
2380 void FrameView::disableLayerFlushThrottlingTemporarilyForInteraction()
2381 {
2382     if (!frame().page())
2383         return;
2384     auto& page = *frame().page();
2385
2386     LayerFlushThrottleState::Flags flags = LayerFlushThrottleState::UserIsInteracting | determineLayerFlushThrottleState(page);
2387     if (page.chrome().client().adjustLayerFlushThrottling(flags))
2388         return;
2389
2390     if (RenderView* view = renderView())
2391         view->compositor().disableLayerFlushThrottlingTemporarilyForInteraction();
2392 }
2393
2394 void FrameView::loadProgressingStatusChanged()
2395 {
2396     updateLayerFlushThrottling();
2397     adjustTiledBackingCoverage();
2398 }
2399
2400 void FrameView::updateLayerFlushThrottling()
2401 {
2402     Page* page = frame().page();
2403     if (!page)
2404         return;
2405
2406     ASSERT(frame().isMainFrame());
2407
2408     LayerFlushThrottleState::Flags flags = determineLayerFlushThrottleState(*page);
2409
2410     // See if the client is handling throttling.
2411     if (page->chrome().client().adjustLayerFlushThrottling(flags))
2412         return;
2413
2414     for (auto* frame = m_frame.ptr(); frame; frame = frame->tree().traverseNext(m_frame.ptr())) {
2415         if (RenderView* renderView = frame->contentRenderer())
2416             renderView->compositor().setLayerFlushThrottlingEnabled(flags & LayerFlushThrottleState::Enabled);
2417     }
2418 }
2419
2420 void FrameView::adjustTiledBackingCoverage()
2421 {
2422     if (!m_speculativeTilingEnabled)
2423         enableSpeculativeTilingIfNeeded();
2424
2425     RenderView* renderView = this->renderView();
2426     if (renderView && renderView->layer()->backing())
2427         renderView->layer()->backing()->adjustTiledBackingCoverage();
2428 #if PLATFORM(IOS)
2429     if (LegacyTileCache* tileCache = legacyTileCache())
2430         tileCache->setSpeculativeTileCreationEnabled(m_speculativeTilingEnabled);
2431 #endif
2432 }
2433
2434 static bool shouldEnableSpeculativeTilingDuringLoading(const FrameView& view)
2435 {
2436     Page* page = view.frame().page();
2437     return page && view.isVisuallyNonEmpty() && !page->progress().isMainLoadProgressing();
2438 }
2439
2440 void FrameView::enableSpeculativeTilingIfNeeded()
2441 {
2442     ASSERT(!m_speculativeTilingEnabled);
2443     if (m_wasScrolledByUser) {
2444         m_speculativeTilingEnabled = true;
2445         return;
2446     }
2447     if (!shouldEnableSpeculativeTilingDuringLoading(*this))
2448         return;
2449     if (m_speculativeTilingEnableTimer.isActive())
2450         return;
2451     // Delay enabling a bit as load completion may trigger further loading from scripts.
2452     static const double speculativeTilingEnableDelay = 0.5;
2453     m_speculativeTilingEnableTimer.startOneShot(speculativeTilingEnableDelay);
2454 }
2455
2456 void FrameView::speculativeTilingEnableTimerFired()
2457 {
2458     if (m_speculativeTilingEnabled)
2459         return;
2460     m_speculativeTilingEnabled = shouldEnableSpeculativeTilingDuringLoading(*this);
2461     adjustTiledBackingCoverage();
2462 }
2463
2464 void FrameView::layoutTimerFired()
2465 {
2466 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2467     if (!frame().document()->ownerElement())
2468         printf("Layout timer fired at %lld\n", frame().document()->elapsedTime().count());
2469 #endif
2470     layout();
2471 }
2472
2473 void FrameView::scheduleRelayout()
2474 {
2475     // FIXME: We should assert the page is not in the page cache, but that is causing
2476     // too many false assertions.  See <rdar://problem/7218118>.
2477     ASSERT(frame().view() == this);
2478
2479     if (m_layoutRoot) {
2480         m_layoutRoot->markContainingBlocksForLayout(false);
2481         m_layoutRoot = nullptr;
2482     }
2483     if (!m_layoutSchedulingEnabled)
2484         return;
2485     if (!needsLayout())
2486         return;
2487     if (!frame().document()->shouldScheduleLayout())
2488         return;
2489     InspectorInstrumentation::didInvalidateLayout(frame());
2490     // When frame flattening is enabled, the contents of the frame could affect the layout of the parent frames.
2491     // Also invalidate parent frame starting from the owner element of this frame.
2492     if (frame().ownerRenderer() && isInChildFrameWithFrameFlattening())
2493         frame().ownerRenderer()->setNeedsLayout(MarkContainingBlockChain);
2494
2495     std::chrono::milliseconds delay = frame().document()->minimumLayoutDelay();
2496     if (m_layoutTimer.isActive() && m_delayedLayout && !delay.count())
2497         unscheduleRelayout();
2498     if (m_layoutTimer.isActive())
2499         return;
2500
2501     m_delayedLayout = delay.count();
2502
2503 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2504     if (!frame().document()->ownerElement())
2505         printf("Scheduling layout for %d\n", delay);
2506 #endif
2507
2508     m_layoutTimer.startOneShot(delay);
2509 }
2510
2511 static bool isObjectAncestorContainerOf(RenderObject* ancestor, RenderObject* descendant)
2512 {
2513     for (RenderObject* r = descendant; r; r = r->container()) {
2514         if (r == ancestor)
2515             return true;
2516     }
2517     return false;
2518 }
2519
2520 void FrameView::scheduleRelayoutOfSubtree(RenderElement& newRelayoutRoot)
2521 {
2522     ASSERT(renderView());
2523     RenderView& renderView = *this->renderView();
2524
2525     // Try to catch unnecessary work during render tree teardown.
2526     ASSERT(!renderView.documentBeingDestroyed());
2527     ASSERT(frame().view() == this);
2528
2529     if (renderView.needsLayout()) {
2530         newRelayoutRoot.markContainingBlocksForLayout(false);
2531         return;
2532     }
2533
2534     if (!layoutPending() && m_layoutSchedulingEnabled) {
2535         std::chrono::milliseconds delay = renderView.document().minimumLayoutDelay();
2536         ASSERT(!newRelayoutRoot.container() || !newRelayoutRoot.container()->needsLayout());
2537         m_layoutRoot = &newRelayoutRoot;
2538         InspectorInstrumentation::didInvalidateLayout(frame());
2539         m_delayedLayout = delay.count();
2540         m_layoutTimer.startOneShot(delay);
2541         return;
2542     }
2543
2544     if (m_layoutRoot == &newRelayoutRoot)
2545         return;
2546
2547     if (!m_layoutRoot) {
2548         // Just relayout the subtree.
2549         newRelayoutRoot.markContainingBlocksForLayout(false);
2550         InspectorInstrumentation::didInvalidateLayout(frame());
2551         return;
2552     }
2553
2554     if (isObjectAncestorContainerOf(m_layoutRoot, &newRelayoutRoot)) {
2555         // Keep the current root.
2556         newRelayoutRoot.markContainingBlocksForLayout(false, m_layoutRoot);
2557         ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
2558         return;
2559     }
2560
2561     if (isObjectAncestorContainerOf(&newRelayoutRoot, m_layoutRoot)) {
2562         // Re-root at newRelayoutRoot.
2563         m_layoutRoot->markContainingBlocksForLayout(false, &newRelayoutRoot);
2564         m_layoutRoot = &newRelayoutRoot;
2565         ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
2566         InspectorInstrumentation::didInvalidateLayout(frame());
2567         return;
2568     }
2569
2570     // Just do a full relayout.
2571     m_layoutRoot->markContainingBlocksForLayout(false);
2572     m_layoutRoot = nullptr;
2573     newRelayoutRoot.markContainingBlocksForLayout(false);
2574     InspectorInstrumentation::didInvalidateLayout(frame());
2575 }
2576
2577 bool FrameView::layoutPending() const
2578 {
2579     return m_layoutTimer.isActive();
2580 }
2581
2582 bool FrameView::needsStyleRecalcOrLayout(bool includeSubframes) const
2583 {
2584     if (frame().document() && frame().document()->childNeedsStyleRecalc())
2585         return true;
2586     
2587     if (needsLayout())
2588         return true;
2589
2590     if (!includeSubframes)
2591         return false;
2592
2593     for (auto& frameView : renderedChildFrameViews()) {
2594         if (frameView->needsStyleRecalcOrLayout())
2595             return true;
2596     }
2597
2598     return false;
2599 }
2600
2601 bool FrameView::needsLayout() const
2602 {
2603     // This can return true in cases where the document does not have a body yet.
2604     // Document::shouldScheduleLayout takes care of preventing us from scheduling
2605     // layout in that case.
2606     RenderView* renderView = this->renderView();
2607     return layoutPending()
2608         || (renderView && renderView->needsLayout())
2609         || m_layoutRoot
2610         || (m_deferSetNeedsLayoutCount && m_setNeedsLayoutWasDeferred);
2611 }
2612
2613 void FrameView::setNeedsLayout()
2614 {
2615     if (m_deferSetNeedsLayoutCount) {
2616         m_setNeedsLayoutWasDeferred = true;
2617         return;
2618     }
2619
2620     if (RenderView* renderView = this->renderView())
2621         renderView->setNeedsLayout();
2622 }
2623
2624 void FrameView::unscheduleRelayout()
2625 {
2626     if (m_postLayoutTasksTimer.isActive())
2627         m_postLayoutTasksTimer.stop();
2628
2629     if (!m_layoutTimer.isActive())
2630         return;
2631
2632 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2633     if (!frame().document()->ownerElement())
2634         printf("Layout timer unscheduled at %d\n", frame().document()->elapsedTime());
2635 #endif
2636     
2637     m_layoutTimer.stop();
2638     m_delayedLayout = false;
2639 }
2640
2641 #if ENABLE(REQUEST_ANIMATION_FRAME)
2642 void FrameView::serviceScriptedAnimations(double monotonicAnimationStartTime)
2643 {
2644     for (auto* frame = m_frame.ptr(); frame; frame = frame->tree().traverseNext()) {
2645         frame->view()->serviceScrollAnimations();
2646         frame->animation().serviceAnimations();
2647     }
2648
2649     Vector<RefPtr<Document>> documents;
2650     for (auto* frame = m_frame.ptr(); frame; frame = frame->tree().traverseNext())
2651         documents.append(frame->document());
2652
2653     for (size_t i = 0; i < documents.size(); ++i)
2654         documents[i]->serviceScriptedAnimations(monotonicAnimationStartTime);
2655 }
2656 #endif
2657
2658 bool FrameView::isTransparent() const
2659 {
2660     return m_isTransparent;
2661 }
2662
2663 void FrameView::setTransparent(bool isTransparent)
2664 {
2665     if (m_isTransparent == isTransparent)
2666         return;
2667
2668     m_isTransparent = isTransparent;
2669
2670     // setTransparent can be called in the window between FrameView initialization
2671     // and switching in the new Document; this means that the RenderView that we
2672     // retrieve is actually attached to the previous Document, which is going away,
2673     // and must not update compositing layers.
2674     if (!isViewForDocumentInFrame())
2675         return;
2676
2677     renderView()->compositor().rootBackgroundTransparencyChanged();
2678 }
2679
2680 bool FrameView::hasOpaqueBackground() const
2681 {
2682     return !m_isTransparent && !m_baseBackgroundColor.hasAlpha();
2683 }
2684
2685 Color FrameView::baseBackgroundColor() const
2686 {
2687     return m_baseBackgroundColor;
2688 }
2689
2690 void FrameView::setBaseBackgroundColor(const Color& backgroundColor)
2691 {
2692     bool hadAlpha = m_baseBackgroundColor.hasAlpha();
2693     
2694     if (!backgroundColor.isValid())
2695         m_baseBackgroundColor = Color::white;
2696     else
2697         m_baseBackgroundColor = backgroundColor;
2698
2699     if (!isViewForDocumentInFrame())
2700         return;
2701
2702     recalculateScrollbarOverlayStyle();
2703
2704     if (m_baseBackgroundColor.hasAlpha() != hadAlpha)
2705         renderView()->compositor().rootBackgroundTransparencyChanged();
2706 }
2707
2708 void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent)
2709 {
2710     for (auto* frame = m_frame.ptr(); frame; frame = frame->tree().traverseNext(m_frame.ptr())) {
2711         if (FrameView* view = frame->view()) {
2712             view->setTransparent(transparent);
2713             view->setBaseBackgroundColor(backgroundColor);
2714         }
2715     }
2716 }
2717
2718 bool FrameView::hasExtendedBackgroundRectForPainting() const
2719 {
2720     if (!frame().settings().backgroundShouldExtendBeyondPage())
2721         return false;
2722
2723     TiledBacking* tiledBacking = this->tiledBacking();
2724     if (!tiledBacking)
2725         return false;
2726
2727     return tiledBacking->hasMargins();
2728 }
2729
2730 void FrameView::updateExtendBackgroundIfNecessary()
2731 {
2732     ExtendedBackgroundMode mode = calculateExtendedBackgroundMode();
2733     if (mode == ExtendedBackgroundModeNone)
2734         return;
2735
2736     updateTilesForExtendedBackgroundMode(mode);
2737 }
2738
2739 FrameView::ExtendedBackgroundMode FrameView::calculateExtendedBackgroundMode() const
2740 {
2741     // Just because Settings::backgroundShouldExtendBeyondPage() is true does not necessarily mean
2742     // that the background rect needs to be extended for painting. Simple backgrounds can be extended
2743     // just with RenderLayerCompositor::setRootExtendedBackgroundColor(). More complicated backgrounds,
2744     // such as images, require extending the background rect to continue painting into the extended
2745     // region. This function finds out if it is necessary to extend the background rect for painting.
2746
2747 #if PLATFORM(IOS)
2748     // <rdar://problem/16201373>
2749     return ExtendedBackgroundModeNone;
2750 #endif
2751
2752     if (!frame().settings().backgroundShouldExtendBeyondPage())
2753         return ExtendedBackgroundModeNone;
2754
2755     if (!frame().isMainFrame())
2756         return ExtendedBackgroundModeNone;
2757
2758     Document* document = frame().document();
2759     if (!document)
2760         return ExtendedBackgroundModeNone;
2761
2762     auto documentElement = document->documentElement();
2763     auto documentElementRenderer = documentElement ? documentElement->renderer() : nullptr;
2764     if (!documentElementRenderer)
2765         return ExtendedBackgroundModeNone;
2766
2767     auto& renderer = documentElementRenderer->rendererForRootBackground();
2768     if (!renderer.style().hasBackgroundImage())
2769         return ExtendedBackgroundModeNone;
2770
2771     ExtendedBackgroundMode mode = ExtendedBackgroundModeNone;
2772
2773     if (renderer.style().backgroundRepeatX() == RepeatFill)
2774         mode |= ExtendedBackgroundModeHorizontal;
2775     if (renderer.style().backgroundRepeatY() == RepeatFill)
2776         mode |= ExtendedBackgroundModeVertical;
2777
2778     return mode;
2779 }
2780
2781 void FrameView::updateTilesForExtendedBackgroundMode(ExtendedBackgroundMode mode)
2782 {
2783     if (!frame().settings().backgroundShouldExtendBeyondPage())
2784         return;
2785
2786     RenderView* renderView = this->renderView();
2787     if (!renderView)
2788         return;
2789
2790     RenderLayerBacking* backing = renderView->layer()->backing();
2791     if (!backing)
2792         return;
2793
2794     TiledBacking* tiledBacking = backing->graphicsLayer()->tiledBacking();
2795     if (!tiledBacking)
2796         return;
2797
2798     ExtendedBackgroundMode existingMode = ExtendedBackgroundModeNone;
2799     if (tiledBacking->hasVerticalMargins())
2800         existingMode |= ExtendedBackgroundModeVertical;
2801     if (tiledBacking->hasHorizontalMargins())
2802         existingMode |= ExtendedBackgroundModeHorizontal;
2803
2804     if (existingMode == mode)
2805         return;
2806
2807     renderView->compositor().setRootExtendedBackgroundColor(mode == ExtendedBackgroundModeAll ? Color() : documentBackgroundColor());
2808     backing->setTiledBackingHasMargins(mode & ExtendedBackgroundModeHorizontal, mode & ExtendedBackgroundModeVertical);
2809 }
2810
2811 IntRect FrameView::extendedBackgroundRectForPainting() const
2812 {
2813     TiledBacking* tiledBacking = this->tiledBacking();
2814     if (!tiledBacking)
2815         return IntRect();
2816     
2817     RenderView* renderView = this->renderView();
2818     if (!renderView)
2819         return IntRect();
2820     
2821     LayoutRect extendedRect = renderView->unextendedBackgroundRect(renderView);
2822     if (!tiledBacking->hasMargins())
2823         return snappedIntRect(extendedRect);
2824     
2825     extendedRect.moveBy(LayoutPoint(-tiledBacking->leftMarginWidth(), -tiledBacking->topMarginHeight()));
2826     extendedRect.expand(LayoutSize(tiledBacking->leftMarginWidth() + tiledBacking->rightMarginWidth(), tiledBacking->topMarginHeight() + tiledBacking->bottomMarginHeight()));
2827     return snappedIntRect(extendedRect);
2828 }
2829
2830 bool FrameView::shouldUpdateWhileOffscreen() const
2831 {
2832     return m_shouldUpdateWhileOffscreen;
2833 }
2834
2835 void FrameView::setShouldUpdateWhileOffscreen(bool shouldUpdateWhileOffscreen)
2836 {
2837     m_shouldUpdateWhileOffscreen = shouldUpdateWhileOffscreen;
2838 }
2839
2840 bool FrameView::shouldUpdate() const
2841 {
2842     if (isOffscreen() && !shouldUpdateWhileOffscreen())
2843         return false;
2844     return true;
2845 }
2846
2847 void FrameView::scrollToAnchor()
2848 {
2849     RefPtr<ContainerNode> anchorNode = m_maintainScrollPositionAnchor;
2850     if (!anchorNode)
2851         return;
2852
2853     if (!anchorNode->renderer())
2854         return;
2855
2856     LayoutRect rect;
2857     if (anchorNode != frame().document() && anchorNode->renderer())
2858         rect = anchorNode->renderer()->anchorRect();
2859
2860     // Scroll nested layers and frames to reveal the anchor.
2861     // Align to the top and to the closest side (this matches other browsers).
2862     if (anchorNode->renderer()->style().isHorizontalWritingMode())
2863         anchorNode->renderer()->scrollRectToVisible(rect, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
2864     else if (anchorNode->renderer()->style().isFlippedBlocksWritingMode())
2865         anchorNode->renderer()->scrollRectToVisible(rect, ScrollAlignment::alignRightAlways, ScrollAlignment::alignToEdgeIfNeeded);
2866     else
2867         anchorNode->renderer()->scrollRectToVisible(rect, ScrollAlignment::alignLeftAlways, ScrollAlignment::alignToEdgeIfNeeded);
2868
2869     if (AXObjectCache* cache = frame().document()->existingAXObjectCache())
2870         cache->handleScrolledToAnchor(anchorNode.get());
2871
2872     // scrollRectToVisible can call into setScrollPosition(), which resets m_maintainScrollPositionAnchor.
2873     m_maintainScrollPositionAnchor = anchorNode;
2874 }
2875
2876 void FrameView::updateEmbeddedObject(RenderEmbeddedObject& embeddedObject)
2877 {
2878     // No need to update if it's already crashed or known to be missing.
2879     if (embeddedObject.isPluginUnavailable())
2880         return;
2881
2882     HTMLFrameOwnerElement& element = embeddedObject.frameOwnerElement();
2883
2884     if (embeddedObject.isSnapshottedPlugIn()) {
2885         if (is<HTMLObjectElement>(element) || is<HTMLEmbedElement>(element)) {
2886             HTMLPlugInImageElement& pluginElement = downcast<HTMLPlugInImageElement>(element);
2887             pluginElement.checkSnapshotStatus();
2888         }
2889         return;
2890     }
2891
2892     auto weakRenderer = embeddedObject.createWeakPtr();
2893
2894     // FIXME: This could turn into a real virtual dispatch if we defined
2895     // updateWidget(PluginCreationOption) on HTMLElement.
2896     if (is<HTMLPlugInImageElement>(element)) {
2897         HTMLPlugInImageElement& pluginElement = downcast<HTMLPlugInImageElement>(element);
2898         if (pluginElement.needsCheckForSizeChange()) {
2899             pluginElement.checkSnapshotStatus();
2900             return;
2901         }
2902         if (pluginElement.needsWidgetUpdate())
2903             pluginElement.updateWidget(CreateAnyWidgetType);
2904     } else
2905         ASSERT_NOT_REACHED();
2906
2907     // It's possible the renderer was destroyed below updateWidget() since loading a plugin may execute arbitrary JavaScript.
2908     if (!weakRenderer)
2909         return;
2910
2911     embeddedObject.updateWidgetPosition();
2912 }
2913
2914 bool FrameView::updateEmbeddedObjects()
2915 {
2916     if (m_nestedLayoutCount > 1 || !m_embeddedObjectsToUpdate || m_embeddedObjectsToUpdate->isEmpty())
2917         return true;
2918
2919     WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
2920
2921     // Insert a marker for where we should stop.
2922     ASSERT(!m_embeddedObjectsToUpdate->contains(nullptr));
2923     m_embeddedObjectsToUpdate->add(nullptr);
2924
2925     while (!m_embeddedObjectsToUpdate->isEmpty()) {
2926         RenderEmbeddedObject* embeddedObject = m_embeddedObjectsToUpdate->takeFirst();
2927         if (!embeddedObject)
2928             break;
2929         updateEmbeddedObject(*embeddedObject);
2930     }
2931
2932     return m_embeddedObjectsToUpdate->isEmpty();
2933 }
2934
2935 void FrameView::updateEmbeddedObjectsTimerFired()
2936 {
2937     RefPtr<FrameView> protect(this);
2938     m_updateEmbeddedObjectsTimer.stop();
2939     for (unsigned i = 0; i < maxUpdateEmbeddedObjectsIterations; i++) {
2940         if (updateEmbeddedObjects())
2941             break;
2942     }
2943 }
2944
2945 void FrameView::flushAnyPendingPostLayoutTasks()
2946 {
2947     if (m_postLayoutTasksTimer.isActive())
2948         performPostLayoutTasks();
2949     if (m_updateEmbeddedObjectsTimer.isActive())
2950         updateEmbeddedObjectsTimerFired();
2951 }
2952
2953 void FrameView::performPostLayoutTasks()
2954 {
2955     // FIXME: We should not run any JavaScript code in this function.
2956
2957     m_postLayoutTasksTimer.stop();
2958
2959     frame().selection().didLayout();
2960
2961     if (m_nestedLayoutCount <= 1 && frame().document()->documentElement())
2962         fireLayoutRelatedMilestonesIfNeeded();
2963
2964 #if PLATFORM(IOS)
2965     // Only send layout-related delegate callbacks synchronously for the main frame to
2966     // avoid re-entering layout for the main frame while delivering a layout-related delegate
2967     // callback for a subframe.
2968     if (frame().isMainFrame()) {
2969         if (Page* page = frame().page())
2970             page->chrome().client().didLayout();
2971     }
2972 #endif
2973
2974 #if ENABLE(FONT_LOAD_EVENTS)
2975     if (RuntimeEnabledFeatures::sharedFeatures().fontLoadEventsEnabled())
2976         frame().document()->fonts()->didLayout();
2977 #endif
2978     
2979     // FIXME: We should consider adding DidLayout as a LayoutMilestone. That would let us merge this
2980     // with didLayout(LayoutMilestones).
2981     frame().loader().client().dispatchDidLayout();
2982
2983     updateWidgetPositions();
2984
2985 #if ENABLE(CSS_SCROLL_SNAP)
2986     updateSnapOffsets();
2987 #endif
2988
2989     // layout() protects FrameView, but it still can get destroyed when updateEmbeddedObjects()
2990     // is called through the post layout timer.
2991     Ref<FrameView> protect(*this);
2992
2993     m_updateEmbeddedObjectsTimer.startOneShot(0);
2994
2995     if (auto* page = frame().page()) {
2996         if (auto* scrollingCoordinator = page->scrollingCoordinator())
2997             scrollingCoordinator->frameViewLayoutUpdated(*this);
2998     }
2999
3000     if (RenderView* renderView = this->renderView()) {
3001         if (renderView->usesCompositing())
3002             renderView->compositor().frameViewDidLayout();
3003     }
3004
3005     scrollToAnchor();
3006
3007     sendResizeEventIfNeeded();
3008     viewportContentsChanged();
3009
3010     updateScrollSnapState();
3011 }
3012
3013 IntSize FrameView::sizeForResizeEvent() const
3014 {
3015 #if PLATFORM(IOS)
3016     if (m_useCustomSizeForResizeEvent)
3017         return m_customSizeForResizeEvent;
3018 #endif
3019     if (useFixedLayout() && !fixedLayoutSize().isEmpty() && delegatesScrolling())
3020         return fixedLayoutSize();
3021     return visibleContentRectIncludingScrollbars().size();
3022 }
3023
3024 void FrameView::sendResizeEventIfNeeded()
3025 {
3026     if (isInLayout() || needsLayout())
3027         return;
3028
3029     RenderView* renderView = this->renderView();
3030     if (!renderView || renderView->printing())
3031         return;
3032
3033     if (frame().page() && frame().page()->chrome().client().isSVGImageChromeClient())
3034         return;
3035
3036     IntSize currentSize = sizeForResizeEvent();
3037     float currentZoomFactor = renderView->style().zoom();
3038
3039     if (currentSize == m_lastViewportSize && currentZoomFactor == m_lastZoomFactor)
3040         return;
3041
3042     m_lastViewportSize = currentSize;
3043     m_lastZoomFactor = currentZoomFactor;
3044
3045     if (m_firstLayout)
3046         return;
3047
3048 #if PLATFORM(IOS)
3049     // Don't send the resize event if the document is loading. Some pages automatically reload
3050     // when the window is resized; Safari on iOS often resizes the window while setting up its
3051     // viewport. This obviously can cause problems.
3052     if (DocumentLoader* documentLoader = frame().loader().documentLoader()) {
3053         if (documentLoader->isLoadingInAPISense())
3054             return;
3055     }
3056 #endif
3057
3058     bool isMainFrame = frame().isMainFrame();
3059     bool canSendResizeEventSynchronously = isMainFrame && !m_shouldAutoSize;
3060
3061     RefPtr<Event> resizeEvent = Event::create(eventNames().resizeEvent, false, false);
3062     if (canSendResizeEventSynchronously)
3063         frame().document()->dispatchWindowEvent(resizeEvent.release());
3064     else {
3065         // FIXME: Queueing this event for an unpredictable time in the future seems
3066         // intrinsically racy. By the time this resize event fires, the frame might
3067         // be resized again, so we could end up with two resize events for the same size.
3068         frame().document()->enqueueWindowEvent(resizeEvent.release());
3069     }
3070
3071     if (InspectorInstrumentation::hasFrontends() && isMainFrame) {
3072         if (Page* page = frame().page()) {
3073             if (InspectorClient* inspectorClient = page->inspectorController().inspectorClient())
3074                 inspectorClient->didResizeMainFrame(&frame());
3075         }
3076     }
3077 }
3078
3079 void FrameView::willStartLiveResize()
3080 {
3081     ScrollView::willStartLiveResize();
3082     adjustTiledBackingCoverage();
3083 }
3084     
3085 void FrameView::willEndLiveResize()
3086 {
3087     ScrollView::willEndLiveResize();
3088     adjustTiledBackingCoverage();
3089 }
3090
3091 void FrameView::postLayoutTimerFired()
3092 {
3093     performPostLayoutTasks();
3094 }
3095
3096 void FrameView::registerThrottledDOMTimer(DOMTimer* timer)
3097 {
3098     m_throttledTimers.add(timer);
3099 }
3100
3101 void FrameView::unregisterThrottledDOMTimer(DOMTimer* timer)
3102 {
3103     m_throttledTimers.remove(timer);
3104 }
3105
3106 void FrameView::updateThrottledDOMTimersState(const IntRect& visibleRect)
3107 {
3108     if (m_throttledTimers.isEmpty())
3109         return;
3110
3111     // Do not iterate over the HashSet because calling DOMTimer::updateThrottlingStateAfterViewportChange()
3112     // may cause timers to remove themselves from it while we are iterating.
3113     Vector<DOMTimer*> timers;
3114     copyToVector(m_throttledTimers, timers);
3115     for (auto* timer : timers)
3116         timer->updateThrottlingStateAfterViewportChange(visibleRect);
3117 }
3118
3119 void FrameView::autoSizeIfEnabled()
3120 {
3121     if (!m_shouldAutoSize)
3122         return;
3123
3124     if (m_inAutoSize)
3125         return;
3126
3127     TemporaryChange<bool> changeInAutoSize(m_inAutoSize, true);
3128
3129     Document* document = frame().document();
3130     if (!document)
3131         return;
3132
3133     RenderView* documentView = document->renderView();
3134     Element* documentElement = document->documentElement();
3135     if (!documentView || !documentElement)
3136         return;
3137
3138     // Start from the minimum size and allow it to grow.
3139     resize(m_minAutoSize.width(), m_minAutoSize.height());
3140
3141     IntSize size = frameRect().size();
3142
3143     // Do the resizing twice. The first time is basically a rough calculation using the preferred width
3144     // which may result in a height change during the second iteration.
3145     for (int i = 0; i < 2; i++) {
3146         // Update various sizes including contentsSize, scrollHeight, etc.
3147         document->updateLayoutIgnorePendingStylesheets();
3148         int width = documentView->minPreferredLogicalWidth();
3149         int height = documentView->documentRect().height();
3150         IntSize newSize(width, height);
3151
3152         // Check to see if a scrollbar is needed for a given dimension and
3153         // if so, increase the other dimension to account for the scrollbar.
3154         // Since the dimensions are only for the view rectangle, once a
3155         // dimension exceeds the maximum, there is no need to increase it further.
3156         if (newSize.width() > m_maxAutoSize.width()) {
3157             RefPtr<Scrollbar> localHorizontalScrollbar = horizontalScrollbar();
3158             if (!localHorizontalScrollbar)
3159                 localHorizontalScrollbar = createScrollbar(HorizontalScrollbar);
3160             if (!localHorizontalScrollbar->isOverlayScrollbar())
3161                 newSize.setHeight(newSize.height() + localHorizontalScrollbar->height());
3162
3163             // Don't bother checking for a vertical scrollbar because the width is at
3164             // already greater the maximum.
3165         } else if (newSize.height() > m_maxAutoSize.height()) {
3166             RefPtr<Scrollbar> localVerticalScrollbar = verticalScrollbar();
3167             if (!localVerticalScrollbar)
3168                 localVerticalScrollbar = createScrollbar(VerticalScrollbar);
3169             if (!localVerticalScrollbar->isOverlayScrollbar())
3170                 newSize.setWidth(newSize.width() + localVerticalScrollbar->width());
3171
3172             // Don't bother checking for a horizontal scrollbar because the height is
3173             // already greater the maximum.
3174         }
3175
3176         // Ensure the size is at least the min bounds.
3177         newSize = newSize.expandedTo(m_minAutoSize);
3178
3179         // Bound the dimensions by the max bounds and determine what scrollbars to show.
3180         ScrollbarMode horizonalScrollbarMode = ScrollbarAlwaysOff;
3181         if (newSize.width() > m_maxAutoSize.width()) {
3182             newSize.setWidth(m_maxAutoSize.width());
3183             horizonalScrollbarMode = ScrollbarAlwaysOn;
3184         }
3185         ScrollbarMode verticalScrollbarMode = ScrollbarAlwaysOff;
3186         if (newSize.height() > m_maxAutoSize.height()) {
3187             newSize.setHeight(m_maxAutoSize.height());
3188             verticalScrollbarMode = ScrollbarAlwaysOn;
3189         }
3190
3191         if (newSize == size)
3192             continue;
3193
3194         // While loading only allow the size to increase (to avoid twitching during intermediate smaller states)
3195         // unless autoresize has just been turned on or the maximum size is smaller than the current size.
3196         if (m_didRunAutosize && size.height() <= m_maxAutoSize.height() && size.width() <= m_maxAutoSize.width()
3197             && !frame().loader().isComplete() && (newSize.height() < size.height() || newSize.width() < size.width()))
3198             break;
3199
3200         resize(newSize.width(), newSize.height());
3201         // Force the scrollbar state to avoid the scrollbar code adding them and causing them to be needed. For example,
3202         // a vertical scrollbar may cause text to wrap and thus increase the height (which is the only reason the scollbar is needed).
3203         setVerticalScrollbarLock(false);
3204         setHorizontalScrollbarLock(false);
3205         setScrollbarModes(horizonalScrollbarMode, verticalScrollbarMode, true, true);
3206     }
3207
3208     m_autoSizeContentSize = contentsSize();
3209
3210     if (m_autoSizeFixedMinimumHeight) {
3211         resize(m_autoSizeContentSize.width(), std::max(m_autoSizeFixedMinimumHeight, m_autoSizeContentSize.height()));
3212         document->updateLayoutIgnorePendingStylesheets();
3213     }
3214
3215     m_didRunAutosize = true;
3216 }
3217
3218 void FrameView::setAutoSizeFixedMinimumHeight(int fixedMinimumHeight)
3219 {
3220     if (m_autoSizeFixedMinimumHeight == fixedMinimumHeight)
3221         return;
3222
3223     m_autoSizeFixedMinimumHeight = fixedMinimumHeight;
3224
3225     setNeedsLayout();
3226 }
3227
3228 void FrameView::updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow)
3229 {
3230     if (!m_viewportRenderer)
3231         return;
3232     
3233     if (m_overflowStatusDirty) {
3234         m_horizontalOverflow = horizontalOverflow;
3235         m_verticalOverflow = verticalOverflow;
3236         m_overflowStatusDirty = false;
3237         return;
3238     }
3239     
3240     bool horizontalOverflowChanged = (m_horizontalOverflow != horizontalOverflow);
3241     bool verticalOverflowChanged = (m_verticalOverflow != verticalOverflow);
3242     
3243     if (horizontalOverflowChanged || verticalOverflowChanged) {
3244         m_horizontalOverflow = horizontalOverflow;
3245         m_verticalOverflow = verticalOverflow;
3246
3247         RefPtr<OverflowEvent> overflowEvent = OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow,
3248             verticalOverflowChanged, verticalOverflow);
3249         overflowEvent->setTarget(m_viewportRenderer->element());
3250
3251         frame().document()->enqueueOverflowEvent(overflowEvent.release());
3252     }
3253 }
3254
3255 const Pagination& FrameView::pagination() const
3256 {
3257     if (m_pagination != Pagination())
3258         return m_pagination;
3259
3260     if (frame().isMainFrame()) {
3261         if (Page* page = frame().page())
3262             return page->pagination();
3263     }
3264
3265     return m_pagination;
3266 }
3267
3268 void FrameView::setPagination(const Pagination& pagination)
3269 {
3270     if (m_pagination == pagination)
3271         return;
3272
3273     m_pagination = pagination;
3274
3275     frame().document()->styleResolverChanged(DeferRecalcStyle);
3276 }
3277
3278 IntRect FrameView::windowClipRect() const
3279 {
3280     ASSERT(frame().view() == this);
3281
3282     if (m_cachedWindowClipRect)
3283         return *m_cachedWindowClipRect;
3284
3285     if (paintsEntireContents())
3286         return contentsToWindow(IntRect(IntPoint(), totalContentsSize()));
3287
3288     // Set our clip rect to be our contents.
3289     IntRect clipRect = contentsToWindow(visibleContentRect(LegacyIOSDocumentVisibleRect));
3290
3291     if (!frame().ownerElement())
3292         return clipRect;
3293
3294     // Take our owner element and get its clip rect.
3295     HTMLFrameOwnerElement* ownerElement = frame().ownerElement();
3296     if (FrameView* parentView = ownerElement->document().view())
3297         clipRect.intersect(parentView->windowClipRectForFrameOwner(ownerElement, true));
3298     return clipRect;
3299 }
3300
3301 IntRect FrameView::windowClipRectForFrameOwner(const HTMLFrameOwnerElement* ownerElement, bool clipToLayerContents) const
3302 {
3303     // The renderer can sometimes be null when style="display:none" interacts
3304     // with external content and plugins.
3305     if (!ownerElement->renderer())
3306         return windowClipRect();
3307
3308     // If we have no layer, just return our window clip rect.
3309     const RenderLayer* enclosingLayer = ownerElement->renderer()->enclosingLayer();
3310     if (!enclosingLayer)
3311         return windowClipRect();
3312
3313     // Apply the clip from the layer.
3314     IntRect clipRect;
3315     if (clipToLayerContents)
3316         clipRect = snappedIntRect(enclosingLayer->childrenClipRect());
3317     else
3318         clipRect = snappedIntRect(enclosingLayer->selfClipRect());
3319     clipRect = contentsToWindow(clipRect); 
3320     return intersection(clipRect, windowClipRect());
3321 }
3322
3323 bool FrameView::isActive() const
3324 {
3325     Page* page = frame().page();
3326     return page && page->focusController().isActive();
3327 }
3328
3329 bool FrameView::updatesScrollLayerPositionOnMainThread() const
3330 {
3331     if (Page* page = frame().page()) {
3332         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
3333             return scrollingCoordinator->shouldUpdateScrollLayerPositionSynchronously();
3334     }
3335
3336     return true;
3337 }
3338
3339 bool FrameView::forceUpdateScrollbarsOnMainThreadForPerformanceTesting() const
3340 {
3341     Page* page = frame().page();
3342     return page && page->settings().forceUpdateScrollbarsOnMainThreadForPerformanceTesting();
3343 }
3344
3345 void FrameView::scrollTo(const IntSize& newOffset)
3346 {
3347     LayoutSize offset = scrollOffset();
3348     IntPoint oldPosition = scrollPosition();
3349     ScrollView::scrollTo(newOffset);
3350     if (offset != scrollOffset())
3351         scrollPositionChanged(oldPosition, scrollPosition());
3352     didChangeScrollOffset();
3353 }
3354
3355 float FrameView::adjustScrollStepForFixedContent(float step, ScrollbarOrientation orientation, ScrollGranularity granularity)
3356 {
3357     if (granularity != ScrollByPage || orientation == HorizontalScrollbar)
3358         return step;
3359
3360     TrackedRendererListHashSet* positionedObjects = nullptr;
3361     if (RenderView* root = frame().contentRenderer()) {
3362         if (!root->hasPositionedObjects())
3363             return step;
3364         positionedObjects = root->positionedObjects();
3365     }
3366
3367     FloatRect unobscuredContentRect = this->unobscuredContentRect();
3368     float topObscuredArea = 0;
3369     float bottomObscuredArea = 0;
3370     for (const auto& positionedObject : *positionedObjects) {
3371         const RenderStyle& style = positionedObject->style();
3372         if (style.position() != FixedPosition || style.visibility() == HIDDEN || !style.opacity())
3373             continue;
3374
3375         FloatQuad contentQuad = positionedObject->absoluteContentQuad();
3376         if (!contentQuad.isRectilinear())
3377             continue;
3378
3379         FloatRect contentBoundingBox = contentQuad.boundingBox();
3380         FloatRect fixedRectInView = intersection(unobscuredContentRect, contentBoundingBox);
3381
3382         if (fixedRectInView.width() < unobscuredContentRect.width())
3383             continue;
3384
3385         if (fixedRectInView.y() == unobscuredContentRect.y())
3386             topObscuredArea = std::max(topObscuredArea, fixedRectInView.height());
3387         else if (fixedRectInView.maxY() == unobscuredContentRect.maxY())
3388             bottomObscuredArea = std::max(bottomObscuredArea, fixedRectInView.height());
3389     }
3390
3391     return Scrollbar::pageStep(unobscuredContentRect.height(), unobscuredContentRect.height() - topObscuredArea - bottomObscuredArea);
3392 }
3393
3394 void FrameView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
3395 {
3396     // Add in our offset within the FrameView.
3397     IntRect dirtyRect = rect;
3398     dirtyRect.moveBy(scrollbar->location());
3399     invalidateRect(dirtyRect);
3400 }
3401
3402 IntRect FrameView::windowResizerRect() const
3403 {
3404     if (Page* page = frame().page())
3405         return page->chrome().windowResizerRect();
3406     return IntRect();
3407 }
3408
3409 float FrameView::visibleContentScaleFactor() const
3410 {
3411     if (!frame().isMainFrame() || !frame().settings().delegatesPageScaling())
3412         return 1;
3413
3414     Page* page = frame().page();
3415     if (!page)
3416         return 1;
3417
3418     return page->pageScaleFactor();
3419 }
3420
3421 void FrameView::setVisibleScrollerThumbRect(const IntRect& scrollerThumb)
3422 {
3423     if (!frame().isMainFrame())
3424         return;
3425
3426     Page* page = frame().page();
3427     if (!page)
3428         return;
3429
3430     page->chrome().client().notifyScrollerThumbIsVisibleInRect(scrollerThumb);
3431 }
3432
3433 ScrollableArea* FrameView::enclosingScrollableArea() const
3434 {
3435     // FIXME: Walk up the frame tree and look for a scrollable parent frame or RenderLayer.
3436     return nullptr;
3437 }
3438
3439 IntRect FrameView::scrollableAreaBoundingBox() const
3440 {
3441     RenderWidget* ownerRenderer = frame().ownerRenderer();
3442     if (!ownerRenderer)
3443         return frameRect();
3444
3445     return ownerRenderer->absoluteContentQuad().enclosingBoundingBox();
3446 }
3447
3448 bool FrameView::isScrollable(Scrollability definitionOfScrollable)
3449 {
3450     // Check for:
3451     // 1) If there an actual overflow.
3452     // 2) display:none or visibility:hidden set to self or inherited.
3453     // 3) overflow{-x,-y}: hidden;
3454     // 4) scrolling: no;
3455
3456     bool requiresActualOverflowToBeConsideredScrollable = !frame().isMainFrame() || definitionOfScrollable != Scrollability::ScrollableOrRubberbandable;
3457 #if !ENABLE(RUBBER_BANDING)
3458     requiresActualOverflowToBeConsideredScrollable = true;
3459 #endif
3460
3461     // Covers #1
3462     if (requiresActualOverflowToBeConsideredScrollable) {
3463         IntSize totalContentsSize = this->totalContentsSize();
3464         IntSize visibleContentSize = visibleContentRect(LegacyIOSDocumentVisibleRect).size();
3465         if (totalContentsSize.height() <= visibleContentSize.height() && totalContentsSize.width() <= visibleContentSize.width())
3466             return false;
3467     }
3468
3469     // Covers #2.
3470     HTMLFrameOwnerElement* owner = frame().ownerElement();
3471     if (owner && (!owner->renderer() || !owner->renderer()->visibleToHitTesting()))
3472         return false;
3473
3474     // Cover #3 and #4.
3475     ScrollbarMode horizontalMode;
3476     ScrollbarMode verticalMode;
3477     calculateScrollbarModesForLayout(horizontalMode, verticalMode, RulesFromWebContentOnly);
3478     if (horizontalMode == ScrollbarAlwaysOff && verticalMode == ScrollbarAlwaysOff)
3479         return false;
3480
3481     return true;
3482 }
3483
3484 bool FrameView::isScrollableOrRubberbandable()
3485 {
3486     return isScrollable(Scrollability::ScrollableOrRubberbandable);
3487 }
3488
3489 bool FrameView::hasScrollableOrRubberbandableAncestor()
3490 {
3491     if (frame().isMainFrame())
3492         return isScrollableOrRubberbandable();
3493
3494     for (FrameView* parent = this->parentFrameView(); parent; parent = parent->parentFrameView()) {
3495         Scrollability frameScrollability = parent->frame().isMainFrame() ? Scrollability::ScrollableOrRubberbandable : Scrollability::Scrollable;
3496         if (parent->isScrollable(frameScrollability))
3497             return true;
3498     }
3499
3500     return false;
3501 }
3502
3503 void FrameView::updateScrollableAreaSet()
3504 {
3505     // That ensures that only inner frames are cached.
3506     FrameView* parentFrameView = this->parentFrameView();
3507     if (!parentFrameView)
3508         return;
3509
3510     if (!isScrollable()) {
3511         parentFrameView->removeScrollableArea(this);
3512         return;
3513     }
3514
3515     parentFrameView->addScrollableArea(this);
3516 }
3517
3518 bool FrameView::shouldSuspendScrollAnimations() const
3519 {
3520     return frame().loader().state() != FrameStateComplete;
3521 }
3522
3523 void FrameView::scrollbarStyleChanged(ScrollbarStyle newStyle, bool forceUpdate)
3524 {
3525     if (!frame().isMainFrame())
3526         return;
3527
3528     if (Page* page = frame().page())
3529         page->chrome().client().recommendedScrollbarStyleDidChange(newStyle);
3530
3531     ScrollView::scrollbarStyleChanged(newStyle, forceUpdate);
3532 }
3533
3534 void FrameView::notifyPageThatContentAreaWillPaint() const
3535 {
3536     Page* page = frame().page();
3537     if (!page)
3538         return;
3539
3540     contentAreaWillPaint();
3541
3542     if (!m_scrollableAreas)
3543         return;
3544
3545     for (auto& scrollableArea : *m_scrollableAreas)
3546         scrollableArea->contentAreaWillPaint();
3547 }
3548
3549 bool FrameView::scrollAnimatorEnabled() const
3550 {
3551 #if ENABLE(SMOOTH_SCROLLING)
3552     if (Page* page = frame().page())
3553         return page->settings().scrollAnimatorEnabled();
3554 #endif
3555
3556     return false;
3557 }
3558
3559 #if ENABLE(DASHBOARD_SUPPORT)
3560 void FrameView::updateAnnotatedRegions()
3561 {
3562     Document* document = frame().document();
3563     if (!document->hasAnnotatedRegions())
3564         return;
3565     Vector<AnnotatedRegionValue> newRegions;
3566     document->renderBox()->collectAnnotatedRegions(newRegions);
3567     if (newRegions == document->annotatedRegions())
3568         return;
3569     document->setAnnotatedRegions(newRegions);
3570     Page* page = frame().page();
3571     if (!page)
3572         return;
3573     page->chrome().client().annotatedRegionsChanged();
3574 }
3575 #endif
3576
3577 void FrameView::updateScrollCorner()
3578 {
3579     RenderElement* renderer = nullptr;
3580     RefPtr<RenderStyle> cornerStyle;
3581     IntRect cornerRect = scrollCornerRect();
3582     
3583     if (!cornerRect.isEmpty()) {
3584         // Try the <body> element first as a scroll corner source.
3585         Document* doc = frame().document();
3586         Element* body = doc ? doc->bodyOrFrameset() : nullptr;
3587         if (body && body->renderer()) {
3588             renderer = body->renderer();
3589             cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3590         }
3591         
3592         if (!cornerStyle) {
3593             // If the <body> didn't have a custom style, then the root element might.
3594             Element* docElement = doc ? doc->documentElement() : nullptr;
3595             if (docElement && docElement->renderer()) {
3596                 renderer = docElement->renderer();
3597                 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3598             }
3599         }
3600         
3601         if (!cornerStyle) {
3602             // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
3603             if (RenderWidget* renderer = frame().ownerRenderer())
3604                 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), &renderer->style());
3605         }
3606     }
3607
3608     if (!cornerStyle)
3609         m_scrollCorner = nullptr;
3610     else {
3611         if (!m_scrollCorner) {
3612             m_scrollCorner = createRenderer<RenderScrollbarPart>(renderer->document(), cornerStyle.releaseNonNull());
3613             m_scrollCorner->initializeStyle();
3614         } else
3615             m_scrollCorner->setStyle(cornerStyle.releaseNonNull());
3616         invalidateScrollCorner(cornerRect);
3617     }
3618
3619     ScrollView::updateScrollCorner();
3620 }
3621
3622 void FrameView::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect)
3623 {
3624     if (context->updatingControlTints()) {
3625         updateScrollCorner();
3626         return;
3627     }
3628
3629     if (m_scrollCorner) {