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