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