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