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