SurfaceFlinger.cpp revision 4803b74e2a12a508f7bbfde6f6a962fe3299c61c
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19#include <stdint.h>
20#include <sys/types.h>
21#include <errno.h>
22#include <math.h>
23#include <dlfcn.h>
24
25#include <EGL/egl.h>
26#include <GLES/gl.h>
27
28#include <cutils/log.h>
29#include <cutils/properties.h>
30
31#include <binder/IPCThreadState.h>
32#include <binder/IServiceManager.h>
33#include <binder/MemoryHeapBase.h>
34#include <binder/PermissionCache.h>
35
36#include <ui/DisplayInfo.h>
37
38#include <gui/BitTube.h>
39#include <gui/BufferQueue.h>
40#include <gui/GuiConfig.h>
41#include <gui/IDisplayEventConnection.h>
42#include <gui/SurfaceTextureClient.h>
43
44#include <ui/GraphicBufferAllocator.h>
45#include <ui/PixelFormat.h>
46#include <ui/UiConfig.h>
47
48#include <utils/misc.h>
49#include <utils/String8.h>
50#include <utils/String16.h>
51#include <utils/StopWatch.h>
52#include <utils/Trace.h>
53
54#include <private/android_filesystem_config.h>
55
56#include "clz.h"
57#include "DdmConnection.h"
58#include "DisplayDevice.h"
59#include "Client.h"
60#include "EventThread.h"
61#include "GLExtensions.h"
62#include "Layer.h"
63#include "LayerDim.h"
64#include "LayerScreenshot.h"
65#include "SurfaceFlinger.h"
66
67#include "DisplayHardware/FramebufferSurface.h"
68#include "DisplayHardware/GraphicBufferAlloc.h"
69#include "DisplayHardware/HWComposer.h"
70
71
72#define EGL_VERSION_HW_ANDROID  0x3143
73
74#define DISPLAY_COUNT       1
75
76namespace android {
77// ---------------------------------------------------------------------------
78
79const String16 sHardwareTest("android.permission.HARDWARE_TEST");
80const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
81const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
82const String16 sDump("android.permission.DUMP");
83
84// ---------------------------------------------------------------------------
85
86SurfaceFlinger::SurfaceFlinger()
87    :   BnSurfaceComposer(), Thread(false),
88        mTransactionFlags(0),
89        mTransationPending(false),
90        mLayersRemoved(false),
91        mRepaintEverything(0),
92        mBootTime(systemTime()),
93        mVisibleRegionsDirty(false),
94        mHwWorkListDirty(false),
95        mDebugRegion(0),
96        mDebugDDMS(0),
97        mDebugDisableHWC(0),
98        mDebugDisableTransformHint(0),
99        mDebugInSwapBuffers(0),
100        mLastSwapBufferTime(0),
101        mDebugInTransaction(0),
102        mLastTransactionTime(0),
103        mBootFinished(false)
104{
105    ALOGI("SurfaceFlinger is starting");
106
107    // debugging stuff...
108    char value[PROPERTY_VALUE_MAX];
109
110    property_get("debug.sf.showupdates", value, "0");
111    mDebugRegion = atoi(value);
112
113    property_get("debug.sf.ddms", value, "0");
114    mDebugDDMS = atoi(value);
115    if (mDebugDDMS) {
116        if (!startDdmConnection()) {
117            // start failed, and DDMS debugging not enabled
118            mDebugDDMS = 0;
119        }
120    }
121    ALOGI_IF(mDebugRegion, "showupdates enabled");
122    ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
123}
124
125void SurfaceFlinger::onFirstRef()
126{
127    mEventQueue.init(this);
128
129    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
130
131    // Wait for the main thread to be done with its initialization
132    mReadyToRunBarrier.wait();
133}
134
135
136SurfaceFlinger::~SurfaceFlinger()
137{
138    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
139    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
140    eglTerminate(display);
141}
142
143void SurfaceFlinger::binderDied(const wp<IBinder>& who)
144{
145    // the window manager died on us. prepare its eulogy.
146
147    // restore initial conditions (default device unblank, etc)
148    initializeDisplays();
149
150    // restart the boot-animation
151    startBootAnim();
152}
153
154sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
155{
156    sp<ISurfaceComposerClient> bclient;
157    sp<Client> client(new Client(this));
158    status_t err = client->initCheck();
159    if (err == NO_ERROR) {
160        bclient = client;
161    }
162    return bclient;
163}
164
165sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName)
166{
167    class DisplayToken : public BBinder {
168        sp<SurfaceFlinger> flinger;
169        virtual ~DisplayToken() {
170             // no more references, this display must be terminated
171             Mutex::Autolock _l(flinger->mStateLock);
172             flinger->mCurrentState.displays.removeItem(this);
173             flinger->setTransactionFlags(eDisplayTransactionNeeded);
174         }
175     public:
176        DisplayToken(const sp<SurfaceFlinger>& flinger)
177            : flinger(flinger) {
178        }
179    };
180
181    sp<BBinder> token = new DisplayToken(this);
182
183    Mutex::Autolock _l(mStateLock);
184    DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
185    info.displayName = displayName;
186    mCurrentState.displays.add(token, info);
187
188    return token;
189}
190
191sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
192    if (uint32_t(id) >= DisplayDevice::NUM_DISPLAY_TYPES) {
193        ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
194        return NULL;
195    }
196    return mDefaultDisplays[id];
197}
198
199sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
200{
201    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
202    return gba;
203}
204
205void SurfaceFlinger::bootFinished()
206{
207    const nsecs_t now = systemTime();
208    const nsecs_t duration = now - mBootTime;
209    ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
210    mBootFinished = true;
211
212    // wait patiently for the window manager death
213    const String16 name("window");
214    sp<IBinder> window(defaultServiceManager()->getService(name));
215    if (window != 0) {
216        window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
217    }
218
219    // stop boot animation
220    // formerly we would just kill the process, but we now ask it to exit so it
221    // can choose where to stop the animation.
222    property_set("service.bootanim.exit", "1");
223}
224
225void SurfaceFlinger::deleteTextureAsync(GLuint texture) {
226    class MessageDestroyGLTexture : public MessageBase {
227        GLuint texture;
228    public:
229        MessageDestroyGLTexture(GLuint texture)
230            : texture(texture) {
231        }
232        virtual bool handler() {
233            glDeleteTextures(1, &texture);
234            return true;
235        }
236    };
237    postMessageAsync(new MessageDestroyGLTexture(texture));
238}
239
240status_t SurfaceFlinger::selectConfigForPixelFormat(
241        EGLDisplay dpy,
242        EGLint const* attrs,
243        PixelFormat format,
244        EGLConfig* outConfig)
245{
246    EGLConfig config = NULL;
247    EGLint numConfigs = -1, n=0;
248    eglGetConfigs(dpy, NULL, 0, &numConfigs);
249    EGLConfig* const configs = new EGLConfig[numConfigs];
250    eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
251
252    for (int i=0 ; i<n ; i++) {
253        EGLint nativeVisualId = 0;
254        eglGetConfigAttrib(dpy, configs[i], EGL_NATIVE_VISUAL_ID, &nativeVisualId);
255        if (nativeVisualId>0 && format == nativeVisualId) {
256            *outConfig = configs[i];
257            delete [] configs;
258            return NO_ERROR;
259        }
260    }
261    delete [] configs;
262    return NAME_NOT_FOUND;
263}
264
265EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) {
266    // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
267    // it is to be used with WIFI displays
268    EGLConfig config;
269    EGLint dummy;
270    status_t err;
271
272    EGLint attribs[] = {
273            EGL_SURFACE_TYPE,           EGL_WINDOW_BIT,
274            // The rest of the attributes must be in this order and at the end
275            // of the list; we rely on that for fallback searches below.
276            EGL_RED_SIZE,               8,
277            EGL_GREEN_SIZE,             8,
278            EGL_BLUE_SIZE,              8,
279            EGL_RECORDABLE_ANDROID,     EGL_TRUE,
280            EGL_NONE
281    };
282    err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
283    if (!err)
284        goto success;
285
286    // maybe we failed because of EGL_RECORDABLE_ANDROID
287    ALOGW("no suitable EGLConfig found, trying without EGL_RECORDABLE_ANDROID");
288    attribs[NELEM(attribs) - 3] = EGL_NONE;
289    err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
290    if (!err)
291        goto success;
292
293    // allow less than 24-bit color; the non-gpu-accelerated emulator only
294    // supports 16-bit color
295    ALOGW("no suitable EGLConfig found, trying with 16-bit color allowed");
296    attribs[NELEM(attribs) - 9] = EGL_NONE;
297    err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
298    if (!err)
299        goto success;
300
301    // this EGL is too lame for Android
302    ALOGE("no suitable EGLConfig found, giving up");
303
304    return 0;
305
306success:
307    if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy))
308        ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
309    return config;
310}
311
312EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) {
313    // Also create our EGLContext
314    EGLint contextAttributes[] = {
315#ifdef EGL_IMG_context_priority
316#ifdef HAS_CONTEXT_PRIORITY
317#warning "using EGL_IMG_context_priority"
318            EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG,
319#endif
320#endif
321            EGL_NONE, EGL_NONE
322    };
323    EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes);
324    ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed");
325    return ctxt;
326}
327
328void SurfaceFlinger::initializeGL(EGLDisplay display) {
329    GLExtensions& extensions(GLExtensions::getInstance());
330    extensions.initWithGLStrings(
331            glGetString(GL_VENDOR),
332            glGetString(GL_RENDERER),
333            glGetString(GL_VERSION),
334            glGetString(GL_EXTENSIONS),
335            eglQueryString(display, EGL_VENDOR),
336            eglQueryString(display, EGL_VERSION),
337            eglQueryString(display, EGL_EXTENSIONS));
338
339    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
340    glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
341
342    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
343    glPixelStorei(GL_PACK_ALIGNMENT, 4);
344    glEnableClientState(GL_VERTEX_ARRAY);
345    glShadeModel(GL_FLAT);
346    glDisable(GL_DITHER);
347    glDisable(GL_CULL_FACE);
348
349    struct pack565 {
350        inline uint16_t operator() (int r, int g, int b) const {
351            return (r<<11)|(g<<5)|b;
352        }
353    } pack565;
354
355    const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
356    glGenTextures(1, &mProtectedTexName);
357    glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
358    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
359    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
360    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
361    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
362    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
363            GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
364
365    // print some debugging info
366    EGLint r,g,b,a;
367    eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE,   &r);
368    eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g);
369    eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE,  &b);
370    eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a);
371    ALOGI("EGL informations:");
372    ALOGI("vendor    : %s", extensions.getEglVendor());
373    ALOGI("version   : %s", extensions.getEglVersion());
374    ALOGI("extensions: %s", extensions.getEglExtension());
375    ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported");
376    ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
377    ALOGI("OpenGL ES informations:");
378    ALOGI("vendor    : %s", extensions.getVendor());
379    ALOGI("renderer  : %s", extensions.getRenderer());
380    ALOGI("version   : %s", extensions.getVersion());
381    ALOGI("extensions: %s", extensions.getExtension());
382    ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize);
383    ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]);
384}
385
386status_t SurfaceFlinger::readyToRun()
387{
388    ALOGI(  "SurfaceFlinger's main thread ready to run. "
389            "Initializing graphics H/W...");
390
391    // initialize EGL for the default display
392    mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
393    eglInitialize(mEGLDisplay, NULL, NULL);
394
395    // Initialize the H/W composer object.  There may or may not be an
396    // actual hardware composer underneath.
397    mHwc = new HWComposer(this,
398            *static_cast<HWComposer::EventHandler *>(this));
399
400    // initialize the config and context
401    EGLint format = mHwc->getVisualID();
402    mEGLConfig  = selectEGLConfig(mEGLDisplay, format);
403    mEGLContext = createGLContext(mEGLDisplay, mEGLConfig);
404
405    LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
406            "couldn't create EGLContext");
407
408    // initialize our non-virtual displays
409    for (size_t i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
410        DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
411        mDefaultDisplays[i] = new BBinder();
412        wp<IBinder> token = mDefaultDisplays[i];
413
414        // set-up the displays that are already connected
415        if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
416            mCurrentState.displays.add(token, DisplayDeviceState(type));
417            sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i);
418            sp<SurfaceTextureClient> stc = new SurfaceTextureClient(
419                        static_cast< sp<ISurfaceTexture> >(fbs->getBufferQueue()));
420            sp<DisplayDevice> hw = new DisplayDevice(this,
421                    type, token, stc, fbs, mEGLConfig);
422
423            if (i > DisplayDevice::DISPLAY_PRIMARY) {
424                // FIXME: currently we don't really handle blank/unblank
425                // for displays other than the main display, so we always
426                // assume a connected display is unblanked.
427                hw->acquireScreen();
428            }
429            mDisplays.add(token, hw);
430        }
431    }
432
433    //  we need a GL context current in a few places, when initializing
434    //  OpenGL ES (see below), or creating a layer,
435    //  or when a texture is (asynchronously) destroyed, and for that
436    //  we need a valid surface, so it's convenient to use the main display
437    //  for that.
438    sp<const DisplayDevice> hw = getDefaultDisplayDevice();
439
440    //  initialize OpenGL ES
441    DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
442    initializeGL(mEGLDisplay);
443
444    // start the EventThread
445    mEventThread = new EventThread(this);
446    mEventQueue.setEventThread(mEventThread);
447
448    // initialize our drawing state
449    mDrawingState = mCurrentState;
450
451
452    // We're now ready to accept clients...
453    mReadyToRunBarrier.open();
454
455    // set initial conditions (e.g. unblank default device)
456    initializeDisplays();
457
458    // start boot animation
459    startBootAnim();
460
461    return NO_ERROR;
462}
463
464int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
465    return (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) ?
466            type : mHwc->allocateDisplayId();
467}
468
469void SurfaceFlinger::startBootAnim() {
470    // start boot animation
471    property_set("service.bootanim.exit", "0");
472    property_set("ctl.start", "bootanim");
473}
474
475uint32_t SurfaceFlinger::getMaxTextureSize() const {
476    return mMaxTextureSize;
477}
478
479uint32_t SurfaceFlinger::getMaxViewportDims() const {
480    return mMaxViewportDims[0] < mMaxViewportDims[1] ?
481            mMaxViewportDims[0] : mMaxViewportDims[1];
482}
483
484// ----------------------------------------------------------------------------
485
486bool SurfaceFlinger::authenticateSurfaceTexture(
487        const sp<ISurfaceTexture>& surfaceTexture) const {
488    Mutex::Autolock _l(mStateLock);
489    sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
490
491    // Check the visible layer list for the ISurface
492    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
493    size_t count = currentLayers.size();
494    for (size_t i=0 ; i<count ; i++) {
495        const sp<LayerBase>& layer(currentLayers[i]);
496        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
497        if (lbc != NULL) {
498            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
499            if (lbcBinder == surfaceTextureBinder) {
500                return true;
501            }
502        }
503    }
504
505    // Check the layers in the purgatory.  This check is here so that if a
506    // SurfaceTexture gets destroyed before all the clients are done using it,
507    // the error will not be reported as "surface XYZ is not authenticated", but
508    // will instead fail later on when the client tries to use the surface,
509    // which should be reported as "surface XYZ returned an -ENODEV".  The
510    // purgatorized layers are no less authentic than the visible ones, so this
511    // should not cause any harm.
512    size_t purgatorySize =  mLayerPurgatory.size();
513    for (size_t i=0 ; i<purgatorySize ; i++) {
514        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
515        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
516        if (lbc != NULL) {
517            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
518            if (lbcBinder == surfaceTextureBinder) {
519                return true;
520            }
521        }
522    }
523
524    return false;
525}
526
527status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
528    int32_t type = BAD_VALUE;
529    for (int i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
530        if (display == mDefaultDisplays[i]) {
531            type = i;
532            break;
533        }
534    }
535
536    if (type < 0) {
537        return type;
538    }
539
540    const HWComposer& hwc(getHwComposer());
541    if (!hwc.isConnected(type)) {
542        return NAME_NOT_FOUND;
543    }
544
545    float xdpi = hwc.getDpiX(type);
546    float ydpi = hwc.getDpiY(type);
547
548    // TODO: Not sure if display density should handled by SF any longer
549    class Density {
550        static int getDensityFromProperty(char const* propName) {
551            char property[PROPERTY_VALUE_MAX];
552            int density = 0;
553            if (property_get(propName, property, NULL) > 0) {
554                density = atoi(property);
555            }
556            return density;
557        }
558    public:
559        static int getEmuDensity() {
560            return getDensityFromProperty("qemu.sf.lcd_density"); }
561        static int getBuildDensity()  {
562            return getDensityFromProperty("ro.sf.lcd_density"); }
563    };
564
565    if (type == DisplayDevice::DISPLAY_PRIMARY) {
566        // The density of the device is provided by a build property
567        float density = Density::getBuildDensity() / 160.0f;
568        if (density == 0) {
569            // the build doesn't provide a density -- this is wrong!
570            // use xdpi instead
571            ALOGE("ro.sf.lcd_density must be defined as a build property");
572            density = xdpi / 160.0f;
573        }
574        if (Density::getEmuDensity()) {
575            // if "qemu.sf.lcd_density" is specified, it overrides everything
576            xdpi = ydpi = density = Density::getEmuDensity();
577            density /= 160.0f;
578        }
579        info->density = density;
580
581        // TODO: this needs to go away (currently needed only by webkit)
582        sp<const DisplayDevice> hw(getDefaultDisplayDevice());
583        info->orientation = hw->getOrientation();
584        getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo);
585    } else {
586        // TODO: where should this value come from?
587        static const int TV_DENSITY = 213;
588        info->density = TV_DENSITY / 160.0f;
589        info->orientation = 0;
590    }
591
592    info->w = hwc.getWidth(type);
593    info->h = hwc.getHeight(type);
594    info->xdpi = xdpi;
595    info->ydpi = ydpi;
596    info->fps = float(1e9 / hwc.getRefreshPeriod(type));
597    return NO_ERROR;
598}
599
600// ----------------------------------------------------------------------------
601
602sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
603    return mEventThread->createEventConnection();
604}
605
606void SurfaceFlinger::connectDisplay(const sp<ISurfaceTexture>& surface) {
607
608    sp<IBinder> token;
609    { // scope for the lock
610        Mutex::Autolock _l(mStateLock);
611        token = mExtDisplayToken;
612    }
613
614    if (token == 0) {
615        token = createDisplay(String8("Display from connectDisplay"));
616    }
617
618    { // scope for the lock
619        Mutex::Autolock _l(mStateLock);
620        if (surface == 0) {
621            // release our current display. we're guarantee to have
622            // a reference to it (token), while we hold the lock
623            mExtDisplayToken = 0;
624        } else {
625            mExtDisplayToken = token;
626        }
627
628        DisplayDeviceState& info(mCurrentState.displays.editValueFor(token));
629        info.surface = surface;
630        setTransactionFlags(eDisplayTransactionNeeded);
631    }
632}
633
634// ----------------------------------------------------------------------------
635
636void SurfaceFlinger::waitForEvent() {
637    mEventQueue.waitMessage();
638}
639
640void SurfaceFlinger::signalTransaction() {
641    mEventQueue.invalidate();
642}
643
644void SurfaceFlinger::signalLayerUpdate() {
645    mEventQueue.invalidate();
646}
647
648void SurfaceFlinger::signalRefresh() {
649    mEventQueue.refresh();
650}
651
652status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
653        nsecs_t reltime, uint32_t flags) {
654    return mEventQueue.postMessage(msg, reltime);
655}
656
657status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
658        nsecs_t reltime, uint32_t flags) {
659    status_t res = mEventQueue.postMessage(msg, reltime);
660    if (res == NO_ERROR) {
661        msg->wait();
662    }
663    return res;
664}
665
666bool SurfaceFlinger::threadLoop() {
667    waitForEvent();
668    return true;
669}
670
671void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
672    if (mEventThread == NULL) {
673        // This is a temporary workaround for b/7145521.  A non-null pointer
674        // does not mean EventThread has finished initializing, so this
675        // is not a correct fix.
676        ALOGW("WARNING: EventThread not started, ignoring vsync");
677        return;
678    }
679    if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
680        // we should only receive DisplayDevice::DisplayType from the vsync callback
681        mEventThread->onVSyncReceived(type, timestamp);
682    }
683}
684
685void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
686    if (mEventThread == NULL) {
687        // This is a temporary workaround for b/7145521.  A non-null pointer
688        // does not mean EventThread has finished initializing, so this
689        // is not a correct fix.
690        ALOGW("WARNING: EventThread not started, ignoring hotplug");
691        return;
692    }
693
694    if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
695        Mutex::Autolock _l(mStateLock);
696        if (connected == false) {
697            mCurrentState.displays.removeItem(mDefaultDisplays[type]);
698        } else {
699            DisplayDeviceState info((DisplayDevice::DisplayType)type);
700            mCurrentState.displays.add(mDefaultDisplays[type], info);
701        }
702        setTransactionFlags(eDisplayTransactionNeeded);
703
704        // we should only receive DisplayDevice::DisplayType from the vsync callback
705        mEventThread->onHotplugReceived(type, connected);
706    }
707}
708
709void SurfaceFlinger::eventControl(int event, int enabled) {
710    getHwComposer().eventControl(event, enabled);
711}
712
713void SurfaceFlinger::onMessageReceived(int32_t what) {
714    ATRACE_CALL();
715    switch (what) {
716    case MessageQueue::INVALIDATE:
717        handleMessageTransaction();
718        handleMessageInvalidate();
719        signalRefresh();
720        break;
721    case MessageQueue::REFRESH:
722        handleMessageRefresh();
723        break;
724    }
725}
726
727void SurfaceFlinger::handleMessageTransaction() {
728    uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
729    if (transactionFlags) {
730        handleTransaction(transactionFlags);
731    }
732}
733
734void SurfaceFlinger::handleMessageInvalidate() {
735    ATRACE_CALL();
736    handlePageFlip();
737}
738
739void SurfaceFlinger::handleMessageRefresh() {
740    ATRACE_CALL();
741    preComposition();
742    rebuildLayerStacks();
743    setUpHWComposer();
744    doDebugFlashRegions();
745    doComposition();
746    postComposition();
747}
748
749void SurfaceFlinger::doDebugFlashRegions()
750{
751    // is debugging enabled
752    if (CC_LIKELY(!mDebugRegion))
753        return;
754
755    const bool repaintEverything = mRepaintEverything;
756    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
757        const sp<DisplayDevice>& hw(mDisplays[dpy]);
758        if (hw->canDraw()) {
759            // transform the dirty region into this screen's coordinate space
760            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
761            if (!dirtyRegion.isEmpty()) {
762                // redraw the whole screen
763                doComposeSurfaces(hw, Region(hw->bounds()));
764
765                // and draw the dirty region
766                glDisable(GL_TEXTURE_EXTERNAL_OES);
767                glDisable(GL_TEXTURE_2D);
768                glDisable(GL_BLEND);
769                glColor4f(1, 0, 1, 1);
770                const int32_t height = hw->getHeight();
771                Region::const_iterator it = dirtyRegion.begin();
772                Region::const_iterator const end = dirtyRegion.end();
773                while (it != end) {
774                    const Rect& r = *it++;
775                    GLfloat vertices[][2] = {
776                            { r.left,  height - r.top },
777                            { r.left,  height - r.bottom },
778                            { r.right, height - r.bottom },
779                            { r.right, height - r.top }
780                    };
781                    glVertexPointer(2, GL_FLOAT, 0, vertices);
782                    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
783                }
784                hw->compositionComplete();
785                hw->swapBuffers(getHwComposer());
786            }
787        }
788    }
789
790    postFramebuffer();
791
792    if (mDebugRegion > 1) {
793        usleep(mDebugRegion * 1000);
794    }
795}
796
797void SurfaceFlinger::preComposition()
798{
799    bool needExtraInvalidate = false;
800    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
801    const size_t count = currentLayers.size();
802    for (size_t i=0 ; i<count ; i++) {
803        if (currentLayers[i]->onPreComposition()) {
804            needExtraInvalidate = true;
805        }
806    }
807    if (needExtraInvalidate) {
808        signalLayerUpdate();
809    }
810}
811
812void SurfaceFlinger::postComposition()
813{
814    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
815    const size_t count = currentLayers.size();
816    for (size_t i=0 ; i<count ; i++) {
817        currentLayers[i]->onPostComposition();
818    }
819}
820
821void SurfaceFlinger::rebuildLayerStacks() {
822    // rebuild the visible layer list per screen
823    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
824        ATRACE_CALL();
825        mVisibleRegionsDirty = false;
826        invalidateHwcGeometry();
827
828        const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
829        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
830            Region opaqueRegion;
831            Region dirtyRegion;
832            Vector< sp<LayerBase> > layersSortedByZ;
833            const sp<DisplayDevice>& hw(mDisplays[dpy]);
834            const Transform& tr(hw->getTransform());
835            const Rect bounds(hw->getBounds());
836            if (hw->canDraw()) {
837                SurfaceFlinger::computeVisibleRegions(currentLayers,
838                        hw->getLayerStack(), dirtyRegion, opaqueRegion);
839
840                const size_t count = currentLayers.size();
841                for (size_t i=0 ; i<count ; i++) {
842                    const sp<LayerBase>& layer(currentLayers[i]);
843                    const Layer::State& s(layer->drawingState());
844                    if (s.layerStack == hw->getLayerStack()) {
845                        Region visibleRegion(tr.transform(layer->visibleRegion));
846                        visibleRegion.andSelf(bounds);
847                        if (!visibleRegion.isEmpty()) {
848                            layersSortedByZ.add(layer);
849                        }
850                    }
851                }
852            }
853            hw->setVisibleLayersSortedByZ(layersSortedByZ);
854            hw->undefinedRegion.set(bounds);
855            hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
856            hw->dirtyRegion.orSelf(dirtyRegion);
857        }
858    }
859}
860
861void SurfaceFlinger::setUpHWComposer() {
862    HWComposer& hwc(getHwComposer());
863    if (hwc.initCheck() == NO_ERROR) {
864        // build the h/w work list
865        const bool workListsDirty = mHwWorkListDirty;
866        mHwWorkListDirty = false;
867        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
868            sp<const DisplayDevice> hw(mDisplays[dpy]);
869            const int32_t id = hw->getHwcDisplayId();
870            if (id >= 0) {
871                const Vector< sp<LayerBase> >& currentLayers(
872                    hw->getVisibleLayersSortedByZ());
873                const size_t count = currentLayers.size();
874                if (hwc.createWorkList(id, count) >= 0) {
875                    HWComposer::LayerListIterator cur = hwc.begin(id);
876                    const HWComposer::LayerListIterator end = hwc.end(id);
877                    for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
878                        const sp<LayerBase>& layer(currentLayers[i]);
879
880                        if (CC_UNLIKELY(workListsDirty)) {
881                            layer->setGeometry(hw, *cur);
882                            if (mDebugDisableHWC || mDebugRegion) {
883                                cur->setSkip(true);
884                            }
885                        }
886
887                        /*
888                         * update the per-frame h/w composer data for each layer
889                         * and build the transparent region of the FB
890                         */
891                        layer->setPerFrameData(hw, *cur);
892                    }
893                }
894            }
895        }
896        status_t err = hwc.prepare();
897        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
898    }
899}
900
901void SurfaceFlinger::doComposition() {
902    ATRACE_CALL();
903    const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
904    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
905        const sp<DisplayDevice>& hw(mDisplays[dpy]);
906        if (hw->canDraw()) {
907            // transform the dirty region into this screen's coordinate space
908            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
909            if (!dirtyRegion.isEmpty()) {
910                // repaint the framebuffer (if needed)
911                doDisplayComposition(hw, dirtyRegion);
912            }
913            hw->dirtyRegion.clear();
914            hw->flip(hw->swapRegion);
915            hw->swapRegion.clear();
916        }
917        // inform the h/w that we're done compositing
918        hw->compositionComplete();
919    }
920    postFramebuffer();
921}
922
923void SurfaceFlinger::postFramebuffer()
924{
925    ATRACE_CALL();
926
927    const nsecs_t now = systemTime();
928    mDebugInSwapBuffers = now;
929
930    HWComposer& hwc(getHwComposer());
931    if (hwc.initCheck() == NO_ERROR) {
932        if (!hwc.supportsFramebufferTarget()) {
933            // EGL spec says:
934            //   "surface must be bound to the calling thread's current context,
935            //    for the current rendering API."
936            DisplayDevice::makeCurrent(mEGLDisplay,
937                    getDefaultDisplayDevice(), mEGLContext);
938        }
939        hwc.commit();
940    }
941
942    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
943        sp<const DisplayDevice> hw(mDisplays[dpy]);
944        const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
945        hw->onSwapBuffersCompleted(hwc);
946        const size_t count = currentLayers.size();
947        int32_t id = hw->getHwcDisplayId();
948        if (id >=0 && hwc.initCheck() == NO_ERROR) {
949            HWComposer::LayerListIterator cur = hwc.begin(id);
950            const HWComposer::LayerListIterator end = hwc.end(id);
951            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
952                currentLayers[i]->onLayerDisplayed(hw, &*cur);
953            }
954        } else {
955            for (size_t i = 0; i < count; i++) {
956                currentLayers[i]->onLayerDisplayed(hw, NULL);
957            }
958        }
959    }
960
961    mLastSwapBufferTime = systemTime() - now;
962    mDebugInSwapBuffers = 0;
963}
964
965void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
966{
967    ATRACE_CALL();
968
969    Mutex::Autolock _l(mStateLock);
970    const nsecs_t now = systemTime();
971    mDebugInTransaction = now;
972
973    // Here we're guaranteed that some transaction flags are set
974    // so we can call handleTransactionLocked() unconditionally.
975    // We call getTransactionFlags(), which will also clear the flags,
976    // with mStateLock held to guarantee that mCurrentState won't change
977    // until the transaction is committed.
978
979    transactionFlags = getTransactionFlags(eTransactionMask);
980    handleTransactionLocked(transactionFlags);
981
982    mLastTransactionTime = systemTime() - now;
983    mDebugInTransaction = 0;
984    invalidateHwcGeometry();
985    // here the transaction has been committed
986}
987
988void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
989{
990    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
991    const size_t count = currentLayers.size();
992
993    /*
994     * Traversal of the children
995     * (perform the transaction for each of them if needed)
996     */
997
998    if (transactionFlags & eTraversalNeeded) {
999        for (size_t i=0 ; i<count ; i++) {
1000            const sp<LayerBase>& layer = currentLayers[i];
1001            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1002            if (!trFlags) continue;
1003
1004            const uint32_t flags = layer->doTransaction(0);
1005            if (flags & Layer::eVisibleRegion)
1006                mVisibleRegionsDirty = true;
1007        }
1008    }
1009
1010    /*
1011     * Perform display own transactions if needed
1012     */
1013
1014    if (transactionFlags & eDisplayTransactionNeeded) {
1015        // here we take advantage of Vector's copy-on-write semantics to
1016        // improve performance by skipping the transaction entirely when
1017        // know that the lists are identical
1018        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1019        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1020        if (!curr.isIdenticalTo(draw)) {
1021            mVisibleRegionsDirty = true;
1022            const size_t cc = curr.size();
1023                  size_t dc = draw.size();
1024
1025            // find the displays that were removed
1026            // (ie: in drawing state but not in current state)
1027            // also handle displays that changed
1028            // (ie: displays that are in both lists)
1029            for (size_t i=0 ; i<dc ; i++) {
1030                const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1031                if (j < 0) {
1032                    // in drawing state but not in current state
1033                    if (!draw[i].isMainDisplay()) {
1034                        mDisplays.removeItem(draw.keyAt(i));
1035                    } else {
1036                        ALOGW("trying to remove the main display");
1037                    }
1038                } else {
1039                    // this display is in both lists. see if something changed.
1040                    const DisplayDeviceState& state(curr[j]);
1041                    const wp<IBinder>& display(curr.keyAt(j));
1042                    if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1043                        // changing the surface is like destroying and
1044                        // recreating the DisplayDevice, so we just remove it
1045                        // from the drawing state, so that it get re-added
1046                        // below.
1047                        mDisplays.removeItem(display);
1048                        mDrawingState.displays.removeItemsAt(i);
1049                        dc--; i--;
1050                        // at this point we must loop to the next item
1051                        continue;
1052                    }
1053
1054                    const sp<DisplayDevice>& disp(getDisplayDevice(display));
1055                    if (disp != NULL) {
1056                        if (state.layerStack != draw[i].layerStack) {
1057                            disp->setLayerStack(state.layerStack);
1058                        }
1059                        if ((state.orientation != draw[i].orientation)
1060                                || (state.viewport != draw[i].viewport)
1061                                || (state.frame != draw[i].frame))
1062                        {
1063                            disp->setProjection(state.orientation,
1064                                    state.viewport, state.frame);
1065                        }
1066
1067                        // Walk through all the layers in currentLayers,
1068                        // and update their transform hint.
1069                        //
1070                        // TODO: we could be much more clever about which
1071                        // layers we touch and how often we do these updates
1072                        // (e.g. only touch the layers associated with this
1073                        // display, and only on a rotation).
1074                        for (size_t i = 0; i < count; i++) {
1075                            const sp<LayerBase>& layerBase = currentLayers[i];
1076                            layerBase->updateTransformHint();
1077                        }
1078                    }
1079                }
1080            }
1081
1082            // find displays that were added
1083            // (ie: in current state but not in drawing state)
1084            for (size_t i=0 ; i<cc ; i++) {
1085                if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1086                    const DisplayDeviceState& state(curr[i]);
1087
1088                    sp<FramebufferSurface> fbs;
1089                    sp<SurfaceTextureClient> stc;
1090                    if (!state.isVirtualDisplay()) {
1091
1092                        ALOGE_IF(state.surface!=NULL,
1093                                "adding a supported display, but rendering "
1094                                "surface is provided (%p), ignoring it",
1095                                state.surface.get());
1096
1097                        // for supported (by hwc) displays we provide our
1098                        // own rendering surface
1099                        fbs = new FramebufferSurface(*mHwc, state.type);
1100                        stc = new SurfaceTextureClient(
1101                                static_cast< sp<ISurfaceTexture> >(fbs->getBufferQueue()));
1102                    } else {
1103                        if (state.surface != NULL) {
1104                            stc = new SurfaceTextureClient(state.surface);
1105                        }
1106                    }
1107
1108                    const wp<IBinder>& display(curr.keyAt(i));
1109                    if (stc != NULL) {
1110                        sp<DisplayDevice> hw = new DisplayDevice(this,
1111                                state.type, display, stc, fbs, mEGLConfig);
1112                        hw->setLayerStack(state.layerStack);
1113                        hw->setProjection(state.orientation,
1114                                state.viewport, state.frame);
1115                        hw->setDisplayName(state.displayName);
1116                        mDisplays.add(display, hw);
1117                        if (hw->getDisplayType() < DisplayDevice::NUM_DISPLAY_TYPES) {
1118                            // notify the system that this display is now up
1119                            // (note onScreenAcquired() is safe to call from
1120                            // here because we're in the main thread)
1121                            onScreenAcquired(hw);
1122                        }
1123                    }
1124                }
1125            }
1126        }
1127    }
1128
1129    /*
1130     * Perform our own transaction if needed
1131     */
1132
1133    const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
1134    if (currentLayers.size() > previousLayers.size()) {
1135        // layers have been added
1136        mVisibleRegionsDirty = true;
1137    }
1138
1139    // some layers might have been removed, so
1140    // we need to update the regions they're exposing.
1141    if (mLayersRemoved) {
1142        mLayersRemoved = false;
1143        mVisibleRegionsDirty = true;
1144        const size_t count = previousLayers.size();
1145        for (size_t i=0 ; i<count ; i++) {
1146            const sp<LayerBase>& layer(previousLayers[i]);
1147            if (currentLayers.indexOf(layer) < 0) {
1148                // this layer is not visible anymore
1149                // TODO: we could traverse the tree from front to back and
1150                //       compute the actual visible region
1151                // TODO: we could cache the transformed region
1152                const Layer::State& s(layer->drawingState());
1153                Region visibleReg = s.transform.transform(
1154                        Region(Rect(s.active.w, s.active.h)));
1155                invalidateLayerStack(s.layerStack, visibleReg);
1156            }
1157        }
1158    }
1159
1160    commitTransaction();
1161}
1162
1163void SurfaceFlinger::commitTransaction()
1164{
1165    if (!mLayersPendingRemoval.isEmpty()) {
1166        // Notify removed layers now that they can't be drawn from
1167        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1168            mLayersPendingRemoval[i]->onRemoved();
1169        }
1170        mLayersPendingRemoval.clear();
1171    }
1172
1173    mDrawingState = mCurrentState;
1174    mTransationPending = false;
1175    mTransactionCV.broadcast();
1176}
1177
1178void SurfaceFlinger::computeVisibleRegions(
1179        const LayerVector& currentLayers, uint32_t layerStack,
1180        Region& outDirtyRegion, Region& outOpaqueRegion)
1181{
1182    ATRACE_CALL();
1183
1184    Region aboveOpaqueLayers;
1185    Region aboveCoveredLayers;
1186    Region dirty;
1187
1188    outDirtyRegion.clear();
1189
1190    size_t i = currentLayers.size();
1191    while (i--) {
1192        const sp<LayerBase>& layer = currentLayers[i];
1193
1194        // start with the whole surface at its current location
1195        const Layer::State& s(layer->drawingState());
1196
1197        // only consider the layers on the given later stack
1198        if (s.layerStack != layerStack)
1199            continue;
1200
1201        /*
1202         * opaqueRegion: area of a surface that is fully opaque.
1203         */
1204        Region opaqueRegion;
1205
1206        /*
1207         * visibleRegion: area of a surface that is visible on screen
1208         * and not fully transparent. This is essentially the layer's
1209         * footprint minus the opaque regions above it.
1210         * Areas covered by a translucent surface are considered visible.
1211         */
1212        Region visibleRegion;
1213
1214        /*
1215         * coveredRegion: area of a surface that is covered by all
1216         * visible regions above it (which includes the translucent areas).
1217         */
1218        Region coveredRegion;
1219
1220
1221        // handle hidden surfaces by setting the visible region to empty
1222        if (CC_LIKELY(layer->isVisible())) {
1223            const bool translucent = !layer->isOpaque();
1224            Rect bounds(layer->computeBounds());
1225            visibleRegion.set(bounds);
1226            if (!visibleRegion.isEmpty()) {
1227                // Remove the transparent area from the visible region
1228                if (translucent) {
1229                    Region transparentRegionScreen;
1230                    const Transform tr(s.transform);
1231                    if (tr.transformed()) {
1232                        if (tr.preserveRects()) {
1233                            // transform the transparent region
1234                            transparentRegionScreen = tr.transform(s.transparentRegion);
1235                        } else {
1236                            // transformation too complex, can't do the
1237                            // transparent region optimization.
1238                            transparentRegionScreen.clear();
1239                        }
1240                    } else {
1241                        transparentRegionScreen = s.transparentRegion;
1242                    }
1243                    visibleRegion.subtractSelf(transparentRegionScreen);
1244                }
1245
1246                // compute the opaque region
1247                const int32_t layerOrientation = s.transform.getOrientation();
1248                if (s.alpha==255 && !translucent &&
1249                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
1250                    // the opaque region is the layer's footprint
1251                    opaqueRegion = visibleRegion;
1252                }
1253            }
1254        }
1255
1256        // Clip the covered region to the visible region
1257        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1258
1259        // Update aboveCoveredLayers for next (lower) layer
1260        aboveCoveredLayers.orSelf(visibleRegion);
1261
1262        // subtract the opaque region covered by the layers above us
1263        visibleRegion.subtractSelf(aboveOpaqueLayers);
1264
1265        // compute this layer's dirty region
1266        if (layer->contentDirty) {
1267            // we need to invalidate the whole region
1268            dirty = visibleRegion;
1269            // as well, as the old visible region
1270            dirty.orSelf(layer->visibleRegion);
1271            layer->contentDirty = false;
1272        } else {
1273            /* compute the exposed region:
1274             *   the exposed region consists of two components:
1275             *   1) what's VISIBLE now and was COVERED before
1276             *   2) what's EXPOSED now less what was EXPOSED before
1277             *
1278             * note that (1) is conservative, we start with the whole
1279             * visible region but only keep what used to be covered by
1280             * something -- which mean it may have been exposed.
1281             *
1282             * (2) handles areas that were not covered by anything but got
1283             * exposed because of a resize.
1284             */
1285            const Region newExposed = visibleRegion - coveredRegion;
1286            const Region oldVisibleRegion = layer->visibleRegion;
1287            const Region oldCoveredRegion = layer->coveredRegion;
1288            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1289            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1290        }
1291        dirty.subtractSelf(aboveOpaqueLayers);
1292
1293        // accumulate to the screen dirty region
1294        outDirtyRegion.orSelf(dirty);
1295
1296        // Update aboveOpaqueLayers for next (lower) layer
1297        aboveOpaqueLayers.orSelf(opaqueRegion);
1298
1299        // Store the visible region is screen space
1300        layer->setVisibleRegion(visibleRegion);
1301        layer->setCoveredRegion(coveredRegion);
1302    }
1303
1304    outOpaqueRegion = aboveOpaqueLayers;
1305}
1306
1307void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1308        const Region& dirty) {
1309    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1310        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1311        if (hw->getLayerStack() == layerStack) {
1312            hw->dirtyRegion.orSelf(dirty);
1313        }
1314    }
1315}
1316
1317void SurfaceFlinger::handlePageFlip()
1318{
1319    Region dirtyRegion;
1320
1321    bool visibleRegions = false;
1322    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1323    const size_t count = currentLayers.size();
1324    for (size_t i=0 ; i<count ; i++) {
1325        const sp<LayerBase>& layer(currentLayers[i]);
1326        const Region dirty(layer->latchBuffer(visibleRegions));
1327        const Layer::State& s(layer->drawingState());
1328        invalidateLayerStack(s.layerStack, dirty);
1329    }
1330
1331    mVisibleRegionsDirty |= visibleRegions;
1332}
1333
1334void SurfaceFlinger::invalidateHwcGeometry()
1335{
1336    mHwWorkListDirty = true;
1337}
1338
1339
1340void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1341        const Region& inDirtyRegion)
1342{
1343    Region dirtyRegion(inDirtyRegion);
1344
1345    // compute the invalid region
1346    hw->swapRegion.orSelf(dirtyRegion);
1347
1348    uint32_t flags = hw->getFlags();
1349    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1350        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1351        // takes a rectangle, we must make sure to update that whole
1352        // rectangle in that case
1353        dirtyRegion.set(hw->swapRegion.bounds());
1354    } else {
1355        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1356            // We need to redraw the rectangle that will be updated
1357            // (pushed to the framebuffer).
1358            // This is needed because PARTIAL_UPDATES only takes one
1359            // rectangle instead of a region (see DisplayDevice::flip())
1360            dirtyRegion.set(hw->swapRegion.bounds());
1361        } else {
1362            // we need to redraw everything (the whole screen)
1363            dirtyRegion.set(hw->bounds());
1364            hw->swapRegion = dirtyRegion;
1365        }
1366    }
1367
1368    doComposeSurfaces(hw, dirtyRegion);
1369
1370    // update the swap region and clear the dirty region
1371    hw->swapRegion.orSelf(dirtyRegion);
1372
1373    // swap buffers (presentation)
1374    hw->swapBuffers(getHwComposer());
1375}
1376
1377void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1378{
1379    const int32_t id = hw->getHwcDisplayId();
1380    HWComposer& hwc(getHwComposer());
1381    HWComposer::LayerListIterator cur = hwc.begin(id);
1382    const HWComposer::LayerListIterator end = hwc.end(id);
1383
1384    const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end);
1385    if (hasGlesComposition) {
1386        DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
1387
1388        // set the frame buffer
1389        glMatrixMode(GL_MODELVIEW);
1390        glLoadIdentity();
1391
1392        // Never touch the framebuffer if we don't have any framebuffer layers
1393        const bool hasHwcComposition = hwc.hasHwcComposition(id);
1394        if (hasHwcComposition) {
1395            // when using overlays, we assume a fully transparent framebuffer
1396            // NOTE: we could reduce how much we need to clear, for instance
1397            // remove where there are opaque FB layers. however, on some
1398            // GPUs doing a "clean slate" glClear might be more efficient.
1399            // We'll revisit later if needed.
1400            glClearColor(0, 0, 0, 0);
1401            glClear(GL_COLOR_BUFFER_BIT);
1402        } else {
1403            const Region region(hw->undefinedRegion.intersect(dirty));
1404            // screen is already cleared here
1405            if (!region.isEmpty()) {
1406                // can happen with SurfaceView
1407                drawWormhole(hw, region);
1408            }
1409        }
1410    }
1411
1412    /*
1413     * and then, render the layers targeted at the framebuffer
1414     */
1415
1416    const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
1417    const size_t count = layers.size();
1418    const Transform& tr = hw->getTransform();
1419    if (cur != end) {
1420        // we're using h/w composer
1421        for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1422            const sp<LayerBase>& layer(layers[i]);
1423            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1424            if (!clip.isEmpty()) {
1425                switch (cur->getCompositionType()) {
1426                    case HWC_OVERLAY: {
1427                        if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1428                                && i
1429                                && layer->isOpaque()
1430                                && hasGlesComposition) {
1431                            // never clear the very first layer since we're
1432                            // guaranteed the FB is already cleared
1433                            layer->clearWithOpenGL(hw, clip);
1434                        }
1435                        break;
1436                    }
1437                    case HWC_FRAMEBUFFER: {
1438                        layer->draw(hw, clip);
1439                        break;
1440                    }
1441                    case HWC_FRAMEBUFFER_TARGET: {
1442                        // this should not happen as the iterator shouldn't
1443                        // let us get there.
1444                        ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i);
1445                        break;
1446                    }
1447                }
1448            }
1449            layer->setAcquireFence(hw, *cur);
1450        }
1451    } else {
1452        // we're not using h/w composer
1453        for (size_t i=0 ; i<count ; ++i) {
1454            const sp<LayerBase>& layer(layers[i]);
1455            const Region clip(dirty.intersect(
1456                    tr.transform(layer->visibleRegion)));
1457            if (!clip.isEmpty()) {
1458                layer->draw(hw, clip);
1459            }
1460        }
1461    }
1462}
1463
1464void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw,
1465        const Region& region) const
1466{
1467    glDisable(GL_TEXTURE_EXTERNAL_OES);
1468    glDisable(GL_TEXTURE_2D);
1469    glDisable(GL_BLEND);
1470    glColor4f(0,0,0,0);
1471
1472    const int32_t height = hw->getHeight();
1473    Region::const_iterator it = region.begin();
1474    Region::const_iterator const end = region.end();
1475    while (it != end) {
1476        const Rect& r = *it++;
1477        GLfloat vertices[][2] = {
1478                { r.left,  height - r.top },
1479                { r.left,  height - r.bottom },
1480                { r.right, height - r.bottom },
1481                { r.right, height - r.top }
1482        };
1483        glVertexPointer(2, GL_FLOAT, 0, vertices);
1484        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1485    }
1486}
1487
1488ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1489        const sp<LayerBaseClient>& lbc)
1490{
1491    // attach this layer to the client
1492    size_t name = client->attachLayer(lbc);
1493
1494    // add this layer to the current state list
1495    Mutex::Autolock _l(mStateLock);
1496    mCurrentState.layersSortedByZ.add(lbc);
1497
1498    return ssize_t(name);
1499}
1500
1501status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1502{
1503    Mutex::Autolock _l(mStateLock);
1504    status_t err = purgatorizeLayer_l(layer);
1505    if (err == NO_ERROR)
1506        setTransactionFlags(eTransactionNeeded);
1507    return err;
1508}
1509
1510status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1511{
1512    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1513    if (index >= 0) {
1514        mLayersRemoved = true;
1515        return NO_ERROR;
1516    }
1517    return status_t(index);
1518}
1519
1520status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1521{
1522    // First add the layer to the purgatory list, which makes sure it won't
1523    // go away, then remove it from the main list (through a transaction).
1524    ssize_t err = removeLayer_l(layerBase);
1525    if (err >= 0) {
1526        mLayerPurgatory.add(layerBase);
1527    }
1528
1529    mLayersPendingRemoval.push(layerBase);
1530
1531    // it's possible that we don't find a layer, because it might
1532    // have been destroyed already -- this is not technically an error
1533    // from the user because there is a race between Client::destroySurface(),
1534    // ~Client() and ~ISurface().
1535    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1536}
1537
1538uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1539{
1540    return android_atomic_release_load(&mTransactionFlags);
1541}
1542
1543uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1544{
1545    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1546}
1547
1548uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1549{
1550    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1551    if ((old & flags)==0) { // wake the server up
1552        signalTransaction();
1553    }
1554    return old;
1555}
1556
1557void SurfaceFlinger::setTransactionState(
1558        const Vector<ComposerState>& state,
1559        const Vector<DisplayState>& displays,
1560        uint32_t flags)
1561{
1562    Mutex::Autolock _l(mStateLock);
1563    uint32_t transactionFlags = 0;
1564
1565    size_t count = displays.size();
1566    for (size_t i=0 ; i<count ; i++) {
1567        const DisplayState& s(displays[i]);
1568        transactionFlags |= setDisplayStateLocked(s);
1569    }
1570
1571    count = state.size();
1572    for (size_t i=0 ; i<count ; i++) {
1573        const ComposerState& s(state[i]);
1574        sp<Client> client( static_cast<Client *>(s.client.get()) );
1575        transactionFlags |= setClientStateLocked(client, s.state);
1576    }
1577
1578    if (transactionFlags) {
1579        // this triggers the transaction
1580        setTransactionFlags(transactionFlags);
1581
1582        // if this is a synchronous transaction, wait for it to take effect
1583        // before returning.
1584        if (flags & eSynchronous) {
1585            mTransationPending = true;
1586        }
1587        while (mTransationPending) {
1588            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1589            if (CC_UNLIKELY(err != NO_ERROR)) {
1590                // just in case something goes wrong in SF, return to the
1591                // called after a few seconds.
1592                ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1593                mTransationPending = false;
1594                break;
1595            }
1596        }
1597    }
1598}
1599
1600uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1601{
1602    uint32_t flags = 0;
1603    DisplayDeviceState& disp(mCurrentState.displays.editValueFor(s.token));
1604    if (disp.isValid()) {
1605        const uint32_t what = s.what;
1606        if (what & DisplayState::eSurfaceChanged) {
1607            if (disp.surface->asBinder() != s.surface->asBinder()) {
1608                disp.surface = s.surface;
1609                flags |= eDisplayTransactionNeeded;
1610            }
1611        }
1612        if (what & DisplayState::eLayerStackChanged) {
1613            if (disp.layerStack != s.layerStack) {
1614                disp.layerStack = s.layerStack;
1615                flags |= eDisplayTransactionNeeded;
1616            }
1617        }
1618        if (what & DisplayState::eDisplayProjectionChanged) {
1619            if (disp.orientation != s.orientation) {
1620                disp.orientation = s.orientation;
1621                flags |= eDisplayTransactionNeeded;
1622            }
1623            if (disp.frame != s.frame) {
1624                disp.frame = s.frame;
1625                flags |= eDisplayTransactionNeeded;
1626            }
1627            if (disp.viewport != s.viewport) {
1628                disp.viewport = s.viewport;
1629                flags |= eDisplayTransactionNeeded;
1630            }
1631        }
1632    }
1633    return flags;
1634}
1635
1636uint32_t SurfaceFlinger::setClientStateLocked(
1637        const sp<Client>& client,
1638        const layer_state_t& s)
1639{
1640    uint32_t flags = 0;
1641    sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1642    if (layer != 0) {
1643        const uint32_t what = s.what;
1644        if (what & layer_state_t::ePositionChanged) {
1645            if (layer->setPosition(s.x, s.y))
1646                flags |= eTraversalNeeded;
1647        }
1648        if (what & layer_state_t::eLayerChanged) {
1649            // NOTE: index needs to be calculated before we update the state
1650            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1651            if (layer->setLayer(s.z)) {
1652                mCurrentState.layersSortedByZ.removeAt(idx);
1653                mCurrentState.layersSortedByZ.add(layer);
1654                // we need traversal (state changed)
1655                // AND transaction (list changed)
1656                flags |= eTransactionNeeded|eTraversalNeeded;
1657            }
1658        }
1659        if (what & layer_state_t::eSizeChanged) {
1660            if (layer->setSize(s.w, s.h)) {
1661                flags |= eTraversalNeeded;
1662            }
1663        }
1664        if (what & layer_state_t::eAlphaChanged) {
1665            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1666                flags |= eTraversalNeeded;
1667        }
1668        if (what & layer_state_t::eMatrixChanged) {
1669            if (layer->setMatrix(s.matrix))
1670                flags |= eTraversalNeeded;
1671        }
1672        if (what & layer_state_t::eTransparentRegionChanged) {
1673            if (layer->setTransparentRegionHint(s.transparentRegion))
1674                flags |= eTraversalNeeded;
1675        }
1676        if (what & layer_state_t::eVisibilityChanged) {
1677            if (layer->setFlags(s.flags, s.mask))
1678                flags |= eTraversalNeeded;
1679        }
1680        if (what & layer_state_t::eCropChanged) {
1681            if (layer->setCrop(s.crop))
1682                flags |= eTraversalNeeded;
1683        }
1684        if (what & layer_state_t::eLayerStackChanged) {
1685            // NOTE: index needs to be calculated before we update the state
1686            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1687            if (layer->setLayerStack(s.layerStack)) {
1688                mCurrentState.layersSortedByZ.removeAt(idx);
1689                mCurrentState.layersSortedByZ.add(layer);
1690                // we need traversal (state changed)
1691                // AND transaction (list changed)
1692                flags |= eTransactionNeeded|eTraversalNeeded;
1693            }
1694        }
1695    }
1696    return flags;
1697}
1698
1699sp<ISurface> SurfaceFlinger::createLayer(
1700        ISurfaceComposerClient::surface_data_t* params,
1701        const String8& name,
1702        const sp<Client>& client,
1703       uint32_t w, uint32_t h, PixelFormat format,
1704        uint32_t flags)
1705{
1706    sp<LayerBaseClient> layer;
1707    sp<ISurface> surfaceHandle;
1708
1709    if (int32_t(w|h) < 0) {
1710        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1711                int(w), int(h));
1712        return surfaceHandle;
1713    }
1714
1715    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1716    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1717        case ISurfaceComposerClient::eFXSurfaceNormal:
1718            layer = createNormalLayer(client, w, h, flags, format);
1719            break;
1720        case ISurfaceComposerClient::eFXSurfaceBlur:
1721        case ISurfaceComposerClient::eFXSurfaceDim:
1722            layer = createDimLayer(client, w, h, flags);
1723            break;
1724        case ISurfaceComposerClient::eFXSurfaceScreenshot:
1725            layer = createScreenshotLayer(client, w, h, flags);
1726            break;
1727    }
1728
1729    if (layer != 0) {
1730        layer->initStates(w, h, flags);
1731        layer->setName(name);
1732        ssize_t token = addClientLayer(client, layer);
1733        surfaceHandle = layer->getSurface();
1734        if (surfaceHandle != 0) {
1735            params->token = token;
1736            params->identity = layer->getIdentity();
1737        }
1738        setTransactionFlags(eTransactionNeeded);
1739    }
1740
1741    return surfaceHandle;
1742}
1743
1744sp<Layer> SurfaceFlinger::createNormalLayer(
1745        const sp<Client>& client,
1746        uint32_t w, uint32_t h, uint32_t flags,
1747        PixelFormat& format)
1748{
1749    // initialize the surfaces
1750    switch (format) {
1751    case PIXEL_FORMAT_TRANSPARENT:
1752    case PIXEL_FORMAT_TRANSLUCENT:
1753        format = PIXEL_FORMAT_RGBA_8888;
1754        break;
1755    case PIXEL_FORMAT_OPAQUE:
1756#ifdef NO_RGBX_8888
1757        format = PIXEL_FORMAT_RGB_565;
1758#else
1759        format = PIXEL_FORMAT_RGBX_8888;
1760#endif
1761        break;
1762    }
1763
1764#ifdef NO_RGBX_8888
1765    if (format == PIXEL_FORMAT_RGBX_8888)
1766        format = PIXEL_FORMAT_RGBA_8888;
1767#endif
1768
1769    sp<Layer> layer = new Layer(this, client);
1770    status_t err = layer->setBuffers(w, h, format, flags);
1771    if (CC_LIKELY(err != NO_ERROR)) {
1772        ALOGE("createNormalLayer() failed (%s)", strerror(-err));
1773        layer.clear();
1774    }
1775    return layer;
1776}
1777
1778sp<LayerDim> SurfaceFlinger::createDimLayer(
1779        const sp<Client>& client,
1780        uint32_t w, uint32_t h, uint32_t flags)
1781{
1782    sp<LayerDim> layer = new LayerDim(this, client);
1783    return layer;
1784}
1785
1786sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer(
1787        const sp<Client>& client,
1788        uint32_t w, uint32_t h, uint32_t flags)
1789{
1790    sp<LayerScreenshot> layer = new LayerScreenshot(this, client);
1791    return layer;
1792}
1793
1794status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid)
1795{
1796    /*
1797     * called by the window manager, when a surface should be marked for
1798     * destruction.
1799     *
1800     * The surface is removed from the current and drawing lists, but placed
1801     * in the purgatory queue, so it's not destroyed right-away (we need
1802     * to wait for all client's references to go away first).
1803     */
1804
1805    status_t err = NAME_NOT_FOUND;
1806    Mutex::Autolock _l(mStateLock);
1807    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1808
1809    if (layer != 0) {
1810        err = purgatorizeLayer_l(layer);
1811        if (err == NO_ERROR) {
1812            setTransactionFlags(eTransactionNeeded);
1813        }
1814    }
1815    return err;
1816}
1817
1818status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer)
1819{
1820    // called by ~ISurface() when all references are gone
1821    status_t err = NO_ERROR;
1822    sp<LayerBaseClient> l(layer.promote());
1823    if (l != NULL) {
1824        Mutex::Autolock _l(mStateLock);
1825        err = removeLayer_l(l);
1826        if (err == NAME_NOT_FOUND) {
1827            // The surface wasn't in the current list, which means it was
1828            // removed already, which means it is in the purgatory,
1829            // and need to be removed from there.
1830            ssize_t idx = mLayerPurgatory.remove(l);
1831            ALOGE_IF(idx < 0,
1832                    "layer=%p is not in the purgatory list", l.get());
1833        }
1834        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1835                "error removing layer=%p (%s)", l.get(), strerror(-err));
1836    }
1837    return err;
1838}
1839
1840// ---------------------------------------------------------------------------
1841
1842void SurfaceFlinger::onInitializeDisplays() {
1843    // reset screen orientation
1844    Vector<ComposerState> state;
1845    Vector<DisplayState> displays;
1846    DisplayState d;
1847    d.what = DisplayState::eDisplayProjectionChanged;
1848    d.token = mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY];
1849    d.orientation = DisplayState::eOrientationDefault;
1850    d.frame.makeInvalid();
1851    d.viewport.makeInvalid();
1852    displays.add(d);
1853    setTransactionState(state, displays, 0);
1854    onScreenAcquired(getDefaultDisplayDevice());
1855}
1856
1857void SurfaceFlinger::initializeDisplays() {
1858    class MessageScreenInitialized : public MessageBase {
1859        SurfaceFlinger* flinger;
1860    public:
1861        MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
1862        virtual bool handler() {
1863            flinger->onInitializeDisplays();
1864            return true;
1865        }
1866    };
1867    sp<MessageBase> msg = new MessageScreenInitialized(this);
1868    postMessageAsync(msg);  // we may be called from main thread, use async message
1869}
1870
1871
1872void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) {
1873    ALOGD("Screen about to return, flinger = %p", this);
1874    getHwComposer().acquire();
1875    hw->acquireScreen();
1876    if (hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1877        // FIXME: eventthread only knows about the main display right now
1878        mEventThread->onScreenAcquired();
1879    }
1880    mVisibleRegionsDirty = true;
1881    repaintEverything();
1882}
1883
1884void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) {
1885    ALOGD("About to give-up screen, flinger = %p", this);
1886    if (hw->isScreenAcquired()) {
1887        if (hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1888            // FIXME: eventthread only knows about the main display right now
1889            mEventThread->onScreenReleased();
1890        }
1891        hw->releaseScreen();
1892        getHwComposer().release();
1893        mVisibleRegionsDirty = true;
1894        // from this point on, SF will stop drawing
1895    }
1896}
1897
1898void SurfaceFlinger::unblank() {
1899    class MessageScreenAcquired : public MessageBase {
1900        SurfaceFlinger* flinger;
1901    public:
1902        MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { }
1903        virtual bool handler() {
1904            // FIXME: should this be per-display?
1905            flinger->onScreenAcquired(flinger->getDefaultDisplayDevice());
1906            return true;
1907        }
1908    };
1909    sp<MessageBase> msg = new MessageScreenAcquired(this);
1910    postMessageSync(msg);
1911}
1912
1913void SurfaceFlinger::blank() {
1914    class MessageScreenReleased : public MessageBase {
1915        SurfaceFlinger* flinger;
1916    public:
1917        MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { }
1918        virtual bool handler() {
1919            // FIXME: should this be per-display?
1920            flinger->onScreenReleased(flinger->getDefaultDisplayDevice());
1921            return true;
1922        }
1923    };
1924    sp<MessageBase> msg = new MessageScreenReleased(this);
1925    postMessageSync(msg);
1926}
1927
1928// ---------------------------------------------------------------------------
1929
1930status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1931{
1932    const size_t SIZE = 4096;
1933    char buffer[SIZE];
1934    String8 result;
1935
1936    if (!PermissionCache::checkCallingPermission(sDump)) {
1937        snprintf(buffer, SIZE, "Permission Denial: "
1938                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1939                IPCThreadState::self()->getCallingPid(),
1940                IPCThreadState::self()->getCallingUid());
1941        result.append(buffer);
1942    } else {
1943        // Try to get the main lock, but don't insist if we can't
1944        // (this would indicate SF is stuck, but we want to be able to
1945        // print something in dumpsys).
1946        int retry = 3;
1947        while (mStateLock.tryLock()<0 && --retry>=0) {
1948            usleep(1000000);
1949        }
1950        const bool locked(retry >= 0);
1951        if (!locked) {
1952            snprintf(buffer, SIZE,
1953                    "SurfaceFlinger appears to be unresponsive, "
1954                    "dumping anyways (no locks held)\n");
1955            result.append(buffer);
1956        }
1957
1958        bool dumpAll = true;
1959        size_t index = 0;
1960        size_t numArgs = args.size();
1961        if (numArgs) {
1962            if ((index < numArgs) &&
1963                    (args[index] == String16("--list"))) {
1964                index++;
1965                listLayersLocked(args, index, result, buffer, SIZE);
1966                dumpAll = false;
1967            }
1968
1969            if ((index < numArgs) &&
1970                    (args[index] == String16("--latency"))) {
1971                index++;
1972                dumpStatsLocked(args, index, result, buffer, SIZE);
1973                dumpAll = false;
1974            }
1975
1976            if ((index < numArgs) &&
1977                    (args[index] == String16("--latency-clear"))) {
1978                index++;
1979                clearStatsLocked(args, index, result, buffer, SIZE);
1980                dumpAll = false;
1981            }
1982        }
1983
1984        if (dumpAll) {
1985            dumpAllLocked(result, buffer, SIZE);
1986        }
1987
1988        if (locked) {
1989            mStateLock.unlock();
1990        }
1991    }
1992    write(fd, result.string(), result.size());
1993    return NO_ERROR;
1994}
1995
1996void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
1997        String8& result, char* buffer, size_t SIZE) const
1998{
1999    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2000    const size_t count = currentLayers.size();
2001    for (size_t i=0 ; i<count ; i++) {
2002        const sp<LayerBase>& layer(currentLayers[i]);
2003        snprintf(buffer, SIZE, "%s\n", layer->getName().string());
2004        result.append(buffer);
2005    }
2006}
2007
2008void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2009        String8& result, char* buffer, size_t SIZE) const
2010{
2011    String8 name;
2012    if (index < args.size()) {
2013        name = String8(args[index]);
2014        index++;
2015    }
2016
2017    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2018    const size_t count = currentLayers.size();
2019    for (size_t i=0 ; i<count ; i++) {
2020        const sp<LayerBase>& layer(currentLayers[i]);
2021        if (name.isEmpty()) {
2022            snprintf(buffer, SIZE, "%s\n", layer->getName().string());
2023            result.append(buffer);
2024        }
2025        if (name.isEmpty() || (name == layer->getName())) {
2026            layer->dumpStats(result, buffer, SIZE);
2027        }
2028    }
2029}
2030
2031void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2032        String8& result, char* buffer, size_t SIZE) const
2033{
2034    String8 name;
2035    if (index < args.size()) {
2036        name = String8(args[index]);
2037        index++;
2038    }
2039
2040    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2041    const size_t count = currentLayers.size();
2042    for (size_t i=0 ; i<count ; i++) {
2043        const sp<LayerBase>& layer(currentLayers[i]);
2044        if (name.isEmpty() || (name == layer->getName())) {
2045            layer->clearStats();
2046        }
2047    }
2048}
2049
2050/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2051{
2052    static const char* config =
2053            " [sf"
2054#ifdef NO_RGBX_8888
2055            " NO_RGBX_8888"
2056#endif
2057#ifdef HAS_CONTEXT_PRIORITY
2058            " HAS_CONTEXT_PRIORITY"
2059#endif
2060#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2061            " NEVER_DEFAULT_TO_ASYNC_MODE"
2062#endif
2063#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2064            " TARGET_DISABLE_TRIPLE_BUFFERING"
2065#endif
2066            "]";
2067    result.append(config);
2068}
2069
2070void SurfaceFlinger::dumpAllLocked(
2071        String8& result, char* buffer, size_t SIZE) const
2072{
2073    // figure out if we're stuck somewhere
2074    const nsecs_t now = systemTime();
2075    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2076    const nsecs_t inTransaction(mDebugInTransaction);
2077    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2078    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2079
2080    /*
2081     * Dump library configuration.
2082     */
2083    result.append("Build configuration:");
2084    appendSfConfigString(result);
2085    appendUiConfigString(result);
2086    appendGuiConfigString(result);
2087    result.append("\n");
2088
2089    /*
2090     * Dump the visible layer list
2091     */
2092    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2093    const size_t count = currentLayers.size();
2094    snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
2095    result.append(buffer);
2096    for (size_t i=0 ; i<count ; i++) {
2097        const sp<LayerBase>& layer(currentLayers[i]);
2098        layer->dump(result, buffer, SIZE);
2099    }
2100
2101    /*
2102     * Dump the layers in the purgatory
2103     */
2104
2105    const size_t purgatorySize = mLayerPurgatory.size();
2106    snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
2107    result.append(buffer);
2108    for (size_t i=0 ; i<purgatorySize ; i++) {
2109        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
2110        layer->shortDump(result, buffer, SIZE);
2111    }
2112
2113    /*
2114     * Dump Display state
2115     */
2116
2117    snprintf(buffer, SIZE, "Displays (%d entries)\n", mDisplays.size());
2118    result.append(buffer);
2119    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2120        const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2121        hw->dump(result, buffer, SIZE);
2122    }
2123
2124    /*
2125     * Dump SurfaceFlinger global state
2126     */
2127
2128    snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
2129    result.append(buffer);
2130
2131    HWComposer& hwc(getHwComposer());
2132    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2133    const GLExtensions& extensions(GLExtensions::getInstance());
2134    snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
2135            extensions.getVendor(),
2136            extensions.getRenderer(),
2137            extensions.getVersion());
2138    result.append(buffer);
2139
2140    snprintf(buffer, SIZE, "EGL : %s\n",
2141            eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID));
2142    result.append(buffer);
2143
2144    snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
2145    result.append(buffer);
2146
2147    hw->undefinedRegion.dump(result, "undefinedRegion");
2148    snprintf(buffer, SIZE,
2149            "  orientation=%d, canDraw=%d\n",
2150            hw->getOrientation(), hw->canDraw());
2151    result.append(buffer);
2152    snprintf(buffer, SIZE,
2153            "  last eglSwapBuffers() time: %f us\n"
2154            "  last transaction time     : %f us\n"
2155            "  transaction-flags         : %08x\n"
2156            "  refresh-rate              : %f fps\n"
2157            "  x-dpi                     : %f\n"
2158            "  y-dpi                     : %f\n",
2159            mLastSwapBufferTime/1000.0,
2160            mLastTransactionTime/1000.0,
2161            mTransactionFlags,
2162            1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2163            hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2164            hwc.getDpiY(HWC_DISPLAY_PRIMARY));
2165    result.append(buffer);
2166
2167    snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
2168            inSwapBuffersDuration/1000.0);
2169    result.append(buffer);
2170
2171    snprintf(buffer, SIZE, "  transaction time: %f us\n",
2172            inTransactionDuration/1000.0);
2173    result.append(buffer);
2174
2175    /*
2176     * VSYNC state
2177     */
2178    mEventThread->dump(result, buffer, SIZE);
2179
2180    /*
2181     * Dump HWComposer state
2182     */
2183    snprintf(buffer, SIZE, "h/w composer state:\n");
2184    result.append(buffer);
2185    snprintf(buffer, SIZE, "  h/w composer %s and %s\n",
2186            hwc.initCheck()==NO_ERROR ? "present" : "not present",
2187                    (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
2188    result.append(buffer);
2189    hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ());
2190
2191    /*
2192     * Dump gralloc state
2193     */
2194    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2195    alloc.dump(result);
2196}
2197
2198bool SurfaceFlinger::startDdmConnection()
2199{
2200    void* libddmconnection_dso =
2201            dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2202    if (!libddmconnection_dso) {
2203        return false;
2204    }
2205    void (*DdmConnection_start)(const char* name);
2206    DdmConnection_start =
2207            (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2208    if (!DdmConnection_start) {
2209        dlclose(libddmconnection_dso);
2210        return false;
2211    }
2212    (*DdmConnection_start)(getServiceName());
2213    return true;
2214}
2215
2216status_t SurfaceFlinger::onTransact(
2217    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2218{
2219    switch (code) {
2220        case CREATE_CONNECTION:
2221        case SET_TRANSACTION_STATE:
2222        case BOOT_FINISHED:
2223        case BLANK:
2224        case UNBLANK:
2225        {
2226            // codes that require permission check
2227            IPCThreadState* ipc = IPCThreadState::self();
2228            const int pid = ipc->getCallingPid();
2229            const int uid = ipc->getCallingUid();
2230            if ((uid != AID_GRAPHICS) &&
2231                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2232                ALOGE("Permission Denial: "
2233                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2234                return PERMISSION_DENIED;
2235            }
2236            break;
2237        }
2238        case CAPTURE_SCREEN:
2239        {
2240            // codes that require permission check
2241            IPCThreadState* ipc = IPCThreadState::self();
2242            const int pid = ipc->getCallingPid();
2243            const int uid = ipc->getCallingUid();
2244            if ((uid != AID_GRAPHICS) &&
2245                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2246                ALOGE("Permission Denial: "
2247                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
2248                return PERMISSION_DENIED;
2249            }
2250            break;
2251        }
2252    }
2253
2254    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2255    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2256        CHECK_INTERFACE(ISurfaceComposer, data, reply);
2257        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2258            IPCThreadState* ipc = IPCThreadState::self();
2259            const int pid = ipc->getCallingPid();
2260            const int uid = ipc->getCallingUid();
2261            ALOGE("Permission Denial: "
2262                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2263            return PERMISSION_DENIED;
2264        }
2265        int n;
2266        switch (code) {
2267            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2268            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2269                return NO_ERROR;
2270            case 1002:  // SHOW_UPDATES
2271                n = data.readInt32();
2272                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2273                invalidateHwcGeometry();
2274                repaintEverything();
2275                return NO_ERROR;
2276            case 1004:{ // repaint everything
2277                repaintEverything();
2278                return NO_ERROR;
2279            }
2280            case 1005:{ // force transaction
2281                setTransactionFlags(
2282                        eTransactionNeeded|
2283                        eDisplayTransactionNeeded|
2284                        eTraversalNeeded);
2285                return NO_ERROR;
2286            }
2287            case 1006:{ // send empty update
2288                signalRefresh();
2289                return NO_ERROR;
2290            }
2291            case 1008:  // toggle use of hw composer
2292                n = data.readInt32();
2293                mDebugDisableHWC = n ? 1 : 0;
2294                invalidateHwcGeometry();
2295                repaintEverything();
2296                return NO_ERROR;
2297            case 1009:  // toggle use of transform hint
2298                n = data.readInt32();
2299                mDebugDisableTransformHint = n ? 1 : 0;
2300                invalidateHwcGeometry();
2301                repaintEverything();
2302                return NO_ERROR;
2303            case 1010:  // interrogate.
2304                reply->writeInt32(0);
2305                reply->writeInt32(0);
2306                reply->writeInt32(mDebugRegion);
2307                reply->writeInt32(0);
2308                reply->writeInt32(mDebugDisableHWC);
2309                return NO_ERROR;
2310            case 1013: {
2311                Mutex::Autolock _l(mStateLock);
2312                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2313                reply->writeInt32(hw->getPageFlipCount());
2314            }
2315            return NO_ERROR;
2316        }
2317    }
2318    return err;
2319}
2320
2321void SurfaceFlinger::repaintEverything() {
2322    android_atomic_or(1, &mRepaintEverything);
2323    signalTransaction();
2324}
2325
2326// ---------------------------------------------------------------------------
2327
2328status_t SurfaceFlinger::renderScreenToTexture(uint32_t layerStack,
2329        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2330{
2331    Mutex::Autolock _l(mStateLock);
2332    return renderScreenToTextureLocked(layerStack, textureName, uOut, vOut);
2333}
2334
2335status_t SurfaceFlinger::renderScreenToTextureLocked(uint32_t layerStack,
2336        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2337{
2338    ATRACE_CALL();
2339
2340    if (!GLExtensions::getInstance().haveFramebufferObject())
2341        return INVALID_OPERATION;
2342
2343    // get screen geometry
2344    // FIXME: figure out what it means to have a screenshot texture w/ multi-display
2345    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2346    const uint32_t hw_w = hw->getWidth();
2347    const uint32_t hw_h = hw->getHeight();
2348    GLfloat u = 1;
2349    GLfloat v = 1;
2350
2351    // make sure to clear all GL error flags
2352    while ( glGetError() != GL_NO_ERROR ) ;
2353
2354    // create a FBO
2355    GLuint name, tname;
2356    glGenTextures(1, &tname);
2357    glBindTexture(GL_TEXTURE_2D, tname);
2358    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2359    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2360    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2361            hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2362    if (glGetError() != GL_NO_ERROR) {
2363        while ( glGetError() != GL_NO_ERROR ) ;
2364        GLint tw = (2 << (31 - clz(hw_w)));
2365        GLint th = (2 << (31 - clz(hw_h)));
2366        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2367                tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2368        u = GLfloat(hw_w) / tw;
2369        v = GLfloat(hw_h) / th;
2370    }
2371    glGenFramebuffersOES(1, &name);
2372    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2373    glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
2374            GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
2375
2376    // redraw the screen entirely...
2377    glDisable(GL_TEXTURE_EXTERNAL_OES);
2378    glDisable(GL_TEXTURE_2D);
2379    glClearColor(0,0,0,1);
2380    glClear(GL_COLOR_BUFFER_BIT);
2381    glMatrixMode(GL_MODELVIEW);
2382    glLoadIdentity();
2383    const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2384    const size_t count = layers.size();
2385    for (size_t i=0 ; i<count ; ++i) {
2386        const sp<LayerBase>& layer(layers[i]);
2387        layer->draw(hw);
2388    }
2389
2390    hw->compositionComplete();
2391
2392    // back to main framebuffer
2393    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2394    glDeleteFramebuffersOES(1, &name);
2395
2396    *textureName = tname;
2397    *uOut = u;
2398    *vOut = v;
2399    return NO_ERROR;
2400}
2401
2402// ---------------------------------------------------------------------------
2403
2404status_t SurfaceFlinger::captureScreenImplLocked(const sp<IBinder>& display,
2405        sp<IMemoryHeap>* heap,
2406        uint32_t* w, uint32_t* h, PixelFormat* f,
2407        uint32_t sw, uint32_t sh,
2408        uint32_t minLayerZ, uint32_t maxLayerZ)
2409{
2410    ATRACE_CALL();
2411
2412    status_t result = PERMISSION_DENIED;
2413
2414    if (!GLExtensions::getInstance().haveFramebufferObject()) {
2415        return INVALID_OPERATION;
2416    }
2417
2418    // get screen geometry
2419    sp<const DisplayDevice> hw(getDisplayDevice(display));
2420    const uint32_t hw_w = hw->getWidth();
2421    const uint32_t hw_h = hw->getHeight();
2422
2423    // if we have secure windows on this display, never allow the screen capture
2424    if (hw->getSecureLayerVisible()) {
2425        ALOGW("FB is protected: PERMISSION_DENIED");
2426        return PERMISSION_DENIED;
2427    }
2428
2429    if ((sw > hw_w) || (sh > hw_h)) {
2430        ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h);
2431        return BAD_VALUE;
2432    }
2433
2434    sw = (!sw) ? hw_w : sw;
2435    sh = (!sh) ? hw_h : sh;
2436    const size_t size = sw * sh * 4;
2437    const bool filtering = sw != hw_w || sh != hw_h;
2438
2439//    ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2440//            sw, sh, minLayerZ, maxLayerZ);
2441
2442    // make sure to clear all GL error flags
2443    while ( glGetError() != GL_NO_ERROR ) ;
2444
2445    // create a FBO
2446    GLuint name, tname;
2447    glGenRenderbuffersOES(1, &tname);
2448    glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2449    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2450
2451    glGenFramebuffersOES(1, &name);
2452    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2453    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2454            GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2455
2456    GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2457
2458    if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2459
2460        // invert everything, b/c glReadPixel() below will invert the FB
2461        glViewport(0, 0, sw, sh);
2462        glMatrixMode(GL_PROJECTION);
2463        glPushMatrix();
2464        glLoadIdentity();
2465        glOrthof(0, hw_w, hw_h, 0, 0, 1);
2466        glMatrixMode(GL_MODELVIEW);
2467
2468        // redraw the screen entirely...
2469        glClearColor(0,0,0,1);
2470        glClear(GL_COLOR_BUFFER_BIT);
2471
2472        const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2473        const size_t count = layers.size();
2474        for (size_t i=0 ; i<count ; ++i) {
2475            const sp<LayerBase>& layer(layers[i]);
2476            const uint32_t z = layer->drawingState().z;
2477            if (z >= minLayerZ && z <= maxLayerZ) {
2478                if (filtering) layer->setFiltering(true);
2479                layer->draw(hw);
2480                if (filtering) layer->setFiltering(false);
2481            }
2482        }
2483
2484        // check for errors and return screen capture
2485        if (glGetError() != GL_NO_ERROR) {
2486            // error while rendering
2487            result = INVALID_OPERATION;
2488        } else {
2489            // allocate shared memory large enough to hold the
2490            // screen capture
2491            sp<MemoryHeapBase> base(
2492                    new MemoryHeapBase(size, 0, "screen-capture") );
2493            void* const ptr = base->getBase();
2494            if (ptr) {
2495                // capture the screen with glReadPixels()
2496                ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2497                glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2498                if (glGetError() == GL_NO_ERROR) {
2499                    *heap = base;
2500                    *w = sw;
2501                    *h = sh;
2502                    *f = PIXEL_FORMAT_RGBA_8888;
2503                    result = NO_ERROR;
2504                }
2505            } else {
2506                result = NO_MEMORY;
2507            }
2508        }
2509        glViewport(0, 0, hw_w, hw_h);
2510        glMatrixMode(GL_PROJECTION);
2511        glPopMatrix();
2512        glMatrixMode(GL_MODELVIEW);
2513    } else {
2514        result = BAD_VALUE;
2515    }
2516
2517    // release FBO resources
2518    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2519    glDeleteRenderbuffersOES(1, &tname);
2520    glDeleteFramebuffersOES(1, &name);
2521
2522    hw->compositionComplete();
2523
2524//    ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2525
2526    return result;
2527}
2528
2529
2530status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2531        sp<IMemoryHeap>* heap,
2532        uint32_t* width, uint32_t* height, PixelFormat* format,
2533        uint32_t sw, uint32_t sh,
2534        uint32_t minLayerZ, uint32_t maxLayerZ)
2535{
2536    if (CC_UNLIKELY(display == 0))
2537        return BAD_VALUE;
2538
2539    if (!GLExtensions::getInstance().haveFramebufferObject())
2540        return INVALID_OPERATION;
2541
2542    class MessageCaptureScreen : public MessageBase {
2543        SurfaceFlinger* flinger;
2544        sp<IBinder> display;
2545        sp<IMemoryHeap>* heap;
2546        uint32_t* w;
2547        uint32_t* h;
2548        PixelFormat* f;
2549        uint32_t sw;
2550        uint32_t sh;
2551        uint32_t minLayerZ;
2552        uint32_t maxLayerZ;
2553        status_t result;
2554    public:
2555        MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display,
2556                sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2557                uint32_t sw, uint32_t sh,
2558                uint32_t minLayerZ, uint32_t maxLayerZ)
2559            : flinger(flinger), display(display),
2560              heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2561              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2562              result(PERMISSION_DENIED)
2563        {
2564        }
2565        status_t getResult() const {
2566            return result;
2567        }
2568        virtual bool handler() {
2569            Mutex::Autolock _l(flinger->mStateLock);
2570            result = flinger->captureScreenImplLocked(display,
2571                    heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2572            return true;
2573        }
2574    };
2575
2576    sp<MessageBase> msg = new MessageCaptureScreen(this,
2577            display, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2578    status_t res = postMessageSync(msg);
2579    if (res == NO_ERROR) {
2580        res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2581    }
2582    return res;
2583}
2584
2585// ---------------------------------------------------------------------------
2586
2587SurfaceFlinger::LayerVector::LayerVector() {
2588}
2589
2590SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2591    : SortedVector<sp<LayerBase> >(rhs) {
2592}
2593
2594int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2595    const void* rhs) const
2596{
2597    // sort layers per layer-stack, then by z-order and finally by sequence
2598    const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
2599    const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
2600
2601    uint32_t ls = l->currentState().layerStack;
2602    uint32_t rs = r->currentState().layerStack;
2603    if (ls != rs)
2604        return ls - rs;
2605
2606    uint32_t lz = l->currentState().z;
2607    uint32_t rz = r->currentState().z;
2608    if (lz != rz)
2609        return lz - rz;
2610
2611    return l->sequence - r->sequence;
2612}
2613
2614// ---------------------------------------------------------------------------
2615
2616SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2617    : type(DisplayDevice::DISPLAY_ID_INVALID) {
2618}
2619
2620SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
2621    : type(type), layerStack(0), orientation(0) {
2622    viewport.makeInvalid();
2623    frame.makeInvalid();
2624}
2625
2626// ---------------------------------------------------------------------------
2627
2628}; // namespace android
2629