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