Add WTF::move()
[WebKit-https.git] / Source / WebKit2 / WebProcess / WebPage / mac / RemoteLayerTreeDrawingArea.mm
1 /*
2  * Copyright (C) 2012-2014 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 "RemoteLayerTreeDrawingArea.h"
28
29 #import "DrawingAreaProxyMessages.h"
30 #import "GraphicsLayerCARemote.h"
31 #import "PlatformCALayerRemote.h"
32 #import "RemoteLayerBackingStoreCollection.h"
33 #import "RemoteLayerTreeContext.h"
34 #import "RemoteLayerTreeDisplayRefreshMonitor.h"
35 #import "RemoteLayerTreeDrawingAreaProxyMessages.h"
36 #import "RemoteScrollingCoordinator.h"
37 #import "RemoteScrollingCoordinatorTransaction.h"
38 #import "WebPage.h"
39 #import "WebProcess.h"
40 #import <WebCore/Frame.h>
41 #import <WebCore/FrameView.h>
42 #import <WebCore/MainFrame.h>
43 #import <WebCore/RenderLayerCompositor.h>
44 #import <WebCore/RenderView.h>
45 #import <WebCore/Settings.h>
46 #import <WebCore/TiledBacking.h>
47 #import <QuartzCore/QuartzCore.h>
48
49 using namespace WebCore;
50
51 namespace WebKit {
52
53 RemoteLayerTreeDrawingArea::RemoteLayerTreeDrawingArea(WebPage& webPage, const WebPageCreationParameters&)
54     : DrawingArea(DrawingAreaTypeRemoteLayerTree, webPage)
55     , m_remoteLayerTreeContext(std::make_unique<RemoteLayerTreeContext>(webPage))
56     , m_rootLayer(GraphicsLayer::create(graphicsLayerFactory(), *this))
57     , m_exposedRect(FloatRect::infiniteRect())
58     , m_scrolledExposedRect(FloatRect::infiniteRect())
59     , m_layerFlushTimer(this, &RemoteLayerTreeDrawingArea::layerFlushTimerFired)
60     , m_isFlushingSuspended(false)
61     , m_hasDeferredFlush(false)
62     , m_isThrottlingLayerFlushes(false)
63     , m_isLayerFlushThrottlingTemporarilyDisabledForInteraction(false)
64     , m_isInitialThrottledLayerFlush(false)
65     , m_waitingForBackingStoreSwap(false)
66     , m_hadFlushDeferredWhileWaitingForBackingStoreSwap(false)
67     , m_displayRefreshMonitorsToNotify(nullptr)
68     , m_currentTransactionID(0)
69 {
70     webPage.corePage()->settings().setForceCompositingMode(true);
71 #if PLATFORM(IOS)
72     webPage.corePage()->settings().setDelegatesPageScaling(true);
73 #endif
74
75     m_commitQueue = dispatch_queue_create("com.apple.WebKit.WebContent.RemoteLayerTreeDrawingArea.CommitQueue", nullptr);
76 }
77
78 RemoteLayerTreeDrawingArea::~RemoteLayerTreeDrawingArea()
79 {
80     dispatch_release(m_commitQueue);
81 }
82
83 void RemoteLayerTreeDrawingArea::setNeedsDisplay()
84 {
85 }
86
87 void RemoteLayerTreeDrawingArea::setNeedsDisplayInRect(const IntRect&)
88 {
89 }
90
91 void RemoteLayerTreeDrawingArea::scroll(const IntRect& scrollRect, const IntSize& scrollDelta)
92 {
93 }
94
95 GraphicsLayerFactory* RemoteLayerTreeDrawingArea::graphicsLayerFactory()
96 {
97     return m_remoteLayerTreeContext.get();
98 }
99
100 PassRefPtr<DisplayRefreshMonitor> RemoteLayerTreeDrawingArea::createDisplayRefreshMonitor(PlatformDisplayID displayID)
101 {
102     RefPtr<RemoteLayerTreeDisplayRefreshMonitor> monitor = RemoteLayerTreeDisplayRefreshMonitor::create(displayID, *this);
103     m_displayRefreshMonitors.add(monitor.get());
104     return monitor.release();
105 }
106
107 void RemoteLayerTreeDrawingArea::willDestroyDisplayRefreshMonitor(DisplayRefreshMonitor* monitor)
108 {
109     auto remoteMonitor = static_cast<RemoteLayerTreeDisplayRefreshMonitor*>(monitor);
110     m_displayRefreshMonitors.remove(remoteMonitor);
111
112     if (m_displayRefreshMonitorsToNotify)
113         m_displayRefreshMonitorsToNotify->remove(remoteMonitor);
114 }
115
116 void RemoteLayerTreeDrawingArea::setRootCompositingLayer(GraphicsLayer* rootLayer)
117 {
118     Vector<GraphicsLayer*> children;
119     if (rootLayer) {
120         children.append(rootLayer);
121         children.append(m_webPage.pageOverlayController().viewOverlayRootLayer());
122     }
123     m_rootLayer->setChildren(children);
124
125     scheduleCompositingLayerFlush();
126 }
127
128 void RemoteLayerTreeDrawingArea::updateGeometry(const IntSize& viewSize, const IntSize& layerPosition)
129 {
130     m_viewSize = viewSize;
131     m_webPage.setSize(viewSize);
132
133     scheduleCompositingLayerFlush();
134
135     m_webPage.send(Messages::DrawingAreaProxy::DidUpdateGeometry());
136 }
137
138 bool RemoteLayerTreeDrawingArea::shouldUseTiledBackingForFrameView(const FrameView* frameView)
139 {
140     return frameView && frameView->frame().isMainFrame();
141 }
142
143 void RemoteLayerTreeDrawingArea::updatePreferences(const WebPreferencesStore&)
144 {
145     Settings& settings = m_webPage.corePage()->settings();
146
147     // Fixed position elements need to be composited and create stacking contexts
148     // in order to be scrolled by the ScrollingCoordinator.
149     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
150     settings.setFixedPositionCreatesStackingContext(true);
151
152     m_rootLayer->setShowDebugBorder(settings.showDebugBorders());
153 }
154
155 #if PLATFORM(IOS)
156 void RemoteLayerTreeDrawingArea::setDeviceScaleFactor(float deviceScaleFactor)
157 {
158     m_webPage.setDeviceScaleFactor(deviceScaleFactor);
159 }
160 #endif
161
162 void RemoteLayerTreeDrawingArea::setLayerTreeStateIsFrozen(bool isFrozen)
163 {
164     if (m_isFlushingSuspended == isFrozen)
165         return;
166
167     m_isFlushingSuspended = isFrozen;
168
169     if (!m_isFlushingSuspended && m_hasDeferredFlush) {
170         m_hasDeferredFlush = false;
171         scheduleCompositingLayerFlush();
172     }
173 }
174
175 void RemoteLayerTreeDrawingArea::forceRepaint()
176 {
177     if (m_isFlushingSuspended)
178         return;
179
180     for (Frame* frame = &m_webPage.corePage()->mainFrame(); frame; frame = frame->tree().traverseNext()) {
181         FrameView* frameView = frame->view();
182         if (!frameView || !frameView->tiledBacking())
183             continue;
184
185         frameView->tiledBacking()->forceRepaint();
186     }
187
188     flushLayers();
189 }
190
191 void RemoteLayerTreeDrawingArea::acceleratedAnimationDidStart(uint64_t layerID, const String& key, double startTime)
192 {
193     m_remoteLayerTreeContext->animationDidStart(layerID, key, startTime);
194 }
195
196 void RemoteLayerTreeDrawingArea::setExposedRect(const FloatRect& exposedRect)
197 {
198     m_exposedRect = exposedRect;
199     updateScrolledExposedRect();
200 }
201
202 #if PLATFORM(IOS)
203 void RemoteLayerTreeDrawingArea::setExposedContentRect(const FloatRect& exposedContentRect)
204 {
205     FrameView* frameView = m_webPage.mainFrameView();
206     if (!frameView)
207         return;
208     if (frameView->exposedContentRect() == exposedContentRect)
209         return;
210
211     frameView->setExposedContentRect(exposedContentRect);
212     scheduleCompositingLayerFlush();
213 }
214 #endif
215
216 void RemoteLayerTreeDrawingArea::updateScrolledExposedRect()
217 {
218     FrameView* frameView = m_webPage.mainFrameView();
219     if (!frameView)
220         return;
221
222     m_scrolledExposedRect = m_exposedRect;
223
224 #if !PLATFORM(IOS)
225     if (!m_exposedRect.isInfinite()) {
226         IntPoint scrollPositionWithOrigin = frameView->scrollPosition() + toIntSize(frameView->scrollOrigin());
227         m_scrolledExposedRect.moveBy(scrollPositionWithOrigin);
228     }
229 #endif
230
231     frameView->setExposedRect(m_scrolledExposedRect);
232
233     m_webPage.pageOverlayController().didChangeExposedRect();
234 }
235
236 TiledBacking* RemoteLayerTreeDrawingArea::mainFrameTiledBacking() const
237 {
238     FrameView* frameView = m_webPage.mainFrameView();
239     return frameView ? frameView->tiledBacking() : nullptr;
240 }
241
242 void RemoteLayerTreeDrawingArea::scheduleCompositingLayerFlush()
243 {
244     if (m_isFlushingSuspended) {
245         m_isLayerFlushThrottlingTemporarilyDisabledForInteraction = false;
246         m_hasDeferredFlush = true;
247         return;
248     }
249     if (m_isLayerFlushThrottlingTemporarilyDisabledForInteraction) {
250         m_isLayerFlushThrottlingTemporarilyDisabledForInteraction = false;
251         m_layerFlushTimer.startOneShot(0_ms);
252         return;
253     }
254
255     if (m_layerFlushTimer.isActive())
256         return;
257
258     const auto initialFlushDelay = 500_ms;
259     const auto flushDelay = 1500_ms;
260     auto throttleDelay = m_isThrottlingLayerFlushes ? (m_isInitialThrottledLayerFlush ? initialFlushDelay : flushDelay) : 0_ms;
261     m_isInitialThrottledLayerFlush = false;
262
263     m_layerFlushTimer.startOneShot(throttleDelay);
264 }
265
266 bool RemoteLayerTreeDrawingArea::adjustLayerFlushThrottling(WebCore::LayerFlushThrottleState::Flags flags)
267 {
268     if (flags & WebCore::LayerFlushThrottleState::UserIsInteracting)
269         m_isLayerFlushThrottlingTemporarilyDisabledForInteraction = true;
270
271     bool wasThrottlingLayerFlushes = m_isThrottlingLayerFlushes;
272     m_isThrottlingLayerFlushes = flags & WebCore::LayerFlushThrottleState::MainLoadProgressing;
273
274     if (!wasThrottlingLayerFlushes && m_isThrottlingLayerFlushes)
275         m_isInitialThrottledLayerFlush = true;
276
277     // Re-schedule the flush if we stopped throttling.
278     if (wasThrottlingLayerFlushes && !m_isThrottlingLayerFlushes && m_layerFlushTimer.isActive()) {
279         m_layerFlushTimer.stop();
280         scheduleCompositingLayerFlush();
281     }
282     return true;
283 }
284
285 void RemoteLayerTreeDrawingArea::layerFlushTimerFired(WebCore::Timer<RemoteLayerTreeDrawingArea>*)
286 {
287     flushLayers();
288 }
289
290 void RemoteLayerTreeDrawingArea::flushLayers()
291 {
292     if (!m_rootLayer)
293         return;
294
295     if (m_isFlushingSuspended) {
296         m_hasDeferredFlush = true;
297         return;
298     }
299
300     if (m_waitingForBackingStoreSwap) {
301         m_hadFlushDeferredWhileWaitingForBackingStoreSwap = true;
302         return;
303     }
304
305     RELEASE_ASSERT(!m_pendingBackingStoreFlusher || m_pendingBackingStoreFlusher->hasFlushed());
306
307     RemoteLayerBackingStoreCollection& backingStoreCollection = m_remoteLayerTreeContext->backingStoreCollection();
308     backingStoreCollection.willFlushLayers();
309
310     m_webPage.layoutIfNeeded();
311
312     FloatRect visibleRect(FloatPoint(), m_viewSize);
313     visibleRect.intersect(m_scrolledExposedRect);
314     m_webPage.pageOverlayController().flushPageOverlayLayers(visibleRect);
315     m_webPage.mainFrameView()->flushCompositingStateIncludingSubframes();
316     m_rootLayer->flushCompositingStateForThisLayerOnly();
317
318     // FIXME: Minimize these transactions if nothing changed.
319     RemoteLayerTreeTransaction layerTransaction;
320     layerTransaction.setTransactionID(takeNextTransactionID());
321     layerTransaction.setCallbackIDs(WTF::move(m_pendingCallbackIDs));
322     m_remoteLayerTreeContext->buildTransaction(layerTransaction, *toGraphicsLayerCARemote(m_rootLayer.get())->platformCALayer());
323     backingStoreCollection.willCommitLayerTree(layerTransaction);
324     m_webPage.willCommitLayerTree(layerTransaction);
325
326     RemoteScrollingCoordinatorTransaction scrollingTransaction;
327 #if ENABLE(ASYNC_SCROLLING)
328     if (m_webPage.scrollingCoordinator())
329         toRemoteScrollingCoordinator(m_webPage.scrollingCoordinator())->buildTransaction(scrollingTransaction);
330 #endif
331
332     m_waitingForBackingStoreSwap = true;
333
334     m_webPage.send(Messages::RemoteLayerTreeDrawingAreaProxy::WillCommitLayerTree(layerTransaction.transactionID()));
335
336     Messages::RemoteLayerTreeDrawingAreaProxy::CommitLayerTree message(layerTransaction, scrollingTransaction);
337     auto commitEncoder = std::make_unique<IPC::MessageEncoder>(Messages::RemoteLayerTreeDrawingAreaProxy::CommitLayerTree::receiverName(), Messages::RemoteLayerTreeDrawingAreaProxy::CommitLayerTree::name(), m_webPage.pageID());
338     commitEncoder->encode(message.arguments());
339
340     // FIXME: Move all backing store flushing management to RemoteLayerBackingStoreCollection.
341     bool hadAnyChangedBackingStore = false;
342     Vector<RetainPtr<CGContextRef>> contextsToFlush;
343     for (auto& layer : layerTransaction.changedLayers()) {
344         if (layer->properties().changedProperties & RemoteLayerTreeTransaction::LayerChanges::BackingStoreChanged) {
345             hadAnyChangedBackingStore = true;
346             if (layer->properties().backingStore) {
347                 if (auto contextPendingFlush = layer->properties().backingStore->takeFrontContextPendingFlush())
348                     contextsToFlush.append(contextPendingFlush);
349             }
350         }
351
352         layer->didCommit();
353     }
354
355     backingStoreCollection.didFlushLayers();
356
357     if (hadAnyChangedBackingStore)
358         backingStoreCollection.scheduleVolatilityTimer();
359
360     RefPtr<BackingStoreFlusher> backingStoreFlusher = BackingStoreFlusher::create(WebProcess::shared().parentProcessConnection(), WTF::move(commitEncoder), WTF::move(contextsToFlush));
361     m_pendingBackingStoreFlusher = backingStoreFlusher;
362
363     dispatch_async(m_commitQueue, [backingStoreFlusher]{
364         backingStoreFlusher->flush();
365     });
366 }
367
368 void RemoteLayerTreeDrawingArea::didUpdate()
369 {
370     // FIXME: This should use a counted replacement for setLayerTreeStateIsFrozen, but
371     // the callers of that function are not strictly paired.
372
373     m_waitingForBackingStoreSwap = false;
374
375     if (m_hadFlushDeferredWhileWaitingForBackingStoreSwap) {
376         scheduleCompositingLayerFlush();
377         m_hadFlushDeferredWhileWaitingForBackingStoreSwap = false;
378     }
379
380     // This empty transaction serves to trigger CA's garbage collection of IOSurfaces. See <rdar://problem/16110687>
381     [CATransaction begin];
382     [CATransaction commit];
383
384     HashSet<RemoteLayerTreeDisplayRefreshMonitor*> monitorsToNotify = m_displayRefreshMonitors;
385     ASSERT(!m_displayRefreshMonitorsToNotify);
386     m_displayRefreshMonitorsToNotify = &monitorsToNotify;
387     while (!monitorsToNotify.isEmpty())
388         monitorsToNotify.takeAny()->didUpdateLayers();
389     m_displayRefreshMonitorsToNotify = nullptr;
390 }
391
392 void RemoteLayerTreeDrawingArea::mainFrameContentSizeChanged(const IntSize& contentsSize)
393 {
394     m_rootLayer->setSize(contentsSize);
395     m_webPage.pageOverlayController().didChangeDocumentSize();
396 }
397
398 bool RemoteLayerTreeDrawingArea::markLayersVolatileImmediatelyIfPossible()
399 {
400     return m_remoteLayerTreeContext->backingStoreCollection().markAllBackingStoreVolatileImmediatelyIfPossible();
401 }
402
403 PassRefPtr<RemoteLayerTreeDrawingArea::BackingStoreFlusher> RemoteLayerTreeDrawingArea::BackingStoreFlusher::create(IPC::Connection* connection, std::unique_ptr<IPC::MessageEncoder> encoder, Vector<RetainPtr<CGContextRef>> contextsToFlush)
404 {
405     return adoptRef(new RemoteLayerTreeDrawingArea::BackingStoreFlusher(connection, WTF::move(encoder), WTF::move(contextsToFlush)));
406 }
407
408 RemoteLayerTreeDrawingArea::BackingStoreFlusher::BackingStoreFlusher(IPC::Connection* connection, std::unique_ptr<IPC::MessageEncoder> encoder, Vector<RetainPtr<CGContextRef>> contextsToFlush)
409     : m_connection(connection)
410     , m_commitEncoder(WTF::move(encoder))
411     , m_contextsToFlush(WTF::move(contextsToFlush))
412     , m_hasFlushed(false)
413 {
414 }
415
416 void RemoteLayerTreeDrawingArea::BackingStoreFlusher::flush()
417 {
418     ASSERT(!m_hasFlushed);
419
420     for (auto& context : m_contextsToFlush)
421         CGContextFlush(context.get());
422     m_hasFlushed = true;
423
424     m_connection->sendMessage(WTF::move(m_commitEncoder));
425 }
426
427 void RemoteLayerTreeDrawingArea::viewStateDidChange(ViewState::Flags, bool wantsDidUpdateViewState)
428 {
429     // FIXME: Should we suspend painting while not visible, like TiledCoreAnimationDrawingArea? Probably.
430 }
431
432 void RemoteLayerTreeDrawingArea::addTransactionCallbackID(uint64_t callbackID)
433 {
434     m_pendingCallbackIDs.append(static_cast<RemoteLayerTreeTransaction::TransactionCallbackID>(callbackID));
435     scheduleCompositingLayerFlush();
436 }
437
438 } // namespace WebKit