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