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