Use TilesBacking for iframes when async frame scrolling is enabled
[WebKit-https.git] / Source / WebKit / WebProcess / WebPage / mac / TiledCoreAnimationDrawingArea.mm
1 /*
2  * Copyright (C) 2011 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "TiledCoreAnimationDrawingArea.h"
28
29 #if !PLATFORM(IOS)
30
31 #import "ColorSpaceData.h"
32 #import "DrawingAreaProxyMessages.h"
33 #import "LayerHostingContext.h"
34 #import "LayerTreeContext.h"
35 #import "Logging.h"
36 #import "ViewGestureControllerMessages.h"
37 #import "WebFrame.h"
38 #import "WebPage.h"
39 #import "WebPageCreationParameters.h"
40 #import "WebPageProxyMessages.h"
41 #import "WebProcess.h"
42 #import <QuartzCore/QuartzCore.h>
43 #import <WebCore/DebugPageOverlays.h>
44 #import <WebCore/FrameView.h>
45 #import <WebCore/GraphicsContext.h>
46 #import <WebCore/GraphicsLayerCA.h>
47 #import <WebCore/InspectorController.h>
48 #import <WebCore/MachSendRight.h>
49 #import <WebCore/MainFrame.h>
50 #import <WebCore/Page.h>
51 #import <WebCore/PlatformCAAnimationCocoa.h>
52 #import <WebCore/RenderLayerBacking.h>
53 #import <WebCore/RenderLayerCompositor.h>
54 #import <WebCore/RenderView.h>
55 #import <WebCore/ScrollbarTheme.h>
56 #import <WebCore/Settings.h>
57 #import <WebCore/TiledBacking.h>
58 #import <WebCore/WebActionDisablingCALayerDelegate.h>
59 #import <pal/spi/cocoa/QuartzCoreSPI.h>
60 #import <wtf/MainThread.h>
61
62 #if ENABLE(ASYNC_SCROLLING)
63 #import <WebCore/AsyncScrollingCoordinator.h>
64 #import <WebCore/ScrollingThread.h>
65 #import <WebCore/ScrollingTree.h>
66 #endif
67
68 @interface CATransaction (Details)
69 + (void)synchronize;
70 @end
71
72 using namespace WebCore;
73
74 namespace WebKit {
75
76 TiledCoreAnimationDrawingArea::TiledCoreAnimationDrawingArea(WebPage& webPage, const WebPageCreationParameters& parameters)
77     : DrawingArea(DrawingAreaTypeTiledCoreAnimation, webPage)
78     , m_layerTreeStateIsFrozen(false)
79     , m_layerFlushScheduler(this)
80     , m_isPaintingSuspended(!(parameters.activityState & ActivityState::IsVisible))
81     , m_transientZoomScale(1)
82     , m_sendDidUpdateActivityStateTimer(RunLoop::main(), this, &TiledCoreAnimationDrawingArea::didUpdateActivityStateTimerFired)
83     , m_wantsDidUpdateActivityState(false)
84     , m_viewOverlayRootLayer(nullptr)
85 {
86     m_webPage.corePage()->settings().setForceCompositingMode(true);
87
88     m_hostingLayer = [CALayer layer];
89     [m_hostingLayer setDelegate:[WebActionDisablingCALayerDelegate shared]];
90     [m_hostingLayer setFrame:m_webPage.bounds()];
91     [m_hostingLayer setOpaque:YES];
92     [m_hostingLayer setGeometryFlipped:YES];
93
94     updateLayerHostingContext();
95     setColorSpace(parameters.colorSpace);
96
97     LayerTreeContext layerTreeContext;
98     layerTreeContext.contextID = m_layerHostingContext->contextID();
99     m_webPage.send(Messages::DrawingAreaProxy::EnterAcceleratedCompositingMode(0, layerTreeContext));
100 }
101
102 TiledCoreAnimationDrawingArea::~TiledCoreAnimationDrawingArea()
103 {
104     m_layerFlushScheduler.invalidate();
105 }
106
107 void TiledCoreAnimationDrawingArea::setNeedsDisplay()
108 {
109 }
110
111 void TiledCoreAnimationDrawingArea::setNeedsDisplayInRect(const IntRect& rect)
112 {
113 }
114
115 void TiledCoreAnimationDrawingArea::scroll(const IntRect& scrollRect, const IntSize& scrollDelta)
116 {
117     updateScrolledExposedRect();
118 }
119
120 void TiledCoreAnimationDrawingArea::setRootCompositingLayer(GraphicsLayer* graphicsLayer)
121 {
122     CALayer *rootLayer = graphicsLayer ? graphicsLayer->platformLayer() : nil;
123
124     if (m_layerTreeStateIsFrozen) {
125         m_pendingRootLayer = rootLayer;
126         return;
127     }
128
129     setRootCompositingLayer(rootLayer);
130 }
131
132 void TiledCoreAnimationDrawingArea::forceRepaint()
133 {
134     if (m_layerTreeStateIsFrozen)
135         return;
136
137     for (Frame* frame = &m_webPage.corePage()->mainFrame(); frame; frame = frame->tree().traverseNext()) {
138         FrameView* frameView = frame->view();
139         if (!frameView || !frameView->tiledBacking())
140             continue;
141
142         frameView->tiledBacking()->forceRepaint();
143     }
144
145     flushLayers();
146     [CATransaction flush];
147     [CATransaction synchronize];
148 }
149
150 bool TiledCoreAnimationDrawingArea::forceRepaintAsync(CallbackID callbackID)
151 {
152     if (m_layerTreeStateIsFrozen)
153         return false;
154
155     dispatchAfterEnsuringUpdatedScrollPosition([this, callbackID] {
156         m_webPage.drawingArea()->forceRepaint();
157         m_webPage.send(Messages::WebPageProxy::VoidCallback(callbackID));
158     });
159     return true;
160 }
161
162 void TiledCoreAnimationDrawingArea::setLayerTreeStateIsFrozen(bool layerTreeStateIsFrozen)
163 {
164     if (m_layerTreeStateIsFrozen == layerTreeStateIsFrozen)
165         return;
166
167     m_layerTreeStateIsFrozen = layerTreeStateIsFrozen;
168     if (m_layerTreeStateIsFrozen)
169         m_layerFlushScheduler.suspend();
170     else
171         m_layerFlushScheduler.resume();
172 }
173
174 bool TiledCoreAnimationDrawingArea::layerTreeStateIsFrozen() const
175 {
176     return m_layerTreeStateIsFrozen;
177 }
178
179 void TiledCoreAnimationDrawingArea::scheduleCompositingLayerFlush()
180 {
181     m_layerFlushScheduler.schedule();
182 }
183
184 void TiledCoreAnimationDrawingArea::scheduleCompositingLayerFlushImmediately()
185 {
186     scheduleCompositingLayerFlush();
187 }
188
189 void TiledCoreAnimationDrawingArea::updatePreferences(const WebPreferencesStore&)
190 {
191     Settings& settings = m_webPage.corePage()->settings();
192
193 #if ENABLE(ASYNC_SCROLLING)
194     if (AsyncScrollingCoordinator* scrollingCoordinator = downcast<AsyncScrollingCoordinator>(m_webPage.corePage()->scrollingCoordinator())) {
195         bool scrollingPerformanceLoggingEnabled = m_webPage.scrollingPerformanceLoggingEnabled();
196         
197         RefPtr<ScrollingTree> scrollingTree = scrollingCoordinator->scrollingTree();
198         ScrollingThread::dispatch([scrollingTree, scrollingPerformanceLoggingEnabled] {
199             scrollingTree->setScrollingPerformanceLoggingEnabled(scrollingPerformanceLoggingEnabled);
200         });
201     }
202 #endif
203
204     // Fixed position elements need to be composited and create stacking contexts
205     // in order to be scrolled by the ScrollingCoordinator.
206     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
207
208     if (MainFrame* mainFrame = m_webPage.mainFrame())
209         DebugPageOverlays::settingsChanged(*mainFrame);
210
211     bool showTiledScrollingIndicator = settings.showTiledScrollingIndicator();
212     if (showTiledScrollingIndicator == !!m_debugInfoLayer)
213         return;
214
215     updateDebugInfoLayer(showTiledScrollingIndicator);
216 }
217
218 void TiledCoreAnimationDrawingArea::updateRootLayers()
219 {
220     if (!m_rootLayer) {
221         [m_hostingLayer setSublayers:@[ ]];
222         return;
223     }
224
225     [m_hostingLayer setSublayers:m_viewOverlayRootLayer ? @[ m_rootLayer.get(), m_viewOverlayRootLayer->platformLayer() ] : @[ m_rootLayer.get() ]];
226     
227     if (m_debugInfoLayer)
228         [m_hostingLayer addSublayer:m_debugInfoLayer.get()];
229 }
230
231 void TiledCoreAnimationDrawingArea::attachViewOverlayGraphicsLayer(Frame* frame, GraphicsLayer* viewOverlayRootLayer)
232 {
233     if (!frame->isMainFrame())
234         return;
235
236     m_viewOverlayRootLayer = viewOverlayRootLayer;
237     updateRootLayers();
238 }
239
240 void TiledCoreAnimationDrawingArea::mainFrameContentSizeChanged(const IntSize& size)
241 {
242
243 }
244
245 void TiledCoreAnimationDrawingArea::updateIntrinsicContentSizeIfNeeded()
246 {
247     if (!m_webPage.minimumLayoutSize().width())
248         return;
249
250     FrameView* frameView = m_webPage.mainFrameView();
251     if (!frameView)
252         return;
253
254     if (frameView->needsLayout())
255         return;
256
257     IntSize contentSize = frameView->autoSizingIntrinsicContentSize();
258     if (m_lastSentIntrinsicContentSize == contentSize)
259         return;
260
261     m_lastSentIntrinsicContentSize = contentSize;
262     m_webPage.send(Messages::DrawingAreaProxy::IntrinsicContentSizeDidChange(contentSize));
263 }
264
265 void TiledCoreAnimationDrawingArea::setShouldScaleViewToFitDocument(bool shouldScaleView)
266 {
267     if (m_shouldScaleViewToFitDocument == shouldScaleView)
268         return;
269
270     m_shouldScaleViewToFitDocument = shouldScaleView;
271     scheduleCompositingLayerFlush();
272 }
273
274 void TiledCoreAnimationDrawingArea::scaleViewToFitDocumentIfNeeded()
275 {
276     const int maximumDocumentWidthForScaling = 1440;
277     const float minimumViewScale = 0.1;
278
279     if (!m_shouldScaleViewToFitDocument)
280         return;
281
282     LOG(Resize, "TiledCoreAnimationDrawingArea %p scaleViewToFitDocumentIfNeeded", this);
283     m_webPage.layoutIfNeeded();
284
285     int viewWidth = m_webPage.size().width();
286     int documentWidth = m_webPage.mainFrameView()->renderView()->unscaledDocumentRect().width();
287
288     bool documentWidthChanged = m_lastDocumentSizeForScaleToFit.width() != documentWidth;
289     bool viewWidthChanged = m_lastViewSizeForScaleToFit.width() != viewWidth;
290
291     LOG(Resize, "  documentWidthChanged=%d, viewWidthChanged=%d", documentWidthChanged, viewWidthChanged);
292
293     if (!documentWidthChanged && !viewWidthChanged)
294         return;
295
296     // The view is now bigger than the document, so we'll re-evaluate whether we have to scale.
297     if (m_isScalingViewToFitDocument && viewWidth >= m_lastDocumentSizeForScaleToFit.width())
298         m_isScalingViewToFitDocument = false;
299
300     // Our current understanding of the document width is still up to date, and we're in scaling mode.
301     // Update the viewScale without doing an extra layout to re-determine the document width.
302     if (m_isScalingViewToFitDocument) {
303         if (!documentWidthChanged) {
304             m_lastViewSizeForScaleToFit = m_webPage.size();
305             float viewScale = (float)viewWidth / (float)m_lastDocumentSizeForScaleToFit.width();
306             if (viewScale < minimumViewScale) {
307                 viewScale = minimumViewScale;
308                 documentWidth = std::ceil(viewWidth / viewScale);
309             }
310             IntSize fixedLayoutSize(documentWidth, std::ceil((m_webPage.size().height() - m_webPage.corePage()->topContentInset()) / viewScale));
311             m_webPage.setFixedLayoutSize(fixedLayoutSize);
312             m_webPage.scaleView(viewScale);
313
314             LOG(Resize, "  using fixed layout at %dx%d. document width %d unchanged, scaled to %.4f to fit view width %d", fixedLayoutSize.width(), fixedLayoutSize.height(), documentWidth, viewScale, viewWidth);
315             return;
316         }
317     
318         IntSize fixedLayoutSize = m_webPage.fixedLayoutSize();
319         if (documentWidth > fixedLayoutSize.width()) {
320             LOG(Resize, "  page laid out wider than fixed layout width. Not attempting to re-scale");
321             return;
322         }
323     }
324
325     LOG(Resize, "  doing unconstrained layout");
326
327     // Lay out at the view size.
328     m_webPage.setUseFixedLayout(false);
329     m_webPage.layoutIfNeeded();
330
331     IntSize documentSize = m_webPage.mainFrameView()->renderView()->unscaledDocumentRect().size();
332     m_lastViewSizeForScaleToFit = m_webPage.size();
333     m_lastDocumentSizeForScaleToFit = documentSize;
334
335     documentWidth = documentSize.width();
336
337     float viewScale = 1;
338
339     LOG(Resize, "  unscaled document size %dx%d. need to scale down: %d", documentSize.width(), documentSize.height(), documentWidth && documentWidth < maximumDocumentWidthForScaling && viewWidth < documentWidth);
340
341     // Avoid scaling down documents that don't fit in a certain width, to allow
342     // sites that want horizontal scrollbars to continue to have them.
343     if (documentWidth && documentWidth < maximumDocumentWidthForScaling && viewWidth < documentWidth) {
344         // If the document doesn't fit in the view, scale it down but lay out at the view size.
345         m_isScalingViewToFitDocument = true;
346         m_webPage.setUseFixedLayout(true);
347         viewScale = (float)viewWidth / (float)documentWidth;
348         if (viewScale < minimumViewScale) {
349             viewScale = minimumViewScale;
350             documentWidth = std::ceil(viewWidth / viewScale);
351         }
352         IntSize fixedLayoutSize(documentWidth, std::ceil((m_webPage.size().height() - m_webPage.corePage()->topContentInset()) / viewScale));
353         m_webPage.setFixedLayoutSize(fixedLayoutSize);
354
355         LOG(Resize, "  using fixed layout at %dx%d. document width %d, scaled to %.4f to fit view width %d", fixedLayoutSize.width(), fixedLayoutSize.height(), documentWidth, viewScale, viewWidth);
356     }
357
358     m_webPage.scaleView(viewScale);
359 }
360
361 void TiledCoreAnimationDrawingArea::dispatchAfterEnsuringUpdatedScrollPosition(WTF::Function<void ()>&& function)
362 {
363 #if ENABLE(ASYNC_SCROLLING)
364     if (!m_webPage.corePage()->scrollingCoordinator()) {
365         function();
366         return;
367     }
368
369     m_webPage.ref();
370     m_webPage.corePage()->scrollingCoordinator()->commitTreeStateIfNeeded();
371
372     if (!m_layerTreeStateIsFrozen)
373         m_layerFlushScheduler.suspend();
374
375     // It is possible for the drawing area to be destroyed before the bound block
376     // is invoked, so grab a reference to the web page here so we can access the drawing area through it.
377     // (The web page is already kept alive by dispatchAfterEnsuringUpdatedScrollPosition).
378     WebPage* webPage = &m_webPage;
379
380     ScrollingThread::dispatchBarrier([this, webPage, function = WTFMove(function)] {
381         DrawingArea* drawingArea = webPage->drawingArea();
382         if (!drawingArea)
383             return;
384
385         function();
386
387         if (!m_layerTreeStateIsFrozen)
388             m_layerFlushScheduler.resume();
389
390         webPage->deref();
391     });
392 #else
393     function();
394 #endif
395 }
396
397 void TiledCoreAnimationDrawingArea::sendPendingNewlyReachedLayoutMilestones()
398 {
399     if (!m_pendingNewlyReachedLayoutMilestones)
400         return;
401
402     m_webPage.send(Messages::WebPageProxy::DidReachLayoutMilestone(m_pendingNewlyReachedLayoutMilestones));
403     m_pendingNewlyReachedLayoutMilestones = 0;
404 }
405
406 void TiledCoreAnimationDrawingArea::addTransactionCallbackID(CallbackID callbackID)
407 {
408     m_pendingCallbackIDs.append(callbackID);
409     scheduleCompositingLayerFlush();
410 }
411
412 bool TiledCoreAnimationDrawingArea::flushLayers()
413 {
414     ASSERT(!m_layerTreeStateIsFrozen);
415
416     @autoreleasepool {
417         scaleViewToFitDocumentIfNeeded();
418
419         m_webPage.layoutIfNeeded();
420         m_webPage.flushPendingEditorStateUpdate();
421
422         updateIntrinsicContentSizeIfNeeded();
423
424         if (m_pendingRootLayer) {
425             setRootCompositingLayer(m_pendingRootLayer.get());
426             m_pendingRootLayer = nullptr;
427         }
428
429         FloatRect visibleRect = [m_hostingLayer frame];
430         if (m_scrolledViewExposedRect)
431             visibleRect.intersect(m_scrolledViewExposedRect.value());
432
433         // Because our view-relative overlay root layer is not attached to the main GraphicsLayer tree, we need to flush it manually.
434         if (m_viewOverlayRootLayer)
435             m_viewOverlayRootLayer->flushCompositingState(visibleRect);
436
437         RefPtr<WebPage> retainedPage = &m_webPage;
438         [CATransaction addCommitHandler:[retainedPage] {
439             if (Page* corePage = retainedPage->corePage()) {
440                 if (Frame* coreFrame = retainedPage->mainFrame())
441                     corePage->inspectorController().didComposite(*coreFrame);
442             }
443             if (auto drawingArea = static_cast<TiledCoreAnimationDrawingArea*>(retainedPage->drawingArea()))
444                 drawingArea->sendPendingNewlyReachedLayoutMilestones();
445         } forPhase:kCATransactionPhasePostCommit];
446
447         bool returnValue = m_webPage.mainFrameView()->flushCompositingStateIncludingSubframes();
448 #if ENABLE(ASYNC_SCROLLING)
449         if (ScrollingCoordinator* scrollingCoordinator = m_webPage.corePage()->scrollingCoordinator())
450             scrollingCoordinator->commitTreeStateIfNeeded();
451 #endif
452
453         // If we have an active transient zoom, we want the zoom to win over any changes
454         // that WebCore makes to the relevant layers, so re-apply our changes after flushing.
455         if (m_transientZoomScale != 1)
456             applyTransientZoomToLayers(m_transientZoomScale, m_transientZoomOrigin);
457
458         if (!m_pendingCallbackIDs.isEmpty()) {
459             m_webPage.send(Messages::DrawingAreaProxy::DispatchPresentationCallbacksAfterFlushingLayers(m_pendingCallbackIDs));
460             m_pendingCallbackIDs.clear();
461         }
462
463         return returnValue;
464     }
465 }
466
467 void TiledCoreAnimationDrawingArea::activityStateDidChange(ActivityState::Flags changed, bool wantsDidUpdateActivityState, const Vector<CallbackID>& nextActivityStateChangeCallbackIDs)
468 {
469     m_nextActivityStateChangeCallbackIDs.appendVector(nextActivityStateChangeCallbackIDs);
470     m_wantsDidUpdateActivityState |= wantsDidUpdateActivityState;
471
472     if (changed & ActivityState::IsVisible) {
473         if (m_webPage.isVisible())
474             resumePainting();
475         else
476             suspendPainting();
477     }
478
479     if (m_wantsDidUpdateActivityState || !m_nextActivityStateChangeCallbackIDs.isEmpty())
480         m_sendDidUpdateActivityStateTimer.startOneShot(0_s);
481 }
482
483 void TiledCoreAnimationDrawingArea::didUpdateActivityStateTimerFired()
484 {
485     [CATransaction flush];
486
487     if (m_wantsDidUpdateActivityState)
488         m_webPage.send(Messages::WebPageProxy::DidUpdateActivityState());
489
490     for (auto callbackID : m_nextActivityStateChangeCallbackIDs)
491         m_webPage.send(Messages::WebPageProxy::VoidCallback(callbackID));
492
493     m_nextActivityStateChangeCallbackIDs.clear();
494     m_wantsDidUpdateActivityState = false;
495 }
496
497 void TiledCoreAnimationDrawingArea::suspendPainting()
498 {
499     ASSERT(!m_isPaintingSuspended);
500     m_isPaintingSuspended = true;
501
502     [m_hostingLayer setValue:@YES forKey:@"NSCAViewRenderPaused"];
503     [[NSNotificationCenter defaultCenter] postNotificationName:@"NSCAViewRenderDidPauseNotification" object:nil userInfo:[NSDictionary dictionaryWithObject:m_hostingLayer.get() forKey:@"layer"]];
504 }
505
506 void TiledCoreAnimationDrawingArea::resumePainting()
507 {
508     if (!m_isPaintingSuspended) {
509         // FIXME: We can get a call to resumePainting when painting is not suspended.
510         // This happens when sending a synchronous message to create a new page. See <rdar://problem/8976531>.
511         return;
512     }
513     m_isPaintingSuspended = false;
514
515     [m_hostingLayer setValue:@NO forKey:@"NSCAViewRenderPaused"];
516     [[NSNotificationCenter defaultCenter] postNotificationName:@"NSCAViewRenderDidResumeNotification" object:nil userInfo:[NSDictionary dictionaryWithObject:m_hostingLayer.get() forKey:@"layer"]];
517 }
518
519 void TiledCoreAnimationDrawingArea::setViewExposedRect(std::optional<WebCore::FloatRect> viewExposedRect)
520 {
521     m_viewExposedRect = viewExposedRect;
522     updateScrolledExposedRect();
523 }
524
525 void TiledCoreAnimationDrawingArea::updateScrolledExposedRect()
526 {
527     FrameView* frameView = m_webPage.mainFrameView();
528     if (!frameView)
529         return;
530
531     m_scrolledViewExposedRect = m_viewExposedRect;
532
533 #if !PLATFORM(IOS)
534     if (m_viewExposedRect) {
535         ScrollOffset scrollOffset = frameView->scrollOffsetFromPosition(frameView->scrollPosition());
536         m_scrolledViewExposedRect.value().moveBy(scrollOffset);
537     }
538 #endif
539
540     frameView->setViewExposedRect(m_scrolledViewExposedRect);
541 }
542
543 void TiledCoreAnimationDrawingArea::updateGeometry(const IntSize& viewSize, const IntSize& layerPosition, bool flushSynchronously, const WebCore::MachSendRight& fencePort)
544 {
545     m_inUpdateGeometry = true;
546
547     IntSize size = viewSize;
548     IntSize contentSize = IntSize(-1, -1);
549
550     if (!m_webPage.minimumLayoutSize().width() || m_webPage.autoSizingShouldExpandToViewHeight())
551         m_webPage.setSize(size);
552
553     FrameView* frameView = m_webPage.mainFrameView();
554
555     if (m_webPage.autoSizingShouldExpandToViewHeight() && frameView)
556         frameView->setAutoSizeFixedMinimumHeight(viewSize.height());
557
558     m_webPage.layoutIfNeeded();
559
560     if (m_webPage.minimumLayoutSize().width() && frameView) {
561         contentSize = frameView->autoSizingIntrinsicContentSize();
562         size = contentSize;
563     }
564
565     if (!m_layerTreeStateIsFrozen)
566         flushLayers();
567
568     [CATransaction begin];
569     [CATransaction setDisableActions:YES];
570
571     [m_hostingLayer setFrame:CGRectMake(layerPosition.width(), layerPosition.height(), viewSize.width(), viewSize.height())];
572
573     [CATransaction commit];
574
575     if (flushSynchronously)
576         [CATransaction flush];
577
578     m_webPage.send(Messages::DrawingAreaProxy::DidUpdateGeometry());
579
580     m_inUpdateGeometry = false;
581
582     m_layerHostingContext->setFencePort(fencePort.sendRight());
583 }
584
585 void TiledCoreAnimationDrawingArea::setDeviceScaleFactor(float deviceScaleFactor)
586 {
587     m_webPage.setDeviceScaleFactor(deviceScaleFactor);
588 }
589
590 void TiledCoreAnimationDrawingArea::setLayerHostingMode(LayerHostingMode)
591 {
592     updateLayerHostingContext();
593
594     // Finally, inform the UIProcess that the context has changed.
595     LayerTreeContext layerTreeContext;
596     layerTreeContext.contextID = m_layerHostingContext->contextID();
597     m_webPage.send(Messages::DrawingAreaProxy::UpdateAcceleratedCompositingMode(0, layerTreeContext));
598 }
599
600 void TiledCoreAnimationDrawingArea::setColorSpace(const ColorSpaceData& colorSpace)
601 {
602     m_layerHostingContext->setColorSpace(colorSpace.cgColorSpace.get());
603 }
604
605 void TiledCoreAnimationDrawingArea::updateLayerHostingContext()
606 {
607     RetainPtr<CGColorSpaceRef> colorSpace;
608
609     // Invalidate the old context.
610     if (m_layerHostingContext) {
611         colorSpace = m_layerHostingContext->colorSpace();
612         m_layerHostingContext->invalidate();
613         m_layerHostingContext = nullptr;
614     }
615
616     // Create a new context and set it up.
617     switch (m_webPage.layerHostingMode()) {
618     case LayerHostingMode::InProcess:
619         m_layerHostingContext = LayerHostingContext::createForPort(WebProcess::singleton().compositingRenderServerPort());
620         break;
621 #if HAVE(OUT_OF_PROCESS_LAYER_HOSTING)
622     case LayerHostingMode::OutOfProcess:
623         m_layerHostingContext = LayerHostingContext::createForExternalHostingProcess();
624         break;
625 #endif
626     }
627
628     if (m_rootLayer)
629         m_layerHostingContext->setRootLayer(m_hostingLayer.get());
630
631     if (colorSpace)
632         m_layerHostingContext->setColorSpace(colorSpace.get());
633 }
634
635 void TiledCoreAnimationDrawingArea::setRootCompositingLayer(CALayer *layer)
636 {
637     ASSERT(!m_layerTreeStateIsFrozen);
638
639     [CATransaction begin];
640     [CATransaction setDisableActions:YES];
641
642     bool hadRootLayer = !!m_rootLayer;
643     m_rootLayer = layer;
644     [m_rootLayer setSublayerTransform:m_transform];
645
646     updateRootLayers();
647
648     if (hadRootLayer != !!layer)
649         m_layerHostingContext->setRootLayer(layer ? m_hostingLayer.get() : nil);
650
651     updateDebugInfoLayer(layer && m_webPage.corePage()->settings().showTiledScrollingIndicator());
652
653     [CATransaction commit];
654 }
655
656 TiledBacking* TiledCoreAnimationDrawingArea::mainFrameTiledBacking() const
657 {
658     FrameView* frameView = m_webPage.mainFrameView();
659     return frameView ? frameView->tiledBacking() : nullptr;
660 }
661
662 void TiledCoreAnimationDrawingArea::updateDebugInfoLayer(bool showLayer)
663 {
664     if (m_debugInfoLayer) {
665         [m_debugInfoLayer removeFromSuperlayer];
666         m_debugInfoLayer = nil;
667     }
668     
669     if (showLayer) {
670         if (TiledBacking* tiledBacking = mainFrameTiledBacking()) {
671             if (PlatformCALayer* indicatorLayer = tiledBacking->tiledScrollingIndicatorLayer())
672                 m_debugInfoLayer = indicatorLayer->platformLayer();
673         }
674
675         if (m_debugInfoLayer) {
676             [m_debugInfoLayer setName:@"Debug Info"];
677             [m_hostingLayer addSublayer:m_debugInfoLayer.get()];
678         }
679     }
680 }
681
682 bool TiledCoreAnimationDrawingArea::shouldUseTiledBackingForFrameView(const FrameView& frameView)
683 {
684     return frameView.frame().isMainFrame() || m_webPage.corePage()->settings().asyncFrameScrollingEnabled();
685 }
686
687 PlatformCALayer* TiledCoreAnimationDrawingArea::layerForTransientZoom() const
688 {
689     RenderLayerBacking* renderViewBacking = m_webPage.mainFrameView()->renderView()->layer()->backing();
690
691     if (GraphicsLayer* contentsContainmentLayer = renderViewBacking->contentsContainmentLayer())
692         return downcast<GraphicsLayerCA>(*contentsContainmentLayer).platformCALayer();
693
694     return downcast<GraphicsLayerCA>(*renderViewBacking->graphicsLayer()).platformCALayer();
695 }
696
697 PlatformCALayer* TiledCoreAnimationDrawingArea::shadowLayerForTransientZoom() const
698 {
699     RenderLayerCompositor& renderLayerCompositor = m_webPage.mainFrameView()->renderView()->compositor();
700
701     if (GraphicsLayer* shadowGraphicsLayer = renderLayerCompositor.layerForContentShadow())
702         return downcast<GraphicsLayerCA>(*shadowGraphicsLayer).platformCALayer();
703
704     return nullptr;
705 }
706     
707 static FloatPoint shadowLayerPositionForFrame(FrameView& frameView, FloatPoint origin)
708 {
709     // FIXME: correct for b-t documents?
710     FloatPoint position = frameView.positionForRootContentLayer();
711     return position + origin.expandedTo(FloatPoint());
712 }
713
714 static FloatRect shadowLayerBoundsForFrame(FrameView& frameView, float transientScale)
715 {
716     FloatRect clipLayerFrame(frameView.renderView()->documentRect());
717     FloatRect shadowLayerFrame = clipLayerFrame;
718     
719     shadowLayerFrame.scale(transientScale / frameView.frame().page()->pageScaleFactor());
720     shadowLayerFrame.intersect(clipLayerFrame);
721     
722     return shadowLayerFrame;
723 }
724
725 void TiledCoreAnimationDrawingArea::applyTransientZoomToLayers(double scale, FloatPoint origin)
726 {
727     // FIXME: Scrollbars should stay in-place and change height while zooming.
728
729     if (!m_hostingLayer)
730         return;
731
732     TransformationMatrix transform;
733     transform.translate(origin.x(), origin.y());
734     transform.scale(scale);
735
736     PlatformCALayer* zoomLayer = layerForTransientZoom();
737     zoomLayer->setTransform(transform);
738     zoomLayer->setAnchorPoint(FloatPoint3D());
739     zoomLayer->setPosition(FloatPoint3D());
740     
741     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom()) {
742         FrameView& frameView = *m_webPage.mainFrameView();
743         shadowLayer->setBounds(shadowLayerBoundsForFrame(frameView, scale));
744         shadowLayer->setPosition(shadowLayerPositionForFrame(frameView, origin));
745     }
746
747     m_transientZoomScale = scale;
748     m_transientZoomOrigin = origin;
749 }
750
751 void TiledCoreAnimationDrawingArea::adjustTransientZoom(double scale, FloatPoint origin)
752 {
753     scale *= m_webPage.viewScaleFactor();
754
755     applyTransientZoomToLayers(scale, origin);
756
757     double currentPageScale = m_webPage.totalScaleFactor();
758     if (scale > currentPageScale)
759         return;
760
761     FrameView* frameView = m_webPage.mainFrameView();
762     FloatRect tileCoverageRect = frameView->visibleContentRectIncludingScrollbars();
763     tileCoverageRect.moveBy(-origin);
764     tileCoverageRect.scale(currentPageScale / scale);
765     frameView->renderView()->layer()->backing()->tiledBacking()->prepopulateRect(tileCoverageRect);
766 }
767
768 static RetainPtr<CABasicAnimation> transientZoomSnapAnimationForKeyPath(String keyPath)
769 {
770     const float transientZoomSnapBackDuration = 0.25;
771
772     RetainPtr<CABasicAnimation> animation = [CABasicAnimation animationWithKeyPath:keyPath];
773     [animation setDuration:transientZoomSnapBackDuration];
774     [animation setFillMode:kCAFillModeForwards];
775     [animation setRemovedOnCompletion:false];
776     [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
777
778     return animation;
779 }
780
781 void TiledCoreAnimationDrawingArea::commitTransientZoom(double scale, FloatPoint origin)
782 {
783     scale *= m_webPage.viewScaleFactor();
784
785     FrameView& frameView = *m_webPage.mainFrameView();
786     FloatRect visibleContentRect = frameView.visibleContentRectIncludingScrollbars();
787
788     FloatPoint constrainedOrigin = visibleContentRect.location();
789     constrainedOrigin.moveBy(-origin);
790
791     IntSize scaledTotalContentsSize = frameView.totalContentsSize();
792     scaledTotalContentsSize.scale(scale / m_webPage.totalScaleFactor());
793
794     // Scaling may have exposed the overhang area, so we need to constrain the final
795     // layer position exactly like scrolling will once it's committed, to ensure that
796     // scrolling doesn't make the view jump.
797     constrainedOrigin = ScrollableArea::constrainScrollPositionForOverhang(roundedIntRect(visibleContentRect), scaledTotalContentsSize, roundedIntPoint(constrainedOrigin), frameView.scrollOrigin(), frameView.headerHeight(), frameView.footerHeight());
798     constrainedOrigin.moveBy(-visibleContentRect.location());
799     constrainedOrigin = -constrainedOrigin;
800
801     if (m_transientZoomScale == scale && roundedIntPoint(m_transientZoomOrigin) == roundedIntPoint(constrainedOrigin)) {
802         // We're already at the right scale and position, so we don't need to animate.
803         applyTransientZoomToPage(scale, origin);
804         return;
805     }
806
807     TransformationMatrix transform;
808     transform.translate(constrainedOrigin.x(), constrainedOrigin.y());
809     transform.scale(scale);
810
811     RetainPtr<CABasicAnimation> renderViewAnimationCA = transientZoomSnapAnimationForKeyPath("transform");
812     RefPtr<PlatformCAAnimation> renderViewAnimation = PlatformCAAnimationCocoa::create(renderViewAnimationCA.get());
813     renderViewAnimation->setToValue(transform);
814
815     RetainPtr<CALayer> shadowCALayer;
816     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom())
817         shadowCALayer = shadowLayer->platformLayer();
818
819     RefPtr<PlatformCALayer> zoomLayer = layerForTransientZoom();
820     RefPtr<WebPage> page = &m_webPage;
821
822     [CATransaction begin];
823     [CATransaction setCompletionBlock:[zoomLayer, shadowCALayer, page, scale, origin] () {
824         zoomLayer->removeAnimationForKey("transientZoomCommit");
825         if (shadowCALayer)
826             [shadowCALayer removeAllAnimations];
827
828         if (TiledCoreAnimationDrawingArea* drawingArea = static_cast<TiledCoreAnimationDrawingArea*>(page->drawingArea()))
829             drawingArea->applyTransientZoomToPage(scale, origin);
830     }];
831
832     zoomLayer->addAnimationForKey("transientZoomCommit", *renderViewAnimation);
833
834     if (shadowCALayer) {
835         FloatRect shadowBounds = shadowLayerBoundsForFrame(frameView, scale);
836         RetainPtr<CGPathRef> shadowPath = adoptCF(CGPathCreateWithRect(shadowBounds, NULL));
837
838         RetainPtr<CABasicAnimation> shadowBoundsAnimation = transientZoomSnapAnimationForKeyPath("bounds");
839         [shadowBoundsAnimation setToValue:[NSValue valueWithRect:shadowBounds]];
840         RetainPtr<CABasicAnimation> shadowPositionAnimation = transientZoomSnapAnimationForKeyPath("position");
841         [shadowPositionAnimation setToValue:[NSValue valueWithPoint:shadowLayerPositionForFrame(frameView, constrainedOrigin)]];
842         RetainPtr<CABasicAnimation> shadowPathAnimation = transientZoomSnapAnimationForKeyPath("shadowPath");
843         [shadowPathAnimation setToValue:(id)shadowPath.get()];
844
845         [shadowCALayer addAnimation:shadowBoundsAnimation.get() forKey:@"transientZoomCommitShadowBounds"];
846         [shadowCALayer addAnimation:shadowPositionAnimation.get() forKey:@"transientZoomCommitShadowPosition"];
847         [shadowCALayer addAnimation:shadowPathAnimation.get() forKey:@"transientZoomCommitShadowPath"];
848     }
849
850     [CATransaction commit];
851 }
852
853 void TiledCoreAnimationDrawingArea::applyTransientZoomToPage(double scale, FloatPoint origin)
854 {
855     // If the page scale is already the target scale, setPageScaleFactor() will short-circuit
856     // and not apply the transform, so we can't depend on it to do so.
857     TransformationMatrix finalTransform;
858     finalTransform.scale(scale);
859     layerForTransientZoom()->setTransform(finalTransform);
860     
861     FrameView& frameView = *m_webPage.mainFrameView();
862
863     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom()) {
864         shadowLayer->setBounds(shadowLayerBoundsForFrame(frameView, 1));
865         shadowLayer->setPosition(shadowLayerPositionForFrame(frameView, FloatPoint()));
866     }
867
868     FloatPoint unscrolledOrigin(origin);
869     FloatRect unobscuredContentRect = frameView.unobscuredContentRectIncludingScrollbars();
870     unscrolledOrigin.moveBy(-unobscuredContentRect.location());
871     m_webPage.scalePage(scale / m_webPage.viewScaleFactor(), roundedIntPoint(-unscrolledOrigin));
872     m_transientZoomScale = 1;
873     flushLayers();
874 }
875
876 void TiledCoreAnimationDrawingArea::addFence(const MachSendRight& fencePort)
877 {
878     m_layerHostingContext->setFencePort(fencePort.sendRight());
879 }
880
881 bool TiledCoreAnimationDrawingArea::dispatchDidReachLayoutMilestone(WebCore::LayoutMilestones layoutMilestones)
882 {
883     m_pendingNewlyReachedLayoutMilestones |= layoutMilestones;
884     return true;
885 }
886
887 } // namespace WebKit
888
889 #endif // !PLATFORM(IOS)