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