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