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