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