SurfaceFlinger.cpp revision df85c455c34a920d22a8e3f7459a1cc615efcd27
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
36#include <utils/String8.h>
37#include <utils/String16.h>
38#include <utils/StopWatch.h>
39
40#include <ui/GraphicBufferAllocator.h>
41#include <ui/GraphicLog.h>
42#include <ui/PixelFormat.h>
43
44#include <pixelflinger/pixelflinger.h>
45#include <GLES/gl.h>
46
47#include "clz.h"
48#include "GLExtensions.h"
49#include "Layer.h"
50#include "LayerBlur.h"
51#include "LayerBuffer.h"
52#include "LayerDim.h"
53#include "SurfaceFlinger.h"
54
55#include "DisplayHardware/DisplayHardware.h"
56
57/* ideally AID_GRAPHICS would be in a semi-public header
58 * or there would be a way to map a user/group name to its id
59 */
60#ifndef AID_GRAPHICS
61#define AID_GRAPHICS 1003
62#endif
63
64#define DISPLAY_COUNT       1
65
66namespace android {
67// ---------------------------------------------------------------------------
68
69SurfaceFlinger::SurfaceFlinger()
70    :   BnSurfaceComposer(), Thread(false),
71        mTransactionFlags(0),
72        mTransactionCount(0),
73        mResizeTransationPending(false),
74        mLayersRemoved(false),
75        mBootTime(systemTime()),
76        mHardwareTest("android.permission.HARDWARE_TEST"),
77        mAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"),
78        mReadFramebuffer("android.permission.READ_FRAME_BUFFER"),
79        mDump("android.permission.DUMP"),
80        mVisibleRegionsDirty(false),
81        mDeferReleaseConsole(false),
82        mFreezeDisplay(false),
83        mFreezeCount(0),
84        mFreezeDisplayTime(0),
85        mDebugRegion(0),
86        mDebugBackground(0),
87        mDebugInSwapBuffers(0),
88        mLastSwapBufferTime(0),
89        mDebugInTransaction(0),
90        mLastTransactionTime(0),
91        mBootFinished(false),
92        mConsoleSignals(0),
93        mSecureFrameBuffer(0)
94{
95    init();
96}
97
98void SurfaceFlinger::init()
99{
100    LOGI("SurfaceFlinger is starting");
101
102    // debugging stuff...
103    char value[PROPERTY_VALUE_MAX];
104    property_get("debug.sf.showupdates", value, "0");
105    mDebugRegion = atoi(value);
106    property_get("debug.sf.showbackground", value, "0");
107    mDebugBackground = atoi(value);
108
109    LOGI_IF(mDebugRegion,       "showupdates enabled");
110    LOGI_IF(mDebugBackground,   "showbackground enabled");
111}
112
113SurfaceFlinger::~SurfaceFlinger()
114{
115    glDeleteTextures(1, &mWormholeTexName);
116}
117
118overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
119{
120    return graphicPlane(0).displayHardware().getOverlayEngine();
121}
122
123sp<IMemoryHeap> SurfaceFlinger::getCblk() const
124{
125    return mServerHeap;
126}
127
128sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
129{
130    sp<ISurfaceComposerClient> bclient;
131    sp<Client> client(new Client(this));
132    status_t err = client->initCheck();
133    if (err == NO_ERROR) {
134        bclient = client;
135    }
136    return bclient;
137}
138
139sp<ISurfaceComposerClient> SurfaceFlinger::createClientConnection()
140{
141    sp<ISurfaceComposerClient> bclient;
142    sp<UserClient> client(new UserClient(this));
143    status_t err = client->initCheck();
144    if (err == NO_ERROR) {
145        bclient = client;
146    }
147    return bclient;
148}
149
150
151const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
152{
153    LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
154    const GraphicPlane& plane(mGraphicPlanes[dpy]);
155    return plane;
156}
157
158GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
159{
160    return const_cast<GraphicPlane&>(
161        const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
162}
163
164void SurfaceFlinger::bootFinished()
165{
166    const nsecs_t now = systemTime();
167    const nsecs_t duration = now - mBootTime;
168    LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
169    mBootFinished = true;
170    property_set("ctl.stop", "bootanim");
171}
172
173void SurfaceFlinger::onFirstRef()
174{
175    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
176
177    // Wait for the main thread to be done with its initialization
178    mReadyToRunBarrier.wait();
179}
180
181static inline uint16_t pack565(int r, int g, int b) {
182    return (r<<11)|(g<<5)|b;
183}
184
185status_t SurfaceFlinger::readyToRun()
186{
187    LOGI(   "SurfaceFlinger's main thread ready to run. "
188            "Initializing graphics H/W...");
189
190    // we only support one display currently
191    int dpy = 0;
192
193    {
194        // initialize the main display
195        GraphicPlane& plane(graphicPlane(dpy));
196        DisplayHardware* const hw = new DisplayHardware(this, dpy);
197        plane.setDisplayHardware(hw);
198    }
199
200    // create the shared control-block
201    mServerHeap = new MemoryHeapBase(4096,
202            MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap");
203    LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
204
205    mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase());
206    LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
207
208    new(mServerCblk) surface_flinger_cblk_t;
209
210    // initialize primary screen
211    // (other display should be initialized in the same manner, but
212    // asynchronously, as they could come and go. None of this is supported
213    // yet).
214    const GraphicPlane& plane(graphicPlane(dpy));
215    const DisplayHardware& hw = plane.displayHardware();
216    const uint32_t w = hw.getWidth();
217    const uint32_t h = hw.getHeight();
218    const uint32_t f = hw.getFormat();
219    hw.makeCurrent();
220
221    // initialize the shared control block
222    mServerCblk->connected |= 1<<dpy;
223    display_cblk_t* dcblk = mServerCblk->displays + dpy;
224    memset(dcblk, 0, sizeof(display_cblk_t));
225    dcblk->w            = plane.getWidth();
226    dcblk->h            = plane.getHeight();
227    dcblk->format       = f;
228    dcblk->orientation  = ISurfaceComposer::eOrientationDefault;
229    dcblk->xdpi         = hw.getDpiX();
230    dcblk->ydpi         = hw.getDpiY();
231    dcblk->fps          = hw.getRefreshRate();
232    dcblk->density      = hw.getDensity();
233
234    // Initialize OpenGL|ES
235    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
236    glPixelStorei(GL_PACK_ALIGNMENT, 4);
237    glEnableClientState(GL_VERTEX_ARRAY);
238    glEnable(GL_SCISSOR_TEST);
239    glShadeModel(GL_FLAT);
240    glDisable(GL_DITHER);
241    glDisable(GL_CULL_FACE);
242
243    const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
244    const uint16_t g1 = pack565(0x17,0x2f,0x17);
245    const uint16_t textureData[4] = { g0, g1, g1, g0 };
246    glGenTextures(1, &mWormholeTexName);
247    glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
248    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
249    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
250    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
251    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
252    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
253            GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
254
255    glViewport(0, 0, w, h);
256    glMatrixMode(GL_PROJECTION);
257    glLoadIdentity();
258    glOrthof(0, w, h, 0, 0, 1);
259
260   LayerDim::initDimmer(this, w, h);
261
262    mReadyToRunBarrier.open();
263
264    /*
265     *  We're now ready to accept clients...
266     */
267
268    // start boot animation
269    property_set("ctl.start", "bootanim");
270
271    return NO_ERROR;
272}
273
274// ----------------------------------------------------------------------------
275#if 0
276#pragma mark -
277#pragma mark Events Handler
278#endif
279
280void SurfaceFlinger::waitForEvent()
281{
282    while (true) {
283        nsecs_t timeout = -1;
284        const nsecs_t freezeDisplayTimeout = ms2ns(5000);
285        if (UNLIKELY(isFrozen())) {
286            // wait 5 seconds
287            const nsecs_t now = systemTime();
288            if (mFreezeDisplayTime == 0) {
289                mFreezeDisplayTime = now;
290            }
291            nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
292            timeout = waitTime>0 ? waitTime : 0;
293        }
294
295        sp<MessageBase> msg = mEventQueue.waitMessage(timeout);
296
297        // see if we timed out
298        if (isFrozen()) {
299            const nsecs_t now = systemTime();
300            nsecs_t frozenTime = (now - mFreezeDisplayTime);
301            if (frozenTime >= freezeDisplayTimeout) {
302                // we timed out and are still frozen
303                LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
304                        mFreezeDisplay, mFreezeCount);
305                mFreezeDisplayTime = 0;
306                mFreezeCount = 0;
307                mFreezeDisplay = false;
308            }
309        }
310
311        if (msg != 0) {
312            switch (msg->what) {
313                case MessageQueue::INVALIDATE:
314                    // invalidate message, just return to the main loop
315                    return;
316            }
317        }
318    }
319}
320
321void SurfaceFlinger::signalEvent() {
322    mEventQueue.invalidate();
323}
324
325void SurfaceFlinger::signal() const {
326    // this is the IPC call
327    const_cast<SurfaceFlinger*>(this)->signalEvent();
328}
329
330status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
331        nsecs_t reltime, uint32_t flags)
332{
333    return mEventQueue.postMessage(msg, reltime, flags);
334}
335
336status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
337        nsecs_t reltime, uint32_t flags)
338{
339    status_t res = mEventQueue.postMessage(msg, reltime, flags);
340    if (res == NO_ERROR) {
341        msg->wait();
342    }
343    return res;
344}
345
346// ----------------------------------------------------------------------------
347#if 0
348#pragma mark -
349#pragma mark Main loop
350#endif
351
352bool SurfaceFlinger::threadLoop()
353{
354    waitForEvent();
355
356    // check for transactions
357    if (UNLIKELY(mConsoleSignals)) {
358        handleConsoleEvents();
359    }
360
361    if (LIKELY(mTransactionCount == 0)) {
362        // if we're in a global transaction, don't do anything.
363        const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
364        uint32_t transactionFlags = getTransactionFlags(mask);
365        if (LIKELY(transactionFlags)) {
366            handleTransaction(transactionFlags);
367        }
368    }
369
370    // post surfaces (if needed)
371    handlePageFlip();
372
373    const DisplayHardware& hw(graphicPlane(0).displayHardware());
374    if (LIKELY(hw.canDraw() && !isFrozen())) {
375        // repaint the framebuffer (if needed)
376
377        const int index = hw.getCurrentBufferIndex();
378        GraphicLog& logger(GraphicLog::getInstance());
379
380        logger.log(GraphicLog::SF_REPAINT, index);
381        handleRepaint();
382
383        // inform the h/w that we're done compositing
384        logger.log(GraphicLog::SF_COMPOSITION_COMPLETE, index);
385        hw.compositionComplete();
386
387        // release the clients before we flip ('cause flip might block)
388        logger.log(GraphicLog::SF_UNLOCK_CLIENTS, index);
389        unlockClients();
390
391        logger.log(GraphicLog::SF_SWAP_BUFFERS, index);
392        postFramebuffer();
393
394        logger.log(GraphicLog::SF_REPAINT_DONE, index);
395    } else {
396        // pretend we did the post
397        unlockClients();
398        usleep(16667); // 60 fps period
399    }
400    return true;
401}
402
403void SurfaceFlinger::postFramebuffer()
404{
405    if (!mInvalidRegion.isEmpty()) {
406        const DisplayHardware& hw(graphicPlane(0).displayHardware());
407        const nsecs_t now = systemTime();
408        mDebugInSwapBuffers = now;
409        hw.flip(mInvalidRegion);
410        mLastSwapBufferTime = systemTime() - now;
411        mDebugInSwapBuffers = 0;
412        mInvalidRegion.clear();
413    }
414}
415
416void SurfaceFlinger::handleConsoleEvents()
417{
418    // something to do with the console
419    const DisplayHardware& hw = graphicPlane(0).displayHardware();
420
421    int what = android_atomic_and(0, &mConsoleSignals);
422    if (what & eConsoleAcquired) {
423        hw.acquireScreen();
424    }
425
426    if (mDeferReleaseConsole && hw.canDraw()) {
427        // We got the release signal before the acquire signal
428        mDeferReleaseConsole = false;
429        hw.releaseScreen();
430    }
431
432    if (what & eConsoleReleased) {
433        if (hw.canDraw()) {
434            hw.releaseScreen();
435        } else {
436            mDeferReleaseConsole = true;
437        }
438    }
439
440    mDirtyRegion.set(hw.bounds());
441}
442
443void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
444{
445    Vector< sp<LayerBase> > ditchedLayers;
446
447    /*
448     * Perform and commit the transaction
449     */
450
451    { // scope for the lock
452        Mutex::Autolock _l(mStateLock);
453        const nsecs_t now = systemTime();
454        mDebugInTransaction = now;
455        handleTransactionLocked(transactionFlags, ditchedLayers);
456        mLastTransactionTime = systemTime() - now;
457        mDebugInTransaction = 0;
458        // here the transaction has been committed
459    }
460
461    /*
462     * Clean-up all layers that went away
463     * (do this without the lock held)
464     */
465    const size_t count = ditchedLayers.size();
466    for (size_t i=0 ; i<count ; i++) {
467        if (ditchedLayers[i] != 0) {
468            //LOGD("ditching layer %p", ditchedLayers[i].get());
469            ditchedLayers[i]->ditch();
470        }
471    }
472}
473
474void SurfaceFlinger::handleTransactionLocked(
475        uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers)
476{
477    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
478    const size_t count = currentLayers.size();
479
480    /*
481     * Traversal of the children
482     * (perform the transaction for each of them if needed)
483     */
484
485    const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
486    if (layersNeedTransaction) {
487        for (size_t i=0 ; i<count ; i++) {
488            const sp<LayerBase>& layer = currentLayers[i];
489            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
490            if (!trFlags) continue;
491
492            const uint32_t flags = layer->doTransaction(0);
493            if (flags & Layer::eVisibleRegion)
494                mVisibleRegionsDirty = true;
495        }
496    }
497
498    /*
499     * Perform our own transaction if needed
500     */
501
502    if (transactionFlags & eTransactionNeeded) {
503        if (mCurrentState.orientation != mDrawingState.orientation) {
504            // the orientation has changed, recompute all visible regions
505            // and invalidate everything.
506
507            const int dpy = 0;
508            const int orientation = mCurrentState.orientation;
509            const uint32_t type = mCurrentState.orientationType;
510            GraphicPlane& plane(graphicPlane(dpy));
511            plane.setOrientation(orientation);
512
513            // update the shared control block
514            const DisplayHardware& hw(plane.displayHardware());
515            volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
516            dcblk->orientation = orientation;
517            dcblk->w = plane.getWidth();
518            dcblk->h = plane.getHeight();
519
520            mVisibleRegionsDirty = true;
521            mDirtyRegion.set(hw.bounds());
522        }
523
524        if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
525            // freezing or unfreezing the display -> trigger animation if needed
526            mFreezeDisplay = mCurrentState.freezeDisplay;
527            if (mFreezeDisplay)
528                 mFreezeDisplayTime = 0;
529        }
530
531        if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
532            // layers have been added
533            mVisibleRegionsDirty = true;
534        }
535
536        // some layers might have been removed, so
537        // we need to update the regions they're exposing.
538        if (mLayersRemoved) {
539            mLayersRemoved = false;
540            mVisibleRegionsDirty = true;
541            const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
542            const size_t count = previousLayers.size();
543            for (size_t i=0 ; i<count ; i++) {
544                const sp<LayerBase>& layer(previousLayers[i]);
545                if (currentLayers.indexOf( layer ) < 0) {
546                    // this layer is not visible anymore
547                    ditchedLayers.add(layer);
548                    mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen);
549                }
550            }
551        }
552    }
553
554    commitTransaction();
555}
556
557sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
558{
559    return new FreezeLock(const_cast<SurfaceFlinger *>(this));
560}
561
562void SurfaceFlinger::computeVisibleRegions(
563    LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
564{
565    const GraphicPlane& plane(graphicPlane(0));
566    const Transform& planeTransform(plane.transform());
567    const DisplayHardware& hw(plane.displayHardware());
568    const Region screenRegion(hw.bounds());
569
570    Region aboveOpaqueLayers;
571    Region aboveCoveredLayers;
572    Region dirty;
573
574    bool secureFrameBuffer = false;
575
576    size_t i = currentLayers.size();
577    while (i--) {
578        const sp<LayerBase>& layer = currentLayers[i];
579        layer->validateVisibility(planeTransform);
580
581        // start with the whole surface at its current location
582        const Layer::State& s(layer->drawingState());
583
584        /*
585         * opaqueRegion: area of a surface that is fully opaque.
586         */
587        Region opaqueRegion;
588
589        /*
590         * visibleRegion: area of a surface that is visible on screen
591         * and not fully transparent. This is essentially the layer's
592         * footprint minus the opaque regions above it.
593         * Areas covered by a translucent surface are considered visible.
594         */
595        Region visibleRegion;
596
597        /*
598         * coveredRegion: area of a surface that is covered by all
599         * visible regions above it (which includes the translucent areas).
600         */
601        Region coveredRegion;
602
603
604        // handle hidden surfaces by setting the visible region to empty
605        if (LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) {
606            const bool translucent = layer->needsBlending();
607            const Rect bounds(layer->visibleBounds());
608            visibleRegion.set(bounds);
609            visibleRegion.andSelf(screenRegion);
610            if (!visibleRegion.isEmpty()) {
611                // Remove the transparent area from the visible region
612                if (translucent) {
613                    visibleRegion.subtractSelf(layer->transparentRegionScreen);
614                }
615
616                // compute the opaque region
617                const int32_t layerOrientation = layer->getOrientation();
618                if (s.alpha==255 && !translucent &&
619                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
620                    // the opaque region is the layer's footprint
621                    opaqueRegion = visibleRegion;
622                }
623            }
624        }
625
626        // Clip the covered region to the visible region
627        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
628
629        // Update aboveCoveredLayers for next (lower) layer
630        aboveCoveredLayers.orSelf(visibleRegion);
631
632        // subtract the opaque region covered by the layers above us
633        visibleRegion.subtractSelf(aboveOpaqueLayers);
634
635        // compute this layer's dirty region
636        if (layer->contentDirty) {
637            // we need to invalidate the whole region
638            dirty = visibleRegion;
639            // as well, as the old visible region
640            dirty.orSelf(layer->visibleRegionScreen);
641            layer->contentDirty = false;
642        } else {
643            /* compute the exposed region:
644             *   the exposed region consists of two components:
645             *   1) what's VISIBLE now and was COVERED before
646             *   2) what's EXPOSED now less what was EXPOSED before
647             *
648             * note that (1) is conservative, we start with the whole
649             * visible region but only keep what used to be covered by
650             * something -- which mean it may have been exposed.
651             *
652             * (2) handles areas that were not covered by anything but got
653             * exposed because of a resize.
654             */
655            const Region newExposed = visibleRegion - coveredRegion;
656            const Region oldVisibleRegion = layer->visibleRegionScreen;
657            const Region oldCoveredRegion = layer->coveredRegionScreen;
658            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
659            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
660        }
661        dirty.subtractSelf(aboveOpaqueLayers);
662
663        // accumulate to the screen dirty region
664        dirtyRegion.orSelf(dirty);
665
666        // Update aboveOpaqueLayers for next (lower) layer
667        aboveOpaqueLayers.orSelf(opaqueRegion);
668
669        // Store the visible region is screen space
670        layer->setVisibleRegion(visibleRegion);
671        layer->setCoveredRegion(coveredRegion);
672
673        // If a secure layer is partially visible, lock-down the screen!
674        if (layer->isSecure() && !visibleRegion.isEmpty()) {
675            secureFrameBuffer = true;
676        }
677    }
678
679    // invalidate the areas where a layer was removed
680    dirtyRegion.orSelf(mDirtyRegionRemovedLayer);
681    mDirtyRegionRemovedLayer.clear();
682
683    mSecureFrameBuffer = secureFrameBuffer;
684    opaqueRegion = aboveOpaqueLayers;
685}
686
687
688void SurfaceFlinger::commitTransaction()
689{
690    mDrawingState = mCurrentState;
691    mResizeTransationPending = false;
692    mTransactionCV.broadcast();
693}
694
695void SurfaceFlinger::handlePageFlip()
696{
697    bool visibleRegions = mVisibleRegionsDirty;
698    LayerVector& currentLayers = const_cast<LayerVector&>(
699            mDrawingState.layersSortedByZ);
700    visibleRegions |= lockPageFlip(currentLayers);
701
702        const DisplayHardware& hw = graphicPlane(0).displayHardware();
703        const Region screenRegion(hw.bounds());
704        if (visibleRegions) {
705            Region opaqueRegion;
706            computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
707
708            /*
709             *  rebuild the visible layer list
710             */
711            mVisibleLayersSortedByZ.clear();
712            const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
713            size_t count = currentLayers.size();
714            mVisibleLayersSortedByZ.setCapacity(count);
715            for (size_t i=0 ; i<count ; i++) {
716                if (!currentLayers[i]->visibleRegionScreen.isEmpty())
717                    mVisibleLayersSortedByZ.add(currentLayers[i]);
718            }
719
720            mWormholeRegion = screenRegion.subtract(opaqueRegion);
721            mVisibleRegionsDirty = false;
722        }
723
724    unlockPageFlip(currentLayers);
725    mDirtyRegion.andSelf(screenRegion);
726}
727
728bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
729{
730    bool recomputeVisibleRegions = false;
731    size_t count = currentLayers.size();
732    sp<LayerBase> const* layers = currentLayers.array();
733    for (size_t i=0 ; i<count ; i++) {
734        const sp<LayerBase>& layer(layers[i]);
735        layer->lockPageFlip(recomputeVisibleRegions);
736    }
737    return recomputeVisibleRegions;
738}
739
740void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
741{
742    const GraphicPlane& plane(graphicPlane(0));
743    const Transform& planeTransform(plane.transform());
744    size_t count = currentLayers.size();
745    sp<LayerBase> const* layers = currentLayers.array();
746    for (size_t i=0 ; i<count ; i++) {
747        const sp<LayerBase>& layer(layers[i]);
748        layer->unlockPageFlip(planeTransform, mDirtyRegion);
749    }
750}
751
752
753void SurfaceFlinger::handleRepaint()
754{
755    // compute the invalid region
756    mInvalidRegion.orSelf(mDirtyRegion);
757    if (mInvalidRegion.isEmpty()) {
758        // nothing to do
759        return;
760    }
761
762    if (UNLIKELY(mDebugRegion)) {
763        debugFlashRegions();
764    }
765
766    // set the frame buffer
767    const DisplayHardware& hw(graphicPlane(0).displayHardware());
768    glMatrixMode(GL_MODELVIEW);
769    glLoadIdentity();
770
771    uint32_t flags = hw.getFlags();
772    if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
773        (flags & DisplayHardware::BUFFER_PRESERVED))
774    {
775        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
776        // takes a rectangle, we must make sure to update that whole
777        // rectangle in that case
778        if (flags & DisplayHardware::SWAP_RECTANGLE) {
779            // TODO: we really should be able to pass a region to
780            // SWAP_RECTANGLE so that we don't have to redraw all this.
781            mDirtyRegion.set(mInvalidRegion.bounds());
782        } else {
783            // in the BUFFER_PRESERVED case, obviously, we can update only
784            // what's needed and nothing more.
785            // NOTE: this is NOT a common case, as preserving the backbuffer
786            // is costly and usually involves copying the whole update back.
787        }
788    } else {
789        if (flags & DisplayHardware::PARTIAL_UPDATES) {
790            // We need to redraw the rectangle that will be updated
791            // (pushed to the framebuffer).
792            // This is needed because PARTIAL_UPDATES only takes one
793            // rectangle instead of a region (see DisplayHardware::flip())
794            mDirtyRegion.set(mInvalidRegion.bounds());
795        } else {
796            // we need to redraw everything (the whole screen)
797            mDirtyRegion.set(hw.bounds());
798            mInvalidRegion = mDirtyRegion;
799        }
800    }
801
802    // compose all surfaces
803    composeSurfaces(mDirtyRegion);
804
805    // clear the dirty regions
806    mDirtyRegion.clear();
807}
808
809void SurfaceFlinger::composeSurfaces(const Region& dirty)
810{
811    if (UNLIKELY(!mWormholeRegion.isEmpty())) {
812        // should never happen unless the window manager has a bug
813        // draw something...
814        drawWormhole();
815    }
816    const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
817    const size_t count = layers.size();
818    for (size_t i=0 ; i<count ; ++i) {
819        const sp<LayerBase>& layer(layers[i]);
820        const Region clip(dirty.intersect(layer->visibleRegionScreen));
821        if (!clip.isEmpty()) {
822            layer->draw(clip);
823        }
824    }
825}
826
827void SurfaceFlinger::unlockClients()
828{
829    const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
830    const size_t count = drawingLayers.size();
831    sp<LayerBase> const* const layers = drawingLayers.array();
832    for (size_t i=0 ; i<count ; ++i) {
833        const sp<LayerBase>& layer = layers[i];
834        layer->finishPageFlip();
835    }
836}
837
838void SurfaceFlinger::debugFlashRegions()
839{
840    const DisplayHardware& hw(graphicPlane(0).displayHardware());
841    const uint32_t flags = hw.getFlags();
842
843    if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
844            (flags & DisplayHardware::BUFFER_PRESERVED))) {
845        const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ?
846                mDirtyRegion.bounds() : hw.bounds());
847        composeSurfaces(repaint);
848    }
849
850    TextureManager::deactivateTextures();
851
852    glDisable(GL_BLEND);
853    glDisable(GL_DITHER);
854    glDisable(GL_SCISSOR_TEST);
855
856    static int toggle = 0;
857    toggle = 1 - toggle;
858    if (toggle) {
859        glColor4f(1, 0, 1, 1);
860    } else {
861        glColor4f(1, 1, 0, 1);
862    }
863
864    Region::const_iterator it = mDirtyRegion.begin();
865    Region::const_iterator const end = mDirtyRegion.end();
866    while (it != end) {
867        const Rect& r = *it++;
868        GLfloat vertices[][2] = {
869                { r.left,  r.top },
870                { r.left,  r.bottom },
871                { r.right, r.bottom },
872                { r.right, r.top }
873        };
874        glVertexPointer(2, GL_FLOAT, 0, vertices);
875        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
876    }
877
878    if (mInvalidRegion.isEmpty()) {
879        mDirtyRegion.dump("mDirtyRegion");
880        mInvalidRegion.dump("mInvalidRegion");
881    }
882    hw.flip(mInvalidRegion);
883
884    if (mDebugRegion > 1)
885        usleep(mDebugRegion * 1000);
886
887    glEnable(GL_SCISSOR_TEST);
888    //mDirtyRegion.dump("mDirtyRegion");
889}
890
891void SurfaceFlinger::drawWormhole() const
892{
893    const Region region(mWormholeRegion.intersect(mDirtyRegion));
894    if (region.isEmpty())
895        return;
896
897    const DisplayHardware& hw(graphicPlane(0).displayHardware());
898    const int32_t width = hw.getWidth();
899    const int32_t height = hw.getHeight();
900
901    glDisable(GL_BLEND);
902    glDisable(GL_DITHER);
903
904    if (LIKELY(!mDebugBackground)) {
905        glClearColor(0,0,0,0);
906        Region::const_iterator it = region.begin();
907        Region::const_iterator const end = region.end();
908        while (it != end) {
909            const Rect& r = *it++;
910            const GLint sy = height - (r.top + r.height());
911            glScissor(r.left, sy, r.width(), r.height());
912            glClear(GL_COLOR_BUFFER_BIT);
913        }
914    } else {
915        const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
916                { width, height }, { 0, height }  };
917        const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 },  { 1, 1 }, { 0, 1 } };
918        glVertexPointer(2, GL_SHORT, 0, vertices);
919        glTexCoordPointer(2, GL_SHORT, 0, tcoords);
920        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
921#if defined(GL_OES_EGL_image_external)
922        if (GLExtensions::getInstance().haveTextureExternal()) {
923            glDisable(GL_TEXTURE_EXTERNAL_OES);
924        }
925#endif
926        glEnable(GL_TEXTURE_2D);
927        glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
928        glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
929        glMatrixMode(GL_TEXTURE);
930        glLoadIdentity();
931        glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
932        Region::const_iterator it = region.begin();
933        Region::const_iterator const end = region.end();
934        while (it != end) {
935            const Rect& r = *it++;
936            const GLint sy = height - (r.top + r.height());
937            glScissor(r.left, sy, r.width(), r.height());
938            glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
939        }
940        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
941    }
942}
943
944void SurfaceFlinger::debugShowFPS() const
945{
946    static int mFrameCount;
947    static int mLastFrameCount = 0;
948    static nsecs_t mLastFpsTime = 0;
949    static float mFps = 0;
950    mFrameCount++;
951    nsecs_t now = systemTime();
952    nsecs_t diff = now - mLastFpsTime;
953    if (diff > ms2ns(250)) {
954        mFps =  ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
955        mLastFpsTime = now;
956        mLastFrameCount = mFrameCount;
957    }
958    // XXX: mFPS has the value we want
959 }
960
961status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
962{
963    Mutex::Autolock _l(mStateLock);
964    addLayer_l(layer);
965    setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
966    return NO_ERROR;
967}
968
969status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
970{
971    ssize_t i = mCurrentState.layersSortedByZ.add(layer);
972    return (i < 0) ? status_t(i) : status_t(NO_ERROR);
973}
974
975ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
976        const sp<LayerBaseClient>& lbc)
977{
978    Mutex::Autolock _l(mStateLock);
979
980    // attach this layer to the client
981    ssize_t name = client->attachLayer(lbc);
982
983    // add this layer to the current state list
984    addLayer_l(lbc);
985
986    return name;
987}
988
989status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
990{
991    Mutex::Autolock _l(mStateLock);
992    status_t err = purgatorizeLayer_l(layer);
993    if (err == NO_ERROR)
994        setTransactionFlags(eTransactionNeeded);
995    return err;
996}
997
998status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
999{
1000    sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient());
1001    if (lbc != 0) {
1002        mLayerMap.removeItem( lbc->getSurface()->asBinder() );
1003    }
1004    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1005    if (index >= 0) {
1006        mLayersRemoved = true;
1007        return NO_ERROR;
1008    }
1009    return status_t(index);
1010}
1011
1012status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1013{
1014    // remove the layer from the main list (through a transaction).
1015    ssize_t err = removeLayer_l(layerBase);
1016
1017    layerBase->onRemoved();
1018
1019    // it's possible that we don't find a layer, because it might
1020    // have been destroyed already -- this is not technically an error
1021    // from the user because there is a race between Client::destroySurface(),
1022    // ~Client() and ~ISurface().
1023    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1024}
1025
1026status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
1027{
1028    layer->forceVisibilityTransaction();
1029    setTransactionFlags(eTraversalNeeded);
1030    return NO_ERROR;
1031}
1032
1033uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1034{
1035    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1036}
1037
1038uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1039{
1040    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1041    if ((old & flags)==0) { // wake the server up
1042        signalEvent();
1043    }
1044    return old;
1045}
1046
1047void SurfaceFlinger::openGlobalTransaction()
1048{
1049    android_atomic_inc(&mTransactionCount);
1050}
1051
1052void SurfaceFlinger::closeGlobalTransaction()
1053{
1054    if (android_atomic_dec(&mTransactionCount) == 1) {
1055        signalEvent();
1056
1057        // if there is a transaction with a resize, wait for it to
1058        // take effect before returning.
1059        Mutex::Autolock _l(mStateLock);
1060        while (mResizeTransationPending) {
1061            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1062            if (CC_UNLIKELY(err != NO_ERROR)) {
1063                // just in case something goes wrong in SF, return to the
1064                // called after a few seconds.
1065                LOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1066                mResizeTransationPending = false;
1067                break;
1068            }
1069        }
1070    }
1071}
1072
1073status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1074{
1075    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1076        return BAD_VALUE;
1077
1078    Mutex::Autolock _l(mStateLock);
1079    mCurrentState.freezeDisplay = 1;
1080    setTransactionFlags(eTransactionNeeded);
1081
1082    // flags is intended to communicate some sort of animation behavior
1083    // (for instance fading)
1084    return NO_ERROR;
1085}
1086
1087status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1088{
1089    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1090        return BAD_VALUE;
1091
1092    Mutex::Autolock _l(mStateLock);
1093    mCurrentState.freezeDisplay = 0;
1094    setTransactionFlags(eTransactionNeeded);
1095
1096    // flags is intended to communicate some sort of animation behavior
1097    // (for instance fading)
1098    return NO_ERROR;
1099}
1100
1101int SurfaceFlinger::setOrientation(DisplayID dpy,
1102        int orientation, uint32_t flags)
1103{
1104    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1105        return BAD_VALUE;
1106
1107    Mutex::Autolock _l(mStateLock);
1108    if (mCurrentState.orientation != orientation) {
1109        if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
1110            mCurrentState.orientationType = flags;
1111            mCurrentState.orientation = orientation;
1112            setTransactionFlags(eTransactionNeeded);
1113            mTransactionCV.wait(mStateLock);
1114        } else {
1115            orientation = BAD_VALUE;
1116        }
1117    }
1118    return orientation;
1119}
1120
1121sp<ISurface> SurfaceFlinger::createSurface(const sp<Client>& client, int pid,
1122        const String8& name, ISurfaceComposerClient::surface_data_t* params,
1123        DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1124        uint32_t flags)
1125{
1126    sp<LayerBaseClient> layer;
1127    sp<LayerBaseClient::Surface> surfaceHandle;
1128
1129    if (int32_t(w|h) < 0) {
1130        LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",
1131                int(w), int(h));
1132        return surfaceHandle;
1133    }
1134
1135    //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1136    sp<Layer> normalLayer;
1137    switch (flags & eFXSurfaceMask) {
1138        case eFXSurfaceNormal:
1139            if (UNLIKELY(flags & ePushBuffers)) {
1140                layer = createPushBuffersSurface(client, d, w, h, flags);
1141            } else {
1142                normalLayer = createNormalSurface(client, d, w, h, flags, format);
1143                layer = normalLayer;
1144            }
1145            break;
1146        case eFXSurfaceBlur:
1147            layer = createBlurSurface(client, d, w, h, flags);
1148            break;
1149        case eFXSurfaceDim:
1150            layer = createDimSurface(client, d, w, h, flags);
1151            break;
1152    }
1153
1154    if (layer != 0) {
1155        layer->initStates(w, h, flags);
1156        layer->setName(name);
1157        ssize_t token = addClientLayer(client, layer);
1158
1159        surfaceHandle = layer->getSurface();
1160        if (surfaceHandle != 0) {
1161            params->token = token;
1162            params->identity = surfaceHandle->getIdentity();
1163            params->width = w;
1164            params->height = h;
1165            params->format = format;
1166            if (normalLayer != 0) {
1167                Mutex::Autolock _l(mStateLock);
1168                mLayerMap.add(surfaceHandle->asBinder(), normalLayer);
1169            }
1170        }
1171
1172        setTransactionFlags(eTransactionNeeded);
1173    }
1174
1175    return surfaceHandle;
1176}
1177
1178sp<Layer> SurfaceFlinger::createNormalSurface(
1179        const sp<Client>& client, DisplayID display,
1180        uint32_t w, uint32_t h, uint32_t flags,
1181        PixelFormat& format)
1182{
1183    // initialize the surfaces
1184    switch (format) { // TODO: take h/w into account
1185    case PIXEL_FORMAT_TRANSPARENT:
1186    case PIXEL_FORMAT_TRANSLUCENT:
1187        format = PIXEL_FORMAT_RGBA_8888;
1188        break;
1189    case PIXEL_FORMAT_OPAQUE:
1190#ifdef NO_RGBX_8888
1191        format = PIXEL_FORMAT_RGB_565;
1192#else
1193        format = PIXEL_FORMAT_RGBX_8888;
1194#endif
1195        break;
1196    }
1197
1198#ifdef NO_RGBX_8888
1199    if (format == PIXEL_FORMAT_RGBX_8888)
1200        format = PIXEL_FORMAT_RGBA_8888;
1201#endif
1202
1203    sp<Layer> layer = new Layer(this, display, client);
1204    status_t err = layer->setBuffers(w, h, format, flags);
1205    if (LIKELY(err != NO_ERROR)) {
1206        LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
1207        layer.clear();
1208    }
1209    return layer;
1210}
1211
1212sp<LayerBlur> SurfaceFlinger::createBlurSurface(
1213        const sp<Client>& client, DisplayID display,
1214        uint32_t w, uint32_t h, uint32_t flags)
1215{
1216    sp<LayerBlur> layer = new LayerBlur(this, display, client);
1217    layer->initStates(w, h, flags);
1218    return layer;
1219}
1220
1221sp<LayerDim> SurfaceFlinger::createDimSurface(
1222        const sp<Client>& client, DisplayID display,
1223        uint32_t w, uint32_t h, uint32_t flags)
1224{
1225    sp<LayerDim> layer = new LayerDim(this, display, client);
1226    layer->initStates(w, h, flags);
1227    return layer;
1228}
1229
1230sp<LayerBuffer> SurfaceFlinger::createPushBuffersSurface(
1231        const sp<Client>& client, DisplayID display,
1232        uint32_t w, uint32_t h, uint32_t flags)
1233{
1234    sp<LayerBuffer> layer = new LayerBuffer(this, display, client);
1235    layer->initStates(w, h, flags);
1236    return layer;
1237}
1238
1239status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid)
1240{
1241    /*
1242     * called by the window manager, when a surface should be marked for
1243     * destruction.
1244     *
1245     * The surface is removed from the current and drawing lists, but placed
1246     * in the purgatory queue, so it's not destroyed right-away (we need
1247     * to wait for all client's references to go away first).
1248     */
1249
1250    status_t err = NAME_NOT_FOUND;
1251    Mutex::Autolock _l(mStateLock);
1252    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1253    if (layer != 0) {
1254        err = purgatorizeLayer_l(layer);
1255        if (err == NO_ERROR) {
1256            setTransactionFlags(eTransactionNeeded);
1257        }
1258    }
1259    return err;
1260}
1261
1262status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1263{
1264    // called by ~ISurface() when all references are gone
1265
1266    class MessageDestroySurface : public MessageBase {
1267        SurfaceFlinger* flinger;
1268        sp<LayerBaseClient> layer;
1269    public:
1270        MessageDestroySurface(
1271                SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1272            : flinger(flinger), layer(layer) { }
1273        virtual bool handler() {
1274            sp<LayerBaseClient> l(layer);
1275            layer.clear(); // clear it outside of the lock;
1276            Mutex::Autolock _l(flinger->mStateLock);
1277            /*
1278             * remove the layer from the current list -- chances are that it's
1279             * not in the list anyway, because it should have been removed
1280             * already upon request of the client (eg: window manager).
1281             * However, a buggy client could have not done that.
1282             * Since we know we don't have any more clients, we don't need
1283             * to use the purgatory.
1284             */
1285            status_t err = flinger->removeLayer_l(l);
1286            LOGE_IF(err<0 && err != NAME_NOT_FOUND,
1287                    "error removing layer=%p (%s)", l.get(), strerror(-err));
1288            return true;
1289        }
1290    };
1291
1292    postMessageAsync( new MessageDestroySurface(this, layer) );
1293    return NO_ERROR;
1294}
1295
1296status_t SurfaceFlinger::setClientState(
1297        const sp<Client>& client,
1298        int32_t count,
1299        const layer_state_t* states)
1300{
1301    Mutex::Autolock _l(mStateLock);
1302    uint32_t flags = 0;
1303    for (int i=0 ; i<count ; i++) {
1304        const layer_state_t& s(states[i]);
1305        sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1306        if (layer != 0) {
1307            const uint32_t what = s.what;
1308            if (what & ePositionChanged) {
1309                if (layer->setPosition(s.x, s.y))
1310                    flags |= eTraversalNeeded;
1311            }
1312            if (what & eLayerChanged) {
1313                ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1314                if (layer->setLayer(s.z)) {
1315                    mCurrentState.layersSortedByZ.removeAt(idx);
1316                    mCurrentState.layersSortedByZ.add(layer);
1317                    // we need traversal (state changed)
1318                    // AND transaction (list changed)
1319                    flags |= eTransactionNeeded|eTraversalNeeded;
1320                }
1321            }
1322            if (what & eSizeChanged) {
1323                if (layer->setSize(s.w, s.h)) {
1324                    flags |= eTraversalNeeded;
1325                    mResizeTransationPending = true;
1326                }
1327            }
1328            if (what & eAlphaChanged) {
1329                if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1330                    flags |= eTraversalNeeded;
1331            }
1332            if (what & eMatrixChanged) {
1333                if (layer->setMatrix(s.matrix))
1334                    flags |= eTraversalNeeded;
1335            }
1336            if (what & eTransparentRegionChanged) {
1337                if (layer->setTransparentRegionHint(s.transparentRegion))
1338                    flags |= eTraversalNeeded;
1339            }
1340            if (what & eVisibilityChanged) {
1341                if (layer->setFlags(s.flags, s.mask))
1342                    flags |= eTraversalNeeded;
1343            }
1344        }
1345    }
1346    if (flags) {
1347        setTransactionFlags(flags);
1348    }
1349    return NO_ERROR;
1350}
1351
1352void SurfaceFlinger::screenReleased(int dpy)
1353{
1354    // this may be called by a signal handler, we can't do too much in here
1355    android_atomic_or(eConsoleReleased, &mConsoleSignals);
1356    signalEvent();
1357}
1358
1359void SurfaceFlinger::screenAcquired(int dpy)
1360{
1361    // this may be called by a signal handler, we can't do too much in here
1362    android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1363    signalEvent();
1364}
1365
1366status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1367{
1368    const size_t SIZE = 1024;
1369    char buffer[SIZE];
1370    String8 result;
1371    if (!mDump.checkCalling()) {
1372        snprintf(buffer, SIZE, "Permission Denial: "
1373                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1374                IPCThreadState::self()->getCallingPid(),
1375                IPCThreadState::self()->getCallingUid());
1376        result.append(buffer);
1377    } else {
1378
1379        // figure out if we're stuck somewhere
1380        const nsecs_t now = systemTime();
1381        const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1382        const nsecs_t inTransaction(mDebugInTransaction);
1383        nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1384        nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1385
1386        // Try to get the main lock, but don't insist if we can't
1387        // (this would indicate SF is stuck, but we want to be able to
1388        // print something in dumpsys).
1389        int retry = 3;
1390        while (mStateLock.tryLock()<0 && --retry>=0) {
1391            usleep(1000000);
1392        }
1393        const bool locked(retry >= 0);
1394        if (!locked) {
1395            snprintf(buffer, SIZE,
1396                    "SurfaceFlinger appears to be unresponsive, "
1397                    "dumping anyways (no locks held)\n");
1398            result.append(buffer);
1399        }
1400
1401        const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1402        const size_t count = currentLayers.size();
1403        for (size_t i=0 ; i<count ; i++) {
1404            const sp<LayerBase>& layer(currentLayers[i]);
1405            layer->dump(result, buffer, SIZE);
1406            const Layer::State& s(layer->drawingState());
1407            s.transparentRegion.dump(result, "transparentRegion");
1408            layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1409            layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1410        }
1411
1412        mWormholeRegion.dump(result, "WormholeRegion");
1413        const DisplayHardware& hw(graphicPlane(0).displayHardware());
1414        snprintf(buffer, SIZE,
1415                "  display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1416                mFreezeDisplay?"yes":"no", mFreezeCount,
1417                mCurrentState.orientation, hw.canDraw());
1418        result.append(buffer);
1419        snprintf(buffer, SIZE,
1420                "  last eglSwapBuffers() time: %f us\n"
1421                "  last transaction time     : %f us\n",
1422                mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0);
1423        result.append(buffer);
1424
1425        if (inSwapBuffersDuration || !locked) {
1426            snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
1427                    inSwapBuffersDuration/1000.0);
1428            result.append(buffer);
1429        }
1430
1431        if (inTransactionDuration || !locked) {
1432            snprintf(buffer, SIZE, "  transaction time: %f us\n",
1433                    inTransactionDuration/1000.0);
1434            result.append(buffer);
1435        }
1436
1437        const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
1438        alloc.dump(result);
1439
1440        if (locked) {
1441            mStateLock.unlock();
1442        }
1443    }
1444    write(fd, result.string(), result.size());
1445    return NO_ERROR;
1446}
1447
1448status_t SurfaceFlinger::onTransact(
1449    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1450{
1451    switch (code) {
1452        case CREATE_CONNECTION:
1453        case OPEN_GLOBAL_TRANSACTION:
1454        case CLOSE_GLOBAL_TRANSACTION:
1455        case SET_ORIENTATION:
1456        case FREEZE_DISPLAY:
1457        case UNFREEZE_DISPLAY:
1458        case BOOT_FINISHED:
1459        {
1460            // codes that require permission check
1461            IPCThreadState* ipc = IPCThreadState::self();
1462            const int pid = ipc->getCallingPid();
1463            const int uid = ipc->getCallingUid();
1464            if ((uid != AID_GRAPHICS) && !mAccessSurfaceFlinger.check(pid, uid)) {
1465                LOGE("Permission Denial: "
1466                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1467                return PERMISSION_DENIED;
1468            }
1469            break;
1470        }
1471        case CAPTURE_SCREEN:
1472        {
1473            // codes that require permission check
1474            IPCThreadState* ipc = IPCThreadState::self();
1475            const int pid = ipc->getCallingPid();
1476            const int uid = ipc->getCallingUid();
1477            if ((uid != AID_GRAPHICS) && !mReadFramebuffer.check(pid, uid)) {
1478                LOGE("Permission Denial: "
1479                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
1480                return PERMISSION_DENIED;
1481            }
1482            break;
1483        }
1484    }
1485
1486    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1487    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1488        CHECK_INTERFACE(ISurfaceComposer, data, reply);
1489        if (UNLIKELY(!mHardwareTest.checkCalling())) {
1490            IPCThreadState* ipc = IPCThreadState::self();
1491            const int pid = ipc->getCallingPid();
1492            const int uid = ipc->getCallingUid();
1493            LOGE("Permission Denial: "
1494                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1495            return PERMISSION_DENIED;
1496        }
1497        int n;
1498        switch (code) {
1499            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
1500            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
1501                return NO_ERROR;
1502            case 1002:  // SHOW_UPDATES
1503                n = data.readInt32();
1504                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1505                return NO_ERROR;
1506            case 1003:  // SHOW_BACKGROUND
1507                n = data.readInt32();
1508                mDebugBackground = n ? 1 : 0;
1509                return NO_ERROR;
1510            case 1004:{ // repaint everything
1511                Mutex::Autolock _l(mStateLock);
1512                const DisplayHardware& hw(graphicPlane(0).displayHardware());
1513                mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1514                signalEvent();
1515                return NO_ERROR;
1516            }
1517            case 1005:{ // force transaction
1518                setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1519                return NO_ERROR;
1520            }
1521            case 1006:{ // enable/disable GraphicLog
1522                int enabled = data.readInt32();
1523                GraphicLog::getInstance().setEnabled(enabled);
1524                return NO_ERROR;
1525            }
1526            case 1007: // set mFreezeCount
1527                mFreezeCount = data.readInt32();
1528                mFreezeDisplayTime = 0;
1529                return NO_ERROR;
1530            case 1010:  // interrogate.
1531                reply->writeInt32(0);
1532                reply->writeInt32(0);
1533                reply->writeInt32(mDebugRegion);
1534                reply->writeInt32(mDebugBackground);
1535                return NO_ERROR;
1536            case 1013: {
1537                Mutex::Autolock _l(mStateLock);
1538                const DisplayHardware& hw(graphicPlane(0).displayHardware());
1539                reply->writeInt32(hw.getPageFlipCount());
1540            }
1541            return NO_ERROR;
1542        }
1543    }
1544    return err;
1545}
1546
1547// ---------------------------------------------------------------------------
1548
1549status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy,
1550        sp<IMemoryHeap>* heap,
1551        uint32_t* w, uint32_t* h, PixelFormat* f,
1552        uint32_t sw, uint32_t sh)
1553{
1554    status_t result = PERMISSION_DENIED;
1555
1556    // only one display supported for now
1557    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1558        return BAD_VALUE;
1559
1560    if (!GLExtensions::getInstance().haveFramebufferObject())
1561        return INVALID_OPERATION;
1562
1563    // get screen geometry
1564    const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
1565    const uint32_t hw_w = hw.getWidth();
1566    const uint32_t hw_h = hw.getHeight();
1567
1568    if ((sw > hw_w) || (sh > hw_h))
1569        return BAD_VALUE;
1570
1571    sw = (!sw) ? hw_w : sw;
1572    sh = (!sh) ? hw_h : sh;
1573    const size_t size = sw * sh * 4;
1574
1575    // make sure to clear all GL error flags
1576    while ( glGetError() != GL_NO_ERROR ) ;
1577
1578    // create a FBO
1579    GLuint name, tname;
1580    glGenRenderbuffersOES(1, &tname);
1581    glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
1582    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
1583    glGenFramebuffersOES(1, &name);
1584    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
1585    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
1586            GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
1587
1588    GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
1589    if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
1590
1591        // invert everything, b/c glReadPixel() below will invert the FB
1592        glViewport(0, 0, sw, sh);
1593        glMatrixMode(GL_PROJECTION);
1594        glPushMatrix();
1595        glLoadIdentity();
1596        glOrthof(0, hw_w, 0, hw_h, 0, 1);
1597        glMatrixMode(GL_MODELVIEW);
1598
1599        // redraw the screen entirely...
1600        glClearColor(0,0,0,1);
1601        glClear(GL_COLOR_BUFFER_BIT);
1602        const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
1603        const size_t count = layers.size();
1604        for (size_t i=0 ; i<count ; ++i) {
1605            const sp<LayerBase>& layer(layers[i]);
1606            layer->drawForSreenShot();
1607        }
1608
1609        // XXX: this is needed on tegra
1610        glScissor(0, 0, sw, sh);
1611
1612        // check for errors and return screen capture
1613        if (glGetError() != GL_NO_ERROR) {
1614            // error while rendering
1615            result = INVALID_OPERATION;
1616        } else {
1617            // allocate shared memory large enough to hold the
1618            // screen capture
1619            sp<MemoryHeapBase> base(
1620                    new MemoryHeapBase(size, 0, "screen-capture") );
1621            void* const ptr = base->getBase();
1622            if (ptr) {
1623                // capture the screen with glReadPixels()
1624                glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
1625                if (glGetError() == GL_NO_ERROR) {
1626                    *heap = base;
1627                    *w = sw;
1628                    *h = sh;
1629                    *f = PIXEL_FORMAT_RGBA_8888;
1630                    result = NO_ERROR;
1631                }
1632            } else {
1633                result = NO_MEMORY;
1634            }
1635        }
1636
1637        glEnable(GL_SCISSOR_TEST);
1638        glViewport(0, 0, hw_w, hw_h);
1639        glMatrixMode(GL_PROJECTION);
1640        glPopMatrix();
1641        glMatrixMode(GL_MODELVIEW);
1642
1643
1644    } else {
1645        result = BAD_VALUE;
1646    }
1647
1648    // release FBO resources
1649    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
1650    glDeleteRenderbuffersOES(1, &tname);
1651    glDeleteFramebuffersOES(1, &name);
1652    return result;
1653}
1654
1655
1656status_t SurfaceFlinger::captureScreen(DisplayID dpy,
1657        sp<IMemoryHeap>* heap,
1658        uint32_t* width, uint32_t* height, PixelFormat* format,
1659        uint32_t sw, uint32_t sh)
1660{
1661    // only one display supported for now
1662    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1663        return BAD_VALUE;
1664
1665    if (!GLExtensions::getInstance().haveFramebufferObject())
1666        return INVALID_OPERATION;
1667
1668    class MessageCaptureScreen : public MessageBase {
1669        SurfaceFlinger* flinger;
1670        DisplayID dpy;
1671        sp<IMemoryHeap>* heap;
1672        uint32_t* w;
1673        uint32_t* h;
1674        PixelFormat* f;
1675        uint32_t sw;
1676        uint32_t sh;
1677        status_t result;
1678    public:
1679        MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy,
1680                sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
1681                uint32_t sw, uint32_t sh)
1682            : flinger(flinger), dpy(dpy),
1683              heap(heap), w(w), h(h), f(f), sw(sw), sh(sh), result(PERMISSION_DENIED)
1684        {
1685        }
1686        status_t getResult() const {
1687            return result;
1688        }
1689        virtual bool handler() {
1690            Mutex::Autolock _l(flinger->mStateLock);
1691
1692            // if we have secure windows, never allow the screen capture
1693            if (flinger->mSecureFrameBuffer)
1694                return true;
1695
1696            result = flinger->captureScreenImplLocked(dpy,
1697                    heap, w, h, f, sw, sh);
1698
1699            return true;
1700        }
1701    };
1702
1703    sp<MessageBase> msg = new MessageCaptureScreen(this,
1704            dpy, heap, width, height, format, sw, sh);
1705    status_t res = postMessageSync(msg);
1706    if (res == NO_ERROR) {
1707        res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
1708    }
1709    return res;
1710}
1711
1712// ---------------------------------------------------------------------------
1713
1714sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const
1715{
1716    sp<Layer> result;
1717    Mutex::Autolock _l(mStateLock);
1718    result = mLayerMap.valueFor( sur->asBinder() ).promote();
1719    return result;
1720}
1721
1722// ---------------------------------------------------------------------------
1723
1724Client::Client(const sp<SurfaceFlinger>& flinger)
1725    : mFlinger(flinger), mNameGenerator(1)
1726{
1727}
1728
1729Client::~Client()
1730{
1731    const size_t count = mLayers.size();
1732    for (size_t i=0 ; i<count ; i++) {
1733        sp<LayerBaseClient> layer(mLayers.valueAt(i).promote());
1734        if (layer != 0) {
1735            mFlinger->removeLayer(layer);
1736        }
1737    }
1738}
1739
1740status_t Client::initCheck() const {
1741    return NO_ERROR;
1742}
1743
1744ssize_t Client::attachLayer(const sp<LayerBaseClient>& layer)
1745{
1746    int32_t name = android_atomic_inc(&mNameGenerator);
1747    mLayers.add(name, layer);
1748    return name;
1749}
1750
1751void Client::detachLayer(const LayerBaseClient* layer)
1752{
1753    // we do a linear search here, because this doesn't happen often
1754    const size_t count = mLayers.size();
1755    for (size_t i=0 ; i<count ; i++) {
1756        if (mLayers.valueAt(i) == layer) {
1757            mLayers.removeItemsAt(i, 1);
1758            break;
1759        }
1760    }
1761}
1762sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1763    sp<LayerBaseClient> lbc;
1764    const wp<LayerBaseClient>& layer(mLayers.valueFor(i));
1765    if (layer != 0) {
1766        lbc = layer.promote();
1767        LOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i));
1768    }
1769    return lbc;
1770}
1771
1772sp<IMemoryHeap> Client::getControlBlock() const {
1773    return 0;
1774}
1775ssize_t Client::getTokenForSurface(const sp<ISurface>& sur) const {
1776    return -1;
1777}
1778sp<ISurface> Client::createSurface(
1779        ISurfaceComposerClient::surface_data_t* params, int pid,
1780        const String8& name,
1781        DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1782        uint32_t flags)
1783{
1784    return mFlinger->createSurface(this, pid, name, params,
1785            display, w, h, format, flags);
1786}
1787status_t Client::destroySurface(SurfaceID sid) {
1788    return mFlinger->removeSurface(this, sid);
1789}
1790status_t Client::setState(int32_t count, const layer_state_t* states) {
1791    return mFlinger->setClientState(this, count, states);
1792}
1793
1794// ---------------------------------------------------------------------------
1795
1796UserClient::UserClient(const sp<SurfaceFlinger>& flinger)
1797    : ctrlblk(0), mBitmap(0), mFlinger(flinger)
1798{
1799    const int pgsize = getpagesize();
1800    const int cblksize = ((sizeof(SharedClient)+(pgsize-1))&~(pgsize-1));
1801
1802    mCblkHeap = new MemoryHeapBase(cblksize, 0,
1803            "SurfaceFlinger Client control-block");
1804
1805    ctrlblk = static_cast<SharedClient *>(mCblkHeap->getBase());
1806    if (ctrlblk) { // construct the shared structure in-place.
1807        new(ctrlblk) SharedClient;
1808    }
1809}
1810
1811UserClient::~UserClient()
1812{
1813    if (ctrlblk) {
1814        ctrlblk->~SharedClient();  // destroy our shared-structure.
1815    }
1816
1817    /*
1818     * When a UserClient dies, it's unclear what to do exactly.
1819     * We could go ahead and destroy all surfaces linked to that client
1820     * however, it wouldn't be fair to the main Client
1821     * (usually the the window-manager), which might want to re-target
1822     * the layer to another UserClient.
1823     * I think the best is to do nothing, or not much; in most cases the
1824     * WM itself will go ahead and clean things up when it detects a client of
1825     * his has died.
1826     * The remaining question is what to display? currently we keep
1827     * just keep the current buffer.
1828     */
1829}
1830
1831status_t UserClient::initCheck() const {
1832    return ctrlblk == 0 ? NO_INIT : NO_ERROR;
1833}
1834
1835void UserClient::detachLayer(const Layer* layer)
1836{
1837    int32_t name = layer->getToken();
1838    if (name >= 0) {
1839        int32_t mask = 1LU<<name;
1840        if ((android_atomic_and(~mask, &mBitmap) & mask) == 0) {
1841            LOGW("token %d wasn't marked as used %08x", name, int(mBitmap));
1842        }
1843    }
1844}
1845
1846sp<IMemoryHeap> UserClient::getControlBlock() const {
1847    return mCblkHeap;
1848}
1849
1850ssize_t UserClient::getTokenForSurface(const sp<ISurface>& sur) const
1851{
1852    int32_t name = NAME_NOT_FOUND;
1853    sp<Layer> layer(mFlinger->getLayer(sur));
1854    if (layer == 0) return name;
1855
1856    // if this layer already has a token, just return it
1857    name = layer->getToken();
1858    if ((name >= 0) && (layer->getClient() == this))
1859        return name;
1860
1861    name = 0;
1862    do {
1863        int32_t mask = 1LU<<name;
1864        if ((android_atomic_or(mask, &mBitmap) & mask) == 0) {
1865            // we found and locked that name
1866            status_t err = layer->setToken(
1867                    const_cast<UserClient*>(this), ctrlblk, name);
1868            if (err != NO_ERROR) {
1869                // free the name
1870                android_atomic_and(~mask, &mBitmap);
1871                name = err;
1872            }
1873            break;
1874        }
1875        if (++name > 31)
1876            name = NO_MEMORY;
1877    } while(name >= 0);
1878
1879    //LOGD("getTokenForSurface(%p) => %d (client=%p, bitmap=%08lx)",
1880    //        sur->asBinder().get(), name, this, mBitmap);
1881    return name;
1882}
1883
1884sp<ISurface> UserClient::createSurface(
1885        ISurfaceComposerClient::surface_data_t* params, int pid,
1886        const String8& name,
1887        DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1888        uint32_t flags) {
1889    return 0;
1890}
1891status_t UserClient::destroySurface(SurfaceID sid) {
1892    return INVALID_OPERATION;
1893}
1894status_t UserClient::setState(int32_t count, const layer_state_t* states) {
1895    return INVALID_OPERATION;
1896}
1897
1898// ---------------------------------------------------------------------------
1899
1900GraphicPlane::GraphicPlane()
1901    : mHw(0)
1902{
1903}
1904
1905GraphicPlane::~GraphicPlane() {
1906    delete mHw;
1907}
1908
1909bool GraphicPlane::initialized() const {
1910    return mHw ? true : false;
1911}
1912
1913int GraphicPlane::getWidth() const {
1914    return mWidth;
1915}
1916
1917int GraphicPlane::getHeight() const {
1918    return mHeight;
1919}
1920
1921void GraphicPlane::setDisplayHardware(DisplayHardware *hw)
1922{
1923    mHw = hw;
1924
1925    // initialize the display orientation transform.
1926    // it's a constant that should come from the display driver.
1927    int displayOrientation = ISurfaceComposer::eOrientationDefault;
1928    char property[PROPERTY_VALUE_MAX];
1929    if (property_get("ro.sf.hwrotation", property, NULL) > 0) {
1930        //displayOrientation
1931        switch (atoi(property)) {
1932        case 90:
1933            displayOrientation = ISurfaceComposer::eOrientation90;
1934            break;
1935        case 270:
1936            displayOrientation = ISurfaceComposer::eOrientation270;
1937            break;
1938        }
1939    }
1940
1941    const float w = hw->getWidth();
1942    const float h = hw->getHeight();
1943    GraphicPlane::orientationToTransfrom(displayOrientation, w, h,
1944            &mDisplayTransform);
1945    if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) {
1946        mDisplayWidth = h;
1947        mDisplayHeight = w;
1948    } else {
1949        mDisplayWidth = w;
1950        mDisplayHeight = h;
1951    }
1952
1953    setOrientation(ISurfaceComposer::eOrientationDefault);
1954}
1955
1956status_t GraphicPlane::orientationToTransfrom(
1957        int orientation, int w, int h, Transform* tr)
1958{
1959    uint32_t flags = 0;
1960    switch (orientation) {
1961    case ISurfaceComposer::eOrientationDefault:
1962        flags = Transform::ROT_0;
1963        break;
1964    case ISurfaceComposer::eOrientation90:
1965        flags = Transform::ROT_90;
1966        break;
1967    case ISurfaceComposer::eOrientation180:
1968        flags = Transform::ROT_180;
1969        break;
1970    case ISurfaceComposer::eOrientation270:
1971        flags = Transform::ROT_270;
1972        break;
1973    default:
1974        return BAD_VALUE;
1975    }
1976    tr->set(flags, w, h);
1977    return NO_ERROR;
1978}
1979
1980status_t GraphicPlane::setOrientation(int orientation)
1981{
1982    // If the rotation can be handled in hardware, this is where
1983    // the magic should happen.
1984
1985    const DisplayHardware& hw(displayHardware());
1986    const float w = mDisplayWidth;
1987    const float h = mDisplayHeight;
1988    mWidth = int(w);
1989    mHeight = int(h);
1990
1991    Transform orientationTransform;
1992    GraphicPlane::orientationToTransfrom(orientation, w, h,
1993            &orientationTransform);
1994    if (orientation & ISurfaceComposer::eOrientationSwapMask) {
1995        mWidth = int(h);
1996        mHeight = int(w);
1997    }
1998
1999    mOrientation = orientation;
2000    mGlobalTransform = mDisplayTransform * orientationTransform;
2001    return NO_ERROR;
2002}
2003
2004const DisplayHardware& GraphicPlane::displayHardware() const {
2005    return *mHw;
2006}
2007
2008const Transform& GraphicPlane::transform() const {
2009    return mGlobalTransform;
2010}
2011
2012EGLDisplay GraphicPlane::getEGLDisplay() const {
2013    return mHw->getEGLDisplay();
2014}
2015
2016// ---------------------------------------------------------------------------
2017
2018}; // namespace android
2019