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