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