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