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