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