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