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