Unreviewed, rolling out r142112.
[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 static void updateOffsetFromViewportForSelf(RenderLayer* renderLayer)
473 {
474     // These conditions must match the conditions in RenderLayerCompositor::requiresCompositingForPosition.
475     RenderLayerBacking* backing = renderLayer->backing();
476     if (!backing)
477         return;
478
479     RenderStyle* style = renderLayer->renderer()->style();
480     if (!style)
481         return;
482
483     if (!renderLayer->renderer()->isOutOfFlowPositioned() || renderLayer->renderer()->style()->position() != FixedPosition)
484         return;
485
486     if (!renderLayer->renderer()->container()->isRenderView())
487         return;
488
489     if (!renderLayer->isStackingContainer())
490         return;
491
492     CoordinatedGraphicsLayer* graphicsLayer = toCoordinatedGraphicsLayer(backing->graphicsLayer());
493     graphicsLayer->setFixedToViewport(true);
494 }
495
496 static void updateOffsetFromViewportForLayer(RenderLayer* renderLayer)
497 {
498     updateOffsetFromViewportForSelf(renderLayer);
499
500     if (renderLayer->firstChild())
501         updateOffsetFromViewportForLayer(renderLayer->firstChild());
502     if (renderLayer->nextSibling())
503         updateOffsetFromViewportForLayer(renderLayer->nextSibling());
504 }
505
506 void CoordinatedLayerTreeHost::syncFixedLayers()
507 {
508     if (!m_webPage->corePage()->settings() || !m_webPage->corePage()->settings()->acceleratedCompositingForFixedPositionEnabled())
509         return;
510
511     if (!m_webPage->mainFrame()->view()->hasViewportConstrainedObjects())
512         return;
513
514     RenderLayer* rootRenderLayer = m_webPage->mainFrame()->contentRenderer()->compositor()->rootRenderLayer();
515     ASSERT(rootRenderLayer);
516     if (rootRenderLayer->firstChild())
517         updateOffsetFromViewportForLayer(rootRenderLayer->firstChild());
518 }
519
520 void CoordinatedLayerTreeHost::lockAnimations()
521 {
522     m_animationsLocked = true;
523     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetAnimationsLocked(true));
524 }
525
526 void CoordinatedLayerTreeHost::unlockAnimations()
527 {
528     if (!m_animationsLocked)
529         return;
530
531     m_animationsLocked = false;
532     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetAnimationsLocked(false));
533 }
534
535 void CoordinatedLayerTreeHost::performScheduledLayerFlush()
536 {
537     if (m_isSuspended || m_waitingForUIProcess)
538         return;
539
540     // We lock the animations while performing layout, to avoid flickers caused by animations continuing in the UI process while
541     // the web process layout wants to cancel them.
542     lockAnimations();
543     syncDisplayState();
544
545     // We can unlock the animations before flushing if there are no visible changes, for example if there are content updates
546     // in a layer with opacity 0.
547     bool canUnlockBeforeFlush = !m_isValid || !toCoordinatedGraphicsLayer(m_rootLayer.get())->hasPendingVisibleChanges();
548     if (canUnlockBeforeFlush)
549         unlockAnimations();
550
551     if (!m_isValid)
552         return;
553
554     if (flushPendingLayerChanges())
555         didPerformScheduledLayerFlush();
556 }
557
558 void CoordinatedLayerTreeHost::syncDisplayState()
559 {
560 #if ENABLE(REQUEST_ANIMATION_FRAME) && !USE(REQUEST_ANIMATION_FRAME_TIMER) && !USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
561     // Make sure that any previously registered animation callbacks are being executed before we flush the layers.
562     m_webPage->corePage()->mainFrame()->view()->serviceScriptedAnimations(convertSecondsToDOMTimeStamp(currentTime()));
563 #endif
564
565     m_webPage->layoutIfNeeded();
566 }
567
568 void CoordinatedLayerTreeHost::didPerformScheduledLayerFlush()
569 {
570     if (m_notifyAfterScheduledLayerFlush) {
571         static_cast<DrawingAreaImpl*>(m_webPage->drawingArea())->layerHostDidFlushLayers();
572         m_notifyAfterScheduledLayerFlush = false;
573     }
574 }
575
576 void CoordinatedLayerTreeHost::layerFlushTimerFired(Timer<CoordinatedLayerTreeHost>*)
577 {
578     performScheduledLayerFlush();
579 }
580
581 void CoordinatedLayerTreeHost::createPageOverlayLayer()
582 {
583     ASSERT(!m_pageOverlayLayer);
584
585     m_pageOverlayLayer = GraphicsLayer::create(this, this);
586 #ifndef NDEBUG
587     m_pageOverlayLayer->setName("CoordinatedLayerTreeHost page overlay content");
588 #endif
589
590     m_pageOverlayLayer->setDrawsContent(true);
591     m_pageOverlayLayer->setSize(m_webPage->size());
592
593     m_rootLayer->addChild(m_pageOverlayLayer.get());
594 }
595
596 void CoordinatedLayerTreeHost::destroyPageOverlayLayer()
597 {
598     ASSERT(m_pageOverlayLayer);
599     m_pageOverlayLayer->removeFromParent();
600     m_pageOverlayLayer = nullptr;
601 }
602
603 PassRefPtr<CoordinatedImageBacking> CoordinatedLayerTreeHost::createImageBackingIfNeeded(Image* image)
604 {
605     CoordinatedImageBackingID imageID = CoordinatedImageBacking::getCoordinatedImageBackingID(image);
606     ImageBackingMap::iterator it = m_imageBackings.find(imageID);
607     RefPtr<CoordinatedImageBacking> imageBacking;
608     if (it == m_imageBackings.end()) {
609         imageBacking = CoordinatedImageBacking::create(this, image);
610         m_imageBackings.add(imageID, imageBacking);
611     } else
612         imageBacking = it->value;
613
614     return imageBacking;
615 }
616
617 void CoordinatedLayerTreeHost::createImageBacking(CoordinatedImageBackingID imageID)
618 {
619     m_shouldSyncFrame = true;
620     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CreateImageBacking(imageID));
621 }
622
623 bool CoordinatedLayerTreeHost::updateImageBacking(CoordinatedImageBackingID imageID, PassRefPtr<CoordinatedSurface> coordinatedSurface)
624 {
625     m_shouldSyncFrame = true;
626     WebCoordinatedSurface* webCoordinatedSurface = static_cast<WebCoordinatedSurface*>(coordinatedSurface.get());
627     WebCoordinatedSurface::Handle handle;
628     if (!webCoordinatedSurface->createHandle(handle))
629         return false;
630     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::UpdateImageBacking(imageID, handle));
631     return true;
632 }
633
634 void CoordinatedLayerTreeHost::clearImageBackingContents(CoordinatedImageBackingID imageID)
635 {
636     m_shouldSyncFrame = true;
637     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::ClearImageBackingContents(imageID));
638 }
639
640 void CoordinatedLayerTreeHost::removeImageBacking(CoordinatedImageBackingID imageID)
641 {
642     if (m_isPurging)
643         return;
644
645     ASSERT(m_imageBackings.contains(imageID));
646     m_shouldSyncFrame = true;
647     m_imageBackings.remove(imageID);
648     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RemoveImageBacking(imageID));
649 }
650
651 void CoordinatedLayerTreeHost::flushPendingImageBackingChanges()
652 {
653     ImageBackingMap::iterator end = m_imageBackings.end();
654     for (ImageBackingMap::iterator iter = m_imageBackings.begin(); iter != end; ++iter)
655         iter->value->update();
656 }
657
658 void CoordinatedLayerTreeHost::notifyAnimationStarted(const WebCore::GraphicsLayer*, double /* time */)
659 {
660 }
661
662 void CoordinatedLayerTreeHost::notifyFlushRequired(const WebCore::GraphicsLayer*)
663 {
664     scheduleLayerFlush();
665 }
666
667 void CoordinatedLayerTreeHost::paintContents(const WebCore::GraphicsLayer* graphicsLayer, WebCore::GraphicsContext& graphicsContext, WebCore::GraphicsLayerPaintingPhase, const WebCore::IntRect& clipRect)
668 {
669     if (graphicsLayer == m_nonCompositedContentLayer) {
670         m_webPage->drawRect(graphicsContext, clipRect);
671         return;
672     }
673
674     if (graphicsLayer == m_pageOverlayLayer) {
675         // Overlays contain transparent contents and won't clear the context as part of their rendering, so we do it here.
676         graphicsContext.clearRect(clipRect);
677         m_webPage->drawPageOverlay(graphicsContext, clipRect);
678         return;
679     }
680 }
681
682 PassOwnPtr<GraphicsLayer> CoordinatedLayerTreeHost::createGraphicsLayer(GraphicsLayerClient* client)
683 {
684     CoordinatedGraphicsLayer* layer = new CoordinatedGraphicsLayer(client);
685     layer->setCoordinator(this);
686     m_registeredLayers.add(layer);
687     m_layersToCreate.append(layer->id());
688     layer->setNeedsVisibleRectAdjustment();
689     scheduleLayerFlush();
690     return adoptPtr(layer);
691 }
692
693 PassRefPtr<CoordinatedSurface> CoordinatedLayerTreeHost::createCoordinatedSurface(const IntSize& size, CoordinatedSurface::Flags flags)
694 {
695     return WebCoordinatedSurface::create(size, flags);
696 }
697
698 float CoordinatedLayerTreeHost::deviceScaleFactor() const
699 {
700     return m_webPage->deviceScaleFactor();
701 }
702
703 float CoordinatedLayerTreeHost::pageScaleFactor() const
704 {
705     return m_webPage->pageScaleFactor();
706 }
707
708 bool LayerTreeHost::supportsAcceleratedCompositing()
709 {
710     return true;
711 }
712
713 void CoordinatedLayerTreeHost::createTile(CoordinatedLayerID layerID, uint32_t tileID, const WebCore::SurfaceUpdateInfo& updateInfo, const WebCore::IntRect& tileRect)
714 {
715     m_shouldSyncFrame = true;
716     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CreateTileForLayer(layerID, tileID, tileRect, updateInfo));
717 }
718
719 void CoordinatedLayerTreeHost::updateTile(CoordinatedLayerID layerID, uint32_t tileID, const WebCore::SurfaceUpdateInfo& updateInfo, const WebCore::IntRect& tileRect)
720 {
721     m_shouldSyncFrame = true;
722     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::UpdateTileForLayer(layerID, tileID, tileRect, updateInfo));
723 }
724
725 void CoordinatedLayerTreeHost::removeTile(CoordinatedLayerID layerID, uint32_t tileID)
726 {
727     if (m_isPurging)
728         return;
729     m_shouldSyncFrame = true;
730     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RemoveTileForLayer(layerID, tileID));
731 }
732
733 bool CoordinatedLayerTreeHost::createUpdateAtlas(uint32_t atlasID, PassRefPtr<CoordinatedSurface> coordinatedSurface)
734 {
735     WebCoordinatedSurface* webCoordinatedSurface = static_cast<WebCoordinatedSurface*>(coordinatedSurface.get());
736     WebCoordinatedSurface::Handle handle;
737     if (!webCoordinatedSurface->createHandle(handle))
738         return false;
739     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CreateUpdateAtlas(atlasID, handle));
740     return true;
741 }
742
743 void CoordinatedLayerTreeHost::removeUpdateAtlas(uint32_t atlasID)
744 {
745     if (m_isPurging)
746         return;
747     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RemoveUpdateAtlas(atlasID));
748 }
749
750 WebCore::FloatRect CoordinatedLayerTreeHost::visibleContentsRect() const
751 {
752     return m_visibleContentsRect;
753 }
754
755
756 void CoordinatedLayerTreeHost::setLayerAnimations(CoordinatedLayerID layerID, const GraphicsLayerAnimations& animations)
757 {
758     m_shouldSyncFrame = true;
759     GraphicsLayerAnimations activeAnimations = animations.getActiveAnimations();
760 #if ENABLE(CSS_SHADERS)
761     for (size_t i = 0; i < activeAnimations.animations().size(); ++i) {
762         const KeyframeValueList& keyframes = animations.animations().at(i).keyframes();
763         if (keyframes.property() != AnimatedPropertyWebkitFilter)
764             continue;
765         for (size_t j = 0; j < keyframes.size(); ++j) {
766             const FilterAnimationValue* filterValue = static_cast<const FilterAnimationValue*>(keyframes.at(i));
767             checkCustomFilterProgramProxies(*filterValue->value());
768         }
769     }
770 #endif
771     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetLayerAnimations(layerID, activeAnimations));
772 }
773
774 void CoordinatedLayerTreeHost::setVisibleContentsRect(const FloatRect& rect, const FloatPoint& trajectoryVector)
775 {
776     // A zero trajectoryVector indicates that tiles all around the viewport are requested.
777     toCoordinatedGraphicsLayer(m_nonCompositedContentLayer.get())->setVisibleContentRectTrajectoryVector(trajectoryVector);
778
779     bool contentsRectDidChange = rect != m_visibleContentsRect;
780     if (contentsRectDidChange) {
781         m_visibleContentsRect = rect;
782
783         HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator end = m_registeredLayers.end();
784         for (HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator it = m_registeredLayers.begin(); it != end; ++it) {
785             (*it)->setNeedsVisibleRectAdjustment();
786         }
787     }
788
789     scheduleLayerFlush();
790     if (m_webPage->useFixedLayout()) {
791         // Round the rect instead of enclosing it to make sure that its size stays
792         // the same while panning. This can have nasty effects on layout.
793         m_webPage->setFixedVisibleContentRect(roundedIntRect(rect));
794     }
795
796     if (contentsRectDidChange)
797         m_shouldSendScrollPositionUpdate = true;
798 }
799
800 void CoordinatedLayerTreeHost::deviceOrPageScaleFactorChanged()
801 {
802     m_rootLayer->deviceOrPageScaleFactorChanged();
803     m_nonCompositedContentLayer->deviceOrPageScaleFactorChanged();
804     if (m_pageOverlayLayer)
805         m_pageOverlayLayer->deviceOrPageScaleFactorChanged();
806 }
807
808 GraphicsLayerFactory* CoordinatedLayerTreeHost::graphicsLayerFactory()
809 {
810     return this;
811 }
812
813 #if ENABLE(REQUEST_ANIMATION_FRAME)
814 void CoordinatedLayerTreeHost::scheduleAnimation()
815 {
816     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::RequestAnimationFrame());
817 }
818
819 void CoordinatedLayerTreeHost::animationFrameReady()
820 {
821     scheduleLayerFlush();
822 }
823 #endif
824
825 void CoordinatedLayerTreeHost::renderNextFrame()
826 {
827     m_waitingForUIProcess = false;
828     scheduleLayerFlush();
829     for (unsigned i = 0; i < m_updateAtlases.size(); ++i)
830         m_updateAtlases[i]->didSwapBuffers();
831 }
832
833 void CoordinatedLayerTreeHost::purgeBackingStores()
834 {
835     TemporaryChange<bool> purgingToggle(m_isPurging, true);
836
837     HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator end = m_registeredLayers.end();
838     for (HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator it = m_registeredLayers.begin(); it != end; ++it)
839         (*it)->purgeBackingStores();
840
841     m_imageBackings.clear();
842     m_updateAtlases.clear();
843 }
844
845 PassOwnPtr<GraphicsContext> CoordinatedLayerTreeHost::beginContentUpdate(const IntSize& size, CoordinatedSurface::Flags flags, uint32_t& atlasID, IntPoint& offset)
846 {
847     OwnPtr<GraphicsContext> graphicsContext;
848     for (unsigned i = 0; i < m_updateAtlases.size(); ++i) {
849         UpdateAtlas* atlas = m_updateAtlases[i].get();
850         if (atlas->supportsAlpha() == (flags & CoordinatedSurface::SupportsAlpha)) {
851             // This will return null if there is no available buffer space.
852             graphicsContext = atlas->beginPaintingOnAvailableBuffer(atlasID, size, offset);
853             if (graphicsContext)
854                 return graphicsContext.release();
855         }
856     }
857
858     static const int ScratchBufferDimension = 1024; // Should be a power of two.
859     m_updateAtlases.append(adoptPtr(new UpdateAtlas(this, ScratchBufferDimension, flags)));
860     scheduleReleaseInactiveAtlases();
861     return m_updateAtlases.last()->beginPaintingOnAvailableBuffer(atlasID, size, offset);
862 }
863
864 const double ReleaseInactiveAtlasesTimerInterval = 0.5;
865
866 void CoordinatedLayerTreeHost::scheduleReleaseInactiveAtlases()
867 {
868     if (!m_releaseInactiveAtlasesTimer.isActive())
869         m_releaseInactiveAtlasesTimer.startRepeating(ReleaseInactiveAtlasesTimerInterval);
870 }
871
872 void CoordinatedLayerTreeHost::releaseInactiveAtlasesTimerFired(Timer<CoordinatedLayerTreeHost>*)
873 {
874     // We always want to keep one atlas for non-composited content.
875     OwnPtr<UpdateAtlas> atlasToKeepAnyway;
876     bool foundActiveAtlasForNonCompositedContent = false;
877     for (int i = m_updateAtlases.size() - 1;  i >= 0; --i) {
878         UpdateAtlas* atlas = m_updateAtlases[i].get();
879         if (!atlas->isInUse())
880             atlas->addTimeInactive(ReleaseInactiveAtlasesTimerInterval);
881         bool usableForNonCompositedContent = !atlas->supportsAlpha();
882         if (atlas->isInactive()) {
883             if (!foundActiveAtlasForNonCompositedContent && !atlasToKeepAnyway && usableForNonCompositedContent)
884                 atlasToKeepAnyway = m_updateAtlases[i].release();
885             m_updateAtlases.remove(i);
886         } else if (usableForNonCompositedContent)
887             foundActiveAtlasForNonCompositedContent = true;
888     }
889
890     if (!foundActiveAtlasForNonCompositedContent && atlasToKeepAnyway)
891         m_updateAtlases.append(atlasToKeepAnyway.release());
892
893     if (m_updateAtlases.size() <= 1)
894         m_releaseInactiveAtlasesTimer.stop();
895 }
896
897 void CoordinatedLayerTreeHost::setBackgroundColor(const WebCore::Color& color)
898 {
899     m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::SetBackgroundColor(color));
900 }
901
902 } // namespace WebKit
903 #endif // USE(COORDINATED_GRAPHICS)