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