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