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