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