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