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