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