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