Accelerated overflow scrolling for Coordinated Graphics.
[WebKit-https.git] / Source / WebKit2 / WebProcess / WebPage / CoordinatedGraphics / CoordinatedLayerTreeHost.cpp
1 /*
2  * Copyright (C) 2011 Apple Inc. All rights reserved.
3  * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4  * Copyright (C) 2012 Company 100, Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
16  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
19  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
25  * THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "config.h"
29
30 #if USE(COORDINATED_GRAPHICS)
31 #include "CoordinatedLayerTreeHost.h"
32
33 #include "CoordinatedGraphicsArgumentCoders.h"
34 #include "CoordinatedLayerTreeHostProxyMessages.h"
35 #include "DrawingAreaImpl.h"
36 #include "GraphicsContext.h"
37 #include "WebCoordinatedSurface.h"
38 #include "WebCoreArgumentCoders.h"
39 #include "WebPage.h"
40 #include "WebPageProxyMessages.h"
41 #include <WebCore/Frame.h>
42 #include <WebCore/FrameView.h>
43 #include <WebCore/GraphicsSurface.h>
44 #include <WebCore/Page.h>
45 #include <WebCore/RenderLayer.h>
46 #include <WebCore/RenderLayerBacking.h>
47 #include <WebCore/RenderLayerCompositor.h>
48 #include <WebCore/RenderView.h>
49 #include <WebCore/Settings.h>
50 #include <WebCore/SurfaceUpdateInfo.h>
51 #include <WebCore/TextureMapperPlatformLayer.h>
52 #include <wtf/TemporaryChange.h>
53
54 #if ENABLE(CSS_SHADERS)
55 #include "CustomFilterValidatedProgram.h"
56 #include "ValidatedCustomFilterOperation.h"
57 #endif
58
59 using namespace WebCore;
60
61 namespace WebKit {
62
63 PassRefPtr<CoordinatedLayerTreeHost> CoordinatedLayerTreeHost::create(WebPage* webPage)
64 {
65     return adoptRef(new CoordinatedLayerTreeHost(webPage));
66 }
67
68 CoordinatedLayerTreeHost::~CoordinatedLayerTreeHost()
69 {
70 #if ENABLE(CSS_SHADERS)
71     disconnectCustomFilterPrograms();
72 #endif
73     purgeBackingStores();
74
75     LayerMap::iterator end = m_registeredLayers.end();
76     for (LayerMap::iterator it = m_registeredLayers.begin(); it != end; ++it)
77         it->value->setCoordinator(0);
78 }
79
80 CoordinatedLayerTreeHost::CoordinatedLayerTreeHost(WebPage* webPage)
81     : LayerTreeHost(webPage)
82     , m_notifyAfterScheduledLayerFlush(false)
83     , m_isValid(true)
84     , m_isPurging(false)
85     , m_isFlushingLayerChanges(false)
86     , m_waitingForUIProcess(true)
87     , m_isSuspended(false)
88     , m_shouldSyncFrame(false)
89     , m_didInitializeRootCompositingLayer(false)
90     , m_layerFlushTimer(this, &CoordinatedLayerTreeHost::layerFlushTimerFired)
91     , m_releaseInactiveAtlasesTimer(this, &CoordinatedLayerTreeHost::releaseInactiveAtlasesTimerFired)
92     , m_layerFlushSchedulingEnabled(true)
93     , m_forceRepaintAsyncCallbackID(0)
94     , m_animationsLocked(false)
95 {
96     m_webPage->corePage()->settings()->setScrollingCoordinatorEnabled(true);
97     m_webPage->corePage()->settings()->setApplyDeviceScaleFactorInCompositor(true);
98
99     // Create a root layer.
100     m_rootLayer = GraphicsLayer::create(this, this);
101     CoordinatedGraphicsLayer* coordinatedRootLayer = toCoordinatedGraphicsLayer(m_rootLayer.get());
102     coordinatedRootLayer->setRootLayer(true);
103 #ifndef NDEBUG
104     m_rootLayer->setName("CoordinatedLayerTreeHost root layer");
105 #endif
106     m_rootLayer->setDrawsContent(false);
107     m_rootLayer->setSize(m_webPage->size());
108     m_layerTreeContext.coordinatedLayerID = toCoordinatedGraphicsLayer(coordinatedRootLayer)->id();
109
110     m_nonCompositedContentLayer = GraphicsLayer::create(this, this);
111 #ifndef NDEBUG
112     m_nonCompositedContentLayer->setName("CoordinatedLayerTreeHost non-composited content");
113 #endif
114     m_nonCompositedContentLayer->setDrawsContent(true);
115     m_nonCompositedContentLayer->setSize(m_webPage->size());
116
117     m_nonCompositedContentLayer->setShowDebugBorder(m_webPage->corePage()->settings()->showDebugBorders());
118     m_nonCompositedContentLayer->setShowRepaintCounter(m_webPage->corePage()->settings()->showRepaintCounter());
119
120     m_rootLayer->addChild(m_nonCompositedContentLayer.get());
121
122     CoordinatedSurface::setFactory(createCoordinatedSurface);
123
124     if (m_webPage->hasPageOverlay())
125         createPageOverlayLayer();
126
127     scheduleLayerFlush();
128 }
129
130 void CoordinatedLayerTreeHost::setLayerFlushSchedulingEnabled(bool layerFlushingEnabled)
131 {
132     if (m_layerFlushSchedulingEnabled == layerFlushingEnabled)
133         return;
134
135     m_layerFlushSchedulingEnabled = layerFlushingEnabled;
136
137     if (m_layerFlushSchedulingEnabled) {
138         scheduleLayerFlush();
139         return;
140     }
141
142     cancelPendingLayerFlush();
143 }
144
145 void CoordinatedLayerTreeHost::scheduleLayerFlush()
146 {
147     if (!m_layerFlushSchedulingEnabled)
148         return;
149
150     if (!m_layerFlushTimer.isActive())
151         m_layerFlushTimer.startOneShot(0);
152 }
153
154 void CoordinatedLayerTreeHost::cancelPendingLayerFlush()
155 {
156     m_layerFlushTimer.stop();
157 }
158
159 void CoordinatedLayerTreeHost::setShouldNotifyAfterNextScheduledLayerFlush(bool notifyAfterScheduledLayerFlush)
160 {
161     m_notifyAfterScheduledLayerFlush = notifyAfterScheduledLayerFlush;
162 }
163
164 void CoordinatedLayerTreeHost::setRootCompositingLayer(WebCore::GraphicsLayer* graphicsLayer)
165 {
166     m_nonCompositedContentLayer->removeAllChildren();
167     m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground() && !m_webPage->drawsTransparentBackground());
168
169     // Add the accelerated layer tree hierarchy.
170     if (graphicsLayer)
171         m_nonCompositedContentLayer->addChild(graphicsLayer);
172 }
173
174 void CoordinatedLayerTreeHost::invalidate()
175 {
176     cancelPendingLayerFlush();
177
178     ASSERT(m_isValid);
179     m_rootLayer = nullptr;
180     m_isValid = false;
181 }
182
183 void CoordinatedLayerTreeHost::setNonCompositedContentsNeedDisplay()
184 {
185     m_nonCompositedContentLayer->setNeedsDisplay();
186     if (m_pageOverlayLayer)
187         m_pageOverlayLayer->setNeedsDisplay();
188
189     scheduleLayerFlush();
190 }
191
192 void CoordinatedLayerTreeHost::setNonCompositedContentsNeedDisplayInRect(const WebCore::IntRect& rect)
193 {
194     m_nonCompositedContentLayer->setNeedsDisplayInRect(rect);
195     if (m_pageOverlayLayer)
196         m_pageOverlayLayer->setNeedsDisplayInRect(rect);
197
198     scheduleLayerFlush();
199 }
200
201 void CoordinatedLayerTreeHost::scrollNonCompositedContents(const WebCore::IntRect&)
202 {
203     // Do nothing because we scroll using TiledBackingStore.
204 }
205
206 void CoordinatedLayerTreeHost::forceRepaint()
207 {
208     // This is necessary for running layout tests. Since in this case we are not waiting for a UIProcess to reply nicely.
209     // Instead we are just triggering forceRepaint. But we still want to have the scripted animation callbacks being executed.
210     syncDisplayState();
211
212     // We need to schedule another flush, otherwise the forced paint might cancel a later expected flush.
213     // This is aligned with LayerTreeHostCA.
214     scheduleLayerFlush();
215     flushPendingLayerChanges();
216 }
217
218 bool CoordinatedLayerTreeHost::forceRepaintAsync(uint64_t callbackID)
219 {
220     // We expect the UI process to not require a new repaint until the previous one has finished.
221     ASSERT(!m_forceRepaintAsyncCallbackID);
222     m_forceRepaintAsyncCallbackID = callbackID;
223     scheduleLayerFlush();
224     return true;
225 }
226
227 void CoordinatedLayerTreeHost::sizeDidChange(const WebCore::IntSize& newSize)
228 {
229     if (m_rootLayer->size() == newSize)
230         return;
231
232     m_rootLayer->setSize(newSize);
233
234     // If the newSize exposes new areas of the non-composited content a setNeedsDisplay is needed
235     // for those newly exposed areas.
236     FloatSize oldSize = m_nonCompositedContentLayer->size();
237     m_nonCompositedContentLayer->setSize(newSize);
238
239     if (newSize.width() > oldSize.width()) {
240         float height = std::min(static_cast<float>(newSize.height()), oldSize.height());
241         m_nonCompositedContentLayer->setNeedsDisplayInRect(FloatRect(oldSize.width(), 0, newSize.width() - oldSize.width(), height));
242     }
243
244     if (newSize.height() > oldSize.height())
245         m_nonCompositedContentLayer->setNeedsDisplayInRect(FloatRect(0, oldSize.height(), newSize.width(), newSize.height() - oldSize.height()));
246
247     if (m_pageOverlayLayer)
248         m_pageOverlayLayer->setSize(newSize);
249
250     scheduleLayerFlush();
251 }
252
253 void CoordinatedLayerTreeHost::didInstallPageOverlay()
254 {
255     createPageOverlayLayer();
256     scheduleLayerFlush();
257 }
258
259 void CoordinatedLayerTreeHost::didUninstallPageOverlay()
260 {
261     destroyPageOverlayLayer();
262     scheduleLayerFlush();
263 }
264
265 void CoordinatedLayerTreeHost::setPageOverlayNeedsDisplay(const WebCore::IntRect& rect)
266 {
267     ASSERT(m_pageOverlayLayer);
268     m_pageOverlayLayer->setNeedsDisplayInRect(rect);
269     scheduleLayerFlush();
270 }
271
272 void CoordinatedLayerTreeHost::setPageOverlayOpacity(float value)
273 {
274     ASSERT(m_pageOverlayLayer);
275     m_pageOverlayLayer->setOpacity(value);
276     scheduleLayerFlush();
277 }
278
279 bool CoordinatedLayerTreeHost::flushPendingLayerChanges()
280 {
281     if (m_waitingForUIProcess)
282         return false;
283
284     TemporaryChange<bool> protector(m_isFlushingLayerChanges, true);
285
286     createCompositingLayers();
287
288     initializeRootCompositingLayerIfNeeded();
289
290     m_rootLayer->flushCompositingStateForThisLayerOnly();
291     m_nonCompositedContentLayer->flushCompositingStateForThisLayerOnly();
292     if (m_pageOverlayLayer)
293         m_pageOverlayLayer->flushCompositingStateForThisLayerOnly();
294
295     bool didSync = m_webPage->corePage()->mainFrame()->view()->flushCompositingStateIncludingSubframes();
296
297     flushPendingImageBackingChanges();
298
299     deleteCompositingLayers();
300
301     if (m_shouldSyncFrame) {
302         didSync = true;
303
304         m_state.contentsSize = roundedIntSize(m_nonCompositedContentLayer->size());
305         m_state.coveredRect = toCoordinatedGraphicsLayer(m_nonCompositedContentLayer.get())->coverRect();
306         m_state.scrollPosition = m_visibleContentsRect.location();
307
308         m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CommitCoordinatedGraphicsState(m_state));
309
310         m_state.layersToUpdate.clear();
311         m_state.imagesToUpdate.clear();
312
313         m_waitingForUIProcess = true;
314         m_shouldSyncFrame = false;
315     } else
316         unlockAnimations();
317
318     if (m_forceRepaintAsyncCallbackID) {
319         m_webPage->send(Messages::WebPageProxy::VoidCallback(m_forceRepaintAsyncCallbackID));
320         m_forceRepaintAsyncCallbackID = 0;
321     }
322
323     return didSync;
324 }
325
326 void CoordinatedLayerTreeHost::createCompositingLayers()
327 {
328     if (m_layersToCreate.isEmpty())
329         return;
330
331     // If a layer gets created and deleted in the same cycle, we can simply remove it from m_layersToCreate and m_layersToDelete.
332     for (int i = m_layersToCreate.size() - 1; i >= 0; --i) {
333         size_t index = m_layersToDelete.find(m_layersToCreate[i]);
334         if (index != notFound) {
335             m_layersToCreate.remove(i);
336             m_layersToDelete.remove(index);
337         }
338     }
339
340     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CreateCompositingLayers(m_layersToCreate));
341     m_layersToCreate.clear();
342     m_shouldSyncFrame = true;
343 }
344
345 void CoordinatedLayerTreeHost::deleteCompositingLayers()
346 {
347     if (m_layersToDelete.isEmpty())
348         return;
349
350     if (m_isPurging) {
351         m_layersToDelete.clear();
352         return;
353     }
354
355     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::DeleteCompositingLayers(m_layersToDelete));
356     m_layersToDelete.clear();
357     m_shouldSyncFrame = true;
358 }
359
360 void CoordinatedLayerTreeHost::initializeRootCompositingLayerIfNeeded()
361 {
362     if (m_didInitializeRootCompositingLayer)
363         return;
364
365     m_state.rootCompositingLayer = toCoordinatedGraphicsLayer(m_rootLayer.get())->id();
366     m_didInitializeRootCompositingLayer = true;
367     m_shouldSyncFrame = true;
368 }
369
370 void CoordinatedLayerTreeHost::syncLayerState(CoordinatedLayerID id, CoordinatedGraphicsLayerState& state)
371 {
372     m_shouldSyncFrame = true;
373
374 #if ENABLE(CSS_SHADERS)
375     prepareCustomFilterProxiesIfNeeded(state);
376 #endif
377
378     m_state.layersToUpdate.append(std::make_pair(id, state));
379 }
380
381 #if ENABLE(CSS_SHADERS)
382 void CoordinatedLayerTreeHost::prepareCustomFilterProxiesIfNeeded(CoordinatedGraphicsLayerState& state)
383 {
384     if (state.animationsChanged) {
385         GraphicsLayerAnimations& activeAnimations = state.animations;
386         for (size_t i = 0; i < activeAnimations.animations().size(); ++i) {
387             const KeyframeValueList& keyframes = activeAnimations.animations().at(i).keyframes();
388             if (keyframes.property() != AnimatedPropertyWebkitFilter)
389                 continue;
390             for (size_t j = 0; j < keyframes.size(); ++j) {
391                 const FilterAnimationValue* filterValue = static_cast<const FilterAnimationValue*>(keyframes.at(i));
392                 checkCustomFilterProgramProxies(*filterValue->value());
393             }
394         }
395     }
396
397     if (state.filtersChanged)
398         checkCustomFilterProgramProxies(state.filters);
399 }
400
401 void CoordinatedLayerTreeHost::checkCustomFilterProgramProxies(const FilterOperations& filters)
402 {
403     // We need to create the WebCustomFilterProgramProxy objects before we get to serialize the
404     // custom filters to the other process. That's because WebCustomFilterProgramProxy needs
405     // to link back to the coordinator, so that we can send a message to the UI process when
406     // the program is not needed anymore.
407     // Note that the serialization will only happen at a later time in ArgumentCoder<WebCore::FilterOperations>::encode.
408     // At that point the program will only be serialized once. All the other times it will only use the ID of the program.
409     for (size_t i = 0; i < filters.size(); ++i) {
410         const FilterOperation* operation = filters.at(i);
411         if (operation->getOperationType() != FilterOperation::VALIDATED_CUSTOM)
412             continue;
413         const ValidatedCustomFilterOperation* customOperation = static_cast<const ValidatedCustomFilterOperation*>(operation);
414         ASSERT(customOperation->validatedProgram()->isInitialized());
415         TextureMapperPlatformCompiledProgram* program = customOperation->validatedProgram()->platformCompiledProgram();
416
417         RefPtr<WebCustomFilterProgramProxy> customFilterProgramProxy;
418         if (program->client())
419             customFilterProgramProxy = static_cast<WebCustomFilterProgramProxy*>(program->client());
420         else {
421             customFilterProgramProxy = WebCustomFilterProgramProxy::create();
422             program->setClient(customFilterProgramProxy);
423         }
424
425         if (!customFilterProgramProxy->client()) {
426             customFilterProgramProxy->setClient(this);
427             m_customFilterPrograms.add(customFilterProgramProxy.get());
428             m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CreateCustomFilterProgram(customFilterProgramProxy->id(), customOperation->validatedProgram()->validatedProgramInfo()));
429         } else {
430             // If the client was not disconnected then this coordinator must be the client for it.
431             ASSERT(customFilterProgramProxy->client() == this);
432         }
433     }
434 }
435
436 void CoordinatedLayerTreeHost::removeCustomFilterProgramProxy(WebCustomFilterProgramProxy* customFilterProgramProxy)
437 {
438     // At this time the shader is not needed anymore, so we remove it from our set and
439     // send a message to the other process to delete it.
440     m_customFilterPrograms.remove(customFilterProgramProxy);
441     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RemoveCustomFilterProgram(customFilterProgramProxy->id()));
442 }
443
444 void CoordinatedLayerTreeHost::disconnectCustomFilterPrograms()
445 {
446     // Make sure that WebCore will not call into this coordinator anymore.
447     HashSet<WebCustomFilterProgramProxy*>::iterator iter = m_customFilterPrograms.begin();
448     for (; iter != m_customFilterPrograms.end(); ++iter)
449         (*iter)->setClient(0);
450 }
451 #endif // ENABLE(CSS_SHADERS)
452
453 void CoordinatedLayerTreeHost::detachLayer(CoordinatedGraphicsLayer* layer)
454 {
455     m_registeredLayers.remove(layer->id());
456     m_layersToDelete.append(layer->id());
457     scheduleLayerFlush();
458 }
459
460 void CoordinatedLayerTreeHost::lockAnimations()
461 {
462     m_animationsLocked = true;
463     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetAnimationsLocked(true));
464 }
465
466 void CoordinatedLayerTreeHost::unlockAnimations()
467 {
468     if (!m_animationsLocked)
469         return;
470
471     m_animationsLocked = false;
472     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetAnimationsLocked(false));
473 }
474
475 void CoordinatedLayerTreeHost::performScheduledLayerFlush()
476 {
477     if (m_isSuspended || m_waitingForUIProcess)
478         return;
479
480     // We lock the animations while performing layout, to avoid flickers caused by animations continuing in the UI process while
481     // the web process layout wants to cancel them.
482     lockAnimations();
483     syncDisplayState();
484
485     // We can unlock the animations before flushing if there are no visible changes, for example if there are content updates
486     // in a layer with opacity 0.
487     bool canUnlockBeforeFlush = !m_isValid || !toCoordinatedGraphicsLayer(m_rootLayer.get())->hasPendingVisibleChanges();
488     if (canUnlockBeforeFlush)
489         unlockAnimations();
490
491     if (!m_isValid)
492         return;
493
494     if (flushPendingLayerChanges())
495         didPerformScheduledLayerFlush();
496 }
497
498 void CoordinatedLayerTreeHost::syncDisplayState()
499 {
500 #if ENABLE(REQUEST_ANIMATION_FRAME) && !USE(REQUEST_ANIMATION_FRAME_TIMER) && !USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
501     // Make sure that any previously registered animation callbacks are being executed before we flush the layers.
502     m_webPage->corePage()->mainFrame()->view()->serviceScriptedAnimations(convertSecondsToDOMTimeStamp(currentTime()));
503 #endif
504
505     m_webPage->layoutIfNeeded();
506 }
507
508 void CoordinatedLayerTreeHost::didPerformScheduledLayerFlush()
509 {
510     if (m_notifyAfterScheduledLayerFlush) {
511         static_cast<DrawingAreaImpl*>(m_webPage->drawingArea())->layerHostDidFlushLayers();
512         m_notifyAfterScheduledLayerFlush = false;
513     }
514 }
515
516 void CoordinatedLayerTreeHost::layerFlushTimerFired(Timer<CoordinatedLayerTreeHost>*)
517 {
518     performScheduledLayerFlush();
519 }
520
521 void CoordinatedLayerTreeHost::createPageOverlayLayer()
522 {
523     ASSERT(!m_pageOverlayLayer);
524
525     m_pageOverlayLayer = GraphicsLayer::create(this, this);
526 #ifndef NDEBUG
527     m_pageOverlayLayer->setName("CoordinatedLayerTreeHost page overlay content");
528 #endif
529
530     m_pageOverlayLayer->setDrawsContent(true);
531     m_pageOverlayLayer->setSize(m_webPage->size());
532
533     m_rootLayer->addChild(m_pageOverlayLayer.get());
534 }
535
536 void CoordinatedLayerTreeHost::destroyPageOverlayLayer()
537 {
538     ASSERT(m_pageOverlayLayer);
539     m_pageOverlayLayer->removeFromParent();
540     m_pageOverlayLayer = nullptr;
541 }
542
543 PassRefPtr<CoordinatedImageBacking> CoordinatedLayerTreeHost::createImageBackingIfNeeded(Image* image)
544 {
545     CoordinatedImageBackingID imageID = CoordinatedImageBacking::getCoordinatedImageBackingID(image);
546     ImageBackingMap::iterator it = m_imageBackings.find(imageID);
547     RefPtr<CoordinatedImageBacking> imageBacking;
548     if (it == m_imageBackings.end()) {
549         imageBacking = CoordinatedImageBacking::create(this, image);
550         m_imageBackings.add(imageID, imageBacking);
551     } else
552         imageBacking = it->value;
553
554     return imageBacking;
555 }
556
557 void CoordinatedLayerTreeHost::createImageBacking(CoordinatedImageBackingID imageID)
558 {
559     m_shouldSyncFrame = true;
560     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CreateImageBacking(imageID));
561 }
562
563 bool CoordinatedLayerTreeHost::updateImageBacking(CoordinatedImageBackingID imageID, PassRefPtr<CoordinatedSurface> coordinatedSurface)
564 {
565     m_shouldSyncFrame = true;
566     WebCoordinatedSurface* webCoordinatedSurface = static_cast<WebCoordinatedSurface*>(coordinatedSurface.get());
567     WebCoordinatedSurface::Handle handle;
568     if (!webCoordinatedSurface->createHandle(handle))
569         return false;
570
571     m_state.imagesToUpdate.append(std::make_pair(imageID, coordinatedSurface));
572     return true;
573 }
574
575 void CoordinatedLayerTreeHost::clearImageBackingContents(CoordinatedImageBackingID imageID)
576 {
577     m_shouldSyncFrame = true;
578     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::ClearImageBackingContents(imageID));
579 }
580
581 void CoordinatedLayerTreeHost::removeImageBacking(CoordinatedImageBackingID imageID)
582 {
583     if (m_isPurging)
584         return;
585
586     ASSERT(m_imageBackings.contains(imageID));
587     m_shouldSyncFrame = true;
588     m_imageBackings.remove(imageID);
589     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RemoveImageBacking(imageID));
590 }
591
592 void CoordinatedLayerTreeHost::flushPendingImageBackingChanges()
593 {
594     ImageBackingMap::iterator end = m_imageBackings.end();
595     for (ImageBackingMap::iterator iter = m_imageBackings.begin(); iter != end; ++iter)
596         iter->value->update();
597 }
598
599 void CoordinatedLayerTreeHost::notifyAnimationStarted(const WebCore::GraphicsLayer*, double /* time */)
600 {
601 }
602
603 void CoordinatedLayerTreeHost::notifyFlushRequired(const WebCore::GraphicsLayer*)
604 {
605     scheduleLayerFlush();
606 }
607
608 void CoordinatedLayerTreeHost::paintContents(const WebCore::GraphicsLayer* graphicsLayer, WebCore::GraphicsContext& graphicsContext, WebCore::GraphicsLayerPaintingPhase, const WebCore::IntRect& clipRect)
609 {
610     if (graphicsLayer == m_nonCompositedContentLayer) {
611         m_webPage->drawRect(graphicsContext, clipRect);
612         return;
613     }
614
615     if (graphicsLayer == m_pageOverlayLayer) {
616         // Overlays contain transparent contents and won't clear the context as part of their rendering, so we do it here.
617         graphicsContext.clearRect(clipRect);
618         m_webPage->drawPageOverlay(graphicsContext, clipRect);
619         return;
620     }
621 }
622
623 PassOwnPtr<GraphicsLayer> CoordinatedLayerTreeHost::createGraphicsLayer(GraphicsLayerClient* client)
624 {
625     CoordinatedGraphicsLayer* layer = new CoordinatedGraphicsLayer(client);
626     layer->setCoordinator(this);
627     m_registeredLayers.add(layer->id(), layer);
628     m_layersToCreate.append(layer->id());
629     layer->setNeedsVisibleRectAdjustment();
630     scheduleLayerFlush();
631     return adoptPtr(layer);
632 }
633
634 PassRefPtr<CoordinatedSurface> CoordinatedLayerTreeHost::createCoordinatedSurface(const IntSize& size, CoordinatedSurface::Flags flags)
635 {
636     return WebCoordinatedSurface::create(size, flags);
637 }
638
639 float CoordinatedLayerTreeHost::deviceScaleFactor() const
640 {
641     return m_webPage->deviceScaleFactor();
642 }
643
644 float CoordinatedLayerTreeHost::pageScaleFactor() const
645 {
646     return m_webPage->pageScaleFactor();
647 }
648
649 bool LayerTreeHost::supportsAcceleratedCompositing()
650 {
651     return true;
652 }
653
654 bool CoordinatedLayerTreeHost::createUpdateAtlas(uint32_t atlasID, PassRefPtr<CoordinatedSurface> coordinatedSurface)
655 {
656     WebCoordinatedSurface* webCoordinatedSurface = static_cast<WebCoordinatedSurface*>(coordinatedSurface.get());
657     WebCoordinatedSurface::Handle handle;
658     if (!webCoordinatedSurface->createHandle(handle))
659         return false;
660     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CreateUpdateAtlas(atlasID, handle));
661     return true;
662 }
663
664 void CoordinatedLayerTreeHost::removeUpdateAtlas(uint32_t atlasID)
665 {
666     if (m_isPurging)
667         return;
668     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RemoveUpdateAtlas(atlasID));
669 }
670
671 WebCore::FloatRect CoordinatedLayerTreeHost::visibleContentsRect() const
672 {
673     return m_visibleContentsRect;
674 }
675
676 void CoordinatedLayerTreeHost::setVisibleContentsRect(const FloatRect& rect, const FloatPoint& trajectoryVector)
677 {
678     // A zero trajectoryVector indicates that tiles all around the viewport are requested.
679     toCoordinatedGraphicsLayer(m_nonCompositedContentLayer.get())->setVisibleContentRectTrajectoryVector(trajectoryVector);
680
681     bool contentsRectDidChange = rect != m_visibleContentsRect;
682     if (contentsRectDidChange) {
683         m_visibleContentsRect = rect;
684
685         LayerMap::iterator end = m_registeredLayers.end();
686         for (LayerMap::iterator it = m_registeredLayers.begin(); it != end; ++it) {
687             it->value->setNeedsVisibleRectAdjustment();
688         }
689     }
690
691     scheduleLayerFlush();
692     if (m_webPage->useFixedLayout()) {
693         // Round the rect instead of enclosing it to make sure that its size stays
694         // the same while panning. This can have nasty effects on layout.
695         m_webPage->setFixedVisibleContentRect(roundedIntRect(rect));
696     }
697 }
698
699 void CoordinatedLayerTreeHost::deviceOrPageScaleFactorChanged()
700 {
701     m_rootLayer->deviceOrPageScaleFactorChanged();
702     m_nonCompositedContentLayer->deviceOrPageScaleFactorChanged();
703     if (m_pageOverlayLayer)
704         m_pageOverlayLayer->deviceOrPageScaleFactorChanged();
705 }
706
707 GraphicsLayerFactory* CoordinatedLayerTreeHost::graphicsLayerFactory()
708 {
709     return this;
710 }
711
712 #if ENABLE(REQUEST_ANIMATION_FRAME)
713 void CoordinatedLayerTreeHost::scheduleAnimation()
714 {
715     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RequestAnimationFrame());
716 }
717
718 void CoordinatedLayerTreeHost::animationFrameReady()
719 {
720     scheduleLayerFlush();
721 }
722 #endif
723
724 void CoordinatedLayerTreeHost::renderNextFrame()
725 {
726     m_waitingForUIProcess = false;
727     scheduleLayerFlush();
728     for (unsigned i = 0; i < m_updateAtlases.size(); ++i)
729         m_updateAtlases[i]->didSwapBuffers();
730 }
731
732 void CoordinatedLayerTreeHost::purgeBackingStores()
733 {
734     TemporaryChange<bool> purgingToggle(m_isPurging, true);
735
736     LayerMap::iterator end = m_registeredLayers.end();
737     for (LayerMap::iterator it = m_registeredLayers.begin(); it != end; ++it)
738         it->value->purgeBackingStores();
739
740     m_imageBackings.clear();
741     m_updateAtlases.clear();
742 }
743
744 PassOwnPtr<GraphicsContext> CoordinatedLayerTreeHost::beginContentUpdate(const IntSize& size, CoordinatedSurface::Flags flags, uint32_t& atlasID, IntPoint& offset)
745 {
746     OwnPtr<GraphicsContext> graphicsContext;
747     for (unsigned i = 0; i < m_updateAtlases.size(); ++i) {
748         UpdateAtlas* atlas = m_updateAtlases[i].get();
749         if (atlas->supportsAlpha() == (flags & CoordinatedSurface::SupportsAlpha)) {
750             // This will return null if there is no available buffer space.
751             graphicsContext = atlas->beginPaintingOnAvailableBuffer(atlasID, size, offset);
752             if (graphicsContext)
753                 return graphicsContext.release();
754         }
755     }
756
757     static const int ScratchBufferDimension = 1024; // Should be a power of two.
758     m_updateAtlases.append(adoptPtr(new UpdateAtlas(this, ScratchBufferDimension, flags)));
759     scheduleReleaseInactiveAtlases();
760     return m_updateAtlases.last()->beginPaintingOnAvailableBuffer(atlasID, size, offset);
761 }
762
763 const double ReleaseInactiveAtlasesTimerInterval = 0.5;
764
765 void CoordinatedLayerTreeHost::scheduleReleaseInactiveAtlases()
766 {
767     if (!m_releaseInactiveAtlasesTimer.isActive())
768         m_releaseInactiveAtlasesTimer.startRepeating(ReleaseInactiveAtlasesTimerInterval);
769 }
770
771 void CoordinatedLayerTreeHost::releaseInactiveAtlasesTimerFired(Timer<CoordinatedLayerTreeHost>*)
772 {
773     // We always want to keep one atlas for non-composited content.
774     OwnPtr<UpdateAtlas> atlasToKeepAnyway;
775     bool foundActiveAtlasForNonCompositedContent = false;
776     for (int i = m_updateAtlases.size() - 1;  i >= 0; --i) {
777         UpdateAtlas* atlas = m_updateAtlases[i].get();
778         if (!atlas->isInUse())
779             atlas->addTimeInactive(ReleaseInactiveAtlasesTimerInterval);
780         bool usableForNonCompositedContent = !atlas->supportsAlpha();
781         if (atlas->isInactive()) {
782             if (!foundActiveAtlasForNonCompositedContent && !atlasToKeepAnyway && usableForNonCompositedContent)
783                 atlasToKeepAnyway = m_updateAtlases[i].release();
784             m_updateAtlases.remove(i);
785         } else if (usableForNonCompositedContent)
786             foundActiveAtlasForNonCompositedContent = true;
787     }
788
789     if (!foundActiveAtlasForNonCompositedContent && atlasToKeepAnyway)
790         m_updateAtlases.append(atlasToKeepAnyway.release());
791
792     if (m_updateAtlases.size() <= 1)
793         m_releaseInactiveAtlasesTimer.stop();
794 }
795
796 void CoordinatedLayerTreeHost::setBackgroundColor(const WebCore::Color& color)
797 {
798     m_shouldSyncFrame = true;
799     m_state.backgroundColor = color;
800 }
801
802 void CoordinatedLayerTreeHost::commitScrollOffset(uint32_t layerID, const WebCore::IntSize& offset)
803 {
804     LayerMap::iterator i = m_registeredLayers.find(layerID);
805     if (i == m_registeredLayers.end())
806         return;
807
808     i->value->commitScrollOffset(offset);
809 }
810
811 } // namespace WebKit
812 #endif // USE(COORDINATED_GRAPHICS)