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