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