[Qt] Race condition in LayerTreeHost/Proxy can cause blank rendering
[qtwebkit:qt5-module.git] / Source / WebKit2 / WebProcess / WebPage / qt / LayerTreeHostQt.cpp
1 /*
2  * Copyright (C) 2011 Apple Inc. All rights reserved.
3  * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28
29 #include "LayerTreeHostQt.h"
30
31 #include "DrawingAreaImpl.h"
32 #include "GraphicsContext.h"
33 #include "LayerTreeHostProxyMessages.h"
34 #include "MessageID.h"
35 #include "SurfaceUpdateInfo.h"
36 #include "WebCoreArgumentCoders.h"
37 #include "WebGraphicsLayer.h"
38 #include "WebPage.h"
39 #include <WebCore/Frame.h>
40 #include <WebCore/FrameView.h>
41 #include <WebCore/Page.h>
42 #include <WebCore/RenderLayer.h>
43 #include <WebCore/RenderLayerBacking.h>
44 #include <WebCore/RenderLayerCompositor.h>
45 #include <WebCore/RenderView.h>
46 #include <WebCore/Settings.h>
47
48 using namespace WebCore;
49
50 namespace WebKit {
51
52 PassRefPtr<LayerTreeHostQt> LayerTreeHostQt::create(WebPage* webPage)
53 {
54     return adoptRef(new LayerTreeHostQt(webPage));
55 }
56
57 LayerTreeHostQt::~LayerTreeHostQt()
58 {
59     // Prevent setWebGraphicsLayerClient(0) -> detachLayer() from modifying the set while we iterate it.
60     HashSet<WebCore::WebGraphicsLayer*> registeredLayers;
61     registeredLayers.swap(m_registeredLayers);
62
63     HashSet<WebCore::WebGraphicsLayer*>::iterator end = registeredLayers.end();
64     for (HashSet<WebCore::WebGraphicsLayer*>::iterator it = registeredLayers.begin(); it != end; ++it)
65         (*it)->setWebGraphicsLayerClient(0);
66 }
67
68 LayerTreeHostQt::LayerTreeHostQt(WebPage* webPage)
69     : LayerTreeHost(webPage)
70     , m_notifyAfterScheduledLayerFlush(false)
71     , m_isValid(true)
72     , m_waitingForUIProcess(true)
73     , m_isSuspended(false)
74     , m_contentsScale(1)
75     , m_shouldSendScrollPositionUpdate(true)
76     , m_shouldSyncFrame(false)
77     , m_shouldSyncRootLayer(true)
78     , m_layerFlushTimer(this, &LayerTreeHostQt::layerFlushTimerFired)
79     , m_layerFlushSchedulingEnabled(true)
80 {
81     // Create a root layer.
82     m_rootLayer = GraphicsLayer::create(this);
83     WebGraphicsLayer* webRootLayer = toWebGraphicsLayer(m_rootLayer.get());
84     webRootLayer->setRootLayer(true);
85 #ifndef NDEBUG
86     m_rootLayer->setName("LayerTreeHostQt root layer");
87 #endif
88     m_rootLayer->setDrawsContent(false);
89     m_rootLayer->setSize(m_webPage->size());
90     m_layerTreeContext.webLayerID = toWebGraphicsLayer(webRootLayer)->id();
91
92     m_nonCompositedContentLayer = GraphicsLayer::create(this);
93     toWebGraphicsLayer(m_rootLayer.get())->setWebGraphicsLayerClient(this);
94 #ifndef NDEBUG
95     m_nonCompositedContentLayer->setName("LayerTreeHostQt non-composited content");
96 #endif
97     m_nonCompositedContentLayer->setDrawsContent(true);
98     m_nonCompositedContentLayer->setSize(m_webPage->size());
99
100     m_rootLayer->addChild(m_nonCompositedContentLayer.get());
101
102     if (m_webPage->hasPageOverlay())
103         createPageOverlayLayer();
104
105     scheduleLayerFlush();
106 }
107
108 void LayerTreeHostQt::setLayerFlushSchedulingEnabled(bool layerFlushingEnabled)
109 {
110     if (m_layerFlushSchedulingEnabled == layerFlushingEnabled)
111         return;
112
113     m_layerFlushSchedulingEnabled = layerFlushingEnabled;
114
115     if (m_layerFlushSchedulingEnabled) {
116         scheduleLayerFlush();
117         return;
118     }
119
120     cancelPendingLayerFlush();
121 }
122
123 void LayerTreeHostQt::scheduleLayerFlush()
124 {
125     if (!m_layerFlushSchedulingEnabled)
126         return;
127
128     if (!m_layerFlushTimer.isActive())
129         m_layerFlushTimer.startOneShot(0);
130 }
131
132 void LayerTreeHostQt::cancelPendingLayerFlush()
133 {
134     m_layerFlushTimer.stop();
135 }
136
137 void LayerTreeHostQt::setShouldNotifyAfterNextScheduledLayerFlush(bool notifyAfterScheduledLayerFlush)
138 {
139     m_notifyAfterScheduledLayerFlush = notifyAfterScheduledLayerFlush;
140 }
141
142 void LayerTreeHostQt::setRootCompositingLayer(WebCore::GraphicsLayer* graphicsLayer)
143 {
144     m_nonCompositedContentLayer->removeAllChildren();
145     m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground() && !m_webPage->drawsTransparentBackground());
146
147     // Add the accelerated layer tree hierarchy.
148     if (graphicsLayer)
149         m_nonCompositedContentLayer->addChild(graphicsLayer);
150 }
151
152 void LayerTreeHostQt::invalidate()
153 {
154     cancelPendingLayerFlush();
155
156     ASSERT(m_isValid);
157     m_rootLayer = nullptr;
158     m_isValid = false;
159 }
160
161 void LayerTreeHostQt::setNonCompositedContentsNeedDisplay(const WebCore::IntRect& rect)
162 {
163     m_nonCompositedContentLayer->setNeedsDisplayInRect(rect);
164     if (m_pageOverlayLayer)
165         m_pageOverlayLayer->setNeedsDisplayInRect(rect);
166
167     scheduleLayerFlush();
168 }
169
170 void LayerTreeHostQt::scrollNonCompositedContents(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset)
171 {
172     setNonCompositedContentsNeedDisplay(scrollRect);
173 }
174
175 void LayerTreeHostQt::forceRepaint()
176 {
177     scheduleLayerFlush();
178 }
179
180 void LayerTreeHostQt::sizeDidChange(const WebCore::IntSize& newSize)
181 {
182     if (m_rootLayer->size() == newSize)
183         return;
184
185     m_rootLayer->setSize(newSize);
186
187     // If the newSize exposes new areas of the non-composited content a setNeedsDisplay is needed
188     // for those newly exposed areas.
189     FloatSize oldSize = m_nonCompositedContentLayer->size();
190     m_nonCompositedContentLayer->setSize(newSize);
191
192     if (newSize.width() > oldSize.width()) {
193         float height = std::min(static_cast<float>(newSize.height()), oldSize.height());
194         m_nonCompositedContentLayer->setNeedsDisplayInRect(FloatRect(oldSize.width(), 0, newSize.width() - oldSize.width(), height));
195     }
196
197     if (newSize.height() > oldSize.height())
198         m_nonCompositedContentLayer->setNeedsDisplayInRect(FloatRect(0, oldSize.height(), newSize.width(), newSize.height() - oldSize.height()));
199
200     if (m_pageOverlayLayer)
201         m_pageOverlayLayer->setSize(newSize);
202
203     scheduleLayerFlush();
204 }
205
206 void LayerTreeHostQt::didInstallPageOverlay()
207 {
208     createPageOverlayLayer();
209     scheduleLayerFlush();
210 }
211
212 void LayerTreeHostQt::didUninstallPageOverlay()
213 {
214     destroyPageOverlayLayer();
215     scheduleLayerFlush();
216 }
217
218 void LayerTreeHostQt::setPageOverlayNeedsDisplay(const WebCore::IntRect& rect)
219 {
220     ASSERT(m_pageOverlayLayer);
221     m_pageOverlayLayer->setNeedsDisplayInRect(rect);
222     scheduleLayerFlush();
223 }
224
225 void LayerTreeHostQt::setPageOverlayOpacity(float value)
226 {
227     ASSERT(m_pageOverlayLayer);
228     m_pageOverlayLayer->setOpacity(value);
229     scheduleLayerFlush();
230 }
231
232 bool LayerTreeHostQt::flushPendingLayerChanges()
233 {
234     bool didSync = m_webPage->corePage()->mainFrame()->view()->syncCompositingStateIncludingSubframes();
235     m_nonCompositedContentLayer->syncCompositingStateForThisLayerOnly();
236     if (m_pageOverlayLayer)
237         m_pageOverlayLayer->syncCompositingStateForThisLayerOnly();
238
239     m_rootLayer->syncCompositingStateForThisLayerOnly();
240     return didSync;
241 }
242
243 void LayerTreeHostQt::syncLayerState(WebLayerID id, const WebLayerInfo& info)
244 {
245     if (m_shouldSendScrollPositionUpdate) {
246         m_webPage->send(Messages::LayerTreeHostProxy::DidChangeScrollPosition(m_visibleContentsRect.location()));
247         m_shouldSendScrollPositionUpdate = false;
248     }
249     m_shouldSyncFrame = true;
250     m_webPage->send(Messages::LayerTreeHostProxy::SetCompositingLayerState(id, info));
251 }
252
253 void LayerTreeHostQt::syncLayerChildren(WebLayerID id, const Vector<WebLayerID>& children)
254 {
255     m_shouldSyncFrame = true;
256     m_webPage->send(Messages::LayerTreeHostProxy::SetCompositingLayerChildren(id, children));
257 }
258
259 #if ENABLE(CSS_FILTERS)
260 void LayerTreeHostQt::syncLayerFilters(WebLayerID id, const FilterOperations& filters)
261 {
262     m_shouldSyncFrame = true;
263     m_webPage->send(Messages::LayerTreeHostProxy::SetCompositingLayerFilters(id, filters));
264 }
265 #endif
266
267 void LayerTreeHostQt::attachLayer(WebGraphicsLayer* layer)
268 {
269     ASSERT(!m_registeredLayers.contains(layer));
270     m_registeredLayers.add(layer);
271
272     layer->setContentsScale(m_contentsScale);
273     layer->adjustVisibleRect();
274 }
275
276 void LayerTreeHostQt::detachLayer(WebGraphicsLayer* layer)
277 {
278     m_registeredLayers.remove(layer);
279     m_shouldSyncFrame = true;
280     m_webPage->send(Messages::LayerTreeHostProxy::DeleteCompositingLayer(layer->id()));
281 }
282
283 static void updateOffsetFromViewportForSelf(RenderLayer* renderLayer)
284 {
285     // These conditions must match the conditions in RenderLayerCompositor::requiresCompositingForPosition.
286     RenderLayerBacking* backing = renderLayer->backing();
287     if (!backing)
288         return;
289
290     RenderStyle* style = renderLayer->renderer()->style();
291     if (!style)
292         return;
293
294     if (!renderLayer->renderer()->isPositioned() || renderLayer->renderer()->style()->position() != FixedPosition)
295         return;
296
297     if (!renderLayer->renderer()->container()->isRenderView())
298         return;
299
300     if (!renderLayer->isStackingContext())
301         return;
302
303     WebGraphicsLayer* graphicsLayer = toWebGraphicsLayer(backing->graphicsLayer());
304     graphicsLayer->setFixedToViewport(true);
305 }
306
307 static void updateOffsetFromViewportForLayer(RenderLayer* renderLayer)
308 {
309     updateOffsetFromViewportForSelf(renderLayer);
310
311     if (renderLayer->firstChild())
312         updateOffsetFromViewportForLayer(renderLayer->firstChild());
313     if (renderLayer->nextSibling())
314         updateOffsetFromViewportForLayer(renderLayer->nextSibling());
315 }
316
317 void LayerTreeHostQt::syncFixedLayers()
318 {
319     if (!m_webPage->corePage()->settings() || !m_webPage->corePage()->settings()->acceleratedCompositingForFixedPositionEnabled())
320         return;
321
322     if (!m_webPage->mainFrame()->view()->hasFixedObjects())
323         return;
324
325     RenderLayer* rootRenderLayer = m_webPage->mainFrame()->contentRenderer()->compositor()->rootRenderLayer();
326     ASSERT(rootRenderLayer);
327     if (rootRenderLayer->firstChild())
328         updateOffsetFromViewportForLayer(rootRenderLayer->firstChild());
329 }
330
331 void LayerTreeHostQt::performScheduledLayerFlush()
332 {
333     if (m_isSuspended || m_waitingForUIProcess)
334         return;
335
336     m_webPage->layoutIfNeeded();
337
338     if (!m_isValid)
339         return;
340
341     m_shouldSyncFrame = false;
342     flushPendingLayerChanges();
343     if (!m_shouldSyncFrame)
344         return;
345
346     if (m_shouldSyncRootLayer) {
347         m_webPage->send(Messages::LayerTreeHostProxy::SetRootCompositingLayer(toWebGraphicsLayer(m_rootLayer.get())->id()));
348         m_shouldSyncRootLayer = false;
349     }
350
351     m_webPage->send(Messages::LayerTreeHostProxy::DidRenderFrame());
352     m_waitingForUIProcess = true;
353
354     if (!m_notifyAfterScheduledLayerFlush)
355         return;
356
357     // Let the drawing area know that we've done a flush of the layer changes.
358     static_cast<DrawingAreaImpl*>(m_webPage->drawingArea())->layerHostDidFlushLayers();
359     m_notifyAfterScheduledLayerFlush = false;
360 }
361
362 void LayerTreeHostQt::layerFlushTimerFired(Timer<LayerTreeHostQt>*)
363 {
364     performScheduledLayerFlush();
365 }
366
367 void LayerTreeHostQt::createPageOverlayLayer()
368 {
369     ASSERT(!m_pageOverlayLayer);
370
371     m_pageOverlayLayer = GraphicsLayer::create(this);
372 #ifndef NDEBUG
373     m_pageOverlayLayer->setName("LayerTreeHostQt page overlay content");
374 #endif
375
376     m_pageOverlayLayer->setDrawsContent(true);
377     m_pageOverlayLayer->setSize(m_webPage->size());
378
379     m_rootLayer->addChild(m_pageOverlayLayer.get());
380 }
381
382 void LayerTreeHostQt::destroyPageOverlayLayer()
383 {
384     ASSERT(m_pageOverlayLayer);
385     m_pageOverlayLayer->removeFromParent();
386     m_pageOverlayLayer = nullptr;
387 }
388
389 int64_t LayerTreeHostQt::adoptImageBackingStore(Image* image)
390 {
391     if (!image)
392         return InvalidWebLayerID;
393     QPixmap* pixmap = image->nativeImageForCurrentFrame();
394
395     if (!pixmap)
396         return InvalidWebLayerID;
397
398     int64_t key = pixmap->cacheKey();
399     HashMap<int64_t, int>::iterator it = m_directlyCompositedImageRefCounts.find(key);
400
401     if (it != m_directlyCompositedImageRefCounts.end()) {
402         ++(it->second);
403         return key;
404     }
405
406     RefPtr<ShareableBitmap> bitmap = ShareableBitmap::createShareable(image->size(), (image->currentFrameHasAlpha() ? ShareableBitmap::SupportsAlpha : 0));
407     {
408         OwnPtr<WebCore::GraphicsContext> graphicsContext = bitmap->createGraphicsContext();
409         graphicsContext->drawImage(image, ColorSpaceDeviceRGB, IntPoint::zero());
410     }
411
412     ShareableBitmap::Handle handle;
413     bitmap->createHandle(handle);
414     m_webPage->send(Messages::LayerTreeHostProxy::CreateDirectlyCompositedImage(key, handle));
415     m_directlyCompositedImageRefCounts.add(key, 1);
416     return key;
417 }
418
419 void LayerTreeHostQt::releaseImageBackingStore(int64_t key)
420 {
421     if (!key)
422         return;
423     HashMap<int64_t, int>::iterator it = m_directlyCompositedImageRefCounts.find(key);
424     if (it == m_directlyCompositedImageRefCounts.end())
425         return;
426
427     it->second--;
428
429     if (it->second)
430         return;
431
432     m_directlyCompositedImageRefCounts.remove(it);
433     m_webPage->send(Messages::LayerTreeHostProxy::DestroyDirectlyCompositedImage(key));
434 }
435
436
437 void LayerTreeHostQt::notifyAnimationStarted(const WebCore::GraphicsLayer*, double time)
438 {
439 }
440
441 void LayerTreeHostQt::notifySyncRequired(const WebCore::GraphicsLayer*)
442 {
443 }
444
445 void LayerTreeHostQt::paintContents(const WebCore::GraphicsLayer* graphicsLayer, WebCore::GraphicsContext& graphicsContext, WebCore::GraphicsLayerPaintingPhase, const WebCore::IntRect& clipRect)
446 {
447     if (graphicsLayer == m_nonCompositedContentLayer) {
448         m_webPage->drawRect(graphicsContext, clipRect);
449         return;
450     }
451
452     if (graphicsLayer == m_pageOverlayLayer) {
453         // Overlays contain transparent contents and won't clear the context as part of their rendering, so we do it here.
454         graphicsContext.clearRect(clipRect);
455         m_webPage->drawPageOverlay(graphicsContext, clipRect);
456         return;
457     }
458 }
459
460 bool LayerTreeHostQt::showDebugBorders(const WebCore::GraphicsLayer*) const
461 {
462     return m_webPage->corePage()->settings()->showDebugBorders();
463 }
464
465 bool LayerTreeHostQt::showRepaintCounter(const WebCore::GraphicsLayer*) const
466 {
467     return m_webPage->corePage()->settings()->showRepaintCounter();
468 }
469
470 bool LayerTreeHost::supportsAcceleratedCompositing()
471 {
472     return true;
473 }
474
475 void LayerTreeHostQt::createTile(WebLayerID layerID, int tileID, const SurfaceUpdateInfo& updateInfo, const WebCore::IntRect& targetRect)
476 {
477     m_shouldSyncFrame = true;
478     m_webPage->send(Messages::LayerTreeHostProxy::CreateTileForLayer(layerID, tileID, targetRect, updateInfo));
479 }
480
481 void LayerTreeHostQt::updateTile(WebLayerID layerID, int tileID, const SurfaceUpdateInfo& updateInfo, const WebCore::IntRect& targetRect)
482 {
483     m_shouldSyncFrame = true;
484     m_webPage->send(Messages::LayerTreeHostProxy::UpdateTileForLayer(layerID, tileID, targetRect, updateInfo));
485 }
486
487 void LayerTreeHostQt::removeTile(WebLayerID layerID, int tileID)
488 {
489     m_shouldSyncFrame = true;
490     m_webPage->send(Messages::LayerTreeHostProxy::RemoveTileForLayer(layerID, tileID));
491 }
492
493 WebCore::IntRect LayerTreeHostQt::visibleContentsRect() const
494 {
495     return m_visibleContentsRect;
496 }
497
498 void LayerTreeHostQt::setVisibleContentsRect(const IntRect& rect, float scale, const FloatPoint& trajectoryVector)
499 {
500     bool contentsRectDidChange = rect != m_visibleContentsRect;
501     bool contentsScaleDidChange = scale != m_contentsScale;
502
503     if (trajectoryVector != FloatPoint::zero())
504         toWebGraphicsLayer(m_nonCompositedContentLayer.get())->setVisibleContentRectTrajectoryVector(trajectoryVector);
505
506     if (contentsRectDidChange || contentsScaleDidChange) {
507         m_visibleContentsRect = rect;
508         m_contentsScale = scale;
509
510         HashSet<WebCore::WebGraphicsLayer*>::iterator end = m_registeredLayers.end();
511         for (HashSet<WebCore::WebGraphicsLayer*>::iterator it = m_registeredLayers.begin(); it != end; ++it) {
512             if (contentsScaleDidChange)
513                 (*it)->setContentsScale(scale);
514             if (contentsRectDidChange)
515                 (*it)->adjustVisibleRect();
516         }
517     }
518
519     scheduleLayerFlush();
520     if (m_webPage->useFixedLayout())
521         m_webPage->setFixedVisibleContentRect(rect);
522     if (contentsRectDidChange)
523         m_shouldSendScrollPositionUpdate = true;
524 }
525
526 void LayerTreeHostQt::renderNextFrame()
527 {
528     m_waitingForUIProcess = false;
529     scheduleLayerFlush();
530     for (int i = 0; i < m_updateAtlases.size(); ++i)
531         m_updateAtlases[i].didSwapBuffers();
532 }
533
534 bool LayerTreeHostQt::layerTreeTileUpdatesAllowed() const
535 {
536     return !m_isSuspended && !m_waitingForUIProcess;
537 }
538
539 void LayerTreeHostQt::purgeBackingStores()
540 {
541     HashSet<WebCore::WebGraphicsLayer*>::iterator end = m_registeredLayers.end();
542     for (HashSet<WebCore::WebGraphicsLayer*>::iterator it = m_registeredLayers.begin(); it != end; ++it)
543         (*it)->purgeBackingStores();
544
545     ASSERT(!m_directlyCompositedImageRefCounts.size());
546     m_updateAtlases.clear();
547 }
548
549 UpdateAtlas& LayerTreeHostQt::getAtlas(ShareableBitmap::Flags flags)
550 {
551     for (int i = 0; i < m_updateAtlases.size(); ++i) {
552         if (m_updateAtlases[i].flags() == flags)
553             return m_updateAtlases[i];
554     }
555     static const int ScratchBufferDimension = 2000;
556     m_updateAtlases.append(UpdateAtlas(ScratchBufferDimension, flags));
557     return m_updateAtlases.last();
558 }
559
560 PassOwnPtr<WebCore::GraphicsContext> LayerTreeHostQt::beginContentUpdate(const WebCore::IntSize& size, ShareableBitmap::Flags flags, ShareableSurface::Handle& handle, WebCore::IntPoint& offset)
561 {
562     UpdateAtlas& atlas = getAtlas(flags);
563     if (!atlas.surface()->createHandle(handle))
564         return PassOwnPtr<WebCore::GraphicsContext>();
565
566     // This will return null if there is no available buffer.
567     OwnPtr<WebCore::GraphicsContext> graphicsContext = atlas.beginPaintingOnAvailableBuffer(size, offset);
568     if (!graphicsContext)
569         return PassOwnPtr<WebCore::GraphicsContext>();
570
571     return graphicsContext.release();
572 }
573
574 } // namespace WebKit