SurfaceFlinger.cpp revision b9494d5c9d44e4a59b6d510fea1665de434f3c6b
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
896    const size_t fbLayerCount = hwc.getLayerCount(HWC_FRAMEBUFFER);
897    if (fbLayerCount) {
898        // Never touch the framebuffer if we don't have any framebuffer layers
899
900        if (hwc.getLayerCount(HWC_OVERLAY)) {
901            // when using overlays, we assume a fully transparent framebuffer
902            // NOTE: we could reduce how much we need to clear, for instance
903            // remove where there are opaque FB layers. however, on some
904            // GPUs doing a "clean slate" glClear might be more efficient.
905            // We'll revisit later if needed.
906            glClearColor(0, 0, 0, 0);
907            glClear(GL_COLOR_BUFFER_BIT);
908        } else {
909            // screen is already cleared here
910            if (!mWormholeRegion.isEmpty()) {
911                // can happen with SurfaceView
912                drawWormhole();
913            }
914        }
915
916        /*
917         * and then, render the layers targeted at the framebuffer
918         */
919
920        hwc_layer_t* const cur(hwc.getLayers());
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    }
1356    return flags;
1357}
1358
1359// ---------------------------------------------------------------------------
1360
1361void SurfaceFlinger::onScreenAcquired() {
1362    const DisplayHardware& hw(graphicPlane(0).displayHardware());
1363    hw.acquireScreen();
1364    mEventThread->onScreenAcquired();
1365    // this is a temporary work-around, eventually this should be called
1366    // by the power-manager
1367    SurfaceFlinger::turnElectronBeamOn(mElectronBeamAnimationMode);
1368    // from this point on, SF will process updates again
1369    repaintEverything();
1370}
1371
1372void SurfaceFlinger::onScreenReleased() {
1373    const DisplayHardware& hw(graphicPlane(0).displayHardware());
1374    if (hw.isScreenAcquired()) {
1375        mEventThread->onScreenReleased();
1376        hw.releaseScreen();
1377        // from this point on, SF will stop drawing
1378    }
1379}
1380
1381void SurfaceFlinger::screenAcquired() {
1382    class MessageScreenAcquired : public MessageBase {
1383        SurfaceFlinger* flinger;
1384    public:
1385        MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { }
1386        virtual bool handler() {
1387            flinger->onScreenAcquired();
1388            return true;
1389        }
1390    };
1391    sp<MessageBase> msg = new MessageScreenAcquired(this);
1392    postMessageSync(msg);
1393}
1394
1395void SurfaceFlinger::screenReleased() {
1396    class MessageScreenReleased : public MessageBase {
1397        SurfaceFlinger* flinger;
1398    public:
1399        MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { }
1400        virtual bool handler() {
1401            flinger->onScreenReleased();
1402            return true;
1403        }
1404    };
1405    sp<MessageBase> msg = new MessageScreenReleased(this);
1406    postMessageSync(msg);
1407}
1408
1409// ---------------------------------------------------------------------------
1410
1411status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1412{
1413    const size_t SIZE = 4096;
1414    char buffer[SIZE];
1415    String8 result;
1416
1417    if (!PermissionCache::checkCallingPermission(sDump)) {
1418        snprintf(buffer, SIZE, "Permission Denial: "
1419                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1420                IPCThreadState::self()->getCallingPid(),
1421                IPCThreadState::self()->getCallingUid());
1422        result.append(buffer);
1423    } else {
1424        // Try to get the main lock, but don't insist if we can't
1425        // (this would indicate SF is stuck, but we want to be able to
1426        // print something in dumpsys).
1427        int retry = 3;
1428        while (mStateLock.tryLock()<0 && --retry>=0) {
1429            usleep(1000000);
1430        }
1431        const bool locked(retry >= 0);
1432        if (!locked) {
1433            snprintf(buffer, SIZE,
1434                    "SurfaceFlinger appears to be unresponsive, "
1435                    "dumping anyways (no locks held)\n");
1436            result.append(buffer);
1437        }
1438
1439        bool dumpAll = true;
1440        size_t index = 0;
1441        size_t numArgs = args.size();
1442        if (numArgs) {
1443            if ((index < numArgs) &&
1444                    (args[index] == String16("--list"))) {
1445                index++;
1446                listLayersLocked(args, index, result, buffer, SIZE);
1447                dumpAll = false;
1448            }
1449
1450            if ((index < numArgs) &&
1451                    (args[index] == String16("--latency"))) {
1452                index++;
1453                dumpStatsLocked(args, index, result, buffer, SIZE);
1454                dumpAll = false;
1455            }
1456
1457            if ((index < numArgs) &&
1458                    (args[index] == String16("--latency-clear"))) {
1459                index++;
1460                clearStatsLocked(args, index, result, buffer, SIZE);
1461                dumpAll = false;
1462            }
1463        }
1464
1465        if (dumpAll) {
1466            dumpAllLocked(result, buffer, SIZE);
1467        }
1468
1469        if (locked) {
1470            mStateLock.unlock();
1471        }
1472    }
1473    write(fd, result.string(), result.size());
1474    return NO_ERROR;
1475}
1476
1477void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
1478        String8& result, char* buffer, size_t SIZE) const
1479{
1480    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1481    const size_t count = currentLayers.size();
1482    for (size_t i=0 ; i<count ; i++) {
1483        const sp<LayerBase>& layer(currentLayers[i]);
1484        snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1485        result.append(buffer);
1486    }
1487}
1488
1489void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
1490        String8& result, char* buffer, size_t SIZE) const
1491{
1492    String8 name;
1493    if (index < args.size()) {
1494        name = String8(args[index]);
1495        index++;
1496    }
1497
1498    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1499    const size_t count = currentLayers.size();
1500    for (size_t i=0 ; i<count ; i++) {
1501        const sp<LayerBase>& layer(currentLayers[i]);
1502        if (name.isEmpty()) {
1503            snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1504            result.append(buffer);
1505        }
1506        if (name.isEmpty() || (name == layer->getName())) {
1507            layer->dumpStats(result, buffer, SIZE);
1508        }
1509    }
1510}
1511
1512void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
1513        String8& result, char* buffer, size_t SIZE) const
1514{
1515    String8 name;
1516    if (index < args.size()) {
1517        name = String8(args[index]);
1518        index++;
1519    }
1520
1521    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1522    const size_t count = currentLayers.size();
1523    for (size_t i=0 ; i<count ; i++) {
1524        const sp<LayerBase>& layer(currentLayers[i]);
1525        if (name.isEmpty() || (name == layer->getName())) {
1526            layer->clearStats();
1527        }
1528    }
1529}
1530
1531void SurfaceFlinger::dumpAllLocked(
1532        String8& result, char* buffer, size_t SIZE) const
1533{
1534    // figure out if we're stuck somewhere
1535    const nsecs_t now = systemTime();
1536    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1537    const nsecs_t inTransaction(mDebugInTransaction);
1538    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1539    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1540
1541    /*
1542     * Dump the visible layer list
1543     */
1544    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1545    const size_t count = currentLayers.size();
1546    snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
1547    result.append(buffer);
1548    for (size_t i=0 ; i<count ; i++) {
1549        const sp<LayerBase>& layer(currentLayers[i]);
1550        layer->dump(result, buffer, SIZE);
1551    }
1552
1553    /*
1554     * Dump the layers in the purgatory
1555     */
1556
1557    const size_t purgatorySize = mLayerPurgatory.size();
1558    snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
1559    result.append(buffer);
1560    for (size_t i=0 ; i<purgatorySize ; i++) {
1561        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
1562        layer->shortDump(result, buffer, SIZE);
1563    }
1564
1565    /*
1566     * Dump SurfaceFlinger global state
1567     */
1568
1569    snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
1570    result.append(buffer);
1571
1572    const GLExtensions& extensions(GLExtensions::getInstance());
1573    snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
1574            extensions.getVendor(),
1575            extensions.getRenderer(),
1576            extensions.getVersion());
1577    result.append(buffer);
1578
1579    snprintf(buffer, SIZE, "EGL : %s\n",
1580            eglQueryString(graphicPlane(0).getEGLDisplay(),
1581                    EGL_VERSION_HW_ANDROID));
1582    result.append(buffer);
1583
1584    snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
1585    result.append(buffer);
1586
1587    mWormholeRegion.dump(result, "WormholeRegion");
1588    const DisplayHardware& hw(graphicPlane(0).displayHardware());
1589    snprintf(buffer, SIZE,
1590            "  orientation=%d, canDraw=%d\n",
1591            mCurrentState.orientation, hw.canDraw());
1592    result.append(buffer);
1593    snprintf(buffer, SIZE,
1594            "  last eglSwapBuffers() time: %f us\n"
1595            "  last transaction time     : %f us\n"
1596            "  transaction-flags         : %08x\n"
1597            "  refresh-rate              : %f fps\n"
1598            "  x-dpi                     : %f\n"
1599            "  y-dpi                     : %f\n"
1600            "  density                   : %f\n",
1601            mLastSwapBufferTime/1000.0,
1602            mLastTransactionTime/1000.0,
1603            mTransactionFlags,
1604            hw.getRefreshRate(),
1605            hw.getDpiX(),
1606            hw.getDpiY(),
1607            hw.getDensity());
1608    result.append(buffer);
1609
1610    snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
1611            inSwapBuffersDuration/1000.0);
1612    result.append(buffer);
1613
1614    snprintf(buffer, SIZE, "  transaction time: %f us\n",
1615            inTransactionDuration/1000.0);
1616    result.append(buffer);
1617
1618    /*
1619     * VSYNC state
1620     */
1621    mEventThread->dump(result, buffer, SIZE);
1622
1623    /*
1624     * Dump HWComposer state
1625     */
1626    HWComposer& hwc(hw.getHwComposer());
1627    snprintf(buffer, SIZE, "h/w composer state:\n");
1628    result.append(buffer);
1629    snprintf(buffer, SIZE, "  h/w composer %s and %s\n",
1630            hwc.initCheck()==NO_ERROR ? "present" : "not present",
1631                    (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
1632    result.append(buffer);
1633    hwc.dump(result, buffer, SIZE, mVisibleLayersSortedByZ);
1634
1635    /*
1636     * Dump gralloc state
1637     */
1638    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
1639    alloc.dump(result);
1640    hw.dump(result);
1641}
1642
1643status_t SurfaceFlinger::onTransact(
1644    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1645{
1646    switch (code) {
1647        case CREATE_CONNECTION:
1648        case SET_TRANSACTION_STATE:
1649        case SET_ORIENTATION:
1650        case BOOT_FINISHED:
1651        case TURN_ELECTRON_BEAM_OFF:
1652        case TURN_ELECTRON_BEAM_ON:
1653        {
1654            // codes that require permission check
1655            IPCThreadState* ipc = IPCThreadState::self();
1656            const int pid = ipc->getCallingPid();
1657            const int uid = ipc->getCallingUid();
1658            if ((uid != AID_GRAPHICS) &&
1659                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
1660                ALOGE("Permission Denial: "
1661                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1662                return PERMISSION_DENIED;
1663            }
1664            break;
1665        }
1666        case CAPTURE_SCREEN:
1667        {
1668            // codes that require permission check
1669            IPCThreadState* ipc = IPCThreadState::self();
1670            const int pid = ipc->getCallingPid();
1671            const int uid = ipc->getCallingUid();
1672            if ((uid != AID_GRAPHICS) &&
1673                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
1674                ALOGE("Permission Denial: "
1675                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
1676                return PERMISSION_DENIED;
1677            }
1678            break;
1679        }
1680    }
1681
1682    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1683    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1684        CHECK_INTERFACE(ISurfaceComposer, data, reply);
1685        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
1686            IPCThreadState* ipc = IPCThreadState::self();
1687            const int pid = ipc->getCallingPid();
1688            const int uid = ipc->getCallingUid();
1689            ALOGE("Permission Denial: "
1690                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1691            return PERMISSION_DENIED;
1692        }
1693        int n;
1694        switch (code) {
1695            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
1696            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
1697                return NO_ERROR;
1698            case 1002:  // SHOW_UPDATES
1699                n = data.readInt32();
1700                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1701                invalidateHwcGeometry();
1702                repaintEverything();
1703                return NO_ERROR;
1704            case 1004:{ // repaint everything
1705                repaintEverything();
1706                return NO_ERROR;
1707            }
1708            case 1005:{ // force transaction
1709                setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1710                return NO_ERROR;
1711            }
1712            case 1006:{ // send empty update
1713                signalRefresh();
1714                return NO_ERROR;
1715            }
1716            case 1008:  // toggle use of hw composer
1717                n = data.readInt32();
1718                mDebugDisableHWC = n ? 1 : 0;
1719                invalidateHwcGeometry();
1720                repaintEverything();
1721                return NO_ERROR;
1722            case 1009:  // toggle use of transform hint
1723                n = data.readInt32();
1724                mDebugDisableTransformHint = n ? 1 : 0;
1725                invalidateHwcGeometry();
1726                repaintEverything();
1727                return NO_ERROR;
1728            case 1010:  // interrogate.
1729                reply->writeInt32(0);
1730                reply->writeInt32(0);
1731                reply->writeInt32(mDebugRegion);
1732                reply->writeInt32(0);
1733                reply->writeInt32(mDebugDisableHWC);
1734                return NO_ERROR;
1735            case 1013: {
1736                Mutex::Autolock _l(mStateLock);
1737                const DisplayHardware& hw(graphicPlane(0).displayHardware());
1738                reply->writeInt32(hw.getPageFlipCount());
1739            }
1740            return NO_ERROR;
1741        }
1742    }
1743    return err;
1744}
1745
1746void SurfaceFlinger::repaintEverything() {
1747    const DisplayHardware& hw(graphicPlane(0).displayHardware());
1748    const Rect bounds(hw.getBounds());
1749    setInvalidateRegion(Region(bounds));
1750    signalTransaction();
1751}
1752
1753void SurfaceFlinger::setInvalidateRegion(const Region& reg) {
1754    Mutex::Autolock _l(mInvalidateLock);
1755    mInvalidateRegion = reg;
1756}
1757
1758Region SurfaceFlinger::getAndClearInvalidateRegion() {
1759    Mutex::Autolock _l(mInvalidateLock);
1760    Region reg(mInvalidateRegion);
1761    mInvalidateRegion.clear();
1762    return reg;
1763}
1764
1765// ---------------------------------------------------------------------------
1766
1767status_t SurfaceFlinger::renderScreenToTexture(DisplayID dpy,
1768        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
1769{
1770    Mutex::Autolock _l(mStateLock);
1771    return renderScreenToTextureLocked(dpy, textureName, uOut, vOut);
1772}
1773
1774status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy,
1775        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
1776{
1777    ATRACE_CALL();
1778
1779    if (!GLExtensions::getInstance().haveFramebufferObject())
1780        return INVALID_OPERATION;
1781
1782    // get screen geometry
1783    const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
1784    const uint32_t hw_w = hw.getWidth();
1785    const uint32_t hw_h = hw.getHeight();
1786    GLfloat u = 1;
1787    GLfloat v = 1;
1788
1789    // make sure to clear all GL error flags
1790    while ( glGetError() != GL_NO_ERROR ) ;
1791
1792    // create a FBO
1793    GLuint name, tname;
1794    glGenTextures(1, &tname);
1795    glBindTexture(GL_TEXTURE_2D, tname);
1796    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1797    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1798    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
1799            hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
1800    if (glGetError() != GL_NO_ERROR) {
1801        while ( glGetError() != GL_NO_ERROR ) ;
1802        GLint tw = (2 << (31 - clz(hw_w)));
1803        GLint th = (2 << (31 - clz(hw_h)));
1804        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
1805                tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
1806        u = GLfloat(hw_w) / tw;
1807        v = GLfloat(hw_h) / th;
1808    }
1809    glGenFramebuffersOES(1, &name);
1810    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
1811    glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
1812            GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
1813
1814    // redraw the screen entirely...
1815    glDisable(GL_TEXTURE_EXTERNAL_OES);
1816    glDisable(GL_TEXTURE_2D);
1817    glDisable(GL_SCISSOR_TEST);
1818    glClearColor(0,0,0,1);
1819    glClear(GL_COLOR_BUFFER_BIT);
1820    glMatrixMode(GL_MODELVIEW);
1821    glLoadIdentity();
1822    const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
1823    const size_t count = layers.size();
1824    for (size_t i=0 ; i<count ; ++i) {
1825        const sp<LayerBase>& layer(layers[i]);
1826        layer->drawForSreenShot();
1827    }
1828
1829    hw.compositionComplete();
1830
1831    // back to main framebuffer
1832    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
1833    glDisable(GL_SCISSOR_TEST);
1834    glDeleteFramebuffersOES(1, &name);
1835
1836    *textureName = tname;
1837    *uOut = u;
1838    *vOut = v;
1839    return NO_ERROR;
1840}
1841
1842// ---------------------------------------------------------------------------
1843
1844status_t SurfaceFlinger::electronBeamOffAnimationImplLocked()
1845{
1846    // get screen geometry
1847    const DisplayHardware& hw(graphicPlane(0).displayHardware());
1848    const uint32_t hw_w = hw.getWidth();
1849    const uint32_t hw_h = hw.getHeight();
1850    const Region screenBounds(hw.getBounds());
1851
1852    GLfloat u, v;
1853    GLuint tname;
1854    status_t result = renderScreenToTextureLocked(0, &tname, &u, &v);
1855    if (result != NO_ERROR) {
1856        return result;
1857    }
1858
1859    GLfloat vtx[8];
1860    const GLfloat texCoords[4][2] = { {0,0}, {0,v}, {u,v}, {u,0} };
1861    glBindTexture(GL_TEXTURE_2D, tname);
1862    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1863    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1864    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1865    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1866    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1867    glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
1868    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1869    glVertexPointer(2, GL_FLOAT, 0, vtx);
1870
1871    /*
1872     * Texture coordinate mapping
1873     *
1874     *                 u
1875     *    1 +----------+---+
1876     *      |     |    |   |  image is inverted
1877     *      |     V    |   |  w.r.t. the texture
1878     *  1-v +----------+   |  coordinates
1879     *      |              |
1880     *      |              |
1881     *      |              |
1882     *    0 +--------------+
1883     *      0              1
1884     *
1885     */
1886
1887    class s_curve_interpolator {
1888        const float nbFrames, s, v;
1889    public:
1890        s_curve_interpolator(int nbFrames, float s)
1891        : nbFrames(1.0f / (nbFrames-1)), s(s),
1892          v(1.0f + expf(-s + 0.5f*s)) {
1893        }
1894        float operator()(int f) {
1895            const float x = f * nbFrames;
1896            return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
1897        }
1898    };
1899
1900    class v_stretch {
1901        const GLfloat hw_w, hw_h;
1902    public:
1903        v_stretch(uint32_t hw_w, uint32_t hw_h)
1904        : hw_w(hw_w), hw_h(hw_h) {
1905        }
1906        void operator()(GLfloat* vtx, float v) {
1907            const GLfloat w = hw_w + (hw_w * v);
1908            const GLfloat h = hw_h - (hw_h * v);
1909            const GLfloat x = (hw_w - w) * 0.5f;
1910            const GLfloat y = (hw_h - h) * 0.5f;
1911            vtx[0] = x;         vtx[1] = y;
1912            vtx[2] = x;         vtx[3] = y + h;
1913            vtx[4] = x + w;     vtx[5] = y + h;
1914            vtx[6] = x + w;     vtx[7] = y;
1915        }
1916    };
1917
1918    class h_stretch {
1919        const GLfloat hw_w, hw_h;
1920    public:
1921        h_stretch(uint32_t hw_w, uint32_t hw_h)
1922        : hw_w(hw_w), hw_h(hw_h) {
1923        }
1924        void operator()(GLfloat* vtx, float v) {
1925            const GLfloat w = hw_w - (hw_w * v);
1926            const GLfloat h = 1.0f;
1927            const GLfloat x = (hw_w - w) * 0.5f;
1928            const GLfloat y = (hw_h - h) * 0.5f;
1929            vtx[0] = x;         vtx[1] = y;
1930            vtx[2] = x;         vtx[3] = y + h;
1931            vtx[4] = x + w;     vtx[5] = y + h;
1932            vtx[6] = x + w;     vtx[7] = y;
1933        }
1934    };
1935
1936    // the full animation is 24 frames
1937    char value[PROPERTY_VALUE_MAX];
1938    property_get("debug.sf.electron_frames", value, "24");
1939    int nbFrames = (atoi(value) + 1) >> 1;
1940    if (nbFrames <= 0) // just in case
1941        nbFrames = 24;
1942
1943    s_curve_interpolator itr(nbFrames, 7.5f);
1944    s_curve_interpolator itg(nbFrames, 8.0f);
1945    s_curve_interpolator itb(nbFrames, 8.5f);
1946
1947    v_stretch vverts(hw_w, hw_h);
1948
1949    glMatrixMode(GL_TEXTURE);
1950    glLoadIdentity();
1951    glMatrixMode(GL_MODELVIEW);
1952    glLoadIdentity();
1953
1954    glEnable(GL_BLEND);
1955    glBlendFunc(GL_ONE, GL_ONE);
1956    for (int i=0 ; i<nbFrames ; i++) {
1957        float x, y, w, h;
1958        const float vr = itr(i);
1959        const float vg = itg(i);
1960        const float vb = itb(i);
1961
1962        // clear screen
1963        glColorMask(1,1,1,1);
1964        glClear(GL_COLOR_BUFFER_BIT);
1965        glEnable(GL_TEXTURE_2D);
1966
1967        // draw the red plane
1968        vverts(vtx, vr);
1969        glColorMask(1,0,0,1);
1970        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1971
1972        // draw the green plane
1973        vverts(vtx, vg);
1974        glColorMask(0,1,0,1);
1975        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1976
1977        // draw the blue plane
1978        vverts(vtx, vb);
1979        glColorMask(0,0,1,1);
1980        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1981
1982        // draw the white highlight (we use the last vertices)
1983        glDisable(GL_TEXTURE_2D);
1984        glColorMask(1,1,1,1);
1985        glColor4f(vg, vg, vg, 1);
1986        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1987        hw.flip(screenBounds);
1988    }
1989
1990    h_stretch hverts(hw_w, hw_h);
1991    glDisable(GL_BLEND);
1992    glDisable(GL_TEXTURE_2D);
1993    glColorMask(1,1,1,1);
1994    for (int i=0 ; i<nbFrames ; i++) {
1995        const float v = itg(i);
1996        hverts(vtx, v);
1997        glClear(GL_COLOR_BUFFER_BIT);
1998        glColor4f(1-v, 1-v, 1-v, 1);
1999        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2000        hw.flip(screenBounds);
2001    }
2002
2003    glColorMask(1,1,1,1);
2004    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
2005    glDeleteTextures(1, &tname);
2006    glDisable(GL_TEXTURE_2D);
2007    glDisable(GL_BLEND);
2008    glDisable(GL_SCISSOR_TEST);
2009    return NO_ERROR;
2010}
2011
2012status_t SurfaceFlinger::electronBeamOnAnimationImplLocked()
2013{
2014    status_t result = PERMISSION_DENIED;
2015
2016    if (!GLExtensions::getInstance().haveFramebufferObject())
2017        return INVALID_OPERATION;
2018
2019
2020    // get screen geometry
2021    const DisplayHardware& hw(graphicPlane(0).displayHardware());
2022    const uint32_t hw_w = hw.getWidth();
2023    const uint32_t hw_h = hw.getHeight();
2024    const Region screenBounds(hw.bounds());
2025
2026    GLfloat u, v;
2027    GLuint tname;
2028    result = renderScreenToTextureLocked(0, &tname, &u, &v);
2029    if (result != NO_ERROR) {
2030        return result;
2031    }
2032
2033    GLfloat vtx[8];
2034    const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} };
2035    glBindTexture(GL_TEXTURE_2D, tname);
2036    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
2037    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2038    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2039    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2040    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2041    glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
2042    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
2043    glVertexPointer(2, GL_FLOAT, 0, vtx);
2044
2045    class s_curve_interpolator {
2046        const float nbFrames, s, v;
2047    public:
2048        s_curve_interpolator(int nbFrames, float s)
2049        : nbFrames(1.0f / (nbFrames-1)), s(s),
2050          v(1.0f + expf(-s + 0.5f*s)) {
2051        }
2052        float operator()(int f) {
2053            const float x = f * nbFrames;
2054            return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
2055        }
2056    };
2057
2058    class v_stretch {
2059        const GLfloat hw_w, hw_h;
2060    public:
2061        v_stretch(uint32_t hw_w, uint32_t hw_h)
2062        : hw_w(hw_w), hw_h(hw_h) {
2063        }
2064        void operator()(GLfloat* vtx, float v) {
2065            const GLfloat w = hw_w + (hw_w * v);
2066            const GLfloat h = hw_h - (hw_h * v);
2067            const GLfloat x = (hw_w - w) * 0.5f;
2068            const GLfloat y = (hw_h - h) * 0.5f;
2069            vtx[0] = x;         vtx[1] = y;
2070            vtx[2] = x;         vtx[3] = y + h;
2071            vtx[4] = x + w;     vtx[5] = y + h;
2072            vtx[6] = x + w;     vtx[7] = y;
2073        }
2074    };
2075
2076    class h_stretch {
2077        const GLfloat hw_w, hw_h;
2078    public:
2079        h_stretch(uint32_t hw_w, uint32_t hw_h)
2080        : hw_w(hw_w), hw_h(hw_h) {
2081        }
2082        void operator()(GLfloat* vtx, float v) {
2083            const GLfloat w = hw_w - (hw_w * v);
2084            const GLfloat h = 1.0f;
2085            const GLfloat x = (hw_w - w) * 0.5f;
2086            const GLfloat y = (hw_h - h) * 0.5f;
2087            vtx[0] = x;         vtx[1] = y;
2088            vtx[2] = x;         vtx[3] = y + h;
2089            vtx[4] = x + w;     vtx[5] = y + h;
2090            vtx[6] = x + w;     vtx[7] = y;
2091        }
2092    };
2093
2094    // the full animation is 12 frames
2095    int nbFrames = 8;
2096    s_curve_interpolator itr(nbFrames, 7.5f);
2097    s_curve_interpolator itg(nbFrames, 8.0f);
2098    s_curve_interpolator itb(nbFrames, 8.5f);
2099
2100    h_stretch hverts(hw_w, hw_h);
2101    glDisable(GL_BLEND);
2102    glDisable(GL_TEXTURE_2D);
2103    glColorMask(1,1,1,1);
2104    for (int i=nbFrames-1 ; i>=0 ; i--) {
2105        const float v = itg(i);
2106        hverts(vtx, v);
2107        glClear(GL_COLOR_BUFFER_BIT);
2108        glColor4f(1-v, 1-v, 1-v, 1);
2109        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2110        hw.flip(screenBounds);
2111    }
2112
2113    nbFrames = 4;
2114    v_stretch vverts(hw_w, hw_h);
2115    glEnable(GL_BLEND);
2116    glBlendFunc(GL_ONE, GL_ONE);
2117    for (int i=nbFrames-1 ; i>=0 ; i--) {
2118        float x, y, w, h;
2119        const float vr = itr(i);
2120        const float vg = itg(i);
2121        const float vb = itb(i);
2122
2123        // clear screen
2124        glColorMask(1,1,1,1);
2125        glClear(GL_COLOR_BUFFER_BIT);
2126        glEnable(GL_TEXTURE_2D);
2127
2128        // draw the red plane
2129        vverts(vtx, vr);
2130        glColorMask(1,0,0,1);
2131        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2132
2133        // draw the green plane
2134        vverts(vtx, vg);
2135        glColorMask(0,1,0,1);
2136        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2137
2138        // draw the blue plane
2139        vverts(vtx, vb);
2140        glColorMask(0,0,1,1);
2141        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2142
2143        hw.flip(screenBounds);
2144    }
2145
2146    glColorMask(1,1,1,1);
2147    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
2148    glDeleteTextures(1, &tname);
2149    glDisable(GL_TEXTURE_2D);
2150    glDisable(GL_BLEND);
2151    glDisable(GL_SCISSOR_TEST);
2152
2153    return NO_ERROR;
2154}
2155
2156// ---------------------------------------------------------------------------
2157
2158status_t SurfaceFlinger::turnElectronBeamOffImplLocked(int32_t mode)
2159{
2160    ATRACE_CALL();
2161
2162    DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
2163    if (!hw.canDraw()) {
2164        // we're already off
2165        return NO_ERROR;
2166    }
2167
2168    // turn off hwc while we're doing the animation
2169    hw.getHwComposer().disable();
2170    // and make sure to turn it back on (if needed) next time we compose
2171    invalidateHwcGeometry();
2172
2173    if (mode & ISurfaceComposer::eElectronBeamAnimationOff) {
2174        electronBeamOffAnimationImplLocked();
2175    }
2176
2177    // always clear the whole screen at the end of the animation
2178    glClearColor(0,0,0,1);
2179    glDisable(GL_SCISSOR_TEST);
2180    glClear(GL_COLOR_BUFFER_BIT);
2181    hw.flip( Region(hw.bounds()) );
2182
2183    return NO_ERROR;
2184}
2185
2186status_t SurfaceFlinger::turnElectronBeamOff(int32_t mode)
2187{
2188    class MessageTurnElectronBeamOff : public MessageBase {
2189        SurfaceFlinger* flinger;
2190        int32_t mode;
2191        status_t result;
2192    public:
2193        MessageTurnElectronBeamOff(SurfaceFlinger* flinger, int32_t mode)
2194            : flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
2195        }
2196        status_t getResult() const {
2197            return result;
2198        }
2199        virtual bool handler() {
2200            Mutex::Autolock _l(flinger->mStateLock);
2201            result = flinger->turnElectronBeamOffImplLocked(mode);
2202            return true;
2203        }
2204    };
2205
2206    sp<MessageBase> msg = new MessageTurnElectronBeamOff(this, mode);
2207    status_t res = postMessageSync(msg);
2208    if (res == NO_ERROR) {
2209        res = static_cast<MessageTurnElectronBeamOff*>( msg.get() )->getResult();
2210
2211        // work-around: when the power-manager calls us we activate the
2212        // animation. eventually, the "on" animation will be called
2213        // by the power-manager itself
2214        mElectronBeamAnimationMode = mode;
2215    }
2216    return res;
2217}
2218
2219// ---------------------------------------------------------------------------
2220
2221status_t SurfaceFlinger::turnElectronBeamOnImplLocked(int32_t mode)
2222{
2223    DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
2224    if (hw.canDraw()) {
2225        // we're already on
2226        return NO_ERROR;
2227    }
2228    if (mode & ISurfaceComposer::eElectronBeamAnimationOn) {
2229        electronBeamOnAnimationImplLocked();
2230    }
2231
2232    // make sure to redraw the whole screen when the animation is done
2233    mDirtyRegion.set(hw.bounds());
2234    signalTransaction();
2235
2236    return NO_ERROR;
2237}
2238
2239status_t SurfaceFlinger::turnElectronBeamOn(int32_t mode)
2240{
2241    class MessageTurnElectronBeamOn : public MessageBase {
2242        SurfaceFlinger* flinger;
2243        int32_t mode;
2244        status_t result;
2245    public:
2246        MessageTurnElectronBeamOn(SurfaceFlinger* flinger, int32_t mode)
2247            : flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
2248        }
2249        status_t getResult() const {
2250            return result;
2251        }
2252        virtual bool handler() {
2253            Mutex::Autolock _l(flinger->mStateLock);
2254            result = flinger->turnElectronBeamOnImplLocked(mode);
2255            return true;
2256        }
2257    };
2258
2259    postMessageAsync( new MessageTurnElectronBeamOn(this, mode) );
2260    return NO_ERROR;
2261}
2262
2263// ---------------------------------------------------------------------------
2264
2265status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy,
2266        sp<IMemoryHeap>* heap,
2267        uint32_t* w, uint32_t* h, PixelFormat* f,
2268        uint32_t sw, uint32_t sh,
2269        uint32_t minLayerZ, uint32_t maxLayerZ)
2270{
2271    ATRACE_CALL();
2272
2273    status_t result = PERMISSION_DENIED;
2274
2275    // only one display supported for now
2276    if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2277        return BAD_VALUE;
2278
2279    if (!GLExtensions::getInstance().haveFramebufferObject())
2280        return INVALID_OPERATION;
2281
2282    // get screen geometry
2283    const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
2284    const uint32_t hw_w = hw.getWidth();
2285    const uint32_t hw_h = hw.getHeight();
2286
2287    if ((sw > hw_w) || (sh > hw_h))
2288        return BAD_VALUE;
2289
2290    sw = (!sw) ? hw_w : sw;
2291    sh = (!sh) ? hw_h : sh;
2292    const size_t size = sw * sh * 4;
2293
2294    //ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2295    //        sw, sh, minLayerZ, maxLayerZ);
2296
2297    // make sure to clear all GL error flags
2298    while ( glGetError() != GL_NO_ERROR ) ;
2299
2300    // create a FBO
2301    GLuint name, tname;
2302    glGenRenderbuffersOES(1, &tname);
2303    glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2304    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2305
2306    glGenFramebuffersOES(1, &name);
2307    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2308    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2309            GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2310
2311    GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2312
2313    if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2314
2315        // invert everything, b/c glReadPixel() below will invert the FB
2316        glViewport(0, 0, sw, sh);
2317        glScissor(0, 0, sw, sh);
2318        glMatrixMode(GL_PROJECTION);
2319        glPushMatrix();
2320        glLoadIdentity();
2321        glOrthof(0, hw_w, hw_h, 0, 0, 1);
2322        glMatrixMode(GL_MODELVIEW);
2323
2324        // redraw the screen entirely...
2325        glClearColor(0,0,0,1);
2326        glClear(GL_COLOR_BUFFER_BIT);
2327
2328        const LayerVector& layers(mDrawingState.layersSortedByZ);
2329        const size_t count = layers.size();
2330        for (size_t i=0 ; i<count ; ++i) {
2331            const sp<LayerBase>& layer(layers[i]);
2332            const uint32_t flags = layer->drawingState().flags;
2333            if (!(flags & ISurfaceComposer::eLayerHidden)) {
2334                const uint32_t z = layer->drawingState().z;
2335                if (z >= minLayerZ && z <= maxLayerZ) {
2336                    layer->drawForSreenShot();
2337                }
2338            }
2339        }
2340
2341        // XXX: this is needed on tegra
2342        glEnable(GL_SCISSOR_TEST);
2343        glScissor(0, 0, sw, sh);
2344
2345        // check for errors and return screen capture
2346        if (glGetError() != GL_NO_ERROR) {
2347            // error while rendering
2348            result = INVALID_OPERATION;
2349        } else {
2350            // allocate shared memory large enough to hold the
2351            // screen capture
2352            sp<MemoryHeapBase> base(
2353                    new MemoryHeapBase(size, 0, "screen-capture") );
2354            void* const ptr = base->getBase();
2355            if (ptr) {
2356                // capture the screen with glReadPixels()
2357                ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2358                glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2359                if (glGetError() == GL_NO_ERROR) {
2360                    *heap = base;
2361                    *w = sw;
2362                    *h = sh;
2363                    *f = PIXEL_FORMAT_RGBA_8888;
2364                    result = NO_ERROR;
2365                }
2366            } else {
2367                result = NO_MEMORY;
2368            }
2369        }
2370        glDisable(GL_SCISSOR_TEST);
2371        glViewport(0, 0, hw_w, hw_h);
2372        glMatrixMode(GL_PROJECTION);
2373        glPopMatrix();
2374        glMatrixMode(GL_MODELVIEW);
2375    } else {
2376        result = BAD_VALUE;
2377    }
2378
2379    // release FBO resources
2380    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2381    glDeleteRenderbuffersOES(1, &tname);
2382    glDeleteFramebuffersOES(1, &name);
2383
2384    hw.compositionComplete();
2385
2386    // ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2387
2388    return result;
2389}
2390
2391
2392status_t SurfaceFlinger::captureScreen(DisplayID dpy,
2393        sp<IMemoryHeap>* heap,
2394        uint32_t* width, uint32_t* height, PixelFormat* format,
2395        uint32_t sw, uint32_t sh,
2396        uint32_t minLayerZ, uint32_t maxLayerZ)
2397{
2398    // only one display supported for now
2399    if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2400        return BAD_VALUE;
2401
2402    if (!GLExtensions::getInstance().haveFramebufferObject())
2403        return INVALID_OPERATION;
2404
2405    class MessageCaptureScreen : public MessageBase {
2406        SurfaceFlinger* flinger;
2407        DisplayID dpy;
2408        sp<IMemoryHeap>* heap;
2409        uint32_t* w;
2410        uint32_t* h;
2411        PixelFormat* f;
2412        uint32_t sw;
2413        uint32_t sh;
2414        uint32_t minLayerZ;
2415        uint32_t maxLayerZ;
2416        status_t result;
2417    public:
2418        MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy,
2419                sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2420                uint32_t sw, uint32_t sh,
2421                uint32_t minLayerZ, uint32_t maxLayerZ)
2422            : flinger(flinger), dpy(dpy),
2423              heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2424              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2425              result(PERMISSION_DENIED)
2426        {
2427        }
2428        status_t getResult() const {
2429            return result;
2430        }
2431        virtual bool handler() {
2432            Mutex::Autolock _l(flinger->mStateLock);
2433
2434            // if we have secure windows, never allow the screen capture
2435            if (flinger->mSecureFrameBuffer)
2436                return true;
2437
2438            result = flinger->captureScreenImplLocked(dpy,
2439                    heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2440
2441            return true;
2442        }
2443    };
2444
2445    sp<MessageBase> msg = new MessageCaptureScreen(this,
2446            dpy, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2447    status_t res = postMessageSync(msg);
2448    if (res == NO_ERROR) {
2449        res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2450    }
2451    return res;
2452}
2453
2454// ---------------------------------------------------------------------------
2455
2456sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const
2457{
2458    sp<Layer> result;
2459    Mutex::Autolock _l(mStateLock);
2460    result = mLayerMap.valueFor( sur->asBinder() ).promote();
2461    return result;
2462}
2463
2464// ---------------------------------------------------------------------------
2465
2466Client::Client(const sp<SurfaceFlinger>& flinger)
2467    : mFlinger(flinger), mNameGenerator(1)
2468{
2469}
2470
2471Client::~Client()
2472{
2473    const size_t count = mLayers.size();
2474    for (size_t i=0 ; i<count ; i++) {
2475        sp<LayerBaseClient> layer(mLayers.valueAt(i).promote());
2476        if (layer != 0) {
2477            mFlinger->removeLayer(layer);
2478        }
2479    }
2480}
2481
2482status_t Client::initCheck() const {
2483    return NO_ERROR;
2484}
2485
2486size_t Client::attachLayer(const sp<LayerBaseClient>& layer)
2487{
2488    Mutex::Autolock _l(mLock);
2489    size_t name = mNameGenerator++;
2490    mLayers.add(name, layer);
2491    return name;
2492}
2493
2494void Client::detachLayer(const LayerBaseClient* layer)
2495{
2496    Mutex::Autolock _l(mLock);
2497    // we do a linear search here, because this doesn't happen often
2498    const size_t count = mLayers.size();
2499    for (size_t i=0 ; i<count ; i++) {
2500        if (mLayers.valueAt(i) == layer) {
2501            mLayers.removeItemsAt(i, 1);
2502            break;
2503        }
2504    }
2505}
2506sp<LayerBaseClient> Client::getLayerUser(int32_t i) const
2507{
2508    Mutex::Autolock _l(mLock);
2509    sp<LayerBaseClient> lbc;
2510    wp<LayerBaseClient> layer(mLayers.valueFor(i));
2511    if (layer != 0) {
2512        lbc = layer.promote();
2513        ALOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i));
2514    }
2515    return lbc;
2516}
2517
2518
2519status_t Client::onTransact(
2520    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2521{
2522    // these must be checked
2523     IPCThreadState* ipc = IPCThreadState::self();
2524     const int pid = ipc->getCallingPid();
2525     const int uid = ipc->getCallingUid();
2526     const int self_pid = getpid();
2527     if (CC_UNLIKELY(pid != self_pid && uid != AID_GRAPHICS && uid != 0)) {
2528         // we're called from a different process, do the real check
2529         if (!PermissionCache::checkCallingPermission(sAccessSurfaceFlinger))
2530         {
2531             ALOGE("Permission Denial: "
2532                     "can't openGlobalTransaction pid=%d, uid=%d", pid, uid);
2533             return PERMISSION_DENIED;
2534         }
2535     }
2536     return BnSurfaceComposerClient::onTransact(code, data, reply, flags);
2537}
2538
2539
2540sp<ISurface> Client::createSurface(
2541        ISurfaceComposerClient::surface_data_t* params,
2542        const String8& name,
2543        DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2544        uint32_t flags)
2545{
2546    /*
2547     * createSurface must be called from the GL thread so that it can
2548     * have access to the GL context.
2549     */
2550
2551    class MessageCreateSurface : public MessageBase {
2552        sp<ISurface> result;
2553        SurfaceFlinger* flinger;
2554        ISurfaceComposerClient::surface_data_t* params;
2555        Client* client;
2556        const String8& name;
2557        DisplayID display;
2558        uint32_t w, h;
2559        PixelFormat format;
2560        uint32_t flags;
2561    public:
2562        MessageCreateSurface(SurfaceFlinger* flinger,
2563                ISurfaceComposerClient::surface_data_t* params,
2564                const String8& name, Client* client,
2565                DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2566                uint32_t flags)
2567            : flinger(flinger), params(params), client(client), name(name),
2568              display(display), w(w), h(h), format(format), flags(flags)
2569        {
2570        }
2571        sp<ISurface> getResult() const { return result; }
2572        virtual bool handler() {
2573            result = flinger->createSurface(params, name, client,
2574                    display, w, h, format, flags);
2575            return true;
2576        }
2577    };
2578
2579    sp<MessageBase> msg = new MessageCreateSurface(mFlinger.get(),
2580            params, name, this, display, w, h, format, flags);
2581    mFlinger->postMessageSync(msg);
2582    return static_cast<MessageCreateSurface*>( msg.get() )->getResult();
2583}
2584status_t Client::destroySurface(SurfaceID sid) {
2585    return mFlinger->removeSurface(this, sid);
2586}
2587
2588// ---------------------------------------------------------------------------
2589
2590GraphicBufferAlloc::GraphicBufferAlloc() {}
2591
2592GraphicBufferAlloc::~GraphicBufferAlloc() {}
2593
2594sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
2595        PixelFormat format, uint32_t usage, status_t* error) {
2596    sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
2597    status_t err = graphicBuffer->initCheck();
2598    *error = err;
2599    if (err != 0 || graphicBuffer->handle == 0) {
2600        if (err == NO_MEMORY) {
2601            GraphicBuffer::dumpAllocationsToSystemLog();
2602        }
2603        ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
2604             "failed (%s), handle=%p",
2605                w, h, strerror(-err), graphicBuffer->handle);
2606        return 0;
2607    }
2608    return graphicBuffer;
2609}
2610
2611// ---------------------------------------------------------------------------
2612
2613GraphicPlane::GraphicPlane()
2614    : mHw(0)
2615{
2616}
2617
2618GraphicPlane::~GraphicPlane() {
2619    delete mHw;
2620}
2621
2622bool GraphicPlane::initialized() const {
2623    return mHw ? true : false;
2624}
2625
2626int GraphicPlane::getWidth() const {
2627    return mWidth;
2628}
2629
2630int GraphicPlane::getHeight() const {
2631    return mHeight;
2632}
2633
2634void GraphicPlane::setDisplayHardware(DisplayHardware *hw)
2635{
2636    mHw = hw;
2637
2638    // initialize the display orientation transform.
2639    // it's a constant that should come from the display driver.
2640    int displayOrientation = ISurfaceComposer::eOrientationDefault;
2641    char property[PROPERTY_VALUE_MAX];
2642    if (property_get("ro.sf.hwrotation", property, NULL) > 0) {
2643        //displayOrientation
2644        switch (atoi(property)) {
2645        case 90:
2646            displayOrientation = ISurfaceComposer::eOrientation90;
2647            break;
2648        case 270:
2649            displayOrientation = ISurfaceComposer::eOrientation270;
2650            break;
2651        }
2652    }
2653
2654    const float w = hw->getWidth();
2655    const float h = hw->getHeight();
2656    GraphicPlane::orientationToTransfrom(displayOrientation, w, h,
2657            &mDisplayTransform);
2658    if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) {
2659        mDisplayWidth = h;
2660        mDisplayHeight = w;
2661    } else {
2662        mDisplayWidth = w;
2663        mDisplayHeight = h;
2664    }
2665
2666    setOrientation(ISurfaceComposer::eOrientationDefault);
2667}
2668
2669status_t GraphicPlane::orientationToTransfrom(
2670        int orientation, int w, int h, Transform* tr)
2671{
2672    uint32_t flags = 0;
2673    switch (orientation) {
2674    case ISurfaceComposer::eOrientationDefault:
2675        flags = Transform::ROT_0;
2676        break;
2677    case ISurfaceComposer::eOrientation90:
2678        flags = Transform::ROT_90;
2679        break;
2680    case ISurfaceComposer::eOrientation180:
2681        flags = Transform::ROT_180;
2682        break;
2683    case ISurfaceComposer::eOrientation270:
2684        flags = Transform::ROT_270;
2685        break;
2686    default:
2687        return BAD_VALUE;
2688    }
2689    tr->set(flags, w, h);
2690    return NO_ERROR;
2691}
2692
2693status_t GraphicPlane::setOrientation(int orientation)
2694{
2695    // If the rotation can be handled in hardware, this is where
2696    // the magic should happen.
2697
2698    const DisplayHardware& hw(displayHardware());
2699    const float w = mDisplayWidth;
2700    const float h = mDisplayHeight;
2701    mWidth = int(w);
2702    mHeight = int(h);
2703
2704    Transform orientationTransform;
2705    GraphicPlane::orientationToTransfrom(orientation, w, h,
2706            &orientationTransform);
2707    if (orientation & ISurfaceComposer::eOrientationSwapMask) {
2708        mWidth = int(h);
2709        mHeight = int(w);
2710    }
2711
2712    mOrientation = orientation;
2713    mGlobalTransform = mDisplayTransform * orientationTransform;
2714    return NO_ERROR;
2715}
2716
2717const DisplayHardware& GraphicPlane::displayHardware() const {
2718    return *mHw;
2719}
2720
2721DisplayHardware& GraphicPlane::editDisplayHardware() {
2722    return *mHw;
2723}
2724
2725const Transform& GraphicPlane::transform() const {
2726    return mGlobalTransform;
2727}
2728
2729EGLDisplay GraphicPlane::getEGLDisplay() const {
2730    return mHw->getEGLDisplay();
2731}
2732
2733// ---------------------------------------------------------------------------
2734
2735}; // namespace android
2736