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