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