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