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