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