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