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