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