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