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