Drop MainFrame class
[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/Frame.h>
45 #import <WebCore/FrameView.h>
46 #import <WebCore/GraphicsContext.h>
47 #import <WebCore/GraphicsLayerCA.h>
48 #import <WebCore/InspectorController.h>
49 #import <WebCore/MachSendRight.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     DebugPageOverlays::settingsChanged(*m_webPage.corePage());
209
210     bool showTiledScrollingIndicator = settings.showTiledScrollingIndicator();
211     if (showTiledScrollingIndicator == !!m_debugInfoLayer)
212         return;
213
214     updateDebugInfoLayer(showTiledScrollingIndicator);
215 }
216
217 void TiledCoreAnimationDrawingArea::updateRootLayers()
218 {
219     if (!m_rootLayer) {
220         [m_hostingLayer setSublayers:@[ ]];
221         return;
222     }
223
224     [m_hostingLayer setSublayers:m_viewOverlayRootLayer ? @[ m_rootLayer.get(), m_viewOverlayRootLayer->platformLayer() ] : @[ m_rootLayer.get() ]];
225     
226     if (m_debugInfoLayer)
227         [m_hostingLayer addSublayer:m_debugInfoLayer.get()];
228 }
229
230 void TiledCoreAnimationDrawingArea::attachViewOverlayGraphicsLayer(Frame* frame, GraphicsLayer* viewOverlayRootLayer)
231 {
232     if (!frame->isMainFrame())
233         return;
234
235     m_viewOverlayRootLayer = viewOverlayRootLayer;
236     updateRootLayers();
237 }
238
239 void TiledCoreAnimationDrawingArea::mainFrameContentSizeChanged(const IntSize& size)
240 {
241
242 }
243
244 void TiledCoreAnimationDrawingArea::updateIntrinsicContentSizeIfNeeded()
245 {
246     if (!m_webPage.minimumLayoutSize().width())
247         return;
248
249     FrameView* frameView = m_webPage.mainFrameView();
250     if (!frameView)
251         return;
252
253     if (frameView->needsLayout())
254         return;
255
256     IntSize contentSize = frameView->autoSizingIntrinsicContentSize();
257     if (m_lastSentIntrinsicContentSize == contentSize)
258         return;
259
260     m_lastSentIntrinsicContentSize = contentSize;
261     m_webPage.send(Messages::DrawingAreaProxy::IntrinsicContentSizeDidChange(contentSize));
262 }
263
264 void TiledCoreAnimationDrawingArea::setShouldScaleViewToFitDocument(bool shouldScaleView)
265 {
266     if (m_shouldScaleViewToFitDocument == shouldScaleView)
267         return;
268
269     m_shouldScaleViewToFitDocument = shouldScaleView;
270     scheduleCompositingLayerFlush();
271 }
272
273 void TiledCoreAnimationDrawingArea::scaleViewToFitDocumentIfNeeded()
274 {
275     const int maximumDocumentWidthForScaling = 1440;
276     const float minimumViewScale = 0.1;
277
278     if (!m_shouldScaleViewToFitDocument)
279         return;
280
281     LOG(Resize, "TiledCoreAnimationDrawingArea %p scaleViewToFitDocumentIfNeeded", this);
282     m_webPage.layoutIfNeeded();
283
284     int viewWidth = m_webPage.size().width();
285     int documentWidth = m_webPage.mainFrameView()->renderView()->unscaledDocumentRect().width();
286
287     bool documentWidthChanged = m_lastDocumentSizeForScaleToFit.width() != documentWidth;
288     bool viewWidthChanged = m_lastViewSizeForScaleToFit.width() != viewWidth;
289
290     LOG(Resize, "  documentWidthChanged=%d, viewWidthChanged=%d", documentWidthChanged, viewWidthChanged);
291
292     if (!documentWidthChanged && !viewWidthChanged)
293         return;
294
295     // The view is now bigger than the document, so we'll re-evaluate whether we have to scale.
296     if (m_isScalingViewToFitDocument && viewWidth >= m_lastDocumentSizeForScaleToFit.width())
297         m_isScalingViewToFitDocument = false;
298
299     // Our current understanding of the document width is still up to date, and we're in scaling mode.
300     // Update the viewScale without doing an extra layout to re-determine the document width.
301     if (m_isScalingViewToFitDocument) {
302         if (!documentWidthChanged) {
303             m_lastViewSizeForScaleToFit = m_webPage.size();
304             float viewScale = (float)viewWidth / (float)m_lastDocumentSizeForScaleToFit.width();
305             if (viewScale < minimumViewScale) {
306                 viewScale = minimumViewScale;
307                 documentWidth = std::ceil(viewWidth / viewScale);
308             }
309             IntSize fixedLayoutSize(documentWidth, std::ceil((m_webPage.size().height() - m_webPage.corePage()->topContentInset()) / viewScale));
310             m_webPage.setFixedLayoutSize(fixedLayoutSize);
311             m_webPage.scaleView(viewScale);
312
313             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);
314             return;
315         }
316     
317         IntSize fixedLayoutSize = m_webPage.fixedLayoutSize();
318         if (documentWidth > fixedLayoutSize.width()) {
319             LOG(Resize, "  page laid out wider than fixed layout width. Not attempting to re-scale");
320             return;
321         }
322     }
323
324     LOG(Resize, "  doing unconstrained layout");
325
326     // Lay out at the view size.
327     m_webPage.setUseFixedLayout(false);
328     m_webPage.layoutIfNeeded();
329
330     IntSize documentSize = m_webPage.mainFrameView()->renderView()->unscaledDocumentRect().size();
331     m_lastViewSizeForScaleToFit = m_webPage.size();
332     m_lastDocumentSizeForScaleToFit = documentSize;
333
334     documentWidth = documentSize.width();
335
336     float viewScale = 1;
337
338     LOG(Resize, "  unscaled document size %dx%d. need to scale down: %d", documentSize.width(), documentSize.height(), documentWidth && documentWidth < maximumDocumentWidthForScaling && viewWidth < documentWidth);
339
340     // Avoid scaling down documents that don't fit in a certain width, to allow
341     // sites that want horizontal scrollbars to continue to have them.
342     if (documentWidth && documentWidth < maximumDocumentWidthForScaling && viewWidth < documentWidth) {
343         // If the document doesn't fit in the view, scale it down but lay out at the view size.
344         m_isScalingViewToFitDocument = true;
345         m_webPage.setUseFixedLayout(true);
346         viewScale = (float)viewWidth / (float)documentWidth;
347         if (viewScale < minimumViewScale) {
348             viewScale = minimumViewScale;
349             documentWidth = std::ceil(viewWidth / viewScale);
350         }
351         IntSize fixedLayoutSize(documentWidth, std::ceil((m_webPage.size().height() - m_webPage.corePage()->topContentInset()) / viewScale));
352         m_webPage.setFixedLayoutSize(fixedLayoutSize);
353
354         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);
355     }
356
357     m_webPage.scaleView(viewScale);
358 }
359
360 void TiledCoreAnimationDrawingArea::dispatchAfterEnsuringUpdatedScrollPosition(WTF::Function<void ()>&& function)
361 {
362 #if ENABLE(ASYNC_SCROLLING)
363     if (!m_webPage.corePage()->scrollingCoordinator()) {
364         function();
365         return;
366     }
367
368     m_webPage.ref();
369     m_webPage.corePage()->scrollingCoordinator()->commitTreeStateIfNeeded();
370
371     if (!m_layerTreeStateIsFrozen)
372         m_layerFlushScheduler.suspend();
373
374     // It is possible for the drawing area to be destroyed before the bound block
375     // is invoked, so grab a reference to the web page here so we can access the drawing area through it.
376     // (The web page is already kept alive by dispatchAfterEnsuringUpdatedScrollPosition).
377     WebPage* webPage = &m_webPage;
378
379     ScrollingThread::dispatchBarrier([this, webPage, function = WTFMove(function)] {
380         DrawingArea* drawingArea = webPage->drawingArea();
381         if (!drawingArea)
382             return;
383
384         function();
385
386         if (!m_layerTreeStateIsFrozen)
387             m_layerFlushScheduler.resume();
388
389         webPage->deref();
390     });
391 #else
392     function();
393 #endif
394 }
395
396 void TiledCoreAnimationDrawingArea::sendPendingNewlyReachedLayoutMilestones()
397 {
398     if (!m_pendingNewlyReachedLayoutMilestones)
399         return;
400
401     m_webPage.send(Messages::WebPageProxy::DidReachLayoutMilestone(m_pendingNewlyReachedLayoutMilestones));
402     m_pendingNewlyReachedLayoutMilestones = 0;
403 }
404
405 void TiledCoreAnimationDrawingArea::addTransactionCallbackID(CallbackID callbackID)
406 {
407     m_pendingCallbackIDs.append(callbackID);
408     scheduleCompositingLayerFlush();
409 }
410
411 bool TiledCoreAnimationDrawingArea::flushLayers()
412 {
413     ASSERT(!m_layerTreeStateIsFrozen);
414
415     @autoreleasepool {
416         scaleViewToFitDocumentIfNeeded();
417
418         m_webPage.layoutIfNeeded();
419         m_webPage.flushPendingEditorStateUpdate();
420
421         updateIntrinsicContentSizeIfNeeded();
422
423         if (m_pendingRootLayer) {
424             setRootCompositingLayer(m_pendingRootLayer.get());
425             m_pendingRootLayer = nullptr;
426         }
427
428         FloatRect visibleRect = [m_hostingLayer frame];
429         if (m_scrolledViewExposedRect)
430             visibleRect.intersect(m_scrolledViewExposedRect.value());
431
432         // Because our view-relative overlay root layer is not attached to the main GraphicsLayer tree, we need to flush it manually.
433         if (m_viewOverlayRootLayer)
434             m_viewOverlayRootLayer->flushCompositingState(visibleRect);
435
436         RefPtr<WebPage> retainedPage = &m_webPage;
437         [CATransaction addCommitHandler:[retainedPage] {
438             if (Page* corePage = retainedPage->corePage()) {
439                 if (Frame* coreFrame = retainedPage->mainFrame())
440                     corePage->inspectorController().didComposite(*coreFrame);
441             }
442             if (auto drawingArea = static_cast<TiledCoreAnimationDrawingArea*>(retainedPage->drawingArea()))
443                 drawingArea->sendPendingNewlyReachedLayoutMilestones();
444         } forPhase:kCATransactionPhasePostCommit];
445
446         bool returnValue = m_webPage.mainFrameView()->flushCompositingStateIncludingSubframes();
447 #if ENABLE(ASYNC_SCROLLING)
448         if (ScrollingCoordinator* scrollingCoordinator = m_webPage.corePage()->scrollingCoordinator())
449             scrollingCoordinator->commitTreeStateIfNeeded();
450 #endif
451
452         // If we have an active transient zoom, we want the zoom to win over any changes
453         // that WebCore makes to the relevant layers, so re-apply our changes after flushing.
454         if (m_transientZoomScale != 1)
455             applyTransientZoomToLayers(m_transientZoomScale, m_transientZoomOrigin);
456
457         if (!m_pendingCallbackIDs.isEmpty()) {
458             m_webPage.send(Messages::DrawingAreaProxy::DispatchPresentationCallbacksAfterFlushingLayers(m_pendingCallbackIDs));
459             m_pendingCallbackIDs.clear();
460         }
461
462         return returnValue;
463     }
464 }
465
466 void TiledCoreAnimationDrawingArea::activityStateDidChange(ActivityState::Flags changed, bool wantsDidUpdateActivityState, const Vector<CallbackID>& nextActivityStateChangeCallbackIDs)
467 {
468     m_nextActivityStateChangeCallbackIDs.appendVector(nextActivityStateChangeCallbackIDs);
469     m_wantsDidUpdateActivityState |= wantsDidUpdateActivityState;
470
471     if (changed & ActivityState::IsVisible) {
472         if (m_webPage.isVisible())
473             resumePainting();
474         else
475             suspendPainting();
476     }
477
478     if (m_wantsDidUpdateActivityState || !m_nextActivityStateChangeCallbackIDs.isEmpty())
479         m_sendDidUpdateActivityStateTimer.startOneShot(0_s);
480 }
481
482 void TiledCoreAnimationDrawingArea::didUpdateActivityStateTimerFired()
483 {
484     [CATransaction flush];
485
486     if (m_wantsDidUpdateActivityState)
487         m_webPage.send(Messages::WebPageProxy::DidUpdateActivityState());
488
489     for (auto callbackID : m_nextActivityStateChangeCallbackIDs)
490         m_webPage.send(Messages::WebPageProxy::VoidCallback(callbackID));
491
492     m_nextActivityStateChangeCallbackIDs.clear();
493     m_wantsDidUpdateActivityState = false;
494 }
495
496 void TiledCoreAnimationDrawingArea::suspendPainting()
497 {
498     ASSERT(!m_isPaintingSuspended);
499     m_isPaintingSuspended = true;
500
501     [m_hostingLayer setValue:@YES forKey:@"NSCAViewRenderPaused"];
502     [[NSNotificationCenter defaultCenter] postNotificationName:@"NSCAViewRenderDidPauseNotification" object:nil userInfo:[NSDictionary dictionaryWithObject:m_hostingLayer.get() forKey:@"layer"]];
503 }
504
505 void TiledCoreAnimationDrawingArea::resumePainting()
506 {
507     if (!m_isPaintingSuspended) {
508         // FIXME: We can get a call to resumePainting when painting is not suspended.
509         // This happens when sending a synchronous message to create a new page. See <rdar://problem/8976531>.
510         return;
511     }
512     m_isPaintingSuspended = false;
513
514     [m_hostingLayer setValue:@NO forKey:@"NSCAViewRenderPaused"];
515     [[NSNotificationCenter defaultCenter] postNotificationName:@"NSCAViewRenderDidResumeNotification" object:nil userInfo:[NSDictionary dictionaryWithObject:m_hostingLayer.get() forKey:@"layer"]];
516 }
517
518 void TiledCoreAnimationDrawingArea::setViewExposedRect(std::optional<WebCore::FloatRect> viewExposedRect)
519 {
520     m_viewExposedRect = viewExposedRect;
521     updateScrolledExposedRect();
522 }
523
524 void TiledCoreAnimationDrawingArea::updateScrolledExposedRect()
525 {
526     FrameView* frameView = m_webPage.mainFrameView();
527     if (!frameView)
528         return;
529
530     m_scrolledViewExposedRect = m_viewExposedRect;
531
532 #if !PLATFORM(IOS)
533     if (m_viewExposedRect) {
534         ScrollOffset scrollOffset = frameView->scrollOffsetFromPosition(frameView->scrollPosition());
535         m_scrolledViewExposedRect.value().moveBy(scrollOffset);
536     }
537 #endif
538
539     frameView->setViewExposedRect(m_scrolledViewExposedRect);
540 }
541
542 void TiledCoreAnimationDrawingArea::updateGeometry(const IntSize& viewSize, bool flushSynchronously, const WebCore::MachSendRight& fencePort)
543 {
544     m_inUpdateGeometry = true;
545
546     IntSize size = viewSize;
547     IntSize contentSize = IntSize(-1, -1);
548
549     if (!m_webPage.minimumLayoutSize().width() || m_webPage.autoSizingShouldExpandToViewHeight())
550         m_webPage.setSize(size);
551
552     FrameView* frameView = m_webPage.mainFrameView();
553
554     if (m_webPage.autoSizingShouldExpandToViewHeight() && frameView)
555         frameView->setAutoSizeFixedMinimumHeight(viewSize.height());
556
557     m_webPage.layoutIfNeeded();
558
559     if (m_webPage.minimumLayoutSize().width() && frameView) {
560         contentSize = frameView->autoSizingIntrinsicContentSize();
561         size = contentSize;
562     }
563
564     if (!m_layerTreeStateIsFrozen)
565         flushLayers();
566
567     [CATransaction begin];
568     [CATransaction setDisableActions:YES];
569
570     [m_hostingLayer setFrame:CGRectMake(0, 0, viewSize.width(), viewSize.height())];
571
572     [CATransaction commit];
573
574     if (flushSynchronously)
575         [CATransaction flush];
576
577     m_webPage.send(Messages::DrawingAreaProxy::DidUpdateGeometry());
578
579     m_inUpdateGeometry = false;
580
581     m_layerHostingContext->setFencePort(fencePort.sendRight());
582 }
583
584 void TiledCoreAnimationDrawingArea::setDeviceScaleFactor(float deviceScaleFactor)
585 {
586     m_webPage.setDeviceScaleFactor(deviceScaleFactor);
587 }
588
589 void TiledCoreAnimationDrawingArea::setLayerHostingMode(LayerHostingMode)
590 {
591     updateLayerHostingContext();
592
593     // Finally, inform the UIProcess that the context has changed.
594     LayerTreeContext layerTreeContext;
595     layerTreeContext.contextID = m_layerHostingContext->contextID();
596     m_webPage.send(Messages::DrawingAreaProxy::UpdateAcceleratedCompositingMode(0, layerTreeContext));
597 }
598
599 void TiledCoreAnimationDrawingArea::setColorSpace(const ColorSpaceData& colorSpace)
600 {
601     m_layerHostingContext->setColorSpace(colorSpace.cgColorSpace.get());
602 }
603
604 void TiledCoreAnimationDrawingArea::updateLayerHostingContext()
605 {
606     RetainPtr<CGColorSpaceRef> colorSpace;
607
608     // Invalidate the old context.
609     if (m_layerHostingContext) {
610         colorSpace = m_layerHostingContext->colorSpace();
611         m_layerHostingContext->invalidate();
612         m_layerHostingContext = nullptr;
613     }
614
615     // Create a new context and set it up.
616     switch (m_webPage.layerHostingMode()) {
617     case LayerHostingMode::InProcess:
618         m_layerHostingContext = LayerHostingContext::createForPort(WebProcess::singleton().compositingRenderServerPort());
619         break;
620 #if HAVE(OUT_OF_PROCESS_LAYER_HOSTING)
621     case LayerHostingMode::OutOfProcess:
622         m_layerHostingContext = LayerHostingContext::createForExternalHostingProcess();
623         break;
624 #endif
625     }
626
627     if (m_rootLayer)
628         m_layerHostingContext->setRootLayer(m_hostingLayer.get());
629
630     if (colorSpace)
631         m_layerHostingContext->setColorSpace(colorSpace.get());
632 }
633
634 void TiledCoreAnimationDrawingArea::setRootCompositingLayer(CALayer *layer)
635 {
636     ASSERT(!m_layerTreeStateIsFrozen);
637
638     [CATransaction begin];
639     [CATransaction setDisableActions:YES];
640
641     bool hadRootLayer = !!m_rootLayer;
642     m_rootLayer = layer;
643     [m_rootLayer setSublayerTransform:m_transform];
644
645     updateRootLayers();
646
647     if (hadRootLayer != !!layer)
648         m_layerHostingContext->setRootLayer(layer ? m_hostingLayer.get() : nil);
649
650     updateDebugInfoLayer(layer && m_webPage.corePage()->settings().showTiledScrollingIndicator());
651
652     [CATransaction commit];
653 }
654
655 TiledBacking* TiledCoreAnimationDrawingArea::mainFrameTiledBacking() const
656 {
657     FrameView* frameView = m_webPage.mainFrameView();
658     return frameView ? frameView->tiledBacking() : nullptr;
659 }
660
661 void TiledCoreAnimationDrawingArea::updateDebugInfoLayer(bool showLayer)
662 {
663     if (m_debugInfoLayer) {
664         [m_debugInfoLayer removeFromSuperlayer];
665         m_debugInfoLayer = nil;
666     }
667     
668     if (showLayer) {
669         if (TiledBacking* tiledBacking = mainFrameTiledBacking()) {
670             if (PlatformCALayer* indicatorLayer = tiledBacking->tiledScrollingIndicatorLayer())
671                 m_debugInfoLayer = indicatorLayer->platformLayer();
672         }
673
674         if (m_debugInfoLayer) {
675             [m_debugInfoLayer setName:@"Debug Info"];
676             [m_hostingLayer addSublayer:m_debugInfoLayer.get()];
677         }
678     }
679 }
680
681 bool TiledCoreAnimationDrawingArea::shouldUseTiledBackingForFrameView(const FrameView& frameView)
682 {
683     return frameView.frame().isMainFrame() || m_webPage.corePage()->settings().asyncFrameScrollingEnabled();
684 }
685
686 PlatformCALayer* TiledCoreAnimationDrawingArea::layerForTransientZoom() const
687 {
688     RenderLayerBacking* renderViewBacking = m_webPage.mainFrameView()->renderView()->layer()->backing();
689
690     if (GraphicsLayer* contentsContainmentLayer = renderViewBacking->contentsContainmentLayer())
691         return downcast<GraphicsLayerCA>(*contentsContainmentLayer).platformCALayer();
692
693     return downcast<GraphicsLayerCA>(*renderViewBacking->graphicsLayer()).platformCALayer();
694 }
695
696 PlatformCALayer* TiledCoreAnimationDrawingArea::shadowLayerForTransientZoom() const
697 {
698     RenderLayerCompositor& renderLayerCompositor = m_webPage.mainFrameView()->renderView()->compositor();
699
700     if (GraphicsLayer* shadowGraphicsLayer = renderLayerCompositor.layerForContentShadow())
701         return downcast<GraphicsLayerCA>(*shadowGraphicsLayer).platformCALayer();
702
703     return nullptr;
704 }
705     
706 static FloatPoint shadowLayerPositionForFrame(FrameView& frameView, FloatPoint origin)
707 {
708     // FIXME: correct for b-t documents?
709     FloatPoint position = frameView.positionForRootContentLayer();
710     return position + origin.expandedTo(FloatPoint());
711 }
712
713 static FloatRect shadowLayerBoundsForFrame(FrameView& frameView, float transientScale)
714 {
715     FloatRect clipLayerFrame(frameView.renderView()->documentRect());
716     FloatRect shadowLayerFrame = clipLayerFrame;
717     
718     shadowLayerFrame.scale(transientScale / frameView.frame().page()->pageScaleFactor());
719     shadowLayerFrame.intersect(clipLayerFrame);
720     
721     return shadowLayerFrame;
722 }
723
724 void TiledCoreAnimationDrawingArea::applyTransientZoomToLayers(double scale, FloatPoint origin)
725 {
726     // FIXME: Scrollbars should stay in-place and change height while zooming.
727
728     if (!m_hostingLayer)
729         return;
730
731     TransformationMatrix transform;
732     transform.translate(origin.x(), origin.y());
733     transform.scale(scale);
734
735     PlatformCALayer* zoomLayer = layerForTransientZoom();
736     zoomLayer->setTransform(transform);
737     zoomLayer->setAnchorPoint(FloatPoint3D());
738     zoomLayer->setPosition(FloatPoint3D());
739     
740     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom()) {
741         FrameView& frameView = *m_webPage.mainFrameView();
742         shadowLayer->setBounds(shadowLayerBoundsForFrame(frameView, scale));
743         shadowLayer->setPosition(shadowLayerPositionForFrame(frameView, origin));
744     }
745
746     m_transientZoomScale = scale;
747     m_transientZoomOrigin = origin;
748 }
749
750 void TiledCoreAnimationDrawingArea::adjustTransientZoom(double scale, FloatPoint origin)
751 {
752     scale *= m_webPage.viewScaleFactor();
753
754     applyTransientZoomToLayers(scale, origin);
755
756     double currentPageScale = m_webPage.totalScaleFactor();
757     if (scale > currentPageScale)
758         return;
759
760     FrameView* frameView = m_webPage.mainFrameView();
761     FloatRect tileCoverageRect = frameView->visibleContentRectIncludingScrollbars();
762     tileCoverageRect.moveBy(-origin);
763     tileCoverageRect.scale(currentPageScale / scale);
764     frameView->renderView()->layer()->backing()->tiledBacking()->prepopulateRect(tileCoverageRect);
765 }
766
767 static RetainPtr<CABasicAnimation> transientZoomSnapAnimationForKeyPath(String keyPath)
768 {
769     const float transientZoomSnapBackDuration = 0.25;
770
771     RetainPtr<CABasicAnimation> animation = [CABasicAnimation animationWithKeyPath:keyPath];
772     [animation setDuration:transientZoomSnapBackDuration];
773     [animation setFillMode:kCAFillModeForwards];
774     [animation setRemovedOnCompletion:false];
775     [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
776
777     return animation;
778 }
779
780 void TiledCoreAnimationDrawingArea::commitTransientZoom(double scale, FloatPoint origin)
781 {
782     scale *= m_webPage.viewScaleFactor();
783
784     FrameView& frameView = *m_webPage.mainFrameView();
785     FloatRect visibleContentRect = frameView.visibleContentRectIncludingScrollbars();
786
787     FloatPoint constrainedOrigin = visibleContentRect.location();
788     constrainedOrigin.moveBy(-origin);
789
790     IntSize scaledTotalContentsSize = frameView.totalContentsSize();
791     scaledTotalContentsSize.scale(scale / m_webPage.totalScaleFactor());
792
793     // Scaling may have exposed the overhang area, so we need to constrain the final
794     // layer position exactly like scrolling will once it's committed, to ensure that
795     // scrolling doesn't make the view jump.
796     constrainedOrigin = ScrollableArea::constrainScrollPositionForOverhang(roundedIntRect(visibleContentRect), scaledTotalContentsSize, roundedIntPoint(constrainedOrigin), frameView.scrollOrigin(), frameView.headerHeight(), frameView.footerHeight());
797     constrainedOrigin.moveBy(-visibleContentRect.location());
798     constrainedOrigin = -constrainedOrigin;
799
800     if (m_transientZoomScale == scale && roundedIntPoint(m_transientZoomOrigin) == roundedIntPoint(constrainedOrigin)) {
801         // We're already at the right scale and position, so we don't need to animate.
802         applyTransientZoomToPage(scale, origin);
803         return;
804     }
805
806     TransformationMatrix transform;
807     transform.translate(constrainedOrigin.x(), constrainedOrigin.y());
808     transform.scale(scale);
809
810     RetainPtr<CABasicAnimation> renderViewAnimationCA = transientZoomSnapAnimationForKeyPath("transform");
811     RefPtr<PlatformCAAnimation> renderViewAnimation = PlatformCAAnimationCocoa::create(renderViewAnimationCA.get());
812     renderViewAnimation->setToValue(transform);
813
814     RetainPtr<CALayer> shadowCALayer;
815     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom())
816         shadowCALayer = shadowLayer->platformLayer();
817
818     RefPtr<PlatformCALayer> zoomLayer = layerForTransientZoom();
819     RefPtr<WebPage> page = &m_webPage;
820
821     [CATransaction begin];
822     [CATransaction setCompletionBlock:[zoomLayer, shadowCALayer, page, scale, origin] () {
823         zoomLayer->removeAnimationForKey("transientZoomCommit");
824         if (shadowCALayer)
825             [shadowCALayer removeAllAnimations];
826
827         if (TiledCoreAnimationDrawingArea* drawingArea = static_cast<TiledCoreAnimationDrawingArea*>(page->drawingArea()))
828             drawingArea->applyTransientZoomToPage(scale, origin);
829     }];
830
831     zoomLayer->addAnimationForKey("transientZoomCommit", *renderViewAnimation);
832
833     if (shadowCALayer) {
834         FloatRect shadowBounds = shadowLayerBoundsForFrame(frameView, scale);
835         RetainPtr<CGPathRef> shadowPath = adoptCF(CGPathCreateWithRect(shadowBounds, NULL));
836
837         RetainPtr<CABasicAnimation> shadowBoundsAnimation = transientZoomSnapAnimationForKeyPath("bounds");
838         [shadowBoundsAnimation setToValue:[NSValue valueWithRect:shadowBounds]];
839         RetainPtr<CABasicAnimation> shadowPositionAnimation = transientZoomSnapAnimationForKeyPath("position");
840         [shadowPositionAnimation setToValue:[NSValue valueWithPoint:shadowLayerPositionForFrame(frameView, constrainedOrigin)]];
841         RetainPtr<CABasicAnimation> shadowPathAnimation = transientZoomSnapAnimationForKeyPath("shadowPath");
842         [shadowPathAnimation setToValue:(id)shadowPath.get()];
843
844         [shadowCALayer addAnimation:shadowBoundsAnimation.get() forKey:@"transientZoomCommitShadowBounds"];
845         [shadowCALayer addAnimation:shadowPositionAnimation.get() forKey:@"transientZoomCommitShadowPosition"];
846         [shadowCALayer addAnimation:shadowPathAnimation.get() forKey:@"transientZoomCommitShadowPath"];
847     }
848
849     [CATransaction commit];
850 }
851
852 void TiledCoreAnimationDrawingArea::applyTransientZoomToPage(double scale, FloatPoint origin)
853 {
854     // If the page scale is already the target scale, setPageScaleFactor() will short-circuit
855     // and not apply the transform, so we can't depend on it to do so.
856     TransformationMatrix finalTransform;
857     finalTransform.scale(scale);
858     layerForTransientZoom()->setTransform(finalTransform);
859     
860     FrameView& frameView = *m_webPage.mainFrameView();
861
862     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom()) {
863         shadowLayer->setBounds(shadowLayerBoundsForFrame(frameView, 1));
864         shadowLayer->setPosition(shadowLayerPositionForFrame(frameView, FloatPoint()));
865     }
866
867     FloatPoint unscrolledOrigin(origin);
868     FloatRect unobscuredContentRect = frameView.unobscuredContentRectIncludingScrollbars();
869     unscrolledOrigin.moveBy(-unobscuredContentRect.location());
870     m_webPage.scalePage(scale / m_webPage.viewScaleFactor(), roundedIntPoint(-unscrolledOrigin));
871     m_transientZoomScale = 1;
872     flushLayers();
873 }
874
875 void TiledCoreAnimationDrawingArea::addFence(const MachSendRight& fencePort)
876 {
877     m_layerHostingContext->setFencePort(fencePort.sendRight());
878 }
879
880 bool TiledCoreAnimationDrawingArea::dispatchDidReachLayoutMilestone(WebCore::LayoutMilestones layoutMilestones)
881 {
882     m_pendingNewlyReachedLayoutMilestones |= layoutMilestones;
883     return true;
884 }
885
886 } // namespace WebKit
887
888 #endif // !PLATFORM(IOS)