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