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