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