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