Add a layout mode that scales down the view to try to fit the document
[WebKit-https.git] / Source / WebKit2 / 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 "ViewGestureControllerMessages.h"
36 #import "WebFrame.h"
37 #import "WebPage.h"
38 #import "WebPageCreationParameters.h"
39 #import "WebPageProxyMessages.h"
40 #import "WebProcess.h"
41 #import <QuartzCore/QuartzCore.h>
42 #import <WebCore/DebugPageOverlays.h>
43 #import <WebCore/FrameView.h>
44 #import <WebCore/GraphicsContext.h>
45 #import <WebCore/GraphicsLayerCA.h>
46 #import <WebCore/MachSendRight.h>
47 #import <WebCore/MainFrame.h>
48 #import <WebCore/Page.h>
49 #import <WebCore/PlatformCAAnimationMac.h>
50 #import <WebCore/RenderLayerBacking.h>
51 #import <WebCore/RenderLayerCompositor.h>
52 #import <WebCore/RenderView.h>
53 #import <WebCore/ScrollbarTheme.h>
54 #import <WebCore/Settings.h>
55 #import <WebCore/TiledBacking.h>
56 #import <WebCore/WebActionDisablingCALayerDelegate.h>
57 #import <wtf/MainThread.h>
58
59 #if ENABLE(ASYNC_SCROLLING)
60 #import <WebCore/AsyncScrollingCoordinator.h>
61 #import <WebCore/ScrollingThread.h>
62 #import <WebCore/ScrollingTree.h>
63 #endif
64
65 @interface CATransaction (Details)
66 + (void)synchronize;
67 @end
68
69 using namespace WebCore;
70
71 namespace WebKit {
72
73 TiledCoreAnimationDrawingArea::TiledCoreAnimationDrawingArea(WebPage& webPage, const WebPageCreationParameters& parameters)
74     : DrawingArea(DrawingAreaTypeTiledCoreAnimation, webPage)
75     , m_layerTreeStateIsFrozen(false)
76     , m_layerFlushScheduler(this)
77     , m_isPaintingSuspended(!(parameters.viewState & ViewState::IsVisible))
78     , m_exposedRect(FloatRect::infiniteRect())
79     , m_scrolledExposedRect(FloatRect::infiniteRect())
80     , m_transientZoomScale(1)
81     , m_sendDidUpdateViewStateTimer(RunLoop::main(), this, &TiledCoreAnimationDrawingArea::didUpdateViewStateTimerFired)
82     , m_wantsDidUpdateViewState(false)
83     , m_viewOverlayRootLayer(nullptr)
84 {
85     m_webPage.corePage()->settings().setForceCompositingMode(true);
86
87     m_hostingLayer = [CALayer layer];
88     [m_hostingLayer setDelegate:[WebActionDisablingCALayerDelegate shared]];
89     [m_hostingLayer setFrame:m_webPage.bounds()];
90     [m_hostingLayer setOpaque:YES];
91     [m_hostingLayer setGeometryFlipped:YES];
92
93     updateLayerHostingContext();
94     setColorSpace(parameters.colorSpace);
95
96     LayerTreeContext layerTreeContext;
97     layerTreeContext.contextID = m_layerHostingContext->contextID();
98     m_webPage.send(Messages::DrawingAreaProxy::EnterAcceleratedCompositingMode(0, layerTreeContext));
99 }
100
101 TiledCoreAnimationDrawingArea::~TiledCoreAnimationDrawingArea()
102 {
103     m_layerFlushScheduler.invalidate();
104 }
105
106 void TiledCoreAnimationDrawingArea::setNeedsDisplay()
107 {
108 }
109
110 void TiledCoreAnimationDrawingArea::setNeedsDisplayInRect(const IntRect& rect)
111 {
112 }
113
114 void TiledCoreAnimationDrawingArea::scroll(const IntRect& scrollRect, const IntSize& scrollDelta)
115 {
116     updateScrolledExposedRect();
117 }
118
119 void TiledCoreAnimationDrawingArea::setRootCompositingLayer(GraphicsLayer* graphicsLayer)
120 {
121     CALayer *rootLayer = graphicsLayer ? graphicsLayer->platformLayer() : nil;
122
123     if (m_layerTreeStateIsFrozen) {
124         m_pendingRootLayer = rootLayer;
125         return;
126     }
127
128     setRootCompositingLayer(rootLayer);
129 }
130
131 void TiledCoreAnimationDrawingArea::forceRepaint()
132 {
133     if (m_layerTreeStateIsFrozen)
134         return;
135
136     for (Frame* frame = &m_webPage.corePage()->mainFrame(); frame; frame = frame->tree().traverseNext()) {
137         FrameView* frameView = frame->view();
138         if (!frameView || !frameView->tiledBacking())
139             continue;
140
141         frameView->tiledBacking()->forceRepaint();
142     }
143
144     flushLayers();
145     [CATransaction flush];
146     [CATransaction synchronize];
147 }
148
149 bool TiledCoreAnimationDrawingArea::forceRepaintAsync(uint64_t callbackID)
150 {
151     if (m_layerTreeStateIsFrozen)
152         return false;
153
154     dispatchAfterEnsuringUpdatedScrollPosition([this, callbackID] {
155         m_webPage.drawingArea()->forceRepaint();
156         m_webPage.send(Messages::WebPageProxy::VoidCallback(callbackID));
157     });
158     return true;
159 }
160
161 void TiledCoreAnimationDrawingArea::setLayerTreeStateIsFrozen(bool layerTreeStateIsFrozen)
162 {
163     if (m_layerTreeStateIsFrozen == layerTreeStateIsFrozen)
164         return;
165
166     m_layerTreeStateIsFrozen = layerTreeStateIsFrozen;
167     if (m_layerTreeStateIsFrozen)
168         m_layerFlushScheduler.suspend();
169     else
170         m_layerFlushScheduler.resume();
171 }
172
173 bool TiledCoreAnimationDrawingArea::layerTreeStateIsFrozen() const
174 {
175     return m_layerTreeStateIsFrozen;
176 }
177
178 void TiledCoreAnimationDrawingArea::scheduleCompositingLayerFlush()
179 {
180     m_layerFlushScheduler.schedule();
181 }
182
183 void TiledCoreAnimationDrawingArea::scheduleCompositingLayerFlushImmediately()
184 {
185     scheduleCompositingLayerFlush();
186 }
187
188 void TiledCoreAnimationDrawingArea::updatePreferences(const WebPreferencesStore&)
189 {
190     Settings& settings = m_webPage.corePage()->settings();
191
192 #if ENABLE(ASYNC_SCROLLING)
193     if (AsyncScrollingCoordinator* scrollingCoordinator = downcast<AsyncScrollingCoordinator>(m_webPage.corePage()->scrollingCoordinator())) {
194         bool scrollingPerformanceLoggingEnabled = m_webPage.scrollingPerformanceLoggingEnabled();
195         
196         RefPtr<ScrollingTree> scrollingTree = scrollingCoordinator->scrollingTree();
197         ScrollingThread::dispatch([scrollingTree, scrollingPerformanceLoggingEnabled] {
198             scrollingTree->setScrollingPerformanceLoggingEnabled(scrollingPerformanceLoggingEnabled);
199         });
200     }
201 #endif
202
203     // Fixed position elements need to be composited and create stacking contexts
204     // in order to be scrolled by the ScrollingCoordinator. We also want to keep
205     // Settings:setFixedPositionCreatesStackingContext() enabled for iOS. See
206     // <rdar://problem/9813262> for more details.
207     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
208     settings.setFixedPositionCreatesStackingContext(true);
209
210     if (MainFrame* mainFrame = m_webPage.mainFrame())
211         DebugPageOverlays::settingsChanged(*mainFrame);
212
213     bool showTiledScrollingIndicator = settings.showTiledScrollingIndicator();
214     if (showTiledScrollingIndicator == !!m_debugInfoLayer)
215         return;
216
217     updateDebugInfoLayer(showTiledScrollingIndicator);
218 }
219
220 void TiledCoreAnimationDrawingArea::updateRootLayers()
221 {
222     if (!m_rootLayer) {
223         [m_hostingLayer setSublayers:@[ ]];
224         return;
225     }
226
227     [m_hostingLayer setSublayers:m_viewOverlayRootLayer ? @[ m_rootLayer.get(), m_viewOverlayRootLayer->platformLayer() ] : @[ m_rootLayer.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     // FIXME: Defer scrollbar flashing until after the second layout.
276
277     const int maximumDocumentWidthForScaling = 1440;
278     const float minimumViewScale = 0.1;
279
280     if (!m_shouldScaleViewToFitDocument)
281         return;
282
283     if (!m_webPage.mainFrame()->view()->needsLayout() && m_lastDocumentSizeForScaleToFit == m_webPage.mainFrameView()->renderView()->unscaledDocumentRect().size() && m_lastViewSizeForScaleToFit == m_webPage.size())
284         return;
285
286     // Lay out at the view size.
287     m_webPage.setUseFixedLayout(false);
288     m_webPage.layoutIfNeeded();
289
290     IntSize documentSize = m_webPage.mainFrameView()->renderView()->unscaledDocumentRect().size();
291     m_lastViewSizeForScaleToFit = m_webPage.size();
292     m_lastDocumentSizeForScaleToFit = documentSize;
293
294     int documentWidth = documentSize.width();
295     int viewWidth = m_webPage.size().width();
296
297     float viewScale = 1;
298
299     // Avoid scaling down documents that don't fit in a certain width, to allow
300     // sites that want horizontal scrollbars to continue to have them.
301     if (documentWidth && documentWidth < maximumDocumentWidthForScaling && viewWidth < documentWidth) {
302         // If the document doesn't fit in the view, scale it down but lay out at the view size.
303         m_webPage.setUseFixedLayout(true);
304         viewScale = (float)viewWidth / (float)documentWidth;
305         viewScale = std::max(viewScale, minimumViewScale);
306         m_webPage.setFixedLayoutSize(IntSize(ceilf(m_webPage.size().width() / viewScale), m_webPage.size().height()));
307     }
308
309     m_webPage.scaleView(viewScale);
310 }
311
312 void TiledCoreAnimationDrawingArea::dispatchAfterEnsuringUpdatedScrollPosition(std::function<void ()> function)
313 {
314 #if ENABLE(ASYNC_SCROLLING)
315     if (!m_webPage.corePage()->scrollingCoordinator()) {
316         function();
317         return;
318     }
319
320     m_webPage.ref();
321     m_webPage.corePage()->scrollingCoordinator()->commitTreeStateIfNeeded();
322
323     if (!m_layerTreeStateIsFrozen)
324         m_layerFlushScheduler.suspend();
325
326     // It is possible for the drawing area to be destroyed before the bound block
327     // is invoked, so grab a reference to the web page here so we can access the drawing area through it.
328     // (The web page is already kept alive by dispatchAfterEnsuringUpdatedScrollPosition).
329     WebPage* webPage = &m_webPage;
330
331     ScrollingThread::dispatchBarrier([this, webPage, function] {
332         DrawingArea* drawingArea = webPage->drawingArea();
333         if (!drawingArea)
334             return;
335
336         function();
337
338         if (!m_layerTreeStateIsFrozen)
339             m_layerFlushScheduler.resume();
340
341         webPage->deref();
342     });
343 #else
344     function();
345 #endif
346 }
347
348 bool TiledCoreAnimationDrawingArea::flushLayers()
349 {
350     ASSERT(!m_layerTreeStateIsFrozen);
351
352     @autoreleasepool {
353         scaleViewToFitDocumentIfNeeded();
354
355         m_webPage.layoutIfNeeded();
356
357         updateIntrinsicContentSizeIfNeeded();
358
359         if (m_pendingRootLayer) {
360             setRootCompositingLayer(m_pendingRootLayer.get());
361             m_pendingRootLayer = nullptr;
362         }
363
364         FloatRect visibleRect = [m_hostingLayer frame];
365         visibleRect.intersect(m_scrolledExposedRect);
366
367         // Because our view-relative overlay root layer is not attached to the main GraphicsLayer tree, we need to flush it manually.
368         if (m_viewOverlayRootLayer)
369             m_viewOverlayRootLayer->flushCompositingState(visibleRect);
370
371         bool returnValue = m_webPage.mainFrameView()->flushCompositingStateIncludingSubframes();
372 #if ENABLE(ASYNC_SCROLLING)
373         if (ScrollingCoordinator* scrollingCoordinator = m_webPage.corePage()->scrollingCoordinator())
374             scrollingCoordinator->commitTreeStateIfNeeded();
375 #endif
376
377         // If we have an active transient zoom, we want the zoom to win over any changes
378         // that WebCore makes to the relevant layers, so re-apply our changes after flushing.
379         if (m_transientZoomScale != 1)
380             applyTransientZoomToLayers(m_transientZoomScale, m_transientZoomOrigin);
381
382         if (!m_fenceCallbacksForAfterNextFlush.isEmpty()) {
383             MachSendRight fencePort = m_layerHostingContext->createFencePort();
384
385             for (auto callbackID : m_fenceCallbacksForAfterNextFlush)
386                 m_webPage.send(Messages::WebPageProxy::MachSendRightCallback(fencePort, callbackID));
387             m_fenceCallbacksForAfterNextFlush.clear();
388
389             m_layerHostingContext->setFencePort(fencePort.sendRight());
390         }
391
392         return returnValue;
393     }
394 }
395
396 void TiledCoreAnimationDrawingArea::viewStateDidChange(ViewState::Flags changed, bool wantsDidUpdateViewState, const Vector<uint64_t>& nextViewStateChangeCallbackIDs)
397 {
398     m_nextViewStateChangeCallbackIDs.appendVector(nextViewStateChangeCallbackIDs);
399     m_wantsDidUpdateViewState |= wantsDidUpdateViewState;
400
401     if (changed & ViewState::IsVisible) {
402         if (m_webPage.isVisible())
403             resumePainting();
404         else
405             suspendPainting();
406     }
407
408     if (m_wantsDidUpdateViewState || !m_nextViewStateChangeCallbackIDs.isEmpty())
409         m_sendDidUpdateViewStateTimer.startOneShot(0);
410 }
411
412 void TiledCoreAnimationDrawingArea::didUpdateViewStateTimerFired()
413 {
414     [CATransaction flush];
415
416     if (m_wantsDidUpdateViewState)
417         m_webPage.send(Messages::WebPageProxy::DidUpdateViewState());
418
419     for (uint64_t callbackID : m_nextViewStateChangeCallbackIDs)
420         m_webPage.send(Messages::WebPageProxy::VoidCallback(callbackID));
421
422     m_nextViewStateChangeCallbackIDs.clear();
423     m_wantsDidUpdateViewState = false;
424 }
425
426 void TiledCoreAnimationDrawingArea::suspendPainting()
427 {
428     ASSERT(!m_isPaintingSuspended);
429     m_isPaintingSuspended = true;
430
431     [m_hostingLayer setValue:@YES forKey:@"NSCAViewRenderPaused"];
432     [[NSNotificationCenter defaultCenter] postNotificationName:@"NSCAViewRenderDidPauseNotification" object:nil userInfo:[NSDictionary dictionaryWithObject:m_hostingLayer.get() forKey:@"layer"]];
433 }
434
435 void TiledCoreAnimationDrawingArea::resumePainting()
436 {
437     if (!m_isPaintingSuspended) {
438         // FIXME: We can get a call to resumePainting when painting is not suspended.
439         // This happens when sending a synchronous message to create a new page. See <rdar://problem/8976531>.
440         return;
441     }
442     m_isPaintingSuspended = false;
443
444     [m_hostingLayer setValue:@NO forKey:@"NSCAViewRenderPaused"];
445     [[NSNotificationCenter defaultCenter] postNotificationName:@"NSCAViewRenderDidResumeNotification" object:nil userInfo:[NSDictionary dictionaryWithObject:m_hostingLayer.get() forKey:@"layer"]];
446 }
447
448 void TiledCoreAnimationDrawingArea::setExposedRect(const FloatRect& exposedRect)
449 {
450     m_exposedRect = exposedRect;
451     updateScrolledExposedRect();
452 }
453
454 void TiledCoreAnimationDrawingArea::updateScrolledExposedRect()
455 {
456     FrameView* frameView = m_webPage.mainFrameView();
457     if (!frameView)
458         return;
459
460     m_scrolledExposedRect = m_exposedRect;
461
462 #if !PLATFORM(IOS)
463     if (!m_exposedRect.isInfinite()) {
464         IntPoint scrollPositionWithOrigin = frameView->scrollPosition() + toIntSize(frameView->scrollOrigin());
465         m_scrolledExposedRect.moveBy(scrollPositionWithOrigin);
466     }
467 #endif
468
469     frameView->setExposedRect(m_scrolledExposedRect);
470 }
471
472 void TiledCoreAnimationDrawingArea::updateGeometry(const IntSize& viewSize, const IntSize& layerPosition, bool flushSynchronously)
473 {
474     m_inUpdateGeometry = true;
475
476     IntSize size = viewSize;
477     IntSize contentSize = IntSize(-1, -1);
478
479     if (!m_webPage.minimumLayoutSize().width() || m_webPage.autoSizingShouldExpandToViewHeight())
480         m_webPage.setSize(size);
481
482     FrameView* frameView = m_webPage.mainFrameView();
483
484     if (m_webPage.autoSizingShouldExpandToViewHeight() && frameView)
485         frameView->setAutoSizeFixedMinimumHeight(viewSize.height());
486
487     m_webPage.layoutIfNeeded();
488
489     if (m_webPage.minimumLayoutSize().width() && frameView) {
490         contentSize = frameView->autoSizingIntrinsicContentSize();
491         size = contentSize;
492     }
493
494     if (!m_layerTreeStateIsFrozen)
495         flushLayers();
496
497     [CATransaction begin];
498     [CATransaction setDisableActions:YES];
499
500     [m_hostingLayer setFrame:CGRectMake(layerPosition.width(), layerPosition.height(), viewSize.width(), viewSize.height())];
501
502     [CATransaction commit];
503
504     if (flushSynchronously) {
505         [CATransaction flush];
506         [CATransaction synchronize];
507     }
508
509     m_webPage.send(Messages::DrawingAreaProxy::DidUpdateGeometry());
510
511     m_inUpdateGeometry = false;
512 }
513
514 void TiledCoreAnimationDrawingArea::setDeviceScaleFactor(float deviceScaleFactor)
515 {
516     m_webPage.setDeviceScaleFactor(deviceScaleFactor);
517 }
518
519 void TiledCoreAnimationDrawingArea::setLayerHostingMode(LayerHostingMode)
520 {
521     updateLayerHostingContext();
522
523     // Finally, inform the UIProcess that the context has changed.
524     LayerTreeContext layerTreeContext;
525     layerTreeContext.contextID = m_layerHostingContext->contextID();
526     m_webPage.send(Messages::DrawingAreaProxy::UpdateAcceleratedCompositingMode(0, layerTreeContext));
527 }
528
529 void TiledCoreAnimationDrawingArea::setColorSpace(const ColorSpaceData& colorSpace)
530 {
531     m_layerHostingContext->setColorSpace(colorSpace.cgColorSpace.get());
532 }
533
534 void TiledCoreAnimationDrawingArea::updateLayerHostingContext()
535 {
536     RetainPtr<CGColorSpaceRef> colorSpace;
537
538     // Invalidate the old context.
539     if (m_layerHostingContext) {
540         colorSpace = m_layerHostingContext->colorSpace();
541         m_layerHostingContext->invalidate();
542         m_layerHostingContext = nullptr;
543     }
544
545     // Create a new context and set it up.
546     switch (m_webPage.layerHostingMode()) {
547     case LayerHostingMode::InProcess:
548         m_layerHostingContext = LayerHostingContext::createForPort(WebProcess::singleton().compositingRenderServerPort());
549         break;
550 #if HAVE(OUT_OF_PROCESS_LAYER_HOSTING)
551     case LayerHostingMode::OutOfProcess:
552         m_layerHostingContext = LayerHostingContext::createForExternalHostingProcess();
553         break;
554 #endif
555     }
556
557     if (m_rootLayer)
558         m_layerHostingContext->setRootLayer(m_hostingLayer.get());
559
560     if (colorSpace)
561         m_layerHostingContext->setColorSpace(colorSpace.get());
562 }
563
564 void TiledCoreAnimationDrawingArea::setRootCompositingLayer(CALayer *layer)
565 {
566     ASSERT(!m_layerTreeStateIsFrozen);
567
568     [CATransaction begin];
569     [CATransaction setDisableActions:YES];
570
571     bool hadRootLayer = !!m_rootLayer;
572     m_rootLayer = layer;
573     [m_rootLayer setSublayerTransform:m_transform];
574
575     updateRootLayers();
576
577     if (hadRootLayer != !!layer)
578         m_layerHostingContext->setRootLayer(layer ? m_hostingLayer.get() : 0);
579
580     updateDebugInfoLayer(m_webPage.corePage()->settings().showTiledScrollingIndicator());
581
582     [CATransaction commit];
583 }
584
585 TiledBacking* TiledCoreAnimationDrawingArea::mainFrameTiledBacking() const
586 {
587     FrameView* frameView = m_webPage.mainFrameView();
588     return frameView ? frameView->tiledBacking() : nullptr;
589 }
590
591 void TiledCoreAnimationDrawingArea::updateDebugInfoLayer(bool showLayer)
592 {
593     if (showLayer) {
594         if (TiledBacking* tiledBacking = mainFrameTiledBacking()) {
595             if (PlatformCALayer* indicatorLayer = tiledBacking->tiledScrollingIndicatorLayer())
596                 m_debugInfoLayer = indicatorLayer->platformLayer();
597         }
598
599         if (m_debugInfoLayer) {
600 #ifndef NDEBUG
601             [m_debugInfoLayer setName:@"Debug Info"];
602 #endif
603             [m_hostingLayer addSublayer:m_debugInfoLayer.get()];
604         }
605     } else if (m_debugInfoLayer) {
606         [m_debugInfoLayer removeFromSuperlayer];
607         m_debugInfoLayer = nullptr;
608     }
609 }
610
611 bool TiledCoreAnimationDrawingArea::shouldUseTiledBackingForFrameView(const FrameView* frameView)
612 {
613     return frameView && frameView->frame().isMainFrame();
614 }
615
616 PlatformCALayer* TiledCoreAnimationDrawingArea::layerForTransientZoom() const
617 {
618     RenderLayerBacking* renderViewBacking = m_webPage.mainFrameView()->renderView()->layer()->backing();
619
620     if (GraphicsLayer* contentsContainmentLayer = renderViewBacking->contentsContainmentLayer())
621         return downcast<GraphicsLayerCA>(*contentsContainmentLayer).platformCALayer();
622
623     return downcast<GraphicsLayerCA>(*renderViewBacking->graphicsLayer()).platformCALayer();
624 }
625
626 PlatformCALayer* TiledCoreAnimationDrawingArea::shadowLayerForTransientZoom() const
627 {
628     RenderLayerCompositor& renderLayerCompositor = m_webPage.mainFrameView()->renderView()->compositor();
629
630     if (GraphicsLayer* shadowGraphicsLayer = renderLayerCompositor.layerForContentShadow())
631         return downcast<GraphicsLayerCA>(*shadowGraphicsLayer).platformCALayer();
632
633     return nullptr;
634 }
635     
636 static FloatPoint shadowLayerPositionForFrame(FrameView& frameView, FloatPoint origin)
637 {
638     FloatPoint position = frameView.renderView()->documentRect().location() + FloatPoint(0, frameView.yPositionForRootContentLayer());
639     return position + origin.expandedTo(FloatPoint());
640 }
641
642 static FloatRect shadowLayerBoundsForFrame(FrameView& frameView, float transientScale)
643 {
644     FloatRect clipLayerFrame(frameView.renderView()->documentRect());
645     FloatRect shadowLayerFrame = clipLayerFrame;
646     
647     shadowLayerFrame.scale(transientScale / frameView.frame().page()->pageScaleFactor());
648     shadowLayerFrame.intersect(clipLayerFrame);
649     
650     return shadowLayerFrame;
651 }
652
653 void TiledCoreAnimationDrawingArea::applyTransientZoomToLayers(double scale, FloatPoint origin)
654 {
655     // FIXME: Scrollbars should stay in-place and change height while zooming.
656
657     if (!m_hostingLayer)
658         return;
659
660     TransformationMatrix transform;
661     transform.translate(origin.x(), origin.y());
662     transform.scale(scale);
663
664     PlatformCALayer* zoomLayer = layerForTransientZoom();
665     zoomLayer->setTransform(transform);
666     zoomLayer->setAnchorPoint(FloatPoint3D());
667     zoomLayer->setPosition(FloatPoint3D());
668     
669     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom()) {
670         FrameView& frameView = *m_webPage.mainFrameView();
671         shadowLayer->setBounds(shadowLayerBoundsForFrame(frameView, scale));
672         shadowLayer->setPosition(shadowLayerPositionForFrame(frameView, origin));
673     }
674
675     m_transientZoomScale = scale;
676     m_transientZoomOrigin = origin;
677 }
678
679 void TiledCoreAnimationDrawingArea::adjustTransientZoom(double scale, FloatPoint origin)
680 {
681     scale *= m_webPage.viewScaleFactor();
682
683     applyTransientZoomToLayers(scale, origin);
684
685     double currentPageScale = m_webPage.totalScaleFactor();
686     if (scale > currentPageScale)
687         return;
688
689     FrameView* frameView = m_webPage.mainFrameView();
690     FloatRect tileCoverageRect = frameView->visibleContentRectIncludingScrollbars();
691     tileCoverageRect.moveBy(-origin);
692     tileCoverageRect.scale(currentPageScale / scale);
693     frameView->renderView()->layer()->backing()->tiledBacking()->prepopulateRect(tileCoverageRect);
694 }
695
696 static RetainPtr<CABasicAnimation> transientZoomSnapAnimationForKeyPath(String keyPath)
697 {
698     const float transientZoomSnapBackDuration = 0.25;
699
700     RetainPtr<CABasicAnimation> animation = [CABasicAnimation animationWithKeyPath:keyPath];
701     [animation setDuration:transientZoomSnapBackDuration];
702     [animation setFillMode:kCAFillModeForwards];
703     [animation setRemovedOnCompletion:false];
704     [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
705
706     return animation;
707 }
708
709 void TiledCoreAnimationDrawingArea::commitTransientZoom(double scale, FloatPoint origin)
710 {
711     scale *= m_webPage.viewScaleFactor();
712
713     FrameView& frameView = *m_webPage.mainFrameView();
714     FloatRect visibleContentRect = frameView.visibleContentRectIncludingScrollbars();
715
716     FloatPoint constrainedOrigin = visibleContentRect.location();
717     constrainedOrigin.moveBy(-origin);
718
719     IntSize scaledTotalContentsSize = frameView.totalContentsSize();
720     scaledTotalContentsSize.scale(scale / m_webPage.totalScaleFactor());
721
722     // Scaling may have exposed the overhang area, so we need to constrain the final
723     // layer position exactly like scrolling will once it's committed, to ensure that
724     // scrolling doesn't make the view jump.
725     constrainedOrigin = ScrollableArea::constrainScrollPositionForOverhang(roundedIntRect(visibleContentRect), scaledTotalContentsSize, roundedIntPoint(constrainedOrigin), frameView.scrollOrigin(), frameView.headerHeight(), frameView.footerHeight());
726     constrainedOrigin.moveBy(-visibleContentRect.location());
727     constrainedOrigin = -constrainedOrigin;
728
729     if (m_transientZoomScale == scale && roundedIntPoint(m_transientZoomOrigin) == roundedIntPoint(constrainedOrigin)) {
730         // We're already at the right scale and position, so we don't need to animate.
731         applyTransientZoomToPage(scale, origin);
732         return;
733     }
734
735     TransformationMatrix transform;
736     transform.translate(constrainedOrigin.x(), constrainedOrigin.y());
737     transform.scale(scale);
738
739     RetainPtr<CABasicAnimation> renderViewAnimationCA = transientZoomSnapAnimationForKeyPath("transform");
740     RefPtr<PlatformCAAnimation> renderViewAnimation = PlatformCAAnimationMac::create(renderViewAnimationCA.get());
741     renderViewAnimation->setToValue(transform);
742
743     RetainPtr<CALayer> shadowCALayer;
744     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom())
745         shadowCALayer = shadowLayer->platformLayer();
746
747     RefPtr<PlatformCALayer> zoomLayer = layerForTransientZoom();
748     RefPtr<WebPage> page = &m_webPage;
749
750     [CATransaction begin];
751     [CATransaction setCompletionBlock:[zoomLayer, shadowCALayer, page, scale, origin] () {
752         zoomLayer->removeAnimationForKey("transientZoomCommit");
753         if (shadowCALayer)
754             [shadowCALayer removeAllAnimations];
755
756         if (TiledCoreAnimationDrawingArea* drawingArea = static_cast<TiledCoreAnimationDrawingArea*>(page->drawingArea()))
757             drawingArea->applyTransientZoomToPage(scale, origin);
758     }];
759
760     zoomLayer->addAnimationForKey("transientZoomCommit", *renderViewAnimation);
761
762     if (shadowCALayer) {
763         FloatRect shadowBounds = shadowLayerBoundsForFrame(frameView, scale);
764         RetainPtr<CGPathRef> shadowPath = adoptCF(CGPathCreateWithRect(shadowBounds, NULL)).get();
765
766         RetainPtr<CABasicAnimation> shadowBoundsAnimation = transientZoomSnapAnimationForKeyPath("bounds");
767         [shadowBoundsAnimation setToValue:[NSValue valueWithRect:shadowBounds]];
768         RetainPtr<CABasicAnimation> shadowPositionAnimation = transientZoomSnapAnimationForKeyPath("position");
769         [shadowPositionAnimation setToValue:[NSValue valueWithPoint:shadowLayerPositionForFrame(frameView, constrainedOrigin)]];
770         RetainPtr<CABasicAnimation> shadowPathAnimation = transientZoomSnapAnimationForKeyPath("shadowPath");
771         [shadowPathAnimation setToValue:(id)shadowPath.get()];
772
773         [shadowCALayer addAnimation:shadowBoundsAnimation.get() forKey:@"transientZoomCommitShadowBounds"];
774         [shadowCALayer addAnimation:shadowPositionAnimation.get() forKey:@"transientZoomCommitShadowPosition"];
775         [shadowCALayer addAnimation:shadowPathAnimation.get() forKey:@"transientZoomCommitShadowPath"];
776     }
777
778     [CATransaction commit];
779 }
780
781 void TiledCoreAnimationDrawingArea::applyTransientZoomToPage(double scale, FloatPoint origin)
782 {
783     // If the page scale is already the target scale, setPageScaleFactor() will short-circuit
784     // and not apply the transform, so we can't depend on it to do so.
785     TransformationMatrix finalTransform;
786     finalTransform.scale(scale);
787     layerForTransientZoom()->setTransform(finalTransform);
788     
789     FrameView& frameView = *m_webPage.mainFrameView();
790
791     if (PlatformCALayer* shadowLayer = shadowLayerForTransientZoom()) {
792         shadowLayer->setBounds(shadowLayerBoundsForFrame(frameView, 1));
793         shadowLayer->setPosition(shadowLayerPositionForFrame(frameView, FloatPoint()));
794     }
795
796     FloatPoint unscrolledOrigin(origin);
797     FloatRect unobscuredContentRect = frameView.unobscuredContentRectIncludingScrollbars();
798     unscrolledOrigin.moveBy(-unobscuredContentRect.location());
799     m_webPage.scalePage(scale / m_webPage.viewScaleFactor(), roundedIntPoint(-unscrolledOrigin));
800     m_transientZoomScale = 1;
801     flushLayers();
802 }
803
804 void TiledCoreAnimationDrawingArea::addFence(const MachSendRight& fencePort)
805 {
806     m_layerHostingContext->setFencePort(fencePort.sendRight());
807 }
808
809 void TiledCoreAnimationDrawingArea::replyWithFenceAfterNextFlush(uint64_t callbackID)
810 {
811     m_fenceCallbacksForAfterNextFlush.append(callbackID);
812 }
813
814 } // namespace WebKit
815
816 #endif // !PLATFORM(IOS)