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