SurfaceFlinger.cpp revision 9a78c90cd46b2a3bd637b056873149d3b94384b4
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        mHwWorkListDirty = true;
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            mHwWorkListDirty = true;
735        }
736
737    unlockPageFlip(currentLayers);
738    mDirtyRegion.andSelf(screenRegion);
739}
740
741bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
742{
743    bool recomputeVisibleRegions = false;
744    size_t count = currentLayers.size();
745    sp<LayerBase> const* layers = currentLayers.array();
746    for (size_t i=0 ; i<count ; i++) {
747        const sp<LayerBase>& layer(layers[i]);
748        layer->lockPageFlip(recomputeVisibleRegions);
749    }
750    return recomputeVisibleRegions;
751}
752
753void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
754{
755    const GraphicPlane& plane(graphicPlane(0));
756    const Transform& planeTransform(plane.transform());
757    size_t count = currentLayers.size();
758    sp<LayerBase> const* layers = currentLayers.array();
759    for (size_t i=0 ; i<count ; i++) {
760        const sp<LayerBase>& layer(layers[i]);
761        layer->unlockPageFlip(planeTransform, mDirtyRegion);
762    }
763}
764
765void SurfaceFlinger::handleWorkList()
766{
767    mHwWorkListDirty = false;
768    HWComposer& hwc(graphicPlane(0).displayHardware().getHwComposer());
769    if (hwc.initCheck() == NO_ERROR) {
770        const Vector< sp<LayerBase> >& currentLayers(mVisibleLayersSortedByZ);
771        const size_t count = currentLayers.size();
772        hwc.createWorkList(count);
773        hwc_layer_t* const cur(hwc.getLayers());
774        for (size_t i=0 ; cur && i<count ; i++) {
775            currentLayers[i]->setGeometry(&cur[i]);
776            if (mDebugDisableHWC) {
777                cur[i].compositionType = HWC_FRAMEBUFFER;
778                cur[i].flags |= HWC_SKIP_LAYER;
779            }
780        }
781    }
782}
783
784void SurfaceFlinger::handleRepaint()
785{
786    // compute the invalid region
787    mInvalidRegion.orSelf(mDirtyRegion);
788
789    if (UNLIKELY(mDebugRegion)) {
790        debugFlashRegions();
791    }
792
793    // set the frame buffer
794    const DisplayHardware& hw(graphicPlane(0).displayHardware());
795    glMatrixMode(GL_MODELVIEW);
796    glLoadIdentity();
797
798    uint32_t flags = hw.getFlags();
799    if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
800        (flags & DisplayHardware::BUFFER_PRESERVED))
801    {
802        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
803        // takes a rectangle, we must make sure to update that whole
804        // rectangle in that case
805        if (flags & DisplayHardware::SWAP_RECTANGLE) {
806            // TODO: we really should be able to pass a region to
807            // SWAP_RECTANGLE so that we don't have to redraw all this.
808            mDirtyRegion.set(mInvalidRegion.bounds());
809        } else {
810            // in the BUFFER_PRESERVED case, obviously, we can update only
811            // what's needed and nothing more.
812            // NOTE: this is NOT a common case, as preserving the backbuffer
813            // is costly and usually involves copying the whole update back.
814        }
815    } else {
816        if (flags & DisplayHardware::PARTIAL_UPDATES) {
817            // We need to redraw the rectangle that will be updated
818            // (pushed to the framebuffer).
819            // This is needed because PARTIAL_UPDATES only takes one
820            // rectangle instead of a region (see DisplayHardware::flip())
821            mDirtyRegion.set(mInvalidRegion.bounds());
822        } else {
823            // we need to redraw everything (the whole screen)
824            mDirtyRegion.set(hw.bounds());
825            mInvalidRegion = mDirtyRegion;
826        }
827    }
828
829    // compose all surfaces
830    composeSurfaces(mDirtyRegion);
831
832    // clear the dirty regions
833    mDirtyRegion.clear();
834}
835
836void SurfaceFlinger::composeSurfaces(const Region& dirty)
837{
838    if (UNLIKELY(!mWormholeRegion.isEmpty())) {
839        // should never happen unless the window manager has a bug
840        // draw something...
841        drawWormhole();
842    }
843
844    status_t err = NO_ERROR;
845    const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
846    size_t count = layers.size();
847
848    const DisplayHardware& hw(graphicPlane(0).displayHardware());
849    HWComposer& hwc(hw.getHwComposer());
850    hwc_layer_t* const cur(hwc.getLayers());
851
852    LOGE_IF(cur && hwc.getNumLayers() != count,
853            "HAL number of layers (%d) doesn't match surfaceflinger (%d)",
854            hwc.getNumLayers(), count);
855
856    // just to be extra-safe, use the smallest count
857    if (hwc.initCheck() == NO_ERROR) {
858        count = count < hwc.getNumLayers() ? count : hwc.getNumLayers();
859    }
860
861    /*
862     *  update the per-frame h/w composer data for each layer
863     *  and build the transparent region of the FB
864     */
865    Region transparent;
866    if (cur) {
867        for (size_t i=0 ; i<count ; i++) {
868            const sp<LayerBase>& layer(layers[i]);
869            layer->setPerFrameData(&cur[i]);
870            if (cur[i].hints & HWC_HINT_CLEAR_FB) {
871                if (!(layer->needsBlending())) {
872                    transparent.orSelf(layer->visibleRegionScreen);
873                }
874            }
875        }
876        err = hwc.prepare();
877        LOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
878    }
879
880    /*
881     *  clear the area of the FB that need to be transparent
882     */
883    transparent.andSelf(dirty);
884    if (!transparent.isEmpty()) {
885        glClearColor(0,0,0,0);
886        Region::const_iterator it = transparent.begin();
887        Region::const_iterator const end = transparent.end();
888        const int32_t height = hw.getHeight();
889        while (it != end) {
890            const Rect& r(*it++);
891            const GLint sy = height - (r.top + r.height());
892            glScissor(r.left, sy, r.width(), r.height());
893            glClear(GL_COLOR_BUFFER_BIT);
894        }
895    }
896
897
898    /*
899     * and then, render the layers targeted at the framebuffer
900     */
901    for (size_t i=0 ; i<count ; i++) {
902        if (cur) {
903            if ((cur[i].compositionType != HWC_FRAMEBUFFER) &&
904                !(cur[i].flags & HWC_SKIP_LAYER)) {
905                // skip layers handled by the HAL
906                continue;
907            }
908        }
909
910        const sp<LayerBase>& layer(layers[i]);
911        const Region clip(dirty.intersect(layer->visibleRegionScreen));
912        if (!clip.isEmpty()) {
913            layer->draw(clip);
914        }
915    }
916}
917
918void SurfaceFlinger::unlockClients()
919{
920    const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
921    const size_t count = drawingLayers.size();
922    sp<LayerBase> const* const layers = drawingLayers.array();
923    for (size_t i=0 ; i<count ; ++i) {
924        const sp<LayerBase>& layer = layers[i];
925        layer->finishPageFlip();
926    }
927}
928
929void SurfaceFlinger::debugFlashRegions()
930{
931    const DisplayHardware& hw(graphicPlane(0).displayHardware());
932    const uint32_t flags = hw.getFlags();
933
934    if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
935            (flags & DisplayHardware::BUFFER_PRESERVED))) {
936        const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ?
937                mDirtyRegion.bounds() : hw.bounds());
938        composeSurfaces(repaint);
939    }
940
941    TextureManager::deactivateTextures();
942
943    glDisable(GL_BLEND);
944    glDisable(GL_DITHER);
945    glDisable(GL_SCISSOR_TEST);
946
947    static int toggle = 0;
948    toggle = 1 - toggle;
949    if (toggle) {
950        glColor4f(1, 0, 1, 1);
951    } else {
952        glColor4f(1, 1, 0, 1);
953    }
954
955    Region::const_iterator it = mDirtyRegion.begin();
956    Region::const_iterator const end = mDirtyRegion.end();
957    while (it != end) {
958        const Rect& r = *it++;
959        GLfloat vertices[][2] = {
960                { r.left,  r.top },
961                { r.left,  r.bottom },
962                { r.right, r.bottom },
963                { r.right, r.top }
964        };
965        glVertexPointer(2, GL_FLOAT, 0, vertices);
966        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
967    }
968
969    if (mInvalidRegion.isEmpty()) {
970        mDirtyRegion.dump("mDirtyRegion");
971        mInvalidRegion.dump("mInvalidRegion");
972    }
973    hw.flip(mInvalidRegion);
974
975    if (mDebugRegion > 1)
976        usleep(mDebugRegion * 1000);
977
978    glEnable(GL_SCISSOR_TEST);
979    //mDirtyRegion.dump("mDirtyRegion");
980}
981
982void SurfaceFlinger::drawWormhole() const
983{
984    const Region region(mWormholeRegion.intersect(mDirtyRegion));
985    if (region.isEmpty())
986        return;
987
988    const DisplayHardware& hw(graphicPlane(0).displayHardware());
989    const int32_t width = hw.getWidth();
990    const int32_t height = hw.getHeight();
991
992    glDisable(GL_BLEND);
993    glDisable(GL_DITHER);
994
995    if (LIKELY(!mDebugBackground)) {
996        glClearColor(0,0,0,0);
997        Region::const_iterator it = region.begin();
998        Region::const_iterator const end = region.end();
999        while (it != end) {
1000            const Rect& r = *it++;
1001            const GLint sy = height - (r.top + r.height());
1002            glScissor(r.left, sy, r.width(), r.height());
1003            glClear(GL_COLOR_BUFFER_BIT);
1004        }
1005    } else {
1006        const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
1007                { width, height }, { 0, height }  };
1008        const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 },  { 1, 1 }, { 0, 1 } };
1009        glVertexPointer(2, GL_SHORT, 0, vertices);
1010        glTexCoordPointer(2, GL_SHORT, 0, tcoords);
1011        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1012#if defined(GL_OES_EGL_image_external)
1013        if (GLExtensions::getInstance().haveTextureExternal()) {
1014            glDisable(GL_TEXTURE_EXTERNAL_OES);
1015        }
1016#endif
1017        glEnable(GL_TEXTURE_2D);
1018        glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
1019        glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1020        glMatrixMode(GL_TEXTURE);
1021        glLoadIdentity();
1022        glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
1023        Region::const_iterator it = region.begin();
1024        Region::const_iterator const end = region.end();
1025        while (it != end) {
1026            const Rect& r = *it++;
1027            const GLint sy = height - (r.top + r.height());
1028            glScissor(r.left, sy, r.width(), r.height());
1029            glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1030        }
1031        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1032        glLoadIdentity();
1033        glMatrixMode(GL_MODELVIEW);
1034    }
1035}
1036
1037void SurfaceFlinger::debugShowFPS() const
1038{
1039    static int mFrameCount;
1040    static int mLastFrameCount = 0;
1041    static nsecs_t mLastFpsTime = 0;
1042    static float mFps = 0;
1043    mFrameCount++;
1044    nsecs_t now = systemTime();
1045    nsecs_t diff = now - mLastFpsTime;
1046    if (diff > ms2ns(250)) {
1047        mFps =  ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1048        mLastFpsTime = now;
1049        mLastFrameCount = mFrameCount;
1050    }
1051    // XXX: mFPS has the value we want
1052 }
1053
1054status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
1055{
1056    Mutex::Autolock _l(mStateLock);
1057    addLayer_l(layer);
1058    setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1059    return NO_ERROR;
1060}
1061
1062status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
1063{
1064    ssize_t i = mCurrentState.layersSortedByZ.add(layer);
1065    return (i < 0) ? status_t(i) : status_t(NO_ERROR);
1066}
1067
1068ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1069        const sp<LayerBaseClient>& lbc)
1070{
1071    Mutex::Autolock _l(mStateLock);
1072
1073    // attach this layer to the client
1074    ssize_t name = client->attachLayer(lbc);
1075
1076    // add this layer to the current state list
1077    addLayer_l(lbc);
1078
1079    return name;
1080}
1081
1082status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1083{
1084    Mutex::Autolock _l(mStateLock);
1085    status_t err = purgatorizeLayer_l(layer);
1086    if (err == NO_ERROR)
1087        setTransactionFlags(eTransactionNeeded);
1088    return err;
1089}
1090
1091status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1092{
1093    sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient());
1094    if (lbc != 0) {
1095        mLayerMap.removeItem( lbc->getSurface()->asBinder() );
1096    }
1097    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1098    if (index >= 0) {
1099        mLayersRemoved = true;
1100        return NO_ERROR;
1101    }
1102    return status_t(index);
1103}
1104
1105status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1106{
1107    // remove the layer from the main list (through a transaction).
1108    ssize_t err = removeLayer_l(layerBase);
1109
1110    layerBase->onRemoved();
1111
1112    // it's possible that we don't find a layer, because it might
1113    // have been destroyed already -- this is not technically an error
1114    // from the user because there is a race between Client::destroySurface(),
1115    // ~Client() and ~ISurface().
1116    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1117}
1118
1119status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
1120{
1121    layer->forceVisibilityTransaction();
1122    setTransactionFlags(eTraversalNeeded);
1123    return NO_ERROR;
1124}
1125
1126uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1127{
1128    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1129}
1130
1131uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1132{
1133    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1134    if ((old & flags)==0) { // wake the server up
1135        signalEvent();
1136    }
1137    return old;
1138}
1139
1140void SurfaceFlinger::openGlobalTransaction()
1141{
1142    android_atomic_inc(&mTransactionCount);
1143}
1144
1145void SurfaceFlinger::closeGlobalTransaction()
1146{
1147    if (android_atomic_dec(&mTransactionCount) == 1) {
1148        signalEvent();
1149
1150        // if there is a transaction with a resize, wait for it to
1151        // take effect before returning.
1152        Mutex::Autolock _l(mStateLock);
1153        while (mResizeTransationPending) {
1154            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1155            if (CC_UNLIKELY(err != NO_ERROR)) {
1156                // just in case something goes wrong in SF, return to the
1157                // called after a few seconds.
1158                LOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1159                mResizeTransationPending = false;
1160                break;
1161            }
1162        }
1163    }
1164}
1165
1166status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1167{
1168    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1169        return BAD_VALUE;
1170
1171    Mutex::Autolock _l(mStateLock);
1172    mCurrentState.freezeDisplay = 1;
1173    setTransactionFlags(eTransactionNeeded);
1174
1175    // flags is intended to communicate some sort of animation behavior
1176    // (for instance fading)
1177    return NO_ERROR;
1178}
1179
1180status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1181{
1182    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1183        return BAD_VALUE;
1184
1185    Mutex::Autolock _l(mStateLock);
1186    mCurrentState.freezeDisplay = 0;
1187    setTransactionFlags(eTransactionNeeded);
1188
1189    // flags is intended to communicate some sort of animation behavior
1190    // (for instance fading)
1191    return NO_ERROR;
1192}
1193
1194int SurfaceFlinger::setOrientation(DisplayID dpy,
1195        int orientation, uint32_t flags)
1196{
1197    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1198        return BAD_VALUE;
1199
1200    Mutex::Autolock _l(mStateLock);
1201    if (mCurrentState.orientation != orientation) {
1202        if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
1203            mCurrentState.orientationType = flags;
1204            mCurrentState.orientation = orientation;
1205            setTransactionFlags(eTransactionNeeded);
1206            mTransactionCV.wait(mStateLock);
1207        } else {
1208            orientation = BAD_VALUE;
1209        }
1210    }
1211    return orientation;
1212}
1213
1214sp<ISurface> SurfaceFlinger::createSurface(const sp<Client>& client, int pid,
1215        const String8& name, ISurfaceComposerClient::surface_data_t* params,
1216        DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1217        uint32_t flags)
1218{
1219    sp<LayerBaseClient> layer;
1220    sp<LayerBaseClient::Surface> surfaceHandle;
1221
1222    if (int32_t(w|h) < 0) {
1223        LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",
1224                int(w), int(h));
1225        return surfaceHandle;
1226    }
1227
1228    //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1229    sp<Layer> normalLayer;
1230    switch (flags & eFXSurfaceMask) {
1231        case eFXSurfaceNormal:
1232            normalLayer = createNormalSurface(client, d, w, h, flags, format);
1233            layer = normalLayer;
1234            break;
1235        case eFXSurfaceBlur:
1236            // for now we treat Blur as Dim, until we can implement it
1237            // efficiently.
1238        case eFXSurfaceDim:
1239            layer = createDimSurface(client, d, w, h, flags);
1240            break;
1241    }
1242
1243    if (layer != 0) {
1244        layer->initStates(w, h, flags);
1245        layer->setName(name);
1246        ssize_t token = addClientLayer(client, layer);
1247
1248        surfaceHandle = layer->getSurface();
1249        if (surfaceHandle != 0) {
1250            params->token = token;
1251            params->identity = surfaceHandle->getIdentity();
1252            params->width = w;
1253            params->height = h;
1254            params->format = format;
1255            if (normalLayer != 0) {
1256                Mutex::Autolock _l(mStateLock);
1257                mLayerMap.add(surfaceHandle->asBinder(), normalLayer);
1258            }
1259        }
1260
1261        setTransactionFlags(eTransactionNeeded);
1262    }
1263
1264    return surfaceHandle;
1265}
1266
1267sp<Layer> SurfaceFlinger::createNormalSurface(
1268        const sp<Client>& client, DisplayID display,
1269        uint32_t w, uint32_t h, uint32_t flags,
1270        PixelFormat& format)
1271{
1272    // initialize the surfaces
1273    switch (format) { // TODO: take h/w into account
1274    case PIXEL_FORMAT_TRANSPARENT:
1275    case PIXEL_FORMAT_TRANSLUCENT:
1276        format = PIXEL_FORMAT_RGBA_8888;
1277        break;
1278    case PIXEL_FORMAT_OPAQUE:
1279#ifdef NO_RGBX_8888
1280        format = PIXEL_FORMAT_RGB_565;
1281#else
1282        format = PIXEL_FORMAT_RGBX_8888;
1283#endif
1284        break;
1285    }
1286
1287#ifdef NO_RGBX_8888
1288    if (format == PIXEL_FORMAT_RGBX_8888)
1289        format = PIXEL_FORMAT_RGBA_8888;
1290#endif
1291
1292    sp<Layer> layer = new Layer(this, display, client);
1293    status_t err = layer->setBuffers(w, h, format, flags);
1294    if (LIKELY(err != NO_ERROR)) {
1295        LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
1296        layer.clear();
1297    }
1298    return layer;
1299}
1300
1301sp<LayerDim> SurfaceFlinger::createDimSurface(
1302        const sp<Client>& client, DisplayID display,
1303        uint32_t w, uint32_t h, uint32_t flags)
1304{
1305    sp<LayerDim> layer = new LayerDim(this, display, client);
1306    layer->initStates(w, h, flags);
1307    return layer;
1308}
1309
1310status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid)
1311{
1312    /*
1313     * called by the window manager, when a surface should be marked for
1314     * destruction.
1315     *
1316     * The surface is removed from the current and drawing lists, but placed
1317     * in the purgatory queue, so it's not destroyed right-away (we need
1318     * to wait for all client's references to go away first).
1319     */
1320
1321    status_t err = NAME_NOT_FOUND;
1322    Mutex::Autolock _l(mStateLock);
1323    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1324    if (layer != 0) {
1325        err = purgatorizeLayer_l(layer);
1326        if (err == NO_ERROR) {
1327            setTransactionFlags(eTransactionNeeded);
1328        }
1329    }
1330    return err;
1331}
1332
1333status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1334{
1335    // called by ~ISurface() when all references are gone
1336
1337    class MessageDestroySurface : public MessageBase {
1338        SurfaceFlinger* flinger;
1339        sp<LayerBaseClient> layer;
1340    public:
1341        MessageDestroySurface(
1342                SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1343            : flinger(flinger), layer(layer) { }
1344        virtual bool handler() {
1345            sp<LayerBaseClient> l(layer);
1346            layer.clear(); // clear it outside of the lock;
1347            Mutex::Autolock _l(flinger->mStateLock);
1348            /*
1349             * remove the layer from the current list -- chances are that it's
1350             * not in the list anyway, because it should have been removed
1351             * already upon request of the client (eg: window manager).
1352             * However, a buggy client could have not done that.
1353             * Since we know we don't have any more clients, we don't need
1354             * to use the purgatory.
1355             */
1356            status_t err = flinger->removeLayer_l(l);
1357            LOGE_IF(err<0 && err != NAME_NOT_FOUND,
1358                    "error removing layer=%p (%s)", l.get(), strerror(-err));
1359            return true;
1360        }
1361    };
1362
1363    postMessageAsync( new MessageDestroySurface(this, layer) );
1364    return NO_ERROR;
1365}
1366
1367status_t SurfaceFlinger::setClientState(
1368        const sp<Client>& client,
1369        int32_t count,
1370        const layer_state_t* states)
1371{
1372    Mutex::Autolock _l(mStateLock);
1373    uint32_t flags = 0;
1374    for (int i=0 ; i<count ; i++) {
1375        const layer_state_t& s(states[i]);
1376        sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1377        if (layer != 0) {
1378            const uint32_t what = s.what;
1379            if (what & ePositionChanged) {
1380                if (layer->setPosition(s.x, s.y))
1381                    flags |= eTraversalNeeded;
1382            }
1383            if (what & eLayerChanged) {
1384                ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1385                if (layer->setLayer(s.z)) {
1386                    mCurrentState.layersSortedByZ.removeAt(idx);
1387                    mCurrentState.layersSortedByZ.add(layer);
1388                    // we need traversal (state changed)
1389                    // AND transaction (list changed)
1390                    flags |= eTransactionNeeded|eTraversalNeeded;
1391                }
1392            }
1393            if (what & eSizeChanged) {
1394                if (layer->setSize(s.w, s.h)) {
1395                    flags |= eTraversalNeeded;
1396                    mResizeTransationPending = true;
1397                }
1398            }
1399            if (what & eAlphaChanged) {
1400                if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1401                    flags |= eTraversalNeeded;
1402            }
1403            if (what & eMatrixChanged) {
1404                if (layer->setMatrix(s.matrix))
1405                    flags |= eTraversalNeeded;
1406            }
1407            if (what & eTransparentRegionChanged) {
1408                if (layer->setTransparentRegionHint(s.transparentRegion))
1409                    flags |= eTraversalNeeded;
1410            }
1411            if (what & eVisibilityChanged) {
1412                if (layer->setFlags(s.flags, s.mask))
1413                    flags |= eTraversalNeeded;
1414            }
1415        }
1416    }
1417    if (flags) {
1418        setTransactionFlags(flags);
1419    }
1420    return NO_ERROR;
1421}
1422
1423void SurfaceFlinger::screenReleased(int dpy)
1424{
1425    // this may be called by a signal handler, we can't do too much in here
1426    android_atomic_or(eConsoleReleased, &mConsoleSignals);
1427    signalEvent();
1428}
1429
1430void SurfaceFlinger::screenAcquired(int dpy)
1431{
1432    // this may be called by a signal handler, we can't do too much in here
1433    android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1434    signalEvent();
1435}
1436
1437status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1438{
1439    const size_t SIZE = 4096;
1440    char buffer[SIZE];
1441    String8 result;
1442    if (!mDump.checkCalling()) {
1443        snprintf(buffer, SIZE, "Permission Denial: "
1444                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1445                IPCThreadState::self()->getCallingPid(),
1446                IPCThreadState::self()->getCallingUid());
1447        result.append(buffer);
1448    } else {
1449
1450        // figure out if we're stuck somewhere
1451        const nsecs_t now = systemTime();
1452        const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1453        const nsecs_t inTransaction(mDebugInTransaction);
1454        nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1455        nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1456
1457        // Try to get the main lock, but don't insist if we can't
1458        // (this would indicate SF is stuck, but we want to be able to
1459        // print something in dumpsys).
1460        int retry = 3;
1461        while (mStateLock.tryLock()<0 && --retry>=0) {
1462            usleep(1000000);
1463        }
1464        const bool locked(retry >= 0);
1465        if (!locked) {
1466            snprintf(buffer, SIZE,
1467                    "SurfaceFlinger appears to be unresponsive, "
1468                    "dumping anyways (no locks held)\n");
1469            result.append(buffer);
1470        }
1471
1472        const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1473        const size_t count = currentLayers.size();
1474        for (size_t i=0 ; i<count ; i++) {
1475            const sp<LayerBase>& layer(currentLayers[i]);
1476            layer->dump(result, buffer, SIZE);
1477            const Layer::State& s(layer->drawingState());
1478            s.transparentRegion.dump(result, "transparentRegion");
1479            layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1480            layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1481        }
1482
1483        mWormholeRegion.dump(result, "WormholeRegion");
1484        const DisplayHardware& hw(graphicPlane(0).displayHardware());
1485        snprintf(buffer, SIZE,
1486                "  display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1487                mFreezeDisplay?"yes":"no", mFreezeCount,
1488                mCurrentState.orientation, hw.canDraw());
1489        result.append(buffer);
1490        snprintf(buffer, SIZE,
1491                "  last eglSwapBuffers() time: %f us\n"
1492                "  last transaction time     : %f us\n",
1493                mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0);
1494        result.append(buffer);
1495
1496        if (inSwapBuffersDuration || !locked) {
1497            snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
1498                    inSwapBuffersDuration/1000.0);
1499            result.append(buffer);
1500        }
1501
1502        if (inTransactionDuration || !locked) {
1503            snprintf(buffer, SIZE, "  transaction time: %f us\n",
1504                    inTransactionDuration/1000.0);
1505            result.append(buffer);
1506        }
1507
1508        HWComposer& hwc(hw.getHwComposer());
1509        snprintf(buffer, SIZE, "  h/w composer %s and %s\n",
1510                hwc.initCheck()==NO_ERROR ? "present" : "not present",
1511                mDebugDisableHWC ? "disabled" : "enabled");
1512        result.append(buffer);
1513        hwc.dump(result, buffer, SIZE);
1514
1515        const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
1516        alloc.dump(result);
1517        hw.dump(result);
1518
1519        if (locked) {
1520            mStateLock.unlock();
1521        }
1522    }
1523    write(fd, result.string(), result.size());
1524    return NO_ERROR;
1525}
1526
1527status_t SurfaceFlinger::onTransact(
1528    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1529{
1530    switch (code) {
1531        case CREATE_CONNECTION:
1532        case OPEN_GLOBAL_TRANSACTION:
1533        case CLOSE_GLOBAL_TRANSACTION:
1534        case SET_ORIENTATION:
1535        case FREEZE_DISPLAY:
1536        case UNFREEZE_DISPLAY:
1537        case BOOT_FINISHED:
1538        case TURN_ELECTRON_BEAM_OFF:
1539        case TURN_ELECTRON_BEAM_ON:
1540        {
1541            // codes that require permission check
1542            IPCThreadState* ipc = IPCThreadState::self();
1543            const int pid = ipc->getCallingPid();
1544            const int uid = ipc->getCallingUid();
1545            if ((uid != AID_GRAPHICS) && !mAccessSurfaceFlinger.check(pid, uid)) {
1546                LOGE("Permission Denial: "
1547                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1548                return PERMISSION_DENIED;
1549            }
1550            break;
1551        }
1552        case CAPTURE_SCREEN:
1553        {
1554            // codes that require permission check
1555            IPCThreadState* ipc = IPCThreadState::self();
1556            const int pid = ipc->getCallingPid();
1557            const int uid = ipc->getCallingUid();
1558            if ((uid != AID_GRAPHICS) && !mReadFramebuffer.check(pid, uid)) {
1559                LOGE("Permission Denial: "
1560                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
1561                return PERMISSION_DENIED;
1562            }
1563            break;
1564        }
1565    }
1566
1567    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1568    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1569        CHECK_INTERFACE(ISurfaceComposer, data, reply);
1570        if (UNLIKELY(!mHardwareTest.checkCalling())) {
1571            IPCThreadState* ipc = IPCThreadState::self();
1572            const int pid = ipc->getCallingPid();
1573            const int uid = ipc->getCallingUid();
1574            LOGE("Permission Denial: "
1575                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1576            return PERMISSION_DENIED;
1577        }
1578        int n;
1579        switch (code) {
1580            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
1581            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
1582                return NO_ERROR;
1583            case 1002:  // SHOW_UPDATES
1584                n = data.readInt32();
1585                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1586                return NO_ERROR;
1587            case 1003:  // SHOW_BACKGROUND
1588                n = data.readInt32();
1589                mDebugBackground = n ? 1 : 0;
1590                return NO_ERROR;
1591            case 1008:  // toggle use of hw composer
1592                n = data.readInt32();
1593                mDebugDisableHWC = n ? 1 : 0;
1594                mHwWorkListDirty = true;
1595                // fall-through...
1596            case 1004:{ // repaint everything
1597                Mutex::Autolock _l(mStateLock);
1598                const DisplayHardware& hw(graphicPlane(0).displayHardware());
1599                mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1600                signalEvent();
1601                return NO_ERROR;
1602            }
1603            case 1005:{ // force transaction
1604                setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1605                return NO_ERROR;
1606            }
1607            case 1006:{ // enable/disable GraphicLog
1608                int enabled = data.readInt32();
1609                GraphicLog::getInstance().setEnabled(enabled);
1610                return NO_ERROR;
1611            }
1612            case 1007: // set mFreezeCount
1613                mFreezeCount = data.readInt32();
1614                mFreezeDisplayTime = 0;
1615                return NO_ERROR;
1616            case 1010:  // interrogate.
1617                reply->writeInt32(0);
1618                reply->writeInt32(0);
1619                reply->writeInt32(mDebugRegion);
1620                reply->writeInt32(mDebugBackground);
1621                return NO_ERROR;
1622            case 1013: {
1623                Mutex::Autolock _l(mStateLock);
1624                const DisplayHardware& hw(graphicPlane(0).displayHardware());
1625                reply->writeInt32(hw.getPageFlipCount());
1626            }
1627            return NO_ERROR;
1628        }
1629    }
1630    return err;
1631}
1632
1633// ---------------------------------------------------------------------------
1634
1635status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy,
1636        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
1637{
1638    if (!GLExtensions::getInstance().haveFramebufferObject())
1639        return INVALID_OPERATION;
1640
1641    // get screen geometry
1642    const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
1643    const uint32_t hw_w = hw.getWidth();
1644    const uint32_t hw_h = hw.getHeight();
1645    GLfloat u = 1;
1646    GLfloat v = 1;
1647
1648    // make sure to clear all GL error flags
1649    while ( glGetError() != GL_NO_ERROR ) ;
1650
1651    // create a FBO
1652    GLuint name, tname;
1653    glGenTextures(1, &tname);
1654    glBindTexture(GL_TEXTURE_2D, tname);
1655    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
1656            hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
1657    if (glGetError() != GL_NO_ERROR) {
1658        while ( glGetError() != GL_NO_ERROR ) ;
1659        GLint tw = (2 << (31 - clz(hw_w)));
1660        GLint th = (2 << (31 - clz(hw_h)));
1661        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
1662                tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
1663        u = GLfloat(hw_w) / tw;
1664        v = GLfloat(hw_h) / th;
1665    }
1666    glGenFramebuffersOES(1, &name);
1667    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
1668    glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
1669            GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
1670
1671    // redraw the screen entirely...
1672    glClearColor(0,0,0,1);
1673    glClear(GL_COLOR_BUFFER_BIT);
1674    const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
1675    const size_t count = layers.size();
1676    for (size_t i=0 ; i<count ; ++i) {
1677        const sp<LayerBase>& layer(layers[i]);
1678        layer->drawForSreenShot();
1679    }
1680
1681    // back to main framebuffer
1682    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
1683    glDisable(GL_SCISSOR_TEST);
1684    glDeleteFramebuffersOES(1, &name);
1685
1686    *textureName = tname;
1687    *uOut = u;
1688    *vOut = v;
1689    return NO_ERROR;
1690}
1691
1692// ---------------------------------------------------------------------------
1693
1694status_t SurfaceFlinger::electronBeamOffAnimationImplLocked()
1695{
1696    status_t result = PERMISSION_DENIED;
1697
1698    if (!GLExtensions::getInstance().haveFramebufferObject())
1699        return INVALID_OPERATION;
1700
1701    // get screen geometry
1702    const DisplayHardware& hw(graphicPlane(0).displayHardware());
1703    const uint32_t hw_w = hw.getWidth();
1704    const uint32_t hw_h = hw.getHeight();
1705    const Region screenBounds(hw.bounds());
1706
1707    GLfloat u, v;
1708    GLuint tname;
1709    result = renderScreenToTextureLocked(0, &tname, &u, &v);
1710    if (result != NO_ERROR) {
1711        return result;
1712    }
1713
1714    GLfloat vtx[8];
1715    const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} };
1716    glEnable(GL_TEXTURE_2D);
1717    glBindTexture(GL_TEXTURE_2D, tname);
1718    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1719    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1720    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1721    glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
1722    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1723    glVertexPointer(2, GL_FLOAT, 0, vtx);
1724
1725    class s_curve_interpolator {
1726        const float nbFrames, s, v;
1727    public:
1728        s_curve_interpolator(int nbFrames, float s)
1729        : nbFrames(1.0f / (nbFrames-1)), s(s),
1730          v(1.0f + expf(-s + 0.5f*s)) {
1731        }
1732        float operator()(int f) {
1733            const float x = f * nbFrames;
1734            return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
1735        }
1736    };
1737
1738    class v_stretch {
1739        const GLfloat hw_w, hw_h;
1740    public:
1741        v_stretch(uint32_t hw_w, uint32_t hw_h)
1742        : hw_w(hw_w), hw_h(hw_h) {
1743        }
1744        void operator()(GLfloat* vtx, float v) {
1745            const GLfloat w = hw_w + (hw_w * v);
1746            const GLfloat h = hw_h - (hw_h * v);
1747            const GLfloat x = (hw_w - w) * 0.5f;
1748            const GLfloat y = (hw_h - h) * 0.5f;
1749            vtx[0] = x;         vtx[1] = y;
1750            vtx[2] = x;         vtx[3] = y + h;
1751            vtx[4] = x + w;     vtx[5] = y + h;
1752            vtx[6] = x + w;     vtx[7] = y;
1753        }
1754    };
1755
1756    class h_stretch {
1757        const GLfloat hw_w, hw_h;
1758    public:
1759        h_stretch(uint32_t hw_w, uint32_t hw_h)
1760        : hw_w(hw_w), hw_h(hw_h) {
1761        }
1762        void operator()(GLfloat* vtx, float v) {
1763            const GLfloat w = hw_w - (hw_w * v);
1764            const GLfloat h = 1.0f;
1765            const GLfloat x = (hw_w - w) * 0.5f;
1766            const GLfloat y = (hw_h - h) * 0.5f;
1767            vtx[0] = x;         vtx[1] = y;
1768            vtx[2] = x;         vtx[3] = y + h;
1769            vtx[4] = x + w;     vtx[5] = y + h;
1770            vtx[6] = x + w;     vtx[7] = y;
1771        }
1772    };
1773
1774    // the full animation is 24 frames
1775    const int nbFrames = 12;
1776    s_curve_interpolator itr(nbFrames, 7.5f);
1777    s_curve_interpolator itg(nbFrames, 8.0f);
1778    s_curve_interpolator itb(nbFrames, 8.5f);
1779
1780    v_stretch vverts(hw_w, hw_h);
1781    glEnable(GL_BLEND);
1782    glBlendFunc(GL_ONE, GL_ONE);
1783    for (int i=0 ; i<nbFrames ; i++) {
1784        float x, y, w, h;
1785        const float vr = itr(i);
1786        const float vg = itg(i);
1787        const float vb = itb(i);
1788
1789        // clear screen
1790        glColorMask(1,1,1,1);
1791        glClear(GL_COLOR_BUFFER_BIT);
1792        glEnable(GL_TEXTURE_2D);
1793
1794        // draw the red plane
1795        vverts(vtx, vr);
1796        glColorMask(1,0,0,1);
1797        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1798
1799        // draw the green plane
1800        vverts(vtx, vg);
1801        glColorMask(0,1,0,1);
1802        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1803
1804        // draw the blue plane
1805        vverts(vtx, vb);
1806        glColorMask(0,0,1,1);
1807        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1808
1809        // draw the white highlight (we use the last vertices)
1810        glDisable(GL_TEXTURE_2D);
1811        glColorMask(1,1,1,1);
1812        glColor4f(vg, vg, vg, 1);
1813        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1814        hw.flip(screenBounds);
1815    }
1816
1817    h_stretch hverts(hw_w, hw_h);
1818    glDisable(GL_BLEND);
1819    glDisable(GL_TEXTURE_2D);
1820    glColorMask(1,1,1,1);
1821    for (int i=0 ; i<nbFrames ; i++) {
1822        const float v = itg(i);
1823        hverts(vtx, v);
1824        glClear(GL_COLOR_BUFFER_BIT);
1825        glColor4f(1-v, 1-v, 1-v, 1);
1826        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1827        hw.flip(screenBounds);
1828    }
1829
1830    glColorMask(1,1,1,1);
1831    glEnable(GL_SCISSOR_TEST);
1832    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1833    glDeleteTextures(1, &tname);
1834    return NO_ERROR;
1835}
1836
1837status_t SurfaceFlinger::electronBeamOnAnimationImplLocked()
1838{
1839    status_t result = PERMISSION_DENIED;
1840
1841    if (!GLExtensions::getInstance().haveFramebufferObject())
1842        return INVALID_OPERATION;
1843
1844
1845    // get screen geometry
1846    const DisplayHardware& hw(graphicPlane(0).displayHardware());
1847    const uint32_t hw_w = hw.getWidth();
1848    const uint32_t hw_h = hw.getHeight();
1849    const Region screenBounds(hw.bounds());
1850
1851    GLfloat u, v;
1852    GLuint tname;
1853    result = renderScreenToTextureLocked(0, &tname, &u, &v);
1854    if (result != NO_ERROR) {
1855        return result;
1856    }
1857
1858    // back to main framebuffer
1859    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
1860    glDisable(GL_SCISSOR_TEST);
1861
1862    GLfloat vtx[8];
1863    const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} };
1864    glEnable(GL_TEXTURE_2D);
1865    glBindTexture(GL_TEXTURE_2D, tname);
1866    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1867    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1868    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1869    glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
1870    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1871    glVertexPointer(2, GL_FLOAT, 0, vtx);
1872
1873    class s_curve_interpolator {
1874        const float nbFrames, s, v;
1875    public:
1876        s_curve_interpolator(int nbFrames, float s)
1877        : nbFrames(1.0f / (nbFrames-1)), s(s),
1878          v(1.0f + expf(-s + 0.5f*s)) {
1879        }
1880        float operator()(int f) {
1881            const float x = f * nbFrames;
1882            return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
1883        }
1884    };
1885
1886    class v_stretch {
1887        const GLfloat hw_w, hw_h;
1888    public:
1889        v_stretch(uint32_t hw_w, uint32_t hw_h)
1890        : hw_w(hw_w), hw_h(hw_h) {
1891        }
1892        void operator()(GLfloat* vtx, float v) {
1893            const GLfloat w = hw_w + (hw_w * v);
1894            const GLfloat h = hw_h - (hw_h * v);
1895            const GLfloat x = (hw_w - w) * 0.5f;
1896            const GLfloat y = (hw_h - h) * 0.5f;
1897            vtx[0] = x;         vtx[1] = y;
1898            vtx[2] = x;         vtx[3] = y + h;
1899            vtx[4] = x + w;     vtx[5] = y + h;
1900            vtx[6] = x + w;     vtx[7] = y;
1901        }
1902    };
1903
1904    class h_stretch {
1905        const GLfloat hw_w, hw_h;
1906    public:
1907        h_stretch(uint32_t hw_w, uint32_t hw_h)
1908        : hw_w(hw_w), hw_h(hw_h) {
1909        }
1910        void operator()(GLfloat* vtx, float v) {
1911            const GLfloat w = hw_w - (hw_w * v);
1912            const GLfloat h = 1.0f;
1913            const GLfloat x = (hw_w - w) * 0.5f;
1914            const GLfloat y = (hw_h - h) * 0.5f;
1915            vtx[0] = x;         vtx[1] = y;
1916            vtx[2] = x;         vtx[3] = y + h;
1917            vtx[4] = x + w;     vtx[5] = y + h;
1918            vtx[6] = x + w;     vtx[7] = y;
1919        }
1920    };
1921
1922    // the full animation is 12 frames
1923    int nbFrames = 8;
1924    s_curve_interpolator itr(nbFrames, 7.5f);
1925    s_curve_interpolator itg(nbFrames, 8.0f);
1926    s_curve_interpolator itb(nbFrames, 8.5f);
1927
1928    h_stretch hverts(hw_w, hw_h);
1929    glDisable(GL_BLEND);
1930    glDisable(GL_TEXTURE_2D);
1931    glColorMask(1,1,1,1);
1932    for (int i=nbFrames-1 ; i>=0 ; i--) {
1933        const float v = itg(i);
1934        hverts(vtx, v);
1935        glClear(GL_COLOR_BUFFER_BIT);
1936        glColor4f(1-v, 1-v, 1-v, 1);
1937        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1938        hw.flip(screenBounds);
1939    }
1940
1941    nbFrames = 4;
1942    v_stretch vverts(hw_w, hw_h);
1943    glEnable(GL_BLEND);
1944    glBlendFunc(GL_ONE, GL_ONE);
1945    for (int i=nbFrames-1 ; i>=0 ; i--) {
1946        float x, y, w, h;
1947        const float vr = itr(i);
1948        const float vg = itg(i);
1949        const float vb = itb(i);
1950
1951        // clear screen
1952        glColorMask(1,1,1,1);
1953        glClear(GL_COLOR_BUFFER_BIT);
1954        glEnable(GL_TEXTURE_2D);
1955
1956        // draw the red plane
1957        vverts(vtx, vr);
1958        glColorMask(1,0,0,1);
1959        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1960
1961        // draw the green plane
1962        vverts(vtx, vg);
1963        glColorMask(0,1,0,1);
1964        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1965
1966        // draw the blue plane
1967        vverts(vtx, vb);
1968        glColorMask(0,0,1,1);
1969        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1970
1971        hw.flip(screenBounds);
1972    }
1973
1974    glColorMask(1,1,1,1);
1975    glEnable(GL_SCISSOR_TEST);
1976    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1977    glDeleteTextures(1, &tname);
1978
1979    return NO_ERROR;
1980}
1981
1982// ---------------------------------------------------------------------------
1983
1984status_t SurfaceFlinger::turnElectronBeamOffImplLocked(int32_t mode)
1985{
1986    DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
1987    if (!hw.canDraw()) {
1988        // we're already off
1989        return NO_ERROR;
1990    }
1991    if (mode & ISurfaceComposer::eElectronBeamAnimationOff) {
1992        electronBeamOffAnimationImplLocked();
1993    }
1994
1995    // always clear the whole screen at the end of the animation
1996    glClearColor(0,0,0,1);
1997    glDisable(GL_SCISSOR_TEST);
1998    glClear(GL_COLOR_BUFFER_BIT);
1999    glEnable(GL_SCISSOR_TEST);
2000    hw.flip( Region(hw.bounds()) );
2001
2002    hw.setCanDraw(false);
2003    return NO_ERROR;
2004}
2005
2006status_t SurfaceFlinger::turnElectronBeamOff(int32_t mode)
2007{
2008    class MessageTurnElectronBeamOff : public MessageBase {
2009        SurfaceFlinger* flinger;
2010        int32_t mode;
2011        status_t result;
2012    public:
2013        MessageTurnElectronBeamOff(SurfaceFlinger* flinger, int32_t mode)
2014            : flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
2015        }
2016        status_t getResult() const {
2017            return result;
2018        }
2019        virtual bool handler() {
2020            Mutex::Autolock _l(flinger->mStateLock);
2021            result = flinger->turnElectronBeamOffImplLocked(mode);
2022            return true;
2023        }
2024    };
2025
2026    sp<MessageBase> msg = new MessageTurnElectronBeamOff(this, mode);
2027    status_t res = postMessageSync(msg);
2028    if (res == NO_ERROR) {
2029        res = static_cast<MessageTurnElectronBeamOff*>( msg.get() )->getResult();
2030
2031        // work-around: when the power-manager calls us we activate the
2032        // animation. eventually, the "on" animation will be called
2033        // by the power-manager itself
2034        mElectronBeamAnimationMode = mode;
2035    }
2036    return res;
2037}
2038
2039// ---------------------------------------------------------------------------
2040
2041status_t SurfaceFlinger::turnElectronBeamOnImplLocked(int32_t mode)
2042{
2043    DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
2044    if (hw.canDraw()) {
2045        // we're already on
2046        return NO_ERROR;
2047    }
2048    if (mode & ISurfaceComposer::eElectronBeamAnimationOn) {
2049        electronBeamOnAnimationImplLocked();
2050    }
2051    hw.setCanDraw(true);
2052
2053    // make sure to redraw the whole screen when the animation is done
2054    mDirtyRegion.set(hw.bounds());
2055    signalEvent();
2056
2057    return NO_ERROR;
2058}
2059
2060status_t SurfaceFlinger::turnElectronBeamOn(int32_t mode)
2061{
2062    class MessageTurnElectronBeamOn : public MessageBase {
2063        SurfaceFlinger* flinger;
2064        int32_t mode;
2065        status_t result;
2066    public:
2067        MessageTurnElectronBeamOn(SurfaceFlinger* flinger, int32_t mode)
2068            : flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
2069        }
2070        status_t getResult() const {
2071            return result;
2072        }
2073        virtual bool handler() {
2074            Mutex::Autolock _l(flinger->mStateLock);
2075            result = flinger->turnElectronBeamOnImplLocked(mode);
2076            return true;
2077        }
2078    };
2079
2080    postMessageAsync( new MessageTurnElectronBeamOn(this, mode) );
2081    return NO_ERROR;
2082}
2083
2084// ---------------------------------------------------------------------------
2085
2086status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy,
2087        sp<IMemoryHeap>* heap,
2088        uint32_t* w, uint32_t* h, PixelFormat* f,
2089        uint32_t sw, uint32_t sh,
2090        uint32_t minLayerZ, uint32_t maxLayerZ)
2091{
2092    status_t result = PERMISSION_DENIED;
2093
2094    // only one display supported for now
2095    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2096        return BAD_VALUE;
2097
2098    if (!GLExtensions::getInstance().haveFramebufferObject())
2099        return INVALID_OPERATION;
2100
2101    // get screen geometry
2102    const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
2103    const uint32_t hw_w = hw.getWidth();
2104    const uint32_t hw_h = hw.getHeight();
2105
2106    if ((sw > hw_w) || (sh > hw_h))
2107        return BAD_VALUE;
2108
2109    sw = (!sw) ? hw_w : sw;
2110    sh = (!sh) ? hw_h : sh;
2111    const size_t size = sw * sh * 4;
2112
2113    // make sure to clear all GL error flags
2114    while ( glGetError() != GL_NO_ERROR ) ;
2115
2116    // create a FBO
2117    GLuint name, tname;
2118    glGenRenderbuffersOES(1, &tname);
2119    glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2120    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2121    glGenFramebuffersOES(1, &name);
2122    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2123    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2124            GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2125
2126    GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2127    if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2128
2129        // invert everything, b/c glReadPixel() below will invert the FB
2130        glViewport(0, 0, sw, sh);
2131        glScissor(0, 0, sw, sh);
2132        glMatrixMode(GL_PROJECTION);
2133        glPushMatrix();
2134        glLoadIdentity();
2135        glOrthof(0, hw_w, 0, hw_h, 0, 1);
2136        glMatrixMode(GL_MODELVIEW);
2137
2138        // redraw the screen entirely...
2139        glClearColor(0,0,0,1);
2140        glClear(GL_COLOR_BUFFER_BIT);
2141
2142        const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
2143        const size_t count = layers.size();
2144        for (size_t i=0 ; i<count ; ++i) {
2145            const sp<LayerBase>& layer(layers[i]);
2146            const uint32_t z = layer->drawingState().z;
2147            if (z >= minLayerZ && z <= maxLayerZ) {
2148                layer->drawForSreenShot();
2149            }
2150        }
2151
2152        // XXX: this is needed on tegra
2153        glScissor(0, 0, sw, sh);
2154
2155        // check for errors and return screen capture
2156        if (glGetError() != GL_NO_ERROR) {
2157            // error while rendering
2158            result = INVALID_OPERATION;
2159        } else {
2160            // allocate shared memory large enough to hold the
2161            // screen capture
2162            sp<MemoryHeapBase> base(
2163                    new MemoryHeapBase(size, 0, "screen-capture") );
2164            void* const ptr = base->getBase();
2165            if (ptr) {
2166                // capture the screen with glReadPixels()
2167                glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2168                if (glGetError() == GL_NO_ERROR) {
2169                    *heap = base;
2170                    *w = sw;
2171                    *h = sh;
2172                    *f = PIXEL_FORMAT_RGBA_8888;
2173                    result = NO_ERROR;
2174                }
2175            } else {
2176                result = NO_MEMORY;
2177            }
2178        }
2179        glEnable(GL_SCISSOR_TEST);
2180        glViewport(0, 0, hw_w, hw_h);
2181        glMatrixMode(GL_PROJECTION);
2182        glPopMatrix();
2183        glMatrixMode(GL_MODELVIEW);
2184
2185
2186    } else {
2187        result = BAD_VALUE;
2188    }
2189
2190    // release FBO resources
2191    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2192    glDeleteRenderbuffersOES(1, &tname);
2193    glDeleteFramebuffersOES(1, &name);
2194
2195    hw.compositionComplete();
2196
2197    return result;
2198}
2199
2200
2201status_t SurfaceFlinger::captureScreen(DisplayID dpy,
2202        sp<IMemoryHeap>* heap,
2203        uint32_t* width, uint32_t* height, PixelFormat* format,
2204        uint32_t sw, uint32_t sh,
2205        uint32_t minLayerZ, uint32_t maxLayerZ)
2206{
2207    // only one display supported for now
2208    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2209        return BAD_VALUE;
2210
2211    if (!GLExtensions::getInstance().haveFramebufferObject())
2212        return INVALID_OPERATION;
2213
2214    class MessageCaptureScreen : public MessageBase {
2215        SurfaceFlinger* flinger;
2216        DisplayID dpy;
2217        sp<IMemoryHeap>* heap;
2218        uint32_t* w;
2219        uint32_t* h;
2220        PixelFormat* f;
2221        uint32_t sw;
2222        uint32_t sh;
2223        uint32_t minLayerZ;
2224        uint32_t maxLayerZ;
2225        status_t result;
2226    public:
2227        MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy,
2228                sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2229                uint32_t sw, uint32_t sh,
2230                uint32_t minLayerZ, uint32_t maxLayerZ)
2231            : flinger(flinger), dpy(dpy),
2232              heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2233              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2234              result(PERMISSION_DENIED)
2235        {
2236        }
2237        status_t getResult() const {
2238            return result;
2239        }
2240        virtual bool handler() {
2241            Mutex::Autolock _l(flinger->mStateLock);
2242
2243            // if we have secure windows, never allow the screen capture
2244            if (flinger->mSecureFrameBuffer)
2245                return true;
2246
2247            result = flinger->captureScreenImplLocked(dpy,
2248                    heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2249
2250            return true;
2251        }
2252    };
2253
2254    sp<MessageBase> msg = new MessageCaptureScreen(this,
2255            dpy, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2256    status_t res = postMessageSync(msg);
2257    if (res == NO_ERROR) {
2258        res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2259    }
2260    return res;
2261}
2262
2263// ---------------------------------------------------------------------------
2264
2265sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const
2266{
2267    sp<Layer> result;
2268    Mutex::Autolock _l(mStateLock);
2269    result = mLayerMap.valueFor( sur->asBinder() ).promote();
2270    return result;
2271}
2272
2273// ---------------------------------------------------------------------------
2274
2275Client::Client(const sp<SurfaceFlinger>& flinger)
2276    : mFlinger(flinger), mNameGenerator(1)
2277{
2278}
2279
2280Client::~Client()
2281{
2282    const size_t count = mLayers.size();
2283    for (size_t i=0 ; i<count ; i++) {
2284        sp<LayerBaseClient> layer(mLayers.valueAt(i).promote());
2285        if (layer != 0) {
2286            mFlinger->removeLayer(layer);
2287        }
2288    }
2289}
2290
2291status_t Client::initCheck() const {
2292    return NO_ERROR;
2293}
2294
2295ssize_t Client::attachLayer(const sp<LayerBaseClient>& layer)
2296{
2297    int32_t name = android_atomic_inc(&mNameGenerator);
2298    mLayers.add(name, layer);
2299    return name;
2300}
2301
2302void Client::detachLayer(const LayerBaseClient* layer)
2303{
2304    // we do a linear search here, because this doesn't happen often
2305    const size_t count = mLayers.size();
2306    for (size_t i=0 ; i<count ; i++) {
2307        if (mLayers.valueAt(i) == layer) {
2308            mLayers.removeItemsAt(i, 1);
2309            break;
2310        }
2311    }
2312}
2313sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
2314    sp<LayerBaseClient> lbc;
2315    const wp<LayerBaseClient>& layer(mLayers.valueFor(i));
2316    if (layer != 0) {
2317        lbc = layer.promote();
2318        LOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i));
2319    }
2320    return lbc;
2321}
2322
2323sp<IMemoryHeap> Client::getControlBlock() const {
2324    return 0;
2325}
2326ssize_t Client::getTokenForSurface(const sp<ISurface>& sur) const {
2327    return -1;
2328}
2329sp<ISurface> Client::createSurface(
2330        ISurfaceComposerClient::surface_data_t* params, int pid,
2331        const String8& name,
2332        DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2333        uint32_t flags)
2334{
2335    return mFlinger->createSurface(this, pid, name, params,
2336            display, w, h, format, flags);
2337}
2338status_t Client::destroySurface(SurfaceID sid) {
2339    return mFlinger->removeSurface(this, sid);
2340}
2341status_t Client::setState(int32_t count, const layer_state_t* states) {
2342    return mFlinger->setClientState(this, count, states);
2343}
2344
2345// ---------------------------------------------------------------------------
2346
2347UserClient::UserClient(const sp<SurfaceFlinger>& flinger)
2348    : ctrlblk(0), mBitmap(0), mFlinger(flinger)
2349{
2350    const int pgsize = getpagesize();
2351    const int cblksize = ((sizeof(SharedClient)+(pgsize-1))&~(pgsize-1));
2352
2353    mCblkHeap = new MemoryHeapBase(cblksize, 0,
2354            "SurfaceFlinger Client control-block");
2355
2356    ctrlblk = static_cast<SharedClient *>(mCblkHeap->getBase());
2357    if (ctrlblk) { // construct the shared structure in-place.
2358        new(ctrlblk) SharedClient;
2359    }
2360}
2361
2362UserClient::~UserClient()
2363{
2364    if (ctrlblk) {
2365        ctrlblk->~SharedClient();  // destroy our shared-structure.
2366    }
2367
2368    /*
2369     * When a UserClient dies, it's unclear what to do exactly.
2370     * We could go ahead and destroy all surfaces linked to that client
2371     * however, it wouldn't be fair to the main Client
2372     * (usually the the window-manager), which might want to re-target
2373     * the layer to another UserClient.
2374     * I think the best is to do nothing, or not much; in most cases the
2375     * WM itself will go ahead and clean things up when it detects a client of
2376     * his has died.
2377     * The remaining question is what to display? currently we keep
2378     * just keep the current buffer.
2379     */
2380}
2381
2382status_t UserClient::initCheck() const {
2383    return ctrlblk == 0 ? NO_INIT : NO_ERROR;
2384}
2385
2386void UserClient::detachLayer(const Layer* layer)
2387{
2388    int32_t name = layer->getToken();
2389    if (name >= 0) {
2390        int32_t mask = 1LU<<name;
2391        if ((android_atomic_and(~mask, &mBitmap) & mask) == 0) {
2392            LOGW("token %d wasn't marked as used %08x", name, int(mBitmap));
2393        }
2394    }
2395}
2396
2397sp<IMemoryHeap> UserClient::getControlBlock() const {
2398    return mCblkHeap;
2399}
2400
2401ssize_t UserClient::getTokenForSurface(const sp<ISurface>& sur) const
2402{
2403    int32_t name = NAME_NOT_FOUND;
2404    sp<Layer> layer(mFlinger->getLayer(sur));
2405    if (layer == 0) {
2406        return name;
2407    }
2408
2409    // if this layer already has a token, just return it
2410    name = layer->getToken();
2411    if ((name >= 0) && (layer->getClient() == this)) {
2412        return name;
2413    }
2414
2415    name = 0;
2416    do {
2417        int32_t mask = 1LU<<name;
2418        if ((android_atomic_or(mask, &mBitmap) & mask) == 0) {
2419            // we found and locked that name
2420            status_t err = layer->setToken(
2421                    const_cast<UserClient*>(this), ctrlblk, name);
2422            if (err != NO_ERROR) {
2423                // free the name
2424                android_atomic_and(~mask, &mBitmap);
2425                name = err;
2426            }
2427            break;
2428        }
2429        if (++name > 31)
2430            name = NO_MEMORY;
2431    } while(name >= 0);
2432
2433    //LOGD("getTokenForSurface(%p) => %d (client=%p, bitmap=%08lx)",
2434    //        sur->asBinder().get(), name, this, mBitmap);
2435    return name;
2436}
2437
2438sp<ISurface> UserClient::createSurface(
2439        ISurfaceComposerClient::surface_data_t* params, int pid,
2440        const String8& name,
2441        DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2442        uint32_t flags) {
2443    return 0;
2444}
2445status_t UserClient::destroySurface(SurfaceID sid) {
2446    return INVALID_OPERATION;
2447}
2448status_t UserClient::setState(int32_t count, const layer_state_t* states) {
2449    return INVALID_OPERATION;
2450}
2451
2452// ---------------------------------------------------------------------------
2453
2454GraphicBufferAlloc::GraphicBufferAlloc() {}
2455
2456GraphicBufferAlloc::~GraphicBufferAlloc() {}
2457
2458sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
2459        PixelFormat format, uint32_t usage) {
2460    sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
2461    status_t err = graphicBuffer->initCheck();
2462    if (err != 0) {
2463        LOGE("createGraphicBuffer: init check failed: %d", err);
2464        return 0;
2465    } else if (graphicBuffer->handle == 0) {
2466        LOGE("createGraphicBuffer: unable to create GraphicBuffer");
2467        return 0;
2468    }
2469    Mutex::Autolock _l(mLock);
2470    mBuffers.add(graphicBuffer);
2471    return graphicBuffer;
2472}
2473
2474void GraphicBufferAlloc::freeAllGraphicBuffersExcept(int bufIdx) {
2475    Mutex::Autolock _l(mLock);
2476    if (0 <= bufIdx && bufIdx < mBuffers.size()) {
2477        sp<GraphicBuffer> b(mBuffers[bufIdx]);
2478        mBuffers.clear();
2479        mBuffers.add(b);
2480    } else {
2481        mBuffers.clear();
2482    }
2483}
2484
2485// ---------------------------------------------------------------------------
2486
2487GraphicPlane::GraphicPlane()
2488    : mHw(0)
2489{
2490}
2491
2492GraphicPlane::~GraphicPlane() {
2493    delete mHw;
2494}
2495
2496bool GraphicPlane::initialized() const {
2497    return mHw ? true : false;
2498}
2499
2500int GraphicPlane::getWidth() const {
2501    return mWidth;
2502}
2503
2504int GraphicPlane::getHeight() const {
2505    return mHeight;
2506}
2507
2508void GraphicPlane::setDisplayHardware(DisplayHardware *hw)
2509{
2510    mHw = hw;
2511
2512    // initialize the display orientation transform.
2513    // it's a constant that should come from the display driver.
2514    int displayOrientation = ISurfaceComposer::eOrientationDefault;
2515    char property[PROPERTY_VALUE_MAX];
2516    if (property_get("ro.sf.hwrotation", property, NULL) > 0) {
2517        //displayOrientation
2518        switch (atoi(property)) {
2519        case 90:
2520            displayOrientation = ISurfaceComposer::eOrientation90;
2521            break;
2522        case 270:
2523            displayOrientation = ISurfaceComposer::eOrientation270;
2524            break;
2525        }
2526    }
2527
2528    const float w = hw->getWidth();
2529    const float h = hw->getHeight();
2530    GraphicPlane::orientationToTransfrom(displayOrientation, w, h,
2531            &mDisplayTransform);
2532    if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) {
2533        mDisplayWidth = h;
2534        mDisplayHeight = w;
2535    } else {
2536        mDisplayWidth = w;
2537        mDisplayHeight = h;
2538    }
2539
2540    setOrientation(ISurfaceComposer::eOrientationDefault);
2541}
2542
2543status_t GraphicPlane::orientationToTransfrom(
2544        int orientation, int w, int h, Transform* tr)
2545{
2546    uint32_t flags = 0;
2547    switch (orientation) {
2548    case ISurfaceComposer::eOrientationDefault:
2549        flags = Transform::ROT_0;
2550        break;
2551    case ISurfaceComposer::eOrientation90:
2552        flags = Transform::ROT_90;
2553        break;
2554    case ISurfaceComposer::eOrientation180:
2555        flags = Transform::ROT_180;
2556        break;
2557    case ISurfaceComposer::eOrientation270:
2558        flags = Transform::ROT_270;
2559        break;
2560    default:
2561        return BAD_VALUE;
2562    }
2563    tr->set(flags, w, h);
2564    return NO_ERROR;
2565}
2566
2567status_t GraphicPlane::setOrientation(int orientation)
2568{
2569    // If the rotation can be handled in hardware, this is where
2570    // the magic should happen.
2571
2572    const DisplayHardware& hw(displayHardware());
2573    const float w = mDisplayWidth;
2574    const float h = mDisplayHeight;
2575    mWidth = int(w);
2576    mHeight = int(h);
2577
2578    Transform orientationTransform;
2579    GraphicPlane::orientationToTransfrom(orientation, w, h,
2580            &orientationTransform);
2581    if (orientation & ISurfaceComposer::eOrientationSwapMask) {
2582        mWidth = int(h);
2583        mHeight = int(w);
2584    }
2585
2586    mOrientation = orientation;
2587    mGlobalTransform = mDisplayTransform * orientationTransform;
2588    return NO_ERROR;
2589}
2590
2591const DisplayHardware& GraphicPlane::displayHardware() const {
2592    return *mHw;
2593}
2594
2595DisplayHardware& GraphicPlane::editDisplayHardware() {
2596    return *mHw;
2597}
2598
2599const Transform& GraphicPlane::transform() const {
2600    return mGlobalTransform;
2601}
2602
2603EGLDisplay GraphicPlane::getEGLDisplay() const {
2604    return mHw->getEGLDisplay();
2605}
2606
2607// ---------------------------------------------------------------------------
2608
2609}; // namespace android
2610