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