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