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