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