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