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