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