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