SurfaceFlinger.cpp revision d9e8c64c3dce1612eb948a5c16ba4ff62202b423
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#include <binder/PermissionCache.h>
36
37#include <utils/String8.h>
38#include <utils/String16.h>
39#include <utils/StopWatch.h>
40
41#include <ui/GraphicBufferAllocator.h>
42#include <ui/GraphicLog.h>
43#include <ui/PixelFormat.h>
44
45#include <pixelflinger/pixelflinger.h>
46#include <GLES/gl.h>
47
48#include "clz.h"
49#include "GLExtensions.h"
50#include "Layer.h"
51#include "LayerDim.h"
52#include "SurfaceFlinger.h"
53
54#include "DisplayHardware/DisplayHardware.h"
55#include "DisplayHardware/HWComposer.h"
56
57#include <private/surfaceflinger/SharedBufferStack.h>
58
59/* ideally AID_GRAPHICS would be in a semi-public header
60 * or there would be a way to map a user/group name to its id
61 */
62#ifndef AID_GRAPHICS
63#define AID_GRAPHICS 1003
64#endif
65
66#define DISPLAY_COUNT       1
67
68namespace android {
69// ---------------------------------------------------------------------------
70
71const String16 sHardwareTest("android.permission.HARDWARE_TEST");
72const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
73const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
74const String16 sDump("android.permission.DUMP");
75
76// ---------------------------------------------------------------------------
77
78SurfaceFlinger::SurfaceFlinger()
79    :   BnSurfaceComposer(), Thread(false),
80        mTransactionFlags(0),
81        mResizeTransationPending(false),
82        mLayersRemoved(false),
83        mBootTime(systemTime()),
84        mVisibleRegionsDirty(false),
85        mHwWorkListDirty(false),
86        mDeferReleaseConsole(false),
87        mFreezeDisplay(false),
88        mElectronBeamAnimationMode(0),
89        mFreezeCount(0),
90        mFreezeDisplayTime(0),
91        mDebugRegion(0),
92        mDebugBackground(0),
93        mDebugDisableHWC(0),
94        mDebugInSwapBuffers(0),
95        mLastSwapBufferTime(0),
96        mDebugInTransaction(0),
97        mLastTransactionTime(0),
98        mBootFinished(false),
99        mConsoleSignals(0),
100        mSecureFrameBuffer(0)
101{
102    init();
103}
104
105void SurfaceFlinger::init()
106{
107    LOGI("SurfaceFlinger is starting");
108
109    // debugging stuff...
110    char value[PROPERTY_VALUE_MAX];
111    property_get("debug.sf.showupdates", value, "0");
112    mDebugRegion = atoi(value);
113    property_get("debug.sf.showbackground", value, "0");
114    mDebugBackground = atoi(value);
115
116    LOGI_IF(mDebugRegion,       "showupdates enabled");
117    LOGI_IF(mDebugBackground,   "showbackground enabled");
118}
119
120SurfaceFlinger::~SurfaceFlinger()
121{
122    glDeleteTextures(1, &mWormholeTexName);
123}
124
125sp<IMemoryHeap> SurfaceFlinger::getCblk() const
126{
127    return mServerHeap;
128}
129
130sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
131{
132    sp<ISurfaceComposerClient> bclient;
133    sp<Client> client(new Client(this));
134    status_t err = client->initCheck();
135    if (err == NO_ERROR) {
136        bclient = client;
137    }
138    return bclient;
139}
140
141sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
142{
143    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
144    return gba;
145}
146
147const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
148{
149    LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
150    const GraphicPlane& plane(mGraphicPlanes[dpy]);
151    return plane;
152}
153
154GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
155{
156    return const_cast<GraphicPlane&>(
157        const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
158}
159
160void SurfaceFlinger::bootFinished()
161{
162    const nsecs_t now = systemTime();
163    const nsecs_t duration = now - mBootTime;
164    LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
165    mBootFinished = true;
166    property_set("ctl.stop", "bootanim");
167}
168
169void SurfaceFlinger::onFirstRef()
170{
171    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
172
173    // Wait for the main thread to be done with its initialization
174    mReadyToRunBarrier.wait();
175}
176
177static inline uint16_t pack565(int r, int g, int b) {
178    return (r<<11)|(g<<5)|b;
179}
180
181status_t SurfaceFlinger::readyToRun()
182{
183    LOGI(   "SurfaceFlinger's main thread ready to run. "
184            "Initializing graphics H/W...");
185
186    // we only support one display currently
187    int dpy = 0;
188
189    {
190        // initialize the main display
191        GraphicPlane& plane(graphicPlane(dpy));
192        DisplayHardware* const hw = new DisplayHardware(this, dpy);
193        plane.setDisplayHardware(hw);
194    }
195
196    // create the shared control-block
197    mServerHeap = new MemoryHeapBase(4096,
198            MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap");
199    LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
200
201    mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase());
202    LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
203
204    new(mServerCblk) surface_flinger_cblk_t;
205
206    // initialize primary screen
207    // (other display should be initialized in the same manner, but
208    // asynchronously, as they could come and go. None of this is supported
209    // yet).
210    const GraphicPlane& plane(graphicPlane(dpy));
211    const DisplayHardware& hw = plane.displayHardware();
212    const uint32_t w = hw.getWidth();
213    const uint32_t h = hw.getHeight();
214    const uint32_t f = hw.getFormat();
215    hw.makeCurrent();
216
217    // initialize the shared control block
218    mServerCblk->connected |= 1<<dpy;
219    display_cblk_t* dcblk = mServerCblk->displays + dpy;
220    memset(dcblk, 0, sizeof(display_cblk_t));
221    dcblk->w            = plane.getWidth();
222    dcblk->h            = plane.getHeight();
223    dcblk->format       = f;
224    dcblk->orientation  = ISurfaceComposer::eOrientationDefault;
225    dcblk->xdpi         = hw.getDpiX();
226    dcblk->ydpi         = hw.getDpiY();
227    dcblk->fps          = hw.getRefreshRate();
228    dcblk->density      = hw.getDensity();
229
230    // Initialize OpenGL|ES
231    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
232    glPixelStorei(GL_PACK_ALIGNMENT, 4);
233    glEnableClientState(GL_VERTEX_ARRAY);
234    glEnable(GL_SCISSOR_TEST);
235    glShadeModel(GL_FLAT);
236    glDisable(GL_DITHER);
237    glDisable(GL_CULL_FACE);
238
239    const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
240    const uint16_t g1 = pack565(0x17,0x2f,0x17);
241    const uint16_t textureData[4] = { g0, g1, g1, g0 };
242    glGenTextures(1, &mWormholeTexName);
243    glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
244    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
245    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
246    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
247    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
248    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
249            GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
250
251    glViewport(0, 0, w, h);
252    glMatrixMode(GL_PROJECTION);
253    glLoadIdentity();
254    glOrthof(0, w, h, 0, 0, 1);
255
256    mReadyToRunBarrier.open();
257
258    /*
259     *  We're now ready to accept clients...
260     */
261
262    // start boot animation
263    property_set("ctl.start", "bootanim");
264
265    return NO_ERROR;
266}
267
268// ----------------------------------------------------------------------------
269#if 0
270#pragma mark -
271#pragma mark Events Handler
272#endif
273
274void SurfaceFlinger::waitForEvent()
275{
276    while (true) {
277        nsecs_t timeout = -1;
278        const nsecs_t freezeDisplayTimeout = ms2ns(5000);
279        if (UNLIKELY(isFrozen())) {
280            // wait 5 seconds
281            const nsecs_t now = systemTime();
282            if (mFreezeDisplayTime == 0) {
283                mFreezeDisplayTime = now;
284            }
285            nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
286            timeout = waitTime>0 ? waitTime : 0;
287        }
288
289        sp<MessageBase> msg = mEventQueue.waitMessage(timeout);
290
291        // see if we timed out
292        if (isFrozen()) {
293            const nsecs_t now = systemTime();
294            nsecs_t frozenTime = (now - mFreezeDisplayTime);
295            if (frozenTime >= freezeDisplayTimeout) {
296                // we timed out and are still frozen
297                LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
298                        mFreezeDisplay, mFreezeCount);
299                mFreezeDisplayTime = 0;
300                mFreezeCount = 0;
301                mFreezeDisplay = false;
302            }
303        }
304
305        if (msg != 0) {
306            switch (msg->what) {
307                case MessageQueue::INVALIDATE:
308                    // invalidate message, just return to the main loop
309                    return;
310            }
311        }
312    }
313}
314
315void SurfaceFlinger::signalEvent() {
316    mEventQueue.invalidate();
317}
318
319bool SurfaceFlinger::authenticateSurface(const sp<ISurface>& surface) const {
320    Mutex::Autolock _l(mStateLock);
321    sp<IBinder> surfBinder(surface->asBinder());
322
323    // Check the visible layer list for the ISurface
324    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
325    size_t count = currentLayers.size();
326    for (size_t i=0 ; i<count ; i++) {
327        const sp<LayerBase>& layer(currentLayers[i]);
328        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
329        if (lbc != NULL && lbc->getSurfaceBinder() == surfBinder) {
330            return true;
331        }
332    }
333
334    // Check the layers in the purgatory.  This check is here so that if a
335    // Surface gets destroyed before all the clients are done using it, the
336    // error will not be reported as "surface XYZ is not authenticated", but
337    // will instead fail later on when the client tries to use the surface,
338    // which should be reported as "surface XYZ returned an -ENODEV".  The
339    // purgatorized layers are no less authentic than the visible ones, so this
340    // should not cause any harm.
341    size_t purgatorySize =  mLayerPurgatory.size();
342    for (size_t i=0 ; i<purgatorySize ; i++) {
343        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
344        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
345        if (lbc != NULL && lbc->getSurfaceBinder() == surfBinder) {
346            return true;
347        }
348    }
349
350    return false;
351}
352
353status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
354        nsecs_t reltime, uint32_t flags)
355{
356    return mEventQueue.postMessage(msg, reltime, flags);
357}
358
359status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
360        nsecs_t reltime, uint32_t flags)
361{
362    status_t res = mEventQueue.postMessage(msg, reltime, flags);
363    if (res == NO_ERROR) {
364        msg->wait();
365    }
366    return res;
367}
368
369// ----------------------------------------------------------------------------
370#if 0
371#pragma mark -
372#pragma mark Main loop
373#endif
374
375bool SurfaceFlinger::threadLoop()
376{
377    waitForEvent();
378
379    // call Layer's destructor
380    handleDestroyLayers();
381
382    // check for transactions
383    if (UNLIKELY(mConsoleSignals)) {
384        handleConsoleEvents();
385    }
386
387    // if we're in a global transaction, don't do anything.
388    const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
389    uint32_t transactionFlags = peekTransactionFlags(mask);
390    if (UNLIKELY(transactionFlags)) {
391        handleTransaction(transactionFlags);
392    }
393
394    // post surfaces (if needed)
395    handlePageFlip();
396
397    if (UNLIKELY(mHwWorkListDirty)) {
398        // build the h/w work list
399        handleWorkList();
400    }
401
402    const DisplayHardware& hw(graphicPlane(0).displayHardware());
403    if (LIKELY(hw.canDraw() && !isFrozen())) {
404        // repaint the framebuffer (if needed)
405
406        const int index = hw.getCurrentBufferIndex();
407        GraphicLog& logger(GraphicLog::getInstance());
408
409        logger.log(GraphicLog::SF_REPAINT, index);
410        handleRepaint();
411
412        // inform the h/w that we're done compositing
413        logger.log(GraphicLog::SF_COMPOSITION_COMPLETE, index);
414        hw.compositionComplete();
415
416        logger.log(GraphicLog::SF_SWAP_BUFFERS, index);
417        postFramebuffer();
418
419        logger.log(GraphicLog::SF_REPAINT_DONE, index);
420    } else {
421        // pretend we did the post
422        hw.compositionComplete();
423        usleep(16667); // 60 fps period
424    }
425    return true;
426}
427
428void SurfaceFlinger::postFramebuffer()
429{
430    if (!mInvalidRegion.isEmpty()) {
431        const DisplayHardware& hw(graphicPlane(0).displayHardware());
432        const nsecs_t now = systemTime();
433        mDebugInSwapBuffers = now;
434        hw.flip(mInvalidRegion);
435        mLastSwapBufferTime = systemTime() - now;
436        mDebugInSwapBuffers = 0;
437        mInvalidRegion.clear();
438    }
439}
440
441void SurfaceFlinger::handleConsoleEvents()
442{
443    // something to do with the console
444    const DisplayHardware& hw = graphicPlane(0).displayHardware();
445
446    int what = android_atomic_and(0, &mConsoleSignals);
447    if (what & eConsoleAcquired) {
448        hw.acquireScreen();
449        // this is a temporary work-around, eventually this should be called
450        // by the power-manager
451        SurfaceFlinger::turnElectronBeamOn(mElectronBeamAnimationMode);
452    }
453
454    if (mDeferReleaseConsole && hw.isScreenAcquired()) {
455        // We got the release signal before the acquire signal
456        mDeferReleaseConsole = false;
457        hw.releaseScreen();
458    }
459
460    if (what & eConsoleReleased) {
461        if (hw.isScreenAcquired()) {
462            hw.releaseScreen();
463        } else {
464            mDeferReleaseConsole = true;
465        }
466    }
467
468    mDirtyRegion.set(hw.bounds());
469}
470
471void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
472{
473    Mutex::Autolock _l(mStateLock);
474    const nsecs_t now = systemTime();
475    mDebugInTransaction = now;
476
477    // Here we're guaranteed that some transaction flags are set
478    // so we can call handleTransactionLocked() unconditionally.
479    // We call getTransactionFlags(), which will also clear the flags,
480    // with mStateLock held to guarantee that mCurrentState won't change
481    // until the transaction is committed.
482
483    const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
484    transactionFlags = getTransactionFlags(mask);
485    handleTransactionLocked(transactionFlags);
486
487    mLastTransactionTime = systemTime() - now;
488    mDebugInTransaction = 0;
489    invalidateHwcGeometry();
490    // here the transaction has been committed
491}
492
493void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
494{
495    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
496    const size_t count = currentLayers.size();
497
498    /*
499     * Traversal of the children
500     * (perform the transaction for each of them if needed)
501     */
502
503    const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
504    if (layersNeedTransaction) {
505        for (size_t i=0 ; i<count ; i++) {
506            const sp<LayerBase>& layer = currentLayers[i];
507            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
508            if (!trFlags) continue;
509
510            const uint32_t flags = layer->doTransaction(0);
511            if (flags & Layer::eVisibleRegion)
512                mVisibleRegionsDirty = true;
513        }
514    }
515
516    /*
517     * Perform our own transaction if needed
518     */
519
520    if (transactionFlags & eTransactionNeeded) {
521        if (mCurrentState.orientation != mDrawingState.orientation) {
522            // the orientation has changed, recompute all visible regions
523            // and invalidate everything.
524
525            const int dpy = 0;
526            const int orientation = mCurrentState.orientation;
527            const uint32_t type = mCurrentState.orientationType;
528            GraphicPlane& plane(graphicPlane(dpy));
529            plane.setOrientation(orientation);
530
531            // update the shared control block
532            const DisplayHardware& hw(plane.displayHardware());
533            volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
534            dcblk->orientation = orientation;
535            dcblk->w = plane.getWidth();
536            dcblk->h = plane.getHeight();
537
538            mVisibleRegionsDirty = true;
539            mDirtyRegion.set(hw.bounds());
540        }
541
542        if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
543            // freezing or unfreezing the display -> trigger animation if needed
544            mFreezeDisplay = mCurrentState.freezeDisplay;
545            if (mFreezeDisplay)
546                 mFreezeDisplayTime = 0;
547        }
548
549        if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
550            // layers have been added
551            mVisibleRegionsDirty = true;
552        }
553
554        // some layers might have been removed, so
555        // we need to update the regions they're exposing.
556        if (mLayersRemoved) {
557            mLayersRemoved = false;
558            mVisibleRegionsDirty = true;
559            const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
560            const size_t count = previousLayers.size();
561            for (size_t i=0 ; i<count ; i++) {
562                const sp<LayerBase>& layer(previousLayers[i]);
563                if (currentLayers.indexOf( layer ) < 0) {
564                    // this layer is not visible anymore
565                    mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen);
566                }
567            }
568        }
569    }
570
571    commitTransaction();
572}
573
574void SurfaceFlinger::destroyLayer(LayerBase const* layer)
575{
576    Mutex::Autolock _l(mDestroyedLayerLock);
577    mDestroyedLayers.add(layer);
578    signalEvent();
579}
580
581void SurfaceFlinger::handleDestroyLayers()
582{
583    Vector<LayerBase const *> destroyedLayers;
584
585    { // scope for the lock
586        Mutex::Autolock _l(mDestroyedLayerLock);
587        destroyedLayers = mDestroyedLayers;
588        mDestroyedLayers.clear();
589    }
590
591    // call destructors without a lock held
592    const size_t count = destroyedLayers.size();
593    for (size_t i=0 ; i<count ; i++) {
594        //LOGD("destroying %s", destroyedLayers[i]->getName().string());
595        delete destroyedLayers[i];
596    }
597}
598
599sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
600{
601    return new FreezeLock(const_cast<SurfaceFlinger *>(this));
602}
603
604void SurfaceFlinger::computeVisibleRegions(
605    const LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
606{
607    const GraphicPlane& plane(graphicPlane(0));
608    const Transform& planeTransform(plane.transform());
609    const DisplayHardware& hw(plane.displayHardware());
610    const Region screenRegion(hw.bounds());
611
612    Region aboveOpaqueLayers;
613    Region aboveCoveredLayers;
614    Region dirty;
615
616    bool secureFrameBuffer = false;
617
618    size_t i = currentLayers.size();
619    while (i--) {
620        const sp<LayerBase>& layer = currentLayers[i];
621        layer->validateVisibility(planeTransform);
622
623        // start with the whole surface at its current location
624        const Layer::State& s(layer->drawingState());
625
626        /*
627         * opaqueRegion: area of a surface that is fully opaque.
628         */
629        Region opaqueRegion;
630
631        /*
632         * visibleRegion: area of a surface that is visible on screen
633         * and not fully transparent. This is essentially the layer's
634         * footprint minus the opaque regions above it.
635         * Areas covered by a translucent surface are considered visible.
636         */
637        Region visibleRegion;
638
639        /*
640         * coveredRegion: area of a surface that is covered by all
641         * visible regions above it (which includes the translucent areas).
642         */
643        Region coveredRegion;
644
645
646        // handle hidden surfaces by setting the visible region to empty
647        if (LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) {
648            const bool translucent = !layer->isOpaque();
649            const Rect bounds(layer->visibleBounds());
650            visibleRegion.set(bounds);
651            visibleRegion.andSelf(screenRegion);
652            if (!visibleRegion.isEmpty()) {
653                // Remove the transparent area from the visible region
654                if (translucent) {
655                    visibleRegion.subtractSelf(layer->transparentRegionScreen);
656                }
657
658                // compute the opaque region
659                const int32_t layerOrientation = layer->getOrientation();
660                if (s.alpha==255 && !translucent &&
661                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
662                    // the opaque region is the layer's footprint
663                    opaqueRegion = visibleRegion;
664                }
665            }
666        }
667
668        // Clip the covered region to the visible region
669        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
670
671        // Update aboveCoveredLayers for next (lower) layer
672        aboveCoveredLayers.orSelf(visibleRegion);
673
674        // subtract the opaque region covered by the layers above us
675        visibleRegion.subtractSelf(aboveOpaqueLayers);
676
677        // compute this layer's dirty region
678        if (layer->contentDirty) {
679            // we need to invalidate the whole region
680            dirty = visibleRegion;
681            // as well, as the old visible region
682            dirty.orSelf(layer->visibleRegionScreen);
683            layer->contentDirty = false;
684        } else {
685            /* compute the exposed region:
686             *   the exposed region consists of two components:
687             *   1) what's VISIBLE now and was COVERED before
688             *   2) what's EXPOSED now less what was EXPOSED before
689             *
690             * note that (1) is conservative, we start with the whole
691             * visible region but only keep what used to be covered by
692             * something -- which mean it may have been exposed.
693             *
694             * (2) handles areas that were not covered by anything but got
695             * exposed because of a resize.
696             */
697            const Region newExposed = visibleRegion - coveredRegion;
698            const Region oldVisibleRegion = layer->visibleRegionScreen;
699            const Region oldCoveredRegion = layer->coveredRegionScreen;
700            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
701            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
702        }
703        dirty.subtractSelf(aboveOpaqueLayers);
704
705        // accumulate to the screen dirty region
706        dirtyRegion.orSelf(dirty);
707
708        // Update aboveOpaqueLayers for next (lower) layer
709        aboveOpaqueLayers.orSelf(opaqueRegion);
710
711        // Store the visible region is screen space
712        layer->setVisibleRegion(visibleRegion);
713        layer->setCoveredRegion(coveredRegion);
714
715        // If a secure layer is partially visible, lock-down the screen!
716        if (layer->isSecure() && !visibleRegion.isEmpty()) {
717            secureFrameBuffer = true;
718        }
719    }
720
721    // invalidate the areas where a layer was removed
722    dirtyRegion.orSelf(mDirtyRegionRemovedLayer);
723    mDirtyRegionRemovedLayer.clear();
724
725    mSecureFrameBuffer = secureFrameBuffer;
726    opaqueRegion = aboveOpaqueLayers;
727}
728
729
730void SurfaceFlinger::commitTransaction()
731{
732    mDrawingState = mCurrentState;
733    mResizeTransationPending = false;
734    mTransactionCV.broadcast();
735}
736
737void SurfaceFlinger::handlePageFlip()
738{
739    bool visibleRegions = mVisibleRegionsDirty;
740    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
741    visibleRegions |= lockPageFlip(currentLayers);
742
743        const DisplayHardware& hw = graphicPlane(0).displayHardware();
744        const Region screenRegion(hw.bounds());
745        if (visibleRegions) {
746            Region opaqueRegion;
747            computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
748
749            /*
750             *  rebuild the visible layer list
751             */
752            const size_t count = currentLayers.size();
753            mVisibleLayersSortedByZ.clear();
754            mVisibleLayersSortedByZ.setCapacity(count);
755            for (size_t i=0 ; i<count ; i++) {
756                if (!currentLayers[i]->visibleRegionScreen.isEmpty())
757                    mVisibleLayersSortedByZ.add(currentLayers[i]);
758            }
759
760            mWormholeRegion = screenRegion.subtract(opaqueRegion);
761            mVisibleRegionsDirty = false;
762            invalidateHwcGeometry();
763        }
764
765    unlockPageFlip(currentLayers);
766    mDirtyRegion.andSelf(screenRegion);
767}
768
769void SurfaceFlinger::invalidateHwcGeometry()
770{
771    mHwWorkListDirty = true;
772}
773
774bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
775{
776    bool recomputeVisibleRegions = false;
777    size_t count = currentLayers.size();
778    sp<LayerBase> const* layers = currentLayers.array();
779    for (size_t i=0 ; i<count ; i++) {
780        const sp<LayerBase>& layer(layers[i]);
781        layer->lockPageFlip(recomputeVisibleRegions);
782    }
783    return recomputeVisibleRegions;
784}
785
786void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
787{
788    const GraphicPlane& plane(graphicPlane(0));
789    const Transform& planeTransform(plane.transform());
790    size_t count = currentLayers.size();
791    sp<LayerBase> const* layers = currentLayers.array();
792    for (size_t i=0 ; i<count ; i++) {
793        const sp<LayerBase>& layer(layers[i]);
794        layer->unlockPageFlip(planeTransform, mDirtyRegion);
795    }
796}
797
798void SurfaceFlinger::handleWorkList()
799{
800    mHwWorkListDirty = false;
801    HWComposer& hwc(graphicPlane(0).displayHardware().getHwComposer());
802    if (hwc.initCheck() == NO_ERROR) {
803        const Vector< sp<LayerBase> >& currentLayers(mVisibleLayersSortedByZ);
804        const size_t count = currentLayers.size();
805        hwc.createWorkList(count);
806        hwc_layer_t* const cur(hwc.getLayers());
807        for (size_t i=0 ; cur && i<count ; i++) {
808            currentLayers[i]->setGeometry(&cur[i]);
809            if (mDebugDisableHWC) {
810                cur[i].compositionType = HWC_FRAMEBUFFER;
811                cur[i].flags |= HWC_SKIP_LAYER;
812            }
813        }
814    }
815}
816
817void SurfaceFlinger::handleRepaint()
818{
819    // compute the invalid region
820    mInvalidRegion.orSelf(mDirtyRegion);
821
822    if (UNLIKELY(mDebugRegion)) {
823        debugFlashRegions();
824    }
825
826    // set the frame buffer
827    const DisplayHardware& hw(graphicPlane(0).displayHardware());
828    glMatrixMode(GL_MODELVIEW);
829    glLoadIdentity();
830
831    uint32_t flags = hw.getFlags();
832    if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
833        (flags & DisplayHardware::BUFFER_PRESERVED))
834    {
835        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
836        // takes a rectangle, we must make sure to update that whole
837        // rectangle in that case
838        if (flags & DisplayHardware::SWAP_RECTANGLE) {
839            // TODO: we really should be able to pass a region to
840            // SWAP_RECTANGLE so that we don't have to redraw all this.
841            mDirtyRegion.set(mInvalidRegion.bounds());
842        } else {
843            // in the BUFFER_PRESERVED case, obviously, we can update only
844            // what's needed and nothing more.
845            // NOTE: this is NOT a common case, as preserving the backbuffer
846            // is costly and usually involves copying the whole update back.
847        }
848    } else {
849        if (flags & DisplayHardware::PARTIAL_UPDATES) {
850            // We need to redraw the rectangle that will be updated
851            // (pushed to the framebuffer).
852            // This is needed because PARTIAL_UPDATES only takes one
853            // rectangle instead of a region (see DisplayHardware::flip())
854            mDirtyRegion.set(mInvalidRegion.bounds());
855        } else {
856            // we need to redraw everything (the whole screen)
857            mDirtyRegion.set(hw.bounds());
858            mInvalidRegion = mDirtyRegion;
859        }
860    }
861
862    // compose all surfaces
863    composeSurfaces(mDirtyRegion);
864
865    // clear the dirty regions
866    mDirtyRegion.clear();
867}
868
869void SurfaceFlinger::composeSurfaces(const Region& dirty)
870{
871    if (UNLIKELY(!mWormholeRegion.isEmpty())) {
872        // should never happen unless the window manager has a bug
873        // draw something...
874        drawWormhole();
875    }
876
877    status_t err = NO_ERROR;
878    const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
879    size_t count = layers.size();
880
881    const DisplayHardware& hw(graphicPlane(0).displayHardware());
882    HWComposer& hwc(hw.getHwComposer());
883    hwc_layer_t* const cur(hwc.getLayers());
884
885    LOGE_IF(cur && hwc.getNumLayers() != count,
886            "HAL number of layers (%d) doesn't match surfaceflinger (%d)",
887            hwc.getNumLayers(), count);
888
889    // just to be extra-safe, use the smallest count
890    if (hwc.initCheck() == NO_ERROR) {
891        count = count < hwc.getNumLayers() ? count : hwc.getNumLayers();
892    }
893
894    /*
895     *  update the per-frame h/w composer data for each layer
896     *  and build the transparent region of the FB
897     */
898    Region transparent;
899    if (cur) {
900        for (size_t i=0 ; i<count ; i++) {
901            const sp<LayerBase>& layer(layers[i]);
902            layer->setPerFrameData(&cur[i]);
903        }
904        err = hwc.prepare();
905        LOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
906
907        if (err == NO_ERROR) {
908            for (size_t i=0 ; i<count ; i++) {
909                if (cur[i].hints & HWC_HINT_CLEAR_FB) {
910                    const sp<LayerBase>& layer(layers[i]);
911                    if (layer->isOpaque()) {
912                        transparent.orSelf(layer->visibleRegionScreen);
913                    }
914                }
915            }
916
917            /*
918             *  clear the area of the FB that need to be transparent
919             */
920            transparent.andSelf(dirty);
921            if (!transparent.isEmpty()) {
922                glClearColor(0,0,0,0);
923                Region::const_iterator it = transparent.begin();
924                Region::const_iterator const end = transparent.end();
925                const int32_t height = hw.getHeight();
926                while (it != end) {
927                    const Rect& r(*it++);
928                    const GLint sy = height - (r.top + r.height());
929                    glScissor(r.left, sy, r.width(), r.height());
930                    glClear(GL_COLOR_BUFFER_BIT);
931                }
932            }
933        }
934    }
935
936
937    /*
938     * and then, render the layers targeted at the framebuffer
939     */
940    for (size_t i=0 ; i<count ; i++) {
941        if (cur) {
942            if ((cur[i].compositionType != HWC_FRAMEBUFFER) &&
943                !(cur[i].flags & HWC_SKIP_LAYER)) {
944                // skip layers handled by the HAL
945                continue;
946            }
947        }
948
949        const sp<LayerBase>& layer(layers[i]);
950        const Region clip(dirty.intersect(layer->visibleRegionScreen));
951        if (!clip.isEmpty()) {
952            layer->draw(clip);
953        }
954    }
955}
956
957void SurfaceFlinger::debugFlashRegions()
958{
959    const DisplayHardware& hw(graphicPlane(0).displayHardware());
960    const uint32_t flags = hw.getFlags();
961
962    if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
963            (flags & DisplayHardware::BUFFER_PRESERVED))) {
964        const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ?
965                mDirtyRegion.bounds() : hw.bounds());
966        composeSurfaces(repaint);
967    }
968
969    glDisable(GL_BLEND);
970    glDisable(GL_DITHER);
971    glDisable(GL_SCISSOR_TEST);
972
973    static int toggle = 0;
974    toggle = 1 - toggle;
975    if (toggle) {
976        glColor4f(1, 0, 1, 1);
977    } else {
978        glColor4f(1, 1, 0, 1);
979    }
980
981    Region::const_iterator it = mDirtyRegion.begin();
982    Region::const_iterator const end = mDirtyRegion.end();
983    while (it != end) {
984        const Rect& r = *it++;
985        GLfloat vertices[][2] = {
986                { r.left,  r.top },
987                { r.left,  r.bottom },
988                { r.right, r.bottom },
989                { r.right, r.top }
990        };
991        glVertexPointer(2, GL_FLOAT, 0, vertices);
992        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
993    }
994
995    if (mInvalidRegion.isEmpty()) {
996        mDirtyRegion.dump("mDirtyRegion");
997        mInvalidRegion.dump("mInvalidRegion");
998    }
999    hw.flip(mInvalidRegion);
1000
1001    if (mDebugRegion > 1)
1002        usleep(mDebugRegion * 1000);
1003
1004    glEnable(GL_SCISSOR_TEST);
1005    //mDirtyRegion.dump("mDirtyRegion");
1006}
1007
1008void SurfaceFlinger::drawWormhole() const
1009{
1010    const Region region(mWormholeRegion.intersect(mDirtyRegion));
1011    if (region.isEmpty())
1012        return;
1013
1014    const DisplayHardware& hw(graphicPlane(0).displayHardware());
1015    const int32_t width = hw.getWidth();
1016    const int32_t height = hw.getHeight();
1017
1018    glDisable(GL_BLEND);
1019    glDisable(GL_DITHER);
1020
1021    if (LIKELY(!mDebugBackground)) {
1022        glClearColor(0,0,0,0);
1023        Region::const_iterator it = region.begin();
1024        Region::const_iterator const end = region.end();
1025        while (it != end) {
1026            const Rect& r = *it++;
1027            const GLint sy = height - (r.top + r.height());
1028            glScissor(r.left, sy, r.width(), r.height());
1029            glClear(GL_COLOR_BUFFER_BIT);
1030        }
1031    } else {
1032        const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
1033                { width, height }, { 0, height }  };
1034        const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 },  { 1, 1 }, { 0, 1 } };
1035        glVertexPointer(2, GL_SHORT, 0, vertices);
1036        glTexCoordPointer(2, GL_SHORT, 0, tcoords);
1037        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1038#if defined(GL_OES_EGL_image_external)
1039        if (GLExtensions::getInstance().haveTextureExternal()) {
1040            glDisable(GL_TEXTURE_EXTERNAL_OES);
1041        }
1042#endif
1043        glEnable(GL_TEXTURE_2D);
1044        glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
1045        glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1046        glMatrixMode(GL_TEXTURE);
1047        glLoadIdentity();
1048        glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
1049        Region::const_iterator it = region.begin();
1050        Region::const_iterator const end = region.end();
1051        while (it != end) {
1052            const Rect& r = *it++;
1053            const GLint sy = height - (r.top + r.height());
1054            glScissor(r.left, sy, r.width(), r.height());
1055            glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1056        }
1057        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1058        glDisable(GL_TEXTURE_2D);
1059        glLoadIdentity();
1060        glMatrixMode(GL_MODELVIEW);
1061    }
1062}
1063
1064void SurfaceFlinger::debugShowFPS() const
1065{
1066    static int mFrameCount;
1067    static int mLastFrameCount = 0;
1068    static nsecs_t mLastFpsTime = 0;
1069    static float mFps = 0;
1070    mFrameCount++;
1071    nsecs_t now = systemTime();
1072    nsecs_t diff = now - mLastFpsTime;
1073    if (diff > ms2ns(250)) {
1074        mFps =  ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1075        mLastFpsTime = now;
1076        mLastFrameCount = mFrameCount;
1077    }
1078    // XXX: mFPS has the value we want
1079 }
1080
1081status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
1082{
1083    Mutex::Autolock _l(mStateLock);
1084    addLayer_l(layer);
1085    setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1086    return NO_ERROR;
1087}
1088
1089status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
1090{
1091    ssize_t i = mCurrentState.layersSortedByZ.add(layer);
1092    return (i < 0) ? status_t(i) : status_t(NO_ERROR);
1093}
1094
1095ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1096        const sp<LayerBaseClient>& lbc)
1097{
1098    // attach this layer to the client
1099    size_t name = client->attachLayer(lbc);
1100
1101    Mutex::Autolock _l(mStateLock);
1102
1103    // add this layer to the current state list
1104    addLayer_l(lbc);
1105
1106    return ssize_t(name);
1107}
1108
1109status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1110{
1111    Mutex::Autolock _l(mStateLock);
1112    status_t err = purgatorizeLayer_l(layer);
1113    if (err == NO_ERROR)
1114        setTransactionFlags(eTransactionNeeded);
1115    return err;
1116}
1117
1118status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1119{
1120    sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient());
1121    if (lbc != 0) {
1122        mLayerMap.removeItem( lbc->getSurfaceBinder() );
1123    }
1124    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1125    if (index >= 0) {
1126        mLayersRemoved = true;
1127        return NO_ERROR;
1128    }
1129    return status_t(index);
1130}
1131
1132status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1133{
1134    // First add the layer to the purgatory list, which makes sure it won't
1135    // go away, then remove it from the main list (through a transaction).
1136    ssize_t err = removeLayer_l(layerBase);
1137    if (err >= 0) {
1138        mLayerPurgatory.add(layerBase);
1139    }
1140
1141    layerBase->onRemoved();
1142
1143    // it's possible that we don't find a layer, because it might
1144    // have been destroyed already -- this is not technically an error
1145    // from the user because there is a race between Client::destroySurface(),
1146    // ~Client() and ~ISurface().
1147    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1148}
1149
1150status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
1151{
1152    layer->forceVisibilityTransaction();
1153    setTransactionFlags(eTraversalNeeded);
1154    return NO_ERROR;
1155}
1156
1157uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1158{
1159    return android_atomic_release_load(&mTransactionFlags);
1160}
1161
1162uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1163{
1164    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1165}
1166
1167uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1168{
1169    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1170    if ((old & flags)==0) { // wake the server up
1171        signalEvent();
1172    }
1173    return old;
1174}
1175
1176
1177void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& state) {
1178    Mutex::Autolock _l(mStateLock);
1179
1180    uint32_t flags = 0;
1181    const size_t count = state.size();
1182    for (size_t i=0 ; i<count ; i++) {
1183        const ComposerState& s(state[i]);
1184        sp<Client> client( static_cast<Client *>(s.client.get()) );
1185        flags |= setClientStateLocked(client, s.state);
1186    }
1187    if (flags) {
1188        setTransactionFlags(flags);
1189    }
1190
1191    signalEvent();
1192
1193    // if there is a transaction with a resize, wait for it to
1194    // take effect before returning.
1195    while (mResizeTransationPending) {
1196        status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1197        if (CC_UNLIKELY(err != NO_ERROR)) {
1198            // just in case something goes wrong in SF, return to the
1199            // called after a few seconds.
1200            LOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1201            mResizeTransationPending = false;
1202            break;
1203        }
1204    }
1205}
1206
1207status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1208{
1209    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1210        return BAD_VALUE;
1211
1212    Mutex::Autolock _l(mStateLock);
1213    mCurrentState.freezeDisplay = 1;
1214    setTransactionFlags(eTransactionNeeded);
1215
1216    // flags is intended to communicate some sort of animation behavior
1217    // (for instance fading)
1218    return NO_ERROR;
1219}
1220
1221status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1222{
1223    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1224        return BAD_VALUE;
1225
1226    Mutex::Autolock _l(mStateLock);
1227    mCurrentState.freezeDisplay = 0;
1228    setTransactionFlags(eTransactionNeeded);
1229
1230    // flags is intended to communicate some sort of animation behavior
1231    // (for instance fading)
1232    return NO_ERROR;
1233}
1234
1235int SurfaceFlinger::setOrientation(DisplayID dpy,
1236        int orientation, uint32_t flags)
1237{
1238    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1239        return BAD_VALUE;
1240
1241    Mutex::Autolock _l(mStateLock);
1242    if (mCurrentState.orientation != orientation) {
1243        if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
1244            mCurrentState.orientationType = flags;
1245            mCurrentState.orientation = orientation;
1246            setTransactionFlags(eTransactionNeeded);
1247            mTransactionCV.wait(mStateLock);
1248        } else {
1249            orientation = BAD_VALUE;
1250        }
1251    }
1252    return orientation;
1253}
1254
1255sp<ISurface> SurfaceFlinger::createSurface(
1256        ISurfaceComposerClient::surface_data_t* params,
1257        const String8& name,
1258        const sp<Client>& client,
1259        DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1260        uint32_t flags)
1261{
1262    sp<LayerBaseClient> layer;
1263    sp<ISurface> surfaceHandle;
1264
1265    if (int32_t(w|h) < 0) {
1266        LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",
1267                int(w), int(h));
1268        return surfaceHandle;
1269    }
1270
1271    //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1272    sp<Layer> normalLayer;
1273    switch (flags & eFXSurfaceMask) {
1274        case eFXSurfaceNormal:
1275            normalLayer = createNormalSurface(client, d, w, h, flags, format);
1276            layer = normalLayer;
1277            break;
1278        case eFXSurfaceBlur:
1279            // for now we treat Blur as Dim, until we can implement it
1280            // efficiently.
1281        case eFXSurfaceDim:
1282            layer = createDimSurface(client, d, w, h, flags);
1283            break;
1284    }
1285
1286    if (layer != 0) {
1287        layer->initStates(w, h, flags);
1288        layer->setName(name);
1289        ssize_t token = addClientLayer(client, layer);
1290
1291        surfaceHandle = layer->getSurface();
1292        if (surfaceHandle != 0) {
1293            params->token = token;
1294            params->identity = layer->getIdentity();
1295            params->width = w;
1296            params->height = h;
1297            params->format = format;
1298            if (normalLayer != 0) {
1299                Mutex::Autolock _l(mStateLock);
1300                mLayerMap.add(layer->getSurfaceBinder(), normalLayer);
1301            }
1302        }
1303
1304        setTransactionFlags(eTransactionNeeded);
1305    }
1306
1307    return surfaceHandle;
1308}
1309
1310sp<Layer> SurfaceFlinger::createNormalSurface(
1311        const sp<Client>& client, DisplayID display,
1312        uint32_t w, uint32_t h, uint32_t flags,
1313        PixelFormat& format)
1314{
1315    // initialize the surfaces
1316    switch (format) { // TODO: take h/w into account
1317    case PIXEL_FORMAT_TRANSPARENT:
1318    case PIXEL_FORMAT_TRANSLUCENT:
1319        format = PIXEL_FORMAT_RGBA_8888;
1320        break;
1321    case PIXEL_FORMAT_OPAQUE:
1322#ifdef NO_RGBX_8888
1323        format = PIXEL_FORMAT_RGB_565;
1324#else
1325        format = PIXEL_FORMAT_RGBX_8888;
1326#endif
1327        break;
1328    }
1329
1330#ifdef NO_RGBX_8888
1331    if (format == PIXEL_FORMAT_RGBX_8888)
1332        format = PIXEL_FORMAT_RGBA_8888;
1333#endif
1334
1335    sp<Layer> layer = new Layer(this, display, client);
1336    status_t err = layer->setBuffers(w, h, format, flags);
1337    if (LIKELY(err != NO_ERROR)) {
1338        LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
1339        layer.clear();
1340    }
1341    return layer;
1342}
1343
1344sp<LayerDim> SurfaceFlinger::createDimSurface(
1345        const sp<Client>& client, DisplayID display,
1346        uint32_t w, uint32_t h, uint32_t flags)
1347{
1348    sp<LayerDim> layer = new LayerDim(this, display, client);
1349    layer->initStates(w, h, flags);
1350    return layer;
1351}
1352
1353status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid)
1354{
1355    /*
1356     * called by the window manager, when a surface should be marked for
1357     * destruction.
1358     *
1359     * The surface is removed from the current and drawing lists, but placed
1360     * in the purgatory queue, so it's not destroyed right-away (we need
1361     * to wait for all client's references to go away first).
1362     */
1363
1364    status_t err = NAME_NOT_FOUND;
1365    Mutex::Autolock _l(mStateLock);
1366    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1367    if (layer != 0) {
1368        err = purgatorizeLayer_l(layer);
1369        if (err == NO_ERROR) {
1370            setTransactionFlags(eTransactionNeeded);
1371        }
1372    }
1373    return err;
1374}
1375
1376status_t SurfaceFlinger::destroySurface(const wp<LayerBaseClient>& layer)
1377{
1378    // called by ~ISurface() when all references are gone
1379    status_t err = NO_ERROR;
1380    sp<LayerBaseClient> l(layer.promote());
1381    if (l != NULL) {
1382        Mutex::Autolock _l(mStateLock);
1383        err = removeLayer_l(l);
1384        if (err == NAME_NOT_FOUND) {
1385            // The surface wasn't in the current list, which means it was
1386            // removed already, which means it is in the purgatory,
1387            // and need to be removed from there.
1388            ssize_t idx = mLayerPurgatory.remove(l);
1389            LOGE_IF(idx < 0,
1390                    "layer=%p is not in the purgatory list", l.get());
1391        }
1392        LOGE_IF(err<0 && err != NAME_NOT_FOUND,
1393                "error removing layer=%p (%s)", l.get(), strerror(-err));
1394    }
1395    return err;
1396}
1397
1398uint32_t SurfaceFlinger::setClientStateLocked(
1399        const sp<Client>& client,
1400        const layer_state_t& s)
1401{
1402    uint32_t flags = 0;
1403    sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1404    if (layer != 0) {
1405        const uint32_t what = s.what;
1406        if (what & ePositionChanged) {
1407            if (layer->setPosition(s.x, s.y))
1408                flags |= eTraversalNeeded;
1409        }
1410        if (what & eLayerChanged) {
1411            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1412            if (layer->setLayer(s.z)) {
1413                mCurrentState.layersSortedByZ.removeAt(idx);
1414                mCurrentState.layersSortedByZ.add(layer);
1415                // we need traversal (state changed)
1416                // AND transaction (list changed)
1417                flags |= eTransactionNeeded|eTraversalNeeded;
1418            }
1419        }
1420        if (what & eSizeChanged) {
1421            if (layer->setSize(s.w, s.h)) {
1422                flags |= eTraversalNeeded;
1423                mResizeTransationPending = true;
1424            }
1425        }
1426        if (what & eAlphaChanged) {
1427            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1428                flags |= eTraversalNeeded;
1429        }
1430        if (what & eMatrixChanged) {
1431            if (layer->setMatrix(s.matrix))
1432                flags |= eTraversalNeeded;
1433        }
1434        if (what & eTransparentRegionChanged) {
1435            if (layer->setTransparentRegionHint(s.transparentRegion))
1436                flags |= eTraversalNeeded;
1437        }
1438        if (what & eVisibilityChanged) {
1439            if (layer->setFlags(s.flags, s.mask))
1440                flags |= eTraversalNeeded;
1441        }
1442    }
1443    return flags;
1444}
1445
1446void SurfaceFlinger::screenReleased(int dpy)
1447{
1448    // this may be called by a signal handler, we can't do too much in here
1449    android_atomic_or(eConsoleReleased, &mConsoleSignals);
1450    signalEvent();
1451}
1452
1453void SurfaceFlinger::screenAcquired(int dpy)
1454{
1455    // this may be called by a signal handler, we can't do too much in here
1456    android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1457    signalEvent();
1458}
1459
1460status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1461{
1462    const size_t SIZE = 4096;
1463    char buffer[SIZE];
1464    String8 result;
1465
1466    if (!PermissionCache::checkCallingPermission(sDump)) {
1467        snprintf(buffer, SIZE, "Permission Denial: "
1468                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1469                IPCThreadState::self()->getCallingPid(),
1470                IPCThreadState::self()->getCallingUid());
1471        result.append(buffer);
1472    } else {
1473
1474        // figure out if we're stuck somewhere
1475        const nsecs_t now = systemTime();
1476        const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1477        const nsecs_t inTransaction(mDebugInTransaction);
1478        nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1479        nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1480
1481        // Try to get the main lock, but don't insist if we can't
1482        // (this would indicate SF is stuck, but we want to be able to
1483        // print something in dumpsys).
1484        int retry = 3;
1485        while (mStateLock.tryLock()<0 && --retry>=0) {
1486            usleep(1000000);
1487        }
1488        const bool locked(retry >= 0);
1489        if (!locked) {
1490            snprintf(buffer, SIZE,
1491                    "SurfaceFlinger appears to be unresponsive, "
1492                    "dumping anyways (no locks held)\n");
1493            result.append(buffer);
1494        }
1495
1496        /*
1497         * Dump the visible layer list
1498         */
1499        const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1500        const size_t count = currentLayers.size();
1501        snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
1502        result.append(buffer);
1503        for (size_t i=0 ; i<count ; i++) {
1504            const sp<LayerBase>& layer(currentLayers[i]);
1505            layer->dump(result, buffer, SIZE);
1506            const Layer::State& s(layer->drawingState());
1507            s.transparentRegion.dump(result, "transparentRegion");
1508            layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1509            layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1510        }
1511
1512        /*
1513         * Dump the layers in the purgatory
1514         */
1515
1516        const size_t purgatorySize =  mLayerPurgatory.size();
1517        snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
1518        result.append(buffer);
1519        for (size_t i=0 ; i<purgatorySize ; i++) {
1520            const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
1521            layer->shortDump(result, buffer, SIZE);
1522        }
1523
1524        /*
1525         * Dump SurfaceFlinger global state
1526         */
1527
1528        snprintf(buffer, SIZE, "SurfaceFlinger global state\n");
1529        result.append(buffer);
1530        mWormholeRegion.dump(result, "WormholeRegion");
1531        const DisplayHardware& hw(graphicPlane(0).displayHardware());
1532        snprintf(buffer, SIZE,
1533                "  display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1534                mFreezeDisplay?"yes":"no", mFreezeCount,
1535                mCurrentState.orientation, hw.canDraw());
1536        result.append(buffer);
1537        snprintf(buffer, SIZE,
1538                "  last eglSwapBuffers() time: %f us\n"
1539                "  last transaction time     : %f us\n",
1540                mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0);
1541        result.append(buffer);
1542
1543        if (inSwapBuffersDuration || !locked) {
1544            snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
1545                    inSwapBuffersDuration/1000.0);
1546            result.append(buffer);
1547        }
1548
1549        if (inTransactionDuration || !locked) {
1550            snprintf(buffer, SIZE, "  transaction time: %f us\n",
1551                    inTransactionDuration/1000.0);
1552            result.append(buffer);
1553        }
1554
1555        /*
1556         * Dump HWComposer state
1557         */
1558        HWComposer& hwc(hw.getHwComposer());
1559        snprintf(buffer, SIZE, "  h/w composer %s and %s\n",
1560                hwc.initCheck()==NO_ERROR ? "present" : "not present",
1561                mDebugDisableHWC ? "disabled" : "enabled");
1562        result.append(buffer);
1563        hwc.dump(result, buffer, SIZE);
1564
1565        /*
1566         * Dump gralloc state
1567         */
1568        const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
1569        alloc.dump(result);
1570        hw.dump(result);
1571
1572        if (locked) {
1573            mStateLock.unlock();
1574        }
1575    }
1576    write(fd, result.string(), result.size());
1577    return NO_ERROR;
1578}
1579
1580status_t SurfaceFlinger::onTransact(
1581    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1582{
1583    switch (code) {
1584        case CREATE_CONNECTION:
1585        case SET_TRANSACTION_STATE:
1586        case SET_ORIENTATION:
1587        case FREEZE_DISPLAY:
1588        case UNFREEZE_DISPLAY:
1589        case BOOT_FINISHED:
1590        case TURN_ELECTRON_BEAM_OFF:
1591        case TURN_ELECTRON_BEAM_ON:
1592        {
1593            // codes that require permission check
1594            IPCThreadState* ipc = IPCThreadState::self();
1595            const int pid = ipc->getCallingPid();
1596            const int uid = ipc->getCallingUid();
1597            if ((uid != AID_GRAPHICS) &&
1598                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
1599                LOGE("Permission Denial: "
1600                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1601                return PERMISSION_DENIED;
1602            }
1603            break;
1604        }
1605        case CAPTURE_SCREEN:
1606        {
1607            // codes that require permission check
1608            IPCThreadState* ipc = IPCThreadState::self();
1609            const int pid = ipc->getCallingPid();
1610            const int uid = ipc->getCallingUid();
1611            if ((uid != AID_GRAPHICS) &&
1612                    !PermissionCache::checkPermission(sReadFramebuffer, 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(!PermissionCache::checkCallingPermission(sHardwareTest))) {
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 + h;
1803            vtx[2] = x;         vtx[3] = y;
1804            vtx[4] = x + w;     vtx[5] = y;
1805            vtx[6] = x + w;     vtx[7] = y + h;
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 + h;
1821            vtx[2] = x;         vtx[3] = y;
1822            vtx[4] = x + w;     vtx[5] = y;
1823            vtx[6] = x + w;     vtx[7] = y + h;
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 (!PermissionCache::checkCallingPermission(sAccessSurfaceFlinger))
2408         {
2409             LOGE("Permission Denial: "
2410                     "can't openGlobalTransaction pid=%d, uid=%d", pid, uid);
2411             return PERMISSION_DENIED;
2412         }
2413     }
2414     return BnSurfaceComposerClient::onTransact(code, data, reply, flags);
2415}
2416
2417
2418sp<ISurface> Client::createSurface(
2419        ISurfaceComposerClient::surface_data_t* params,
2420        const String8& name,
2421        DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2422        uint32_t flags)
2423{
2424    /*
2425     * createSurface must be called from the GL thread so that it can
2426     * have access to the GL context.
2427     */
2428
2429    class MessageCreateSurface : public MessageBase {
2430        sp<ISurface> result;
2431        SurfaceFlinger* flinger;
2432        ISurfaceComposerClient::surface_data_t* params;
2433        Client* client;
2434        const String8& name;
2435        DisplayID display;
2436        uint32_t w, h;
2437        PixelFormat format;
2438        uint32_t flags;
2439    public:
2440        MessageCreateSurface(SurfaceFlinger* flinger,
2441                ISurfaceComposerClient::surface_data_t* params,
2442                const String8& name, Client* client,
2443                DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2444                uint32_t flags)
2445            : flinger(flinger), params(params), client(client), name(name),
2446              display(display), w(w), h(h), format(format), flags(flags)
2447        {
2448        }
2449        sp<ISurface> getResult() const { return result; }
2450        virtual bool handler() {
2451            result = flinger->createSurface(params, name, client,
2452                    display, w, h, format, flags);
2453            return true;
2454        }
2455    };
2456
2457    sp<MessageBase> msg = new MessageCreateSurface(mFlinger.get(),
2458            params, name, this, display, w, h, format, flags);
2459    mFlinger->postMessageSync(msg);
2460    return static_cast<MessageCreateSurface*>( msg.get() )->getResult();
2461}
2462status_t Client::destroySurface(SurfaceID sid) {
2463    return mFlinger->removeSurface(this, sid);
2464}
2465
2466// ---------------------------------------------------------------------------
2467
2468GraphicBufferAlloc::GraphicBufferAlloc() {}
2469
2470GraphicBufferAlloc::~GraphicBufferAlloc() {}
2471
2472sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
2473        PixelFormat format, uint32_t usage, status_t* error) {
2474    sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
2475    status_t err = graphicBuffer->initCheck();
2476    *error = err;
2477    if (err != 0 || graphicBuffer->handle == 0) {
2478        if (err == NO_MEMORY) {
2479            GraphicBuffer::dumpAllocationsToSystemLog();
2480        }
2481        LOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
2482             "failed (%s), handle=%p",
2483                w, h, strerror(-err), graphicBuffer->handle);
2484        return 0;
2485    }
2486    return graphicBuffer;
2487}
2488
2489// ---------------------------------------------------------------------------
2490
2491GraphicPlane::GraphicPlane()
2492    : mHw(0)
2493{
2494}
2495
2496GraphicPlane::~GraphicPlane() {
2497    delete mHw;
2498}
2499
2500bool GraphicPlane::initialized() const {
2501    return mHw ? true : false;
2502}
2503
2504int GraphicPlane::getWidth() const {
2505    return mWidth;
2506}
2507
2508int GraphicPlane::getHeight() const {
2509    return mHeight;
2510}
2511
2512void GraphicPlane::setDisplayHardware(DisplayHardware *hw)
2513{
2514    mHw = hw;
2515
2516    // initialize the display orientation transform.
2517    // it's a constant that should come from the display driver.
2518    int displayOrientation = ISurfaceComposer::eOrientationDefault;
2519    char property[PROPERTY_VALUE_MAX];
2520    if (property_get("ro.sf.hwrotation", property, NULL) > 0) {
2521        //displayOrientation
2522        switch (atoi(property)) {
2523        case 90:
2524            displayOrientation = ISurfaceComposer::eOrientation90;
2525            break;
2526        case 270:
2527            displayOrientation = ISurfaceComposer::eOrientation270;
2528            break;
2529        }
2530    }
2531
2532    const float w = hw->getWidth();
2533    const float h = hw->getHeight();
2534    GraphicPlane::orientationToTransfrom(displayOrientation, w, h,
2535            &mDisplayTransform);
2536    if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) {
2537        mDisplayWidth = h;
2538        mDisplayHeight = w;
2539    } else {
2540        mDisplayWidth = w;
2541        mDisplayHeight = h;
2542    }
2543
2544    setOrientation(ISurfaceComposer::eOrientationDefault);
2545}
2546
2547status_t GraphicPlane::orientationToTransfrom(
2548        int orientation, int w, int h, Transform* tr)
2549{
2550    uint32_t flags = 0;
2551    switch (orientation) {
2552    case ISurfaceComposer::eOrientationDefault:
2553        flags = Transform::ROT_0;
2554        break;
2555    case ISurfaceComposer::eOrientation90:
2556        flags = Transform::ROT_90;
2557        break;
2558    case ISurfaceComposer::eOrientation180:
2559        flags = Transform::ROT_180;
2560        break;
2561    case ISurfaceComposer::eOrientation270:
2562        flags = Transform::ROT_270;
2563        break;
2564    default:
2565        return BAD_VALUE;
2566    }
2567    tr->set(flags, w, h);
2568    return NO_ERROR;
2569}
2570
2571status_t GraphicPlane::setOrientation(int orientation)
2572{
2573    // If the rotation can be handled in hardware, this is where
2574    // the magic should happen.
2575
2576    const DisplayHardware& hw(displayHardware());
2577    const float w = mDisplayWidth;
2578    const float h = mDisplayHeight;
2579    mWidth = int(w);
2580    mHeight = int(h);
2581
2582    Transform orientationTransform;
2583    GraphicPlane::orientationToTransfrom(orientation, w, h,
2584            &orientationTransform);
2585    if (orientation & ISurfaceComposer::eOrientationSwapMask) {
2586        mWidth = int(h);
2587        mHeight = int(w);
2588    }
2589
2590    mOrientation = orientation;
2591    mGlobalTransform = mDisplayTransform * orientationTransform;
2592    return NO_ERROR;
2593}
2594
2595const DisplayHardware& GraphicPlane::displayHardware() const {
2596    return *mHw;
2597}
2598
2599DisplayHardware& GraphicPlane::editDisplayHardware() {
2600    return *mHw;
2601}
2602
2603const Transform& GraphicPlane::transform() const {
2604    return mGlobalTransform;
2605}
2606
2607EGLDisplay GraphicPlane::getEGLDisplay() const {
2608    return mHw->getEGLDisplay();
2609}
2610
2611// ---------------------------------------------------------------------------
2612
2613}; // namespace android
2614