OSDN Git Service

Merge "DO NOT MERGE Fix SW extras for layers" into ics-mr1
[android-x86/external-webkit.git] / Source / WebCore / platform / graphics / android / GLWebViewState.cpp
1 /*
2  * Copyright 2010, The Android Open Source Project
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *  * Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  *  * Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "GLWebViewState.h"
28
29 #if USE(ACCELERATED_COMPOSITING)
30
31 #include "BaseLayerAndroid.h"
32 #include "ClassTracker.h"
33 #include "GLUtils.h"
34 #include "ImagesManager.h"
35 #include "LayerAndroid.h"
36 #include "SkPath.h"
37 #include "TilesManager.h"
38 #include "TilesTracker.h"
39 #include <wtf/CurrentTime.h>
40
41 #include <cutils/log.h>
42 #include <wtf/text/CString.h>
43
44 #undef XLOGC
45 #define XLOGC(...) android_printLog(ANDROID_LOG_DEBUG, "GLWebViewState", __VA_ARGS__)
46
47 #ifdef DEBUG
48
49 #undef XLOG
50 #define XLOG(...) android_printLog(ANDROID_LOG_DEBUG, "GLWebViewState", __VA_ARGS__)
51
52 #else
53
54 #undef XLOG
55 #define XLOG(...)
56
57 #endif // DEBUG
58
59 #define FIRST_TILED_PAGE_ID 1
60 #define SECOND_TILED_PAGE_ID 2
61
62 #define FRAMERATE_CAP 0.01666 // We cap at 60 fps
63
64 // log warnings if scale goes outside this range
65 #define MIN_SCALE_WARNING 0.1
66 #define MAX_SCALE_WARNING 10
67
68 namespace WebCore {
69
70 using namespace android;
71
72 GLWebViewState::GLWebViewState(android::Mutex* buttonMutex)
73     : m_zoomManager(this)
74     , m_paintingBaseLayer(0)
75     , m_currentBaseLayer(0)
76     , m_currentBaseLayerRoot(0)
77     , m_currentPictureCounter(0)
78     , m_usePageA(true)
79     , m_frameworkInval(0, 0, 0, 0)
80     , m_frameworkLayersInval(0, 0, 0, 0)
81     , m_globalButtonMutex(buttonMutex)
82     , m_baseLayerUpdate(true)
83     , m_backgroundColor(SK_ColorWHITE)
84     , m_isScrolling(false)
85     , m_goingDown(true)
86     , m_goingLeft(false)
87     , m_expandedTileBoundsX(0)
88     , m_expandedTileBoundsY(0)
89     , m_scale(1)
90 {
91     m_viewport.setEmpty();
92     m_futureViewportTileBounds.setEmpty();
93     m_viewportTileBounds.setEmpty();
94     m_preZoomBounds.setEmpty();
95
96     m_tiledPageA = new TiledPage(FIRST_TILED_PAGE_ID, this);
97     m_tiledPageB = new TiledPage(SECOND_TILED_PAGE_ID, this);
98
99 #ifdef DEBUG_COUNT
100     ClassTracker::instance()->increment("GLWebViewState");
101 #endif
102 #ifdef MEASURES_PERF
103     m_timeCounter = 0;
104     m_totalTimeCounter = 0;
105     m_measurePerfs = false;
106 #endif
107 }
108
109 GLWebViewState::~GLWebViewState()
110 {
111     // Unref the existing tree/PaintedSurfaces
112     if (m_currentBaseLayerRoot)
113         TilesManager::instance()->swapLayersTextures(m_currentBaseLayerRoot, 0);
114
115     // Take care of the transfer queue such that Tex Gen thread will not stuck
116     TilesManager::instance()->unregisterGLWebViewState(this);
117
118     // We have to destroy the two tiled pages first as their destructor
119     // may depend on the existence of this GLWebViewState and some of its
120     // instance variables in order to complete.
121     // Explicitely, currently we need to have the m_paintingBaseLayer around
122     // in order to complete any pending paint operations (the tiled pages
123     // will remove any pending operations, and wait if one is underway).
124     delete m_tiledPageA;
125     delete m_tiledPageB;
126     SkSafeUnref(m_paintingBaseLayer);
127     SkSafeUnref(m_currentBaseLayer);
128     SkSafeUnref(m_currentBaseLayerRoot);
129     m_paintingBaseLayer = 0;
130     m_currentBaseLayer = 0;
131     m_currentBaseLayerRoot = 0;
132 #ifdef DEBUG_COUNT
133     ClassTracker::instance()->decrement("GLWebViewState");
134 #endif
135
136 }
137
138 void GLWebViewState::setBaseLayer(BaseLayerAndroid* layer, const SkRegion& inval,
139                                   bool showVisualIndicator, bool isPictureAfterFirstLayout)
140 {
141     android::Mutex::Autolock lock(m_baseLayerLock);
142     if (!layer || isPictureAfterFirstLayout) {
143         m_tiledPageA->discardTextures();
144         m_tiledPageB->discardTextures();
145     }
146     if (isPictureAfterFirstLayout) {
147         m_baseLayerUpdate = true;
148         m_invalidateRegion.setEmpty();
149     }
150
151     SkSafeRef(layer);
152     SkSafeUnref(m_currentBaseLayer);
153     m_currentBaseLayer = layer;
154
155
156     // copy content from old composited root to new
157     LayerAndroid* oldRoot = m_currentBaseLayerRoot;
158     if (layer) {
159         layer->setGLWebViewState(this);
160         m_currentBaseLayerRoot = static_cast<LayerAndroid*>(layer->getChild(0));
161         SkSafeRef(m_currentBaseLayerRoot);
162     } else {
163         m_currentBaseLayerRoot = 0;
164     }
165     if (oldRoot != m_currentBaseLayerRoot)
166         TilesManager::instance()->swapLayersTextures(oldRoot, m_currentBaseLayerRoot);
167     SkSafeUnref(oldRoot);
168
169     // We only update the base layer if we are not currently
170     // waiting for a tiledPage to be painted
171     if (m_baseLayerUpdate) {
172         SkSafeRef(layer);
173         SkSafeUnref(m_paintingBaseLayer);
174         m_paintingBaseLayer = layer;
175     }
176     m_glExtras.setDrawExtra(0);
177     invalRegion(inval);
178
179 #ifdef MEASURES_PERF
180     if (m_measurePerfs && !showVisualIndicator)
181         dumpMeasures();
182     m_measurePerfs = showVisualIndicator;
183 #endif
184
185     TilesManager::instance()->setShowVisualIndicator(showVisualIndicator);
186 }
187
188 void GLWebViewState::invalRegion(const SkRegion& region)
189 {
190     SkRegion::Iterator iterator(region);
191     while (!iterator.done()) {
192         SkIRect r = iterator.rect();
193         IntRect ir(r.fLeft, r.fTop, r.width(), r.height());
194         inval(ir);
195         iterator.next();
196     }
197 }
198
199 void GLWebViewState::unlockBaseLayerUpdate() {
200     if (m_baseLayerUpdate)
201         return;
202
203     m_baseLayerUpdate = true;
204     android::Mutex::Autolock lock(m_baseLayerLock);
205     SkSafeRef(m_currentBaseLayer);
206     SkSafeUnref(m_paintingBaseLayer);
207     m_paintingBaseLayer = m_currentBaseLayer;
208
209     invalRegion(m_invalidateRegion);
210     m_invalidateRegion.setEmpty();
211 }
212
213 void GLWebViewState::inval(const IntRect& rect)
214 {
215     if (m_baseLayerUpdate) {
216         // base layer isn't locked, so go ahead and issue the inval to both tiled pages
217         m_currentPictureCounter++;
218         if (!rect.isEmpty()) {
219             // find which tiles fall within the invalRect and mark them as dirty
220             m_tiledPageA->invalidateRect(rect, m_currentPictureCounter);
221             m_tiledPageB->invalidateRect(rect, m_currentPictureCounter);
222             if (m_frameworkInval.isEmpty())
223                 m_frameworkInval = rect;
224             else
225                 m_frameworkInval.unite(rect);
226             XLOG("intermediate invalRect(%d, %d, %d, %d) after unite with rect %d %d %d %d", m_frameworkInval.x(),
227                  m_frameworkInval.y(), m_frameworkInval.width(), m_frameworkInval.height(),
228                  rect.x(), rect.y(), rect.width(), rect.height());
229         }
230     } else {
231         // base layer is locked, so defer invalidation until unlockBaseLayerUpdate()
232         m_invalidateRegion.op(rect.x(), rect.y(), rect.maxX(), rect.maxY(), SkRegion::kUnion_Op);
233     }
234     TilesManager::instance()->getProfiler()->nextInval(rect, zoomManager()->currentScale());
235 }
236
237 unsigned int GLWebViewState::paintBaseLayerContent(SkCanvas* canvas)
238 {
239     android::Mutex::Autolock lock(m_baseLayerLock);
240     if (m_paintingBaseLayer) {
241         m_globalButtonMutex->lock();
242         m_paintingBaseLayer->drawCanvas(canvas);
243         m_globalButtonMutex->unlock();
244     }
245     return m_currentPictureCounter;
246 }
247
248 TiledPage* GLWebViewState::sibling(TiledPage* page)
249 {
250     return (page == m_tiledPageA) ? m_tiledPageB : m_tiledPageA;
251 }
252
253 TiledPage* GLWebViewState::frontPage()
254 {
255     android::Mutex::Autolock lock(m_tiledPageLock);
256     return m_usePageA ? m_tiledPageA : m_tiledPageB;
257 }
258
259 TiledPage* GLWebViewState::backPage()
260 {
261     android::Mutex::Autolock lock(m_tiledPageLock);
262     return m_usePageA ? m_tiledPageB : m_tiledPageA;
263 }
264
265 void GLWebViewState::swapPages()
266 {
267     android::Mutex::Autolock lock(m_tiledPageLock);
268     m_usePageA ^= true;
269     TiledPage* oldPage = m_usePageA ? m_tiledPageB : m_tiledPageA;
270     zoomManager()->swapPages();
271     oldPage->discardTextures();
272 }
273
274 int GLWebViewState::baseContentWidth()
275 {
276     return m_paintingBaseLayer ? m_paintingBaseLayer->content()->width() : 0;
277 }
278 int GLWebViewState::baseContentHeight()
279 {
280     return m_paintingBaseLayer ? m_paintingBaseLayer->content()->height() : 0;
281 }
282
283 void GLWebViewState::setViewport(SkRect& viewport, float scale)
284 {
285     if ((m_viewport == viewport) &&
286         (zoomManager()->futureScale() == scale))
287         return;
288
289     m_goingDown = m_viewport.fTop - viewport.fTop <= 0;
290     m_goingLeft = m_viewport.fLeft - viewport.fLeft >= 0;
291     m_viewport = viewport;
292
293     XLOG("New VIEWPORT %.2f - %.2f %.2f - %.2f (w: %2.f h: %.2f scale: %.2f currentScale: %.2f futureScale: %.2f)",
294          m_viewport.fLeft, m_viewport.fTop, m_viewport.fRight, m_viewport.fBottom,
295          m_viewport.width(), m_viewport.height(), scale,
296          zoomManager()->currentScale(), zoomManager()->futureScale());
297
298     const float invTileContentWidth = scale / TilesManager::tileWidth();
299     const float invTileContentHeight = scale / TilesManager::tileHeight();
300
301     m_viewportTileBounds.set(
302             static_cast<int>(floorf(viewport.fLeft * invTileContentWidth)),
303             static_cast<int>(floorf(viewport.fTop * invTileContentHeight)),
304             static_cast<int>(ceilf(viewport.fRight * invTileContentWidth)),
305             static_cast<int>(ceilf(viewport.fBottom * invTileContentHeight)));
306
307     // allocate max possible number of tiles visible with this viewport
308     int viewMaxTileX = static_cast<int>(ceilf((viewport.width()-1) * invTileContentWidth)) + 1;
309     int viewMaxTileY = static_cast<int>(ceilf((viewport.height()-1) * invTileContentHeight)) + 1;
310     int maxTextureCount = (viewMaxTileX + TILE_PREFETCH_DISTANCE * 2) *
311         (viewMaxTileY + TILE_PREFETCH_DISTANCE * 2) * 2;
312     TilesManager::instance()->setMaxTextureCount(maxTextureCount);
313     m_tiledPageA->updateBaseTileSize();
314     m_tiledPageB->updateBaseTileSize();
315 }
316
317 #ifdef MEASURES_PERF
318 void GLWebViewState::dumpMeasures()
319 {
320     for (int i = 0; i < m_timeCounter; i++) {
321         XLOGC("%d delay: %d ms", m_totalTimeCounter + i,
322              static_cast<int>(m_delayTimes[i]*1000));
323         m_delayTimes[i] = 0;
324     }
325     m_totalTimeCounter += m_timeCounter;
326     m_timeCounter = 0;
327 }
328 #endif // MEASURES_PERF
329
330 void GLWebViewState::resetFrameworkInval()
331 {
332     m_frameworkInval.setX(0);
333     m_frameworkInval.setY(0);
334     m_frameworkInval.setWidth(0);
335     m_frameworkInval.setHeight(0);
336 }
337
338 void GLWebViewState::addDirtyArea(const IntRect& rect)
339 {
340     if (rect.isEmpty())
341         return;
342
343     IntRect inflatedRect = rect;
344     inflatedRect.inflate(8);
345     if (m_frameworkLayersInval.isEmpty())
346         m_frameworkLayersInval = inflatedRect;
347     else
348         m_frameworkLayersInval.unite(inflatedRect);
349 }
350
351 void GLWebViewState::resetLayersDirtyArea()
352 {
353     m_frameworkLayersInval.setX(0);
354     m_frameworkLayersInval.setY(0);
355     m_frameworkLayersInval.setWidth(0);
356     m_frameworkLayersInval.setHeight(0);
357 }
358
359 double GLWebViewState::setupDrawing(IntRect& viewRect, SkRect& visibleRect,
360                                   IntRect& webViewRect, int titleBarHeight,
361                                   IntRect& screenClip, float scale)
362 {
363     int left = viewRect.x();
364     int top = viewRect.y();
365     int width = viewRect.width();
366     int height = viewRect.height();
367
368     if (TilesManager::instance()->invertedScreen()) {
369         float color = 1.0 - ((((float) m_backgroundColor.red() / 255.0) +
370                       ((float) m_backgroundColor.green() / 255.0) +
371                       ((float) m_backgroundColor.blue() / 255.0)) / 3.0);
372         glClearColor(color, color, color, 1);
373     } else {
374         glClearColor((float)m_backgroundColor.red() / 255.0,
375                      (float)m_backgroundColor.green() / 255.0,
376                      (float)m_backgroundColor.blue() / 255.0, 1);
377     }
378     glClear(GL_COLOR_BUFFER_BIT);
379
380     glViewport(left, top, width, height);
381
382     ShaderProgram* shader = TilesManager::instance()->shader();
383     if (shader->program() == -1) {
384         XLOG("Reinit shader");
385         shader->init();
386     }
387     shader->setViewRect(viewRect);
388     shader->setViewport(visibleRect);
389     shader->setWebViewRect(webViewRect);
390     shader->setTitleBarHeight(titleBarHeight);
391     shader->setScreenClip(screenClip);
392     shader->resetBlending();
393
394     double currentTime = WTF::currentTime();
395
396     setViewport(visibleRect, scale);
397     m_zoomManager.processNewScale(currentTime, scale);
398
399     return currentTime;
400 }
401
402 bool GLWebViewState::drawGL(IntRect& rect, SkRect& viewport, IntRect* invalRect,
403                             IntRect& webViewRect, int titleBarHeight,
404                             IntRect& clip, float scale, bool* buffersSwappedPtr)
405 {
406     m_scale = scale;
407     TilesManager::instance()->getProfiler()->nextFrame(viewport.fLeft,
408                                                        viewport.fTop,
409                                                        viewport.fRight,
410                                                        viewport.fBottom,
411                                                        scale);
412     TilesManager::instance()->incDrawGLCount();
413
414 #ifdef DEBUG
415     TilesManager::instance()->getTilesTracker()->clear();
416 #endif
417
418     m_baseLayerLock.lock();
419     BaseLayerAndroid* baseLayer = m_paintingBaseLayer;
420     SkSafeRef(baseLayer);
421     m_baseLayerLock.unlock();
422     if (!baseLayer)
423          return false;
424
425     float viewWidth = (viewport.fRight - viewport.fLeft) * TILE_PREFETCH_RATIO;
426     float viewHeight = (viewport.fBottom - viewport.fTop) * TILE_PREFETCH_RATIO;
427     bool useHorzPrefetch = viewWidth < baseContentWidth();
428     bool useVertPrefetch = viewHeight < baseContentHeight();
429     m_expandedTileBoundsX = (useHorzPrefetch) ? TILE_PREFETCH_DISTANCE : 0;
430     m_expandedTileBoundsY = (useVertPrefetch) ? TILE_PREFETCH_DISTANCE : 0;
431
432     XLOG("drawGL, rect(%d, %d, %d, %d), viewport(%.2f, %.2f, %.2f, %.2f)",
433          rect.x(), rect.y(), rect.width(), rect.height(),
434          viewport.fLeft, viewport.fTop, viewport.fRight, viewport.fBottom);
435
436     resetLayersDirtyArea();
437
438     LayerAndroid* compositedRoot = m_currentBaseLayerRoot;
439     LayerAndroid* paintingBaseLayerRoot = 0;
440     if (baseLayer && baseLayer->countChildren() >= 1)
441         paintingBaseLayerRoot = static_cast<LayerAndroid*>(baseLayer->getChild(0));
442
443     // when adding or removing layers, use the the paintingBaseLayer's tree so
444     // that content that moves to the base layer from a layer is synchronized
445     bool paintingHasLayers = (paintingBaseLayerRoot == 0);
446     bool currentHasLayers = (m_currentBaseLayerRoot == 0);
447     if (paintingHasLayers != currentHasLayers)
448         compositedRoot = paintingBaseLayerRoot;
449
450     if (scale < MIN_SCALE_WARNING || scale > MAX_SCALE_WARNING)
451         XLOGC("WARNING, scale seems corrupted before update: %e", scale);
452
453     // Here before we draw, update the BaseTile which has updated content.
454     // Inside this function, just do GPU blits from the transfer queue into
455     // the BaseTiles' texture.
456     TilesManager::instance()->transferQueue()->updateDirtyBaseTiles();
457
458     // Upload any pending ImageTexture
459     // Return true if we still have some images to upload.
460     // TODO: upload as many textures as possible within a certain time limit
461     bool ret = ImagesManager::instance()->uploadTextures();
462
463     if (scale < MIN_SCALE_WARNING || scale > MAX_SCALE_WARNING) {
464         XLOGC("WARNING, scale seems corrupted after update: %e", scale);
465         CRASH();
466     }
467
468     // gather the textures we can use
469     TilesManager::instance()->gatherLayerTextures();
470
471     // set up zoom manager, shaders, etc.
472     m_backgroundColor = baseLayer->getBackgroundColor();
473     double currentTime = setupDrawing(rect, viewport, webViewRect, titleBarHeight, clip, scale);
474     ret |= baseLayer->drawGL(currentTime, compositedRoot, rect,
475                                  viewport, scale, buffersSwappedPtr);
476     m_glExtras.drawGL(webViewRect, viewport, titleBarHeight);
477
478     glBindBuffer(GL_ARRAY_BUFFER, 0);
479
480     ret |= TilesManager::instance()->invertedScreenSwitch();
481
482     if (ret) {
483         // ret==true && empty inval region means we've inval'd everything,
484         // but don't have new content. Keep redrawing full view (0,0,0,0)
485         // until tile generation catches up and we swap pages.
486         bool fullScreenInval = m_frameworkInval.isEmpty();
487
488         if (TilesManager::instance()->invertedScreenSwitch()) {
489             fullScreenInval = true;
490             TilesManager::instance()->setInvertedScreenSwitch(false);
491         }
492
493         if (!fullScreenInval) {
494             FloatRect frameworkInval = TilesManager::instance()->shader()->rectInInvScreenCoord(
495                     m_frameworkInval);
496             // Inflate the invalidate rect to avoid precision lost.
497             frameworkInval.inflate(1);
498             IntRect inval(frameworkInval.x(), frameworkInval.y(),
499                     frameworkInval.width(), frameworkInval.height());
500
501             inval.unite(m_frameworkLayersInval);
502
503             invalRect->setX(inval.x());
504             invalRect->setY(inval.y());
505             invalRect->setWidth(inval.width());
506             invalRect->setHeight(inval.height());
507
508             XLOG("invalRect(%d, %d, %d, %d)", inval.x(),
509                     inval.y(), inval.width(), inval.height());
510
511             if (!invalRect->intersects(rect)) {
512                 // invalidate is occurring offscreen, do full inval to guarantee redraw
513                 fullScreenInval = true;
514             }
515         }
516
517         if (fullScreenInval) {
518             invalRect->setX(0);
519             invalRect->setY(0);
520             invalRect->setWidth(0);
521             invalRect->setHeight(0);
522         }
523     } else {
524         resetFrameworkInval();
525     }
526
527 #ifdef MEASURES_PERF
528     if (m_measurePerfs) {
529         m_delayTimes[m_timeCounter++] = delta;
530         if (m_timeCounter >= MAX_MEASURES_PERF)
531             dumpMeasures();
532     }
533 #endif
534
535     SkSafeUnref(baseLayer);
536 #ifdef DEBUG
537     TilesManager::instance()->getTilesTracker()->showTrackTextures();
538     ImagesManager::instance()->showImages();
539 #endif
540     return ret;
541 }
542
543 } // namespace WebCore
544
545 #endif // USE(ACCELERATED_COMPOSITING)