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