Unreviewed, rolling out r142141.
[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     HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator end = m_registeredLayers.end();
76     for (HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator it = m_registeredLayers.begin(); it != end; ++it)
77         (*it)->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_shouldSendScrollPositionUpdate(true)
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     // Create a root layer.
98     m_rootLayer = GraphicsLayer::create(this, this);
99     CoordinatedGraphicsLayer* coordinatedRootLayer = toCoordinatedGraphicsLayer(m_rootLayer.get());
100     coordinatedRootLayer->setRootLayer(true);
101 #ifndef NDEBUG
102     m_rootLayer->setName("CoordinatedLayerTreeHost root layer");
103 #endif
104     m_rootLayer->setDrawsContent(false);
105     m_rootLayer->setSize(m_webPage->size());
106     m_layerTreeContext.coordinatedLayerID = toCoordinatedGraphicsLayer(coordinatedRootLayer)->id();
107
108     m_nonCompositedContentLayer = GraphicsLayer::create(this, this);
109 #ifndef NDEBUG
110     m_nonCompositedContentLayer->setName("CoordinatedLayerTreeHost non-composited content");
111 #endif
112     m_nonCompositedContentLayer->setDrawsContent(true);
113     m_nonCompositedContentLayer->setSize(m_webPage->size());
114
115     m_nonCompositedContentLayer->setShowDebugBorder(m_webPage->corePage()->settings()->showDebugBorders());
116     m_nonCompositedContentLayer->setShowRepaintCounter(m_webPage->corePage()->settings()->showRepaintCounter());
117
118     m_rootLayer->addChild(m_nonCompositedContentLayer.get());
119
120     CoordinatedSurface::setFactory(createCoordinatedSurface);
121
122     if (m_webPage->hasPageOverlay())
123         createPageOverlayLayer();
124
125     scheduleLayerFlush();
126 }
127
128 void CoordinatedLayerTreeHost::setLayerFlushSchedulingEnabled(bool layerFlushingEnabled)
129 {
130     if (m_layerFlushSchedulingEnabled == layerFlushingEnabled)
131         return;
132
133     m_layerFlushSchedulingEnabled = layerFlushingEnabled;
134
135     if (m_layerFlushSchedulingEnabled) {
136         scheduleLayerFlush();
137         return;
138     }
139
140     cancelPendingLayerFlush();
141 }
142
143 void CoordinatedLayerTreeHost::scheduleLayerFlush()
144 {
145     if (!m_layerFlushSchedulingEnabled)
146         return;
147
148     if (!m_layerFlushTimer.isActive())
149         m_layerFlushTimer.startOneShot(0);
150 }
151
152 void CoordinatedLayerTreeHost::cancelPendingLayerFlush()
153 {
154     m_layerFlushTimer.stop();
155 }
156
157 void CoordinatedLayerTreeHost::setShouldNotifyAfterNextScheduledLayerFlush(bool notifyAfterScheduledLayerFlush)
158 {
159     m_notifyAfterScheduledLayerFlush = notifyAfterScheduledLayerFlush;
160 }
161
162 void CoordinatedLayerTreeHost::setRootCompositingLayer(WebCore::GraphicsLayer* graphicsLayer)
163 {
164     m_nonCompositedContentLayer->removeAllChildren();
165     m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground() && !m_webPage->drawsTransparentBackground());
166
167     // Add the accelerated layer tree hierarchy.
168     if (graphicsLayer)
169         m_nonCompositedContentLayer->addChild(graphicsLayer);
170 }
171
172 void CoordinatedLayerTreeHost::invalidate()
173 {
174     cancelPendingLayerFlush();
175
176     ASSERT(m_isValid);
177     m_rootLayer = nullptr;
178     m_isValid = false;
179 }
180
181 void CoordinatedLayerTreeHost::setNonCompositedContentsNeedDisplay(const WebCore::IntRect& rect)
182 {
183     m_nonCompositedContentLayer->setNeedsDisplayInRect(rect);
184     if (m_pageOverlayLayer)
185         m_pageOverlayLayer->setNeedsDisplayInRect(rect);
186
187     scheduleLayerFlush();
188 }
189
190 void CoordinatedLayerTreeHost::scrollNonCompositedContents(const WebCore::IntRect& scrollRect, const WebCore::IntSize& /* scrollOffset */)
191 {
192     setNonCompositedContentsNeedDisplay(scrollRect);
193 }
194
195 void CoordinatedLayerTreeHost::forceRepaint()
196 {
197     // This is necessary for running layout tests. Since in this case we are not waiting for a UIProcess to reply nicely.
198     // Instead we are just triggering forceRepaint. But we still want to have the scripted animation callbacks being executed.
199     syncDisplayState();
200
201     // We need to schedule another flush, otherwise the forced paint might cancel a later expected flush.
202     // This is aligned with LayerTreeHostCA.
203     scheduleLayerFlush();
204     flushPendingLayerChanges();
205 }
206
207 bool CoordinatedLayerTreeHost::forceRepaintAsync(uint64_t callbackID)
208 {
209     // We expect the UI process to not require a new repaint until the previous one has finished.
210     ASSERT(!m_forceRepaintAsyncCallbackID);
211     m_forceRepaintAsyncCallbackID = callbackID;
212     scheduleLayerFlush();
213     return true;
214 }
215
216 void CoordinatedLayerTreeHost::sizeDidChange(const WebCore::IntSize& newSize)
217 {
218     if (m_rootLayer->size() == newSize)
219         return;
220
221     m_rootLayer->setSize(newSize);
222
223     // If the newSize exposes new areas of the non-composited content a setNeedsDisplay is needed
224     // for those newly exposed areas.
225     FloatSize oldSize = m_nonCompositedContentLayer->size();
226     m_nonCompositedContentLayer->setSize(newSize);
227
228     if (newSize.width() > oldSize.width()) {
229         float height = std::min(static_cast<float>(newSize.height()), oldSize.height());
230         m_nonCompositedContentLayer->setNeedsDisplayInRect(FloatRect(oldSize.width(), 0, newSize.width() - oldSize.width(), height));
231     }
232
233     if (newSize.height() > oldSize.height())
234         m_nonCompositedContentLayer->setNeedsDisplayInRect(FloatRect(0, oldSize.height(), newSize.width(), newSize.height() - oldSize.height()));
235
236     if (m_pageOverlayLayer)
237         m_pageOverlayLayer->setSize(newSize);
238
239     scheduleLayerFlush();
240 }
241
242 void CoordinatedLayerTreeHost::didInstallPageOverlay()
243 {
244     createPageOverlayLayer();
245     scheduleLayerFlush();
246 }
247
248 void CoordinatedLayerTreeHost::didUninstallPageOverlay()
249 {
250     destroyPageOverlayLayer();
251     scheduleLayerFlush();
252 }
253
254 void CoordinatedLayerTreeHost::setPageOverlayNeedsDisplay(const WebCore::IntRect& rect)
255 {
256     ASSERT(m_pageOverlayLayer);
257     m_pageOverlayLayer->setNeedsDisplayInRect(rect);
258     scheduleLayerFlush();
259 }
260
261 void CoordinatedLayerTreeHost::setPageOverlayOpacity(float value)
262 {
263     ASSERT(m_pageOverlayLayer);
264     m_pageOverlayLayer->setOpacity(value);
265     scheduleLayerFlush();
266 }
267
268 bool CoordinatedLayerTreeHost::flushPendingLayerChanges()
269 {
270     if (m_waitingForUIProcess)
271         return false;
272
273     TemporaryChange<bool> protector(m_isFlushingLayerChanges, true);
274
275     createCompositingLayers();
276
277     initializeRootCompositingLayerIfNeeded();
278
279     m_rootLayer->flushCompositingStateForThisLayerOnly();
280     m_nonCompositedContentLayer->flushCompositingStateForThisLayerOnly();
281     if (m_pageOverlayLayer)
282         m_pageOverlayLayer->flushCompositingStateForThisLayerOnly();
283
284     bool didSync = m_webPage->corePage()->mainFrame()->view()->flushCompositingStateIncludingSubframes();
285
286     flushPendingImageBackingChanges();
287
288     deleteCompositingLayers();
289
290     if (m_shouldSyncFrame) {
291         didSync = true;
292
293         IntSize contentsSize = roundedIntSize(m_nonCompositedContentLayer->size());
294         IntRect coveredRect = toCoordinatedGraphicsLayer(m_nonCompositedContentLayer.get())->coverRect();
295         m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::DidRenderFrame(contentsSize, coveredRect));
296         m_waitingForUIProcess = true;
297         m_shouldSyncFrame = false;
298     } else
299         unlockAnimations();
300
301     if (m_forceRepaintAsyncCallbackID) {
302         m_webPage->send(Messages::WebPageProxy::VoidCallback(m_forceRepaintAsyncCallbackID));
303         m_forceRepaintAsyncCallbackID = 0;
304     }
305
306     return didSync;
307 }
308
309 void CoordinatedLayerTreeHost::createCompositingLayers()
310 {
311     if (m_layersToCreate.isEmpty())
312         return;
313
314     // If a layer gets created and deleted in the same cycle, we can simply remove it from m_layersToCreate and m_layersToDelete.
315     for (int i = m_layersToCreate.size() - 1; i >= 0; --i) {
316         size_t index = m_layersToDelete.find(m_layersToCreate[i]);
317         if (index != notFound) {
318             m_layersToCreate.remove(i);
319             m_layersToDelete.remove(index);
320         }
321     }
322
323     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CreateCompositingLayers(m_layersToCreate));
324     m_layersToCreate.clear();
325     m_shouldSyncFrame = true;
326 }
327
328 void CoordinatedLayerTreeHost::deleteCompositingLayers()
329 {
330     if (m_layersToDelete.isEmpty())
331         return;
332
333     if (m_isPurging) {
334         m_layersToDelete.clear();
335         return;
336     }
337
338     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::DeleteCompositingLayers(m_layersToDelete));
339     m_layersToDelete.clear();
340     m_shouldSyncFrame = true;
341 }
342
343 void CoordinatedLayerTreeHost::initializeRootCompositingLayerIfNeeded()
344 {
345     if (m_didInitializeRootCompositingLayer)
346         return;
347
348     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetRootCompositingLayer(toCoordinatedGraphicsLayer(m_rootLayer.get())->id()));
349     m_didInitializeRootCompositingLayer = true;
350     m_shouldSyncFrame = true;
351 }
352
353 void CoordinatedLayerTreeHost::syncLayerState(CoordinatedLayerID id, const CoordinatedLayerInfo& info)
354 {
355     if (m_shouldSendScrollPositionUpdate) {
356         m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::DidChangeScrollPosition(m_visibleContentsRect.location()));
357         m_shouldSendScrollPositionUpdate = false;
358     }
359
360     m_shouldSyncFrame = true;
361     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetCompositingLayerState(id, info));
362 }
363
364 void CoordinatedLayerTreeHost::syncLayerChildren(CoordinatedLayerID id, const Vector<CoordinatedLayerID>& children)
365 {
366     m_shouldSyncFrame = true;
367     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetCompositingLayerChildren(id, children));
368 }
369
370 #if USE(GRAPHICS_SURFACE)
371 void CoordinatedLayerTreeHost::createCanvas(CoordinatedLayerID id, PlatformLayer* canvasPlatformLayer)
372 {
373     m_shouldSyncFrame = true;
374     GraphicsSurfaceToken token = canvasPlatformLayer->graphicsSurfaceToken();
375     IntSize canvasSize = canvasPlatformLayer->platformLayerSize();
376     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CreateCanvas(id, canvasSize, token));
377 }
378
379 void CoordinatedLayerTreeHost::syncCanvas(CoordinatedLayerID id, PlatformLayer* canvasPlatformLayer)
380 {
381     m_shouldSyncFrame = true;
382     uint32_t frontBuffer = canvasPlatformLayer->copyToGraphicsSurface();
383     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SyncCanvas(id, frontBuffer));
384 }
385
386 void CoordinatedLayerTreeHost::destroyCanvas(CoordinatedLayerID id)
387 {
388     if (m_isPurging)
389         return;
390
391     m_shouldSyncFrame = true;
392     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::DestroyCanvas(id));
393 }
394 #endif
395
396 void CoordinatedLayerTreeHost::setLayerRepaintCount(CoordinatedLayerID id, int value)
397 {
398     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetLayerRepaintCount(id, value));
399 }
400
401 #if ENABLE(CSS_FILTERS)
402 void CoordinatedLayerTreeHost::syncLayerFilters(CoordinatedLayerID id, const FilterOperations& filters)
403 {
404     m_shouldSyncFrame = true;
405 #if ENABLE(CSS_SHADERS)
406     checkCustomFilterProgramProxies(filters);
407 #endif
408     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetCompositingLayerFilters(id, filters));
409 }
410 #endif
411
412 #if ENABLE(CSS_SHADERS)
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
464
465 void CoordinatedLayerTreeHost::detachLayer(CoordinatedGraphicsLayer* layer)
466 {
467     m_registeredLayers.remove(layer);
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(convertSecondsToDOMTimeStamp(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     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::UpdateImageBacking(imageID, handle));
583     return true;
584 }
585
586 void CoordinatedLayerTreeHost::clearImageBackingContents(CoordinatedImageBackingID imageID)
587 {
588     m_shouldSyncFrame = true;
589     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::ClearImageBackingContents(imageID));
590 }
591
592 void CoordinatedLayerTreeHost::removeImageBacking(CoordinatedImageBackingID imageID)
593 {
594     if (m_isPurging)
595         return;
596
597     ASSERT(m_imageBackings.contains(imageID));
598     m_shouldSyncFrame = true;
599     m_imageBackings.remove(imageID);
600     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RemoveImageBacking(imageID));
601 }
602
603 void CoordinatedLayerTreeHost::flushPendingImageBackingChanges()
604 {
605     ImageBackingMap::iterator end = m_imageBackings.end();
606     for (ImageBackingMap::iterator iter = m_imageBackings.begin(); iter != end; ++iter)
607         iter->value->update();
608 }
609
610 void CoordinatedLayerTreeHost::notifyAnimationStarted(const WebCore::GraphicsLayer*, double /* time */)
611 {
612 }
613
614 void CoordinatedLayerTreeHost::notifyFlushRequired(const WebCore::GraphicsLayer*)
615 {
616     scheduleLayerFlush();
617 }
618
619 void CoordinatedLayerTreeHost::paintContents(const WebCore::GraphicsLayer* graphicsLayer, WebCore::GraphicsContext& graphicsContext, WebCore::GraphicsLayerPaintingPhase, const WebCore::IntRect& clipRect)
620 {
621     if (graphicsLayer == m_nonCompositedContentLayer) {
622         m_webPage->drawRect(graphicsContext, clipRect);
623         return;
624     }
625
626     if (graphicsLayer == m_pageOverlayLayer) {
627         // Overlays contain transparent contents and won't clear the context as part of their rendering, so we do it here.
628         graphicsContext.clearRect(clipRect);
629         m_webPage->drawPageOverlay(graphicsContext, clipRect);
630         return;
631     }
632 }
633
634 PassOwnPtr<GraphicsLayer> CoordinatedLayerTreeHost::createGraphicsLayer(GraphicsLayerClient* client)
635 {
636     CoordinatedGraphicsLayer* layer = new CoordinatedGraphicsLayer(client);
637     layer->setCoordinator(this);
638     m_registeredLayers.add(layer);
639     m_layersToCreate.append(layer->id());
640     layer->setNeedsVisibleRectAdjustment();
641     scheduleLayerFlush();
642     return adoptPtr(layer);
643 }
644
645 PassRefPtr<CoordinatedSurface> CoordinatedLayerTreeHost::createCoordinatedSurface(const IntSize& size, CoordinatedSurface::Flags flags)
646 {
647     return WebCoordinatedSurface::create(size, flags);
648 }
649
650 float CoordinatedLayerTreeHost::deviceScaleFactor() const
651 {
652     return m_webPage->deviceScaleFactor();
653 }
654
655 float CoordinatedLayerTreeHost::pageScaleFactor() const
656 {
657     return m_webPage->pageScaleFactor();
658 }
659
660 bool LayerTreeHost::supportsAcceleratedCompositing()
661 {
662     return true;
663 }
664
665 void CoordinatedLayerTreeHost::createTile(CoordinatedLayerID layerID, uint32_t tileID, const WebCore::SurfaceUpdateInfo& updateInfo, const WebCore::IntRect& tileRect)
666 {
667     m_shouldSyncFrame = true;
668     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CreateTileForLayer(layerID, tileID, tileRect, updateInfo));
669 }
670
671 void CoordinatedLayerTreeHost::updateTile(CoordinatedLayerID layerID, uint32_t tileID, const WebCore::SurfaceUpdateInfo& updateInfo, const WebCore::IntRect& tileRect)
672 {
673     m_shouldSyncFrame = true;
674     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::UpdateTileForLayer(layerID, tileID, tileRect, updateInfo));
675 }
676
677 void CoordinatedLayerTreeHost::removeTile(CoordinatedLayerID layerID, uint32_t tileID)
678 {
679     if (m_isPurging)
680         return;
681     m_shouldSyncFrame = true;
682     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RemoveTileForLayer(layerID, tileID));
683 }
684
685 bool CoordinatedLayerTreeHost::createUpdateAtlas(uint32_t atlasID, PassRefPtr<CoordinatedSurface> coordinatedSurface)
686 {
687     WebCoordinatedSurface* webCoordinatedSurface = static_cast<WebCoordinatedSurface*>(coordinatedSurface.get());
688     WebCoordinatedSurface::Handle handle;
689     if (!webCoordinatedSurface->createHandle(handle))
690         return false;
691     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CreateUpdateAtlas(atlasID, handle));
692     return true;
693 }
694
695 void CoordinatedLayerTreeHost::removeUpdateAtlas(uint32_t atlasID)
696 {
697     if (m_isPurging)
698         return;
699     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RemoveUpdateAtlas(atlasID));
700 }
701
702 WebCore::FloatRect CoordinatedLayerTreeHost::visibleContentsRect() const
703 {
704     return m_visibleContentsRect;
705 }
706
707
708 void CoordinatedLayerTreeHost::setLayerAnimations(CoordinatedLayerID layerID, const GraphicsLayerAnimations& animations)
709 {
710     m_shouldSyncFrame = true;
711     GraphicsLayerAnimations activeAnimations = animations.getActiveAnimations();
712 #if ENABLE(CSS_SHADERS)
713     for (size_t i = 0; i < activeAnimations.animations().size(); ++i) {
714         const KeyframeValueList& keyframes = animations.animations().at(i).keyframes();
715         if (keyframes.property() != AnimatedPropertyWebkitFilter)
716             continue;
717         for (size_t j = 0; j < keyframes.size(); ++j) {
718             const FilterAnimationValue* filterValue = static_cast<const FilterAnimationValue*>(keyframes.at(i));
719             checkCustomFilterProgramProxies(*filterValue->value());
720         }
721     }
722 #endif
723     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetLayerAnimations(layerID, activeAnimations));
724 }
725
726 void CoordinatedLayerTreeHost::setVisibleContentsRect(const FloatRect& rect, const FloatPoint& trajectoryVector)
727 {
728     // A zero trajectoryVector indicates that tiles all around the viewport are requested.
729     toCoordinatedGraphicsLayer(m_nonCompositedContentLayer.get())->setVisibleContentRectTrajectoryVector(trajectoryVector);
730
731     bool contentsRectDidChange = rect != m_visibleContentsRect;
732     if (contentsRectDidChange) {
733         m_visibleContentsRect = rect;
734
735         HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator end = m_registeredLayers.end();
736         for (HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator it = m_registeredLayers.begin(); it != end; ++it) {
737             (*it)->setNeedsVisibleRectAdjustment();
738         }
739     }
740
741     scheduleLayerFlush();
742     if (m_webPage->useFixedLayout()) {
743         // Round the rect instead of enclosing it to make sure that its size stays
744         // the same while panning. This can have nasty effects on layout.
745         m_webPage->setFixedVisibleContentRect(roundedIntRect(rect));
746     }
747
748     if (contentsRectDidChange)
749         m_shouldSendScrollPositionUpdate = true;
750 }
751
752 void CoordinatedLayerTreeHost::deviceOrPageScaleFactorChanged()
753 {
754     m_rootLayer->deviceOrPageScaleFactorChanged();
755     m_nonCompositedContentLayer->deviceOrPageScaleFactorChanged();
756     if (m_pageOverlayLayer)
757         m_pageOverlayLayer->deviceOrPageScaleFactorChanged();
758 }
759
760 GraphicsLayerFactory* CoordinatedLayerTreeHost::graphicsLayerFactory()
761 {
762     return this;
763 }
764
765 #if ENABLE(REQUEST_ANIMATION_FRAME)
766 void CoordinatedLayerTreeHost::scheduleAnimation()
767 {
768     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RequestAnimationFrame());
769 }
770
771 void CoordinatedLayerTreeHost::animationFrameReady()
772 {
773     scheduleLayerFlush();
774 }
775 #endif
776
777 void CoordinatedLayerTreeHost::renderNextFrame()
778 {
779     m_waitingForUIProcess = false;
780     scheduleLayerFlush();
781     for (unsigned i = 0; i < m_updateAtlases.size(); ++i)
782         m_updateAtlases[i]->didSwapBuffers();
783 }
784
785 void CoordinatedLayerTreeHost::purgeBackingStores()
786 {
787     TemporaryChange<bool> purgingToggle(m_isPurging, true);
788
789     HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator end = m_registeredLayers.end();
790     for (HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator it = m_registeredLayers.begin(); it != end; ++it)
791         (*it)->purgeBackingStores();
792
793     m_imageBackings.clear();
794     m_updateAtlases.clear();
795 }
796
797 PassOwnPtr<GraphicsContext> CoordinatedLayerTreeHost::beginContentUpdate(const IntSize& size, CoordinatedSurface::Flags flags, uint32_t& atlasID, IntPoint& offset)
798 {
799     OwnPtr<GraphicsContext> graphicsContext;
800     for (unsigned i = 0; i < m_updateAtlases.size(); ++i) {
801         UpdateAtlas* atlas = m_updateAtlases[i].get();
802         if (atlas->supportsAlpha() == (flags & CoordinatedSurface::SupportsAlpha)) {
803             // This will return null if there is no available buffer space.
804             graphicsContext = atlas->beginPaintingOnAvailableBuffer(atlasID, size, offset);
805             if (graphicsContext)
806                 return graphicsContext.release();
807         }
808     }
809
810     static const int ScratchBufferDimension = 1024; // Should be a power of two.
811     m_updateAtlases.append(adoptPtr(new UpdateAtlas(this, ScratchBufferDimension, flags)));
812     scheduleReleaseInactiveAtlases();
813     return m_updateAtlases.last()->beginPaintingOnAvailableBuffer(atlasID, size, offset);
814 }
815
816 const double ReleaseInactiveAtlasesTimerInterval = 0.5;
817
818 void CoordinatedLayerTreeHost::scheduleReleaseInactiveAtlases()
819 {
820     if (!m_releaseInactiveAtlasesTimer.isActive())
821         m_releaseInactiveAtlasesTimer.startRepeating(ReleaseInactiveAtlasesTimerInterval);
822 }
823
824 void CoordinatedLayerTreeHost::releaseInactiveAtlasesTimerFired(Timer<CoordinatedLayerTreeHost>*)
825 {
826     // We always want to keep one atlas for non-composited content.
827     OwnPtr<UpdateAtlas> atlasToKeepAnyway;
828     bool foundActiveAtlasForNonCompositedContent = false;
829     for (int i = m_updateAtlases.size() - 1;  i >= 0; --i) {
830         UpdateAtlas* atlas = m_updateAtlases[i].get();
831         if (!atlas->isInUse())
832             atlas->addTimeInactive(ReleaseInactiveAtlasesTimerInterval);
833         bool usableForNonCompositedContent = !atlas->supportsAlpha();
834         if (atlas->isInactive()) {
835             if (!foundActiveAtlasForNonCompositedContent && !atlasToKeepAnyway && usableForNonCompositedContent)
836                 atlasToKeepAnyway = m_updateAtlases[i].release();
837             m_updateAtlases.remove(i);
838         } else if (usableForNonCompositedContent)
839             foundActiveAtlasForNonCompositedContent = true;
840     }
841
842     if (!foundActiveAtlasForNonCompositedContent && atlasToKeepAnyway)
843         m_updateAtlases.append(atlasToKeepAnyway.release());
844
845     if (m_updateAtlases.size() <= 1)
846         m_releaseInactiveAtlasesTimer.stop();
847 }
848
849 void CoordinatedLayerTreeHost::setBackgroundColor(const WebCore::Color& color)
850 {
851     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetBackgroundColor(color));
852 }
853
854 } // namespace WebKit
855 #endif // USE(COORDINATED_GRAPHICS)