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