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