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