Rename Source/WebKit2 to Source/WebKit.
[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/QuartzCoreSPI.h>
53 #import <WebCore/RenderLayerBacking.h>
54 #import <WebCore/RenderLayerCompositor.h>
55 #import <WebCore/RenderView.h>
56 #import <WebCore/ScrollbarTheme.h>
57 #import <WebCore/Settings.h>
58 #import <WebCore/TiledBacking.h>
59 #import <WebCore/WebActionDisablingCALayerDelegate.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 bool TiledCoreAnimationDrawingArea::flushLayers()
407 {
408     ASSERT(!m_layerTreeStateIsFrozen);
409
410     @autoreleasepool {
411         scaleViewToFitDocumentIfNeeded();
412
413         m_webPage.layoutIfNeeded();
414
415         updateIntrinsicContentSizeIfNeeded();
416
417         if (m_pendingRootLayer) {
418             setRootCompositingLayer(m_pendingRootLayer.get());
419             m_pendingRootLayer = nullptr;
420         }
421
422         FloatRect visibleRect = [m_hostingLayer frame];
423         if (m_scrolledViewExposedRect)
424             visibleRect.intersect(m_scrolledViewExposedRect.value());
425
426         // Because our view-relative overlay root layer is not attached to the main GraphicsLayer tree, we need to flush it manually.
427         if (m_viewOverlayRootLayer)
428             m_viewOverlayRootLayer->flushCompositingState(visibleRect);
429
430         RefPtr<WebPage> retainedPage = &m_webPage;
431         [CATransaction addCommitHandler:[retainedPage] {
432             if (Page* corePage = retainedPage->corePage()) {
433                 if (Frame* coreFrame = retainedPage->mainFrame())
434                     corePage->inspectorController().didComposite(*coreFrame);
435             }
436             if (auto drawingArea = static_cast<TiledCoreAnimationDrawingArea*>(retainedPage->drawingArea()))
437                 drawingArea->sendPendingNewlyReachedLayoutMilestones();
438         } forPhase:kCATransactionPhasePostCommit];
439
440         bool returnValue = m_webPage.mainFrameView()->flushCompositingStateIncludingSubframes();
441 #if ENABLE(ASYNC_SCROLLING)
442         if (ScrollingCoordinator* scrollingCoordinator = m_webPage.corePage()->scrollingCoordinator())
443             scrollingCoordinator->commitTreeStateIfNeeded();
444 #endif
445
446         // If we have an active transient zoom, we want the zoom to win over any changes
447         // that WebCore makes to the relevant layers, so re-apply our changes after flushing.
448         if (m_transientZoomScale != 1)
449             applyTransientZoomToLayers(m_transientZoomScale, m_transientZoomOrigin);
450
451         return returnValue;
452     }
453 }
454
455 void TiledCoreAnimationDrawingArea::activityStateDidChange(ActivityState::Flags changed, bool wantsDidUpdateActivityState, const Vector<CallbackID>& nextActivityStateChangeCallbackIDs)
456 {
457     m_nextActivityStateChangeCallbackIDs.appendVector(nextActivityStateChangeCallbackIDs);
458     m_wantsDidUpdateActivityState |= wantsDidUpdateActivityState;
459
460     if (changed & ActivityState::IsVisible) {
461         if (m_webPage.isVisible())
462             resumePainting();
463         else
464             suspendPainting();
465     }
466
467     if (m_wantsDidUpdateActivityState || !m_nextActivityStateChangeCallbackIDs.isEmpty())
468         m_sendDidUpdateActivityStateTimer.startOneShot(0_s);
469 }
470
471 void TiledCoreAnimationDrawingArea::didUpdateActivityStateTimerFired()
472 {
473     [CATransaction flush];
474
475     if (m_wantsDidUpdateActivityState)
476         m_webPage.send(Messages::WebPageProxy::DidUpdateActivityState());
477
478     for (auto callbackID : m_nextActivityStateChangeCallbackIDs)
479         m_webPage.send(Messages::WebPageProxy::VoidCallback(callbackID));
480
481     m_nextActivityStateChangeCallbackIDs.clear();
482     m_wantsDidUpdateActivityState = false;
483 }
484
485 void TiledCoreAnimationDrawingArea::suspendPainting()
486 {
487     ASSERT(!m_isPaintingSuspended);
488     m_isPaintingSuspended = true;
489
490     [m_hostingLayer setValue:@YES forKey:@"NSCAViewRenderPaused"];
491     [[NSNotificationCenter defaultCenter] postNotificationName:@"NSCAViewRenderDidPauseNotification" object:nil userInfo:[NSDictionary dictionaryWithObject:m_hostingLayer.get() forKey:@"layer"]];
492 }
493
494 void TiledCoreAnimationDrawingArea::resumePainting()
495 {
496     if (!m_isPaintingSuspended) {
497         // FIXME: We can get a call to resumePainting when painting is not suspended.
498         // This happens when sending a synchronous message to create a new page. See <rdar://problem/8976531>.
499         return;
500     }
501     m_isPaintingSuspended = false;
502
503     [m_hostingLayer setValue:@NO forKey:@"NSCAViewRenderPaused"];
504     [[NSNotificationCenter defaultCenter] postNotificationName:@"NSCAViewRenderDidResumeNotification" object:nil userInfo:[NSDictionary dictionaryWithObject:m_hostingLayer.get() forKey:@"layer"]];
505 }
506
507 void TiledCoreAnimationDrawingArea::setViewExposedRect(std::optional<WebCore::FloatRect> viewExposedRect)
508 {
509     m_viewExposedRect = viewExposedRect;
510     updateScrolledExposedRect();
511 }
512
513 void TiledCoreAnimationDrawingArea::updateScrolledExposedRect()
514 {
515     FrameView* frameView = m_webPage.mainFrameView();
516     if (!frameView)
517         return;
518
519     m_scrolledViewExposedRect = m_viewExposedRect;
520
521 #if !PLATFORM(IOS)
522     if (m_viewExposedRect) {
523         ScrollOffset scrollOffset = frameView->scrollOffsetFromPosition(frameView->scrollPosition());
524         m_scrolledViewExposedRect.value().moveBy(scrollOffset);
525     }
526 #endif
527
528     frameView->setViewExposedRect(m_scrolledViewExposedRect);
529 }
530
531 void TiledCoreAnimationDrawingArea::updateGeometry(const IntSize& viewSize, const IntSize& layerPosition, bool flushSynchronously, const WebCore::MachSendRight& fencePort)
532 {
533     m_inUpdateGeometry = true;
534
535     IntSize size = viewSize;
536     IntSize contentSize = IntSize(-1, -1);
537
538     if (!m_webPage.minimumLayoutSize().width() || m_webPage.autoSizingShouldExpandToViewHeight())
539         m_webPage.setSize(size);
540
541     FrameView* frameView = m_webPage.mainFrameView();
542
543     if (m_webPage.autoSizingShouldExpandToViewHeight() && frameView)
544         frameView->setAutoSizeFixedMinimumHeight(viewSize.height());
545
546     m_webPage.layoutIfNeeded();
547
548     if (m_webPage.minimumLayoutSize().width() && frameView) {
549         contentSize = frameView->autoSizingIntrinsicContentSize();
550         size = contentSize;
551     }
552
553     if (!m_layerTreeStateIsFrozen)
554         flushLayers();
555
556     [CATransaction begin];
557     [CATransaction setDisableActions:YES];
558
559     [m_hostingLayer setFrame:CGRectMake(layerPosition.width(), layerPosition.height(), viewSize.width(), viewSize.height())];
560
561     [CATransaction commit];
562
563     if (flushSynchronously)
564         [CATransaction flush];
565
566     m_webPage.send(Messages::DrawingAreaProxy::DidUpdateGeometry());
567
568     m_inUpdateGeometry = false;
569
570     m_layerHostingContext->setFencePort(fencePort.sendRight());
571 }
572
573 void TiledCoreAnimationDrawingArea::setDeviceScaleFactor(float deviceScaleFactor)
574 {
575     m_webPage.setDeviceScaleFactor(deviceScaleFactor);
576 }
577
578 void TiledCoreAnimationDrawingArea::setLayerHostingMode(LayerHostingMode)
579 {
580     updateLayerHostingContext();
581
582     // Finally, inform the UIProcess that the context has changed.
583     LayerTreeContext layerTreeContext;
584     layerTreeContext.contextID = m_layerHostingContext->contextID();
585     m_webPage.send(Messages::DrawingAreaProxy::UpdateAcceleratedCompositingMode(0, layerTreeContext));
586 }
587
588 void TiledCoreAnimationDrawingArea::setColorSpace(const ColorSpaceData& colorSpace)
589 {
590     m_layerHostingContext->setColorSpace(colorSpace.cgColorSpace.get());
591 }
592
593 void TiledCoreAnimationDrawingArea::updateLayerHostingContext()
594 {
595     RetainPtr<CGColorSpaceRef> colorSpace;
596
597     // Invalidate the old context.
598     if (m_layerHostingContext) {
599         colorSpace = m_layerHostingContext->colorSpace();
600         m_layerHostingContext->invalidate();
601         m_layerHostingContext = nullptr;
602     }
603
604     // Create a new context and set it up.
605     switch (m_webPage.layerHostingMode()) {
606     case LayerHostingMode::InProcess:
607         m_layerHostingContext = LayerHostingContext::createForPort(WebProcess::singleton().compositingRenderServerPort());
608         break;
609 #if HAVE(OUT_OF_PROCESS_LAYER_HOSTING)
610     case LayerHostingMode::OutOfProcess:
611         m_layerHostingContext = LayerHostingContext::createForExternalHostingProcess();
612         break;
613 #endif
614     }
615
616     if (m_rootLayer)
617         m_layerHostingContext->setRootLayer(m_hostingLayer.get());
618
619     if (colorSpace)
620         m_layerHostingContext->setColorSpace(colorSpace.get());
621 }
622
623 void TiledCoreAnimationDrawingArea::setRootCompositingLayer(CALayer *layer)
624 {
625     ASSERT(!m_layerTreeStateIsFrozen);
626
627     [CATransaction begin];
628     [CATransaction setDisableActions:YES];
629
630     bool hadRootLayer = !!m_rootLayer;
631     m_rootLayer = layer;
632     [m_rootLayer setSublayerTransform:m_transform];
633
634     updateRootLayers();
635
636     if (hadRootLayer != !!layer)
637         m_layerHostingContext->setRootLayer(layer ? m_hostingLayer.get() : nil);
638
639     updateDebugInfoLayer(layer && m_webPage.corePage()->settings().showTiledScrollingIndicator());
640
641     [CATransaction commit];
642 }
643
644 TiledBacking* TiledCoreAnimationDrawingArea::mainFrameTiledBacking() const
645 {
646     FrameView* frameView = m_webPage.mainFrameView();
647     return frameView ? frameView->tiledBacking() : nullptr;
648 }
649
650 void TiledCoreAnimationDrawingArea::updateDebugInfoLayer(bool showLayer)
651 {
652     if (m_debugInfoLayer) {
653         [m_debugInfoLayer removeFromSuperlayer];
654         m_debugInfoLayer = nil;
655     }
656     
657     if (showLayer) {
658         if (TiledBacking* tiledBacking = mainFrameTiledBacking()) {
659             if (PlatformCALayer* indicatorLayer = tiledBacking->tiledScrollingIndicatorLayer())
660                 m_debugInfoLayer = indicatorLayer->platformLayer();
661         }
662
663         if (m_debugInfoLayer) {
664             [m_debugInfoLayer setName:@"Debug Info"];
665             [m_hostingLayer addSublayer:m_debugInfoLayer.get()];
666         }
667     }
668 }
669
670 bool TiledCoreAnimationDrawingArea::shouldUseTiledBackingForFrameView(const FrameView& frameView)
671 {
672     return frameView.frame().isMainFrame();
673 }
674
675 PlatformCALayer* TiledCoreAnimationDrawingArea::layerForTransientZoom() const
676 {
677     RenderLayerBacking* renderViewBacking = m_webPage.mainFrameView()->renderView()->layer()->backing();
678
679     if (GraphicsLayer* contentsContainmentLayer = renderViewBacking->contentsContainmentLayer())
680         return downcast<GraphicsLayerCA>(*contentsContainmentLayer).platformCALayer();
681
682     return downcast<GraphicsLayerCA>(*renderViewBacking->graphicsLayer()).platformCALayer();
683 }
684
685 PlatformCALayer* TiledCoreAnimationDrawingArea::shadowLayerForTransientZoom() const
686 {
687     RenderLayerCompositor& renderLayerCompositor = m_webPage.mainFrameView()->renderView()->compositor();
688
689     if (GraphicsLayer* shadowGraphicsLayer = renderLayerCompositor.layerForContentShadow())
690         return downcast<GraphicsLayerCA>(*shadowGraphicsLayer).platformCALayer();
691
692     return nullptr;
693 }
694     
695 static FloatPoint shadowLayerPositionForFrame(FrameView& frameView, FloatPoint origin)
696 {
697     // FIXME: correct for b-t documents?
698     FloatPoint position = frameView.positionForRootContentLayer();
699     return position + origin.expandedTo(FloatPoint());
700 }
701
702 static FloatRect shadowLayerBoundsForFrame(FrameView& frameView, float transientScale)
703 {
704     FloatRect clipLayerFrame(frameView.renderView()->documentRect());
705     FloatRect shadowLayerFrame = clipLayerFrame;
706     
707     shadowLayerFrame.scale(transientScale / frameView.frame().page()->pageScaleFactor());
708     shadowLayerFrame.intersect(clipLayerFrame);
709     
710     return shadowLayerFrame;
711 }
712
713 void TiledCoreAnimationDrawingArea::applyTransientZoomToLayers(double scale, FloatPoint origin)
714 {
715     // FIXME: Scrollbars should stay in-place and change height while zooming.
716
717     if (!m_hostingLayer)
718         return;
719
720     TransformationMatrix transform;
721     transform.translate(origin.x(), origin.y());
722     transform.scale(scale);
723
724     PlatformCALayer* zoomLayer = layerForTransientZoom();
725     zoomLayer->setTransform(transform);
726     zoomLayer->setAnchorPoint(FloatPoint3D());
727     zoomLayer->setPosition(FloatPoint3D());
728     
729     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom()) {
730         FrameView& frameView = *m_webPage.mainFrameView();
731         shadowLayer->setBounds(shadowLayerBoundsForFrame(frameView, scale));
732         shadowLayer->setPosition(shadowLayerPositionForFrame(frameView, origin));
733     }
734
735     m_transientZoomScale = scale;
736     m_transientZoomOrigin = origin;
737 }
738
739 void TiledCoreAnimationDrawingArea::adjustTransientZoom(double scale, FloatPoint origin)
740 {
741     scale *= m_webPage.viewScaleFactor();
742
743     applyTransientZoomToLayers(scale, origin);
744
745     double currentPageScale = m_webPage.totalScaleFactor();
746     if (scale > currentPageScale)
747         return;
748
749     FrameView* frameView = m_webPage.mainFrameView();
750     FloatRect tileCoverageRect = frameView->visibleContentRectIncludingScrollbars();
751     tileCoverageRect.moveBy(-origin);
752     tileCoverageRect.scale(currentPageScale / scale);
753     frameView->renderView()->layer()->backing()->tiledBacking()->prepopulateRect(tileCoverageRect);
754 }
755
756 static RetainPtr<CABasicAnimation> transientZoomSnapAnimationForKeyPath(String keyPath)
757 {
758     const float transientZoomSnapBackDuration = 0.25;
759
760     RetainPtr<CABasicAnimation> animation = [CABasicAnimation animationWithKeyPath:keyPath];
761     [animation setDuration:transientZoomSnapBackDuration];
762     [animation setFillMode:kCAFillModeForwards];
763     [animation setRemovedOnCompletion:false];
764     [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
765
766     return animation;
767 }
768
769 void TiledCoreAnimationDrawingArea::commitTransientZoom(double scale, FloatPoint origin)
770 {
771     scale *= m_webPage.viewScaleFactor();
772
773     FrameView& frameView = *m_webPage.mainFrameView();
774     FloatRect visibleContentRect = frameView.visibleContentRectIncludingScrollbars();
775
776     FloatPoint constrainedOrigin = visibleContentRect.location();
777     constrainedOrigin.moveBy(-origin);
778
779     IntSize scaledTotalContentsSize = frameView.totalContentsSize();
780     scaledTotalContentsSize.scale(scale / m_webPage.totalScaleFactor());
781
782     // Scaling may have exposed the overhang area, so we need to constrain the final
783     // layer position exactly like scrolling will once it's committed, to ensure that
784     // scrolling doesn't make the view jump.
785     constrainedOrigin = ScrollableArea::constrainScrollPositionForOverhang(roundedIntRect(visibleContentRect), scaledTotalContentsSize, roundedIntPoint(constrainedOrigin), frameView.scrollOrigin(), frameView.headerHeight(), frameView.footerHeight());
786     constrainedOrigin.moveBy(-visibleContentRect.location());
787     constrainedOrigin = -constrainedOrigin;
788
789     if (m_transientZoomScale == scale && roundedIntPoint(m_transientZoomOrigin) == roundedIntPoint(constrainedOrigin)) {
790         // We're already at the right scale and position, so we don't need to animate.
791         applyTransientZoomToPage(scale, origin);
792         return;
793     }
794
795     TransformationMatrix transform;
796     transform.translate(constrainedOrigin.x(), constrainedOrigin.y());
797     transform.scale(scale);
798
799     RetainPtr<CABasicAnimation> renderViewAnimationCA = transientZoomSnapAnimationForKeyPath("transform");
800     RefPtr<PlatformCAAnimation> renderViewAnimation = PlatformCAAnimationCocoa::create(renderViewAnimationCA.get());
801     renderViewAnimation->setToValue(transform);
802
803     RetainPtr<CALayer> shadowCALayer;
804     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom())
805         shadowCALayer = shadowLayer->platformLayer();
806
807     RefPtr<PlatformCALayer> zoomLayer = layerForTransientZoom();
808     RefPtr<WebPage> page = &m_webPage;
809
810     [CATransaction begin];
811     [CATransaction setCompletionBlock:[zoomLayer, shadowCALayer, page, scale, origin] () {
812         zoomLayer->removeAnimationForKey("transientZoomCommit");
813         if (shadowCALayer)
814             [shadowCALayer removeAllAnimations];
815
816         if (TiledCoreAnimationDrawingArea* drawingArea = static_cast<TiledCoreAnimationDrawingArea*>(page->drawingArea()))
817             drawingArea->applyTransientZoomToPage(scale, origin);
818     }];
819
820     zoomLayer->addAnimationForKey("transientZoomCommit", *renderViewAnimation);
821
822     if (shadowCALayer) {
823         FloatRect shadowBounds = shadowLayerBoundsForFrame(frameView, scale);
824         RetainPtr<CGPathRef> shadowPath = adoptCF(CGPathCreateWithRect(shadowBounds, NULL));
825
826         RetainPtr<CABasicAnimation> shadowBoundsAnimation = transientZoomSnapAnimationForKeyPath("bounds");
827         [shadowBoundsAnimation setToValue:[NSValue valueWithRect:shadowBounds]];
828         RetainPtr<CABasicAnimation> shadowPositionAnimation = transientZoomSnapAnimationForKeyPath("position");
829         [shadowPositionAnimation setToValue:[NSValue valueWithPoint:shadowLayerPositionForFrame(frameView, constrainedOrigin)]];
830         RetainPtr<CABasicAnimation> shadowPathAnimation = transientZoomSnapAnimationForKeyPath("shadowPath");
831         [shadowPathAnimation setToValue:(id)shadowPath.get()];
832
833         [shadowCALayer addAnimation:shadowBoundsAnimation.get() forKey:@"transientZoomCommitShadowBounds"];
834         [shadowCALayer addAnimation:shadowPositionAnimation.get() forKey:@"transientZoomCommitShadowPosition"];
835         [shadowCALayer addAnimation:shadowPathAnimation.get() forKey:@"transientZoomCommitShadowPath"];
836     }
837
838     [CATransaction commit];
839 }
840
841 void TiledCoreAnimationDrawingArea::applyTransientZoomToPage(double scale, FloatPoint origin)
842 {
843     // If the page scale is already the target scale, setPageScaleFactor() will short-circuit
844     // and not apply the transform, so we can't depend on it to do so.
845     TransformationMatrix finalTransform;
846     finalTransform.scale(scale);
847     layerForTransientZoom()->setTransform(finalTransform);
848     
849     FrameView& frameView = *m_webPage.mainFrameView();
850
851     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom()) {
852         shadowLayer->setBounds(shadowLayerBoundsForFrame(frameView, 1));
853         shadowLayer->setPosition(shadowLayerPositionForFrame(frameView, FloatPoint()));
854     }
855
856     FloatPoint unscrolledOrigin(origin);
857     FloatRect unobscuredContentRect = frameView.unobscuredContentRectIncludingScrollbars();
858     unscrolledOrigin.moveBy(-unobscuredContentRect.location());
859     m_webPage.scalePage(scale / m_webPage.viewScaleFactor(), roundedIntPoint(-unscrolledOrigin));
860     m_transientZoomScale = 1;
861     flushLayers();
862 }
863
864 void TiledCoreAnimationDrawingArea::addFence(const MachSendRight& fencePort)
865 {
866     m_layerHostingContext->setFencePort(fencePort.sendRight());
867 }
868
869 bool TiledCoreAnimationDrawingArea::dispatchDidReachLayoutMilestone(WebCore::LayoutMilestones layoutMilestones)
870 {
871     m_pendingNewlyReachedLayoutMilestones |= layoutMilestones;
872     return true;
873 }
874
875 } // namespace WebKit
876
877 #endif // !PLATFORM(IOS)