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