SurfaceFlinger.cpp revision c6694b4cb4829164cd490869c557103f310fd761
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19#include <stdint.h>
20#include <sys/types.h>
21#include <errno.h>
22#include <math.h>
23#include <dlfcn.h>
24
25#include <EGL/egl.h>
26
27#include <cutils/log.h>
28#include <cutils/properties.h>
29
30#include <binder/IPCThreadState.h>
31#include <binder/IServiceManager.h>
32#include <binder/MemoryHeapBase.h>
33#include <binder/PermissionCache.h>
34
35#include <ui/DisplayInfo.h>
36
37#include <gui/BitTube.h>
38#include <gui/BufferQueue.h>
39#include <gui/GuiConfig.h>
40#include <gui/IDisplayEventConnection.h>
41#include <gui/Surface.h>
42#include <gui/GraphicBufferAlloc.h>
43
44#include <ui/GraphicBufferAllocator.h>
45#include <ui/PixelFormat.h>
46#include <ui/UiConfig.h>
47
48#include <utils/misc.h>
49#include <utils/String8.h>
50#include <utils/String16.h>
51#include <utils/StopWatch.h>
52#include <utils/Trace.h>
53
54#include <private/android_filesystem_config.h>
55#include <private/gui/SyncFeatures.h>
56
57#include "Client.h"
58#include "clz.h"
59#include "Colorizer.h"
60#include "DdmConnection.h"
61#include "DisplayDevice.h"
62#include "DispSync.h"
63#include "EventThread.h"
64#include "Layer.h"
65#include "LayerDim.h"
66#include "SurfaceFlinger.h"
67
68#include "DisplayHardware/FramebufferSurface.h"
69#include "DisplayHardware/HWComposer.h"
70#include "DisplayHardware/VirtualDisplaySurface.h"
71
72#include "Effects/Daltonizer.h"
73
74#include "RenderEngine/RenderEngine.h"
75#include <cutils/compiler.h>
76
77#define DISPLAY_COUNT       1
78
79/*
80 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
81 * black pixels.
82 */
83#define DEBUG_SCREENSHOTS   false
84
85EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
86
87namespace android {
88
89// This works around the lack of support for the sync framework on some
90// devices.
91#ifdef RUNNING_WITHOUT_SYNC_FRAMEWORK
92static const bool runningWithoutSyncFramework = true;
93#else
94static const bool runningWithoutSyncFramework = false;
95#endif
96
97// This is the phase offset in nanoseconds of the software vsync event
98// relative to the vsync event reported by HWComposer.  The software vsync
99// event is when SurfaceFlinger and Choreographer-based applications run each
100// frame.
101//
102// This phase offset allows adjustment of the minimum latency from application
103// wake-up (by Choregographer) time to the time at which the resulting window
104// image is displayed.  This value may be either positive (after the HW vsync)
105// or negative (before the HW vsync).  Setting it to 0 will result in a
106// minimum latency of two vsync periods because the app and SurfaceFlinger
107// will run just after the HW vsync.  Setting it to a positive number will
108// result in the minimum latency being:
109//
110//     (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
111//
112// Note that reducing this latency makes it more likely for the applications
113// to not have their window content image ready in time.  When this happens
114// the latency will end up being an additional vsync period, and animations
115// will hiccup.  Therefore, this latency should be tuned somewhat
116// conservatively (or at least with awareness of the trade-off being made).
117static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
118
119// ---------------------------------------------------------------------------
120
121const String16 sHardwareTest("android.permission.HARDWARE_TEST");
122const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
123const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
124const String16 sDump("android.permission.DUMP");
125
126// ---------------------------------------------------------------------------
127
128SurfaceFlinger::SurfaceFlinger()
129    :   BnSurfaceComposer(),
130        mTransactionFlags(0),
131        mTransactionPending(false),
132        mAnimTransactionPending(false),
133        mLayersRemoved(false),
134        mRepaintEverything(0),
135        mRenderEngine(NULL),
136        mBootTime(systemTime()),
137        mVisibleRegionsDirty(false),
138        mHwWorkListDirty(false),
139        mAnimCompositionPending(false),
140        mDebugRegion(0),
141        mDebugDDMS(0),
142        mDebugDisableHWC(0),
143        mDebugDisableTransformHint(0),
144        mDebugInSwapBuffers(0),
145        mLastSwapBufferTime(0),
146        mDebugInTransaction(0),
147        mLastTransactionTime(0),
148        mBootFinished(false),
149        mPrimaryHWVsyncEnabled(false),
150        mHWVsyncAvailable(false),
151        mDaltonize(false),
152        mHasColorMatrix(false)
153{
154    ALOGI("SurfaceFlinger is starting");
155
156    // debugging stuff...
157    char value[PROPERTY_VALUE_MAX];
158
159    property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
160    mGpuToCpuSupported = !atoi(value);
161
162    property_get("debug.sf.showupdates", value, "0");
163    mDebugRegion = atoi(value);
164
165    property_get("debug.sf.ddms", value, "0");
166    mDebugDDMS = atoi(value);
167    if (mDebugDDMS) {
168        if (!startDdmConnection()) {
169            // start failed, and DDMS debugging not enabled
170            mDebugDDMS = 0;
171        }
172    }
173    ALOGI_IF(mDebugRegion, "showupdates enabled");
174    ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
175}
176
177void SurfaceFlinger::onFirstRef()
178{
179    mEventQueue.init(this);
180}
181
182SurfaceFlinger::~SurfaceFlinger()
183{
184    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
185    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
186    eglTerminate(display);
187}
188
189void SurfaceFlinger::binderDied(const wp<IBinder>& who)
190{
191    // the window manager died on us. prepare its eulogy.
192
193    // restore initial conditions (default device unblank, etc)
194    initializeDisplays();
195
196    // restart the boot-animation
197    startBootAnim();
198}
199
200sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
201{
202    sp<ISurfaceComposerClient> bclient;
203    sp<Client> client(new Client(this));
204    status_t err = client->initCheck();
205    if (err == NO_ERROR) {
206        bclient = client;
207    }
208    return bclient;
209}
210
211sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
212        bool secure)
213{
214    class DisplayToken : public BBinder {
215        sp<SurfaceFlinger> flinger;
216        virtual ~DisplayToken() {
217             // no more references, this display must be terminated
218             Mutex::Autolock _l(flinger->mStateLock);
219             flinger->mCurrentState.displays.removeItem(this);
220             flinger->setTransactionFlags(eDisplayTransactionNeeded);
221         }
222     public:
223        DisplayToken(const sp<SurfaceFlinger>& flinger)
224            : flinger(flinger) {
225        }
226    };
227
228    sp<BBinder> token = new DisplayToken(this);
229
230    Mutex::Autolock _l(mStateLock);
231    DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
232    info.displayName = displayName;
233    info.isSecure = secure;
234    mCurrentState.displays.add(token, info);
235
236    return token;
237}
238
239void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
240    Mutex::Autolock _l(mStateLock);
241
242    ssize_t idx = mCurrentState.displays.indexOfKey(display);
243    if (idx < 0) {
244        ALOGW("destroyDisplay: invalid display token");
245        return;
246    }
247
248    const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
249    if (!info.isVirtualDisplay()) {
250        ALOGE("destroyDisplay called for non-virtual display");
251        return;
252    }
253
254    mCurrentState.displays.removeItemsAt(idx);
255    setTransactionFlags(eDisplayTransactionNeeded);
256}
257
258void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
259    ALOGW_IF(mBuiltinDisplays[type],
260            "Overwriting display token for display type %d", type);
261    mBuiltinDisplays[type] = new BBinder();
262    DisplayDeviceState info(type);
263    // All non-virtual displays are currently considered secure.
264    info.isSecure = true;
265    mCurrentState.displays.add(mBuiltinDisplays[type], info);
266}
267
268sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
269    if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
270        ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
271        return NULL;
272    }
273    return mBuiltinDisplays[id];
274}
275
276sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
277{
278    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
279    return gba;
280}
281
282void SurfaceFlinger::bootFinished()
283{
284    const nsecs_t now = systemTime();
285    const nsecs_t duration = now - mBootTime;
286    ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
287    mBootFinished = true;
288
289    // wait patiently for the window manager death
290    const String16 name("window");
291    sp<IBinder> window(defaultServiceManager()->getService(name));
292    if (window != 0) {
293        window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
294    }
295
296    // stop boot animation
297    // formerly we would just kill the process, but we now ask it to exit so it
298    // can choose where to stop the animation.
299    property_set("service.bootanim.exit", "1");
300}
301
302void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
303    class MessageDestroyGLTexture : public MessageBase {
304        RenderEngine& engine;
305        uint32_t texture;
306    public:
307        MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
308            : engine(engine), texture(texture) {
309        }
310        virtual bool handler() {
311            engine.deleteTextures(1, &texture);
312            return true;
313        }
314    };
315    postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
316}
317
318status_t SurfaceFlinger::selectConfigForAttribute(
319        EGLDisplay dpy,
320        EGLint const* attrs,
321        EGLint attribute, EGLint wanted,
322        EGLConfig* outConfig)
323{
324    EGLConfig config = NULL;
325    EGLint numConfigs = -1, n=0;
326    eglGetConfigs(dpy, NULL, 0, &numConfigs);
327    EGLConfig* const configs = new EGLConfig[numConfigs];
328    eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
329
330    if (n) {
331        if (attribute != EGL_NONE) {
332            for (int i=0 ; i<n ; i++) {
333                EGLint value = 0;
334                eglGetConfigAttrib(dpy, configs[i], attribute, &value);
335                if (wanted == value) {
336                    *outConfig = configs[i];
337                    delete [] configs;
338                    return NO_ERROR;
339                }
340            }
341        } else {
342            // just pick the first one
343            *outConfig = configs[0];
344            delete [] configs;
345            return NO_ERROR;
346        }
347    }
348    delete [] configs;
349    return NAME_NOT_FOUND;
350}
351
352class EGLAttributeVector {
353    struct Attribute;
354    class Adder;
355    friend class Adder;
356    KeyedVector<Attribute, EGLint> mList;
357    struct Attribute {
358        Attribute() {};
359        Attribute(EGLint v) : v(v) { }
360        EGLint v;
361        bool operator < (const Attribute& other) const {
362            // this places EGL_NONE at the end
363            EGLint lhs(v);
364            EGLint rhs(other.v);
365            if (lhs == EGL_NONE) lhs = 0x7FFFFFFF;
366            if (rhs == EGL_NONE) rhs = 0x7FFFFFFF;
367            return lhs < rhs;
368        }
369    };
370    class Adder {
371        friend class EGLAttributeVector;
372        EGLAttributeVector& v;
373        EGLint attribute;
374        Adder(EGLAttributeVector& v, EGLint attribute)
375            : v(v), attribute(attribute) {
376        }
377    public:
378        void operator = (EGLint value) {
379            if (attribute != EGL_NONE) {
380                v.mList.add(attribute, value);
381            }
382        }
383        operator EGLint () const { return v.mList[attribute]; }
384    };
385public:
386    EGLAttributeVector() {
387        mList.add(EGL_NONE, EGL_NONE);
388    }
389    void remove(EGLint attribute) {
390        if (attribute != EGL_NONE) {
391            mList.removeItem(attribute);
392        }
393    }
394    Adder operator [] (EGLint attribute) {
395        return Adder(*this, attribute);
396    }
397    EGLint operator [] (EGLint attribute) const {
398       return mList[attribute];
399    }
400    // cast-operator to (EGLint const*)
401    operator EGLint const* () const { return &mList.keyAt(0).v; }
402};
403
404status_t SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId,
405    EGLint renderableType, EGLConfig* config) {
406    // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
407    // it is to be used with WIFI displays
408    status_t err;
409    EGLint wantedAttribute;
410    EGLint wantedAttributeValue;
411
412    EGLAttributeVector attribs;
413    if (renderableType) {
414        attribs[EGL_RENDERABLE_TYPE]            = renderableType;
415        attribs[EGL_RECORDABLE_ANDROID]         = EGL_TRUE;
416        attribs[EGL_SURFACE_TYPE]               = EGL_WINDOW_BIT|EGL_PBUFFER_BIT;
417        attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE;
418        attribs[EGL_RED_SIZE]                   = 8;
419        attribs[EGL_GREEN_SIZE]                 = 8;
420        attribs[EGL_BLUE_SIZE]                  = 8;
421        wantedAttribute                         = EGL_NONE;
422        wantedAttributeValue                    = EGL_NONE;
423
424    } else {
425        // if no renderable type specified, fallback to a simplified query
426        wantedAttribute                         = EGL_NATIVE_VISUAL_ID;
427        wantedAttributeValue                    = nativeVisualId;
428    }
429
430    err = selectConfigForAttribute(display, attribs, wantedAttribute,
431        wantedAttributeValue, config);
432    if (err == NO_ERROR) {
433        EGLint caveat;
434        if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
435            ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
436    }
437    return err;
438}
439
440class DispSyncSource : public VSyncSource, private DispSync::Callback {
441public:
442    DispSyncSource(DispSync* dispSync) : mValue(0), mDispSync(dispSync) {}
443
444    virtual ~DispSyncSource() {}
445
446    virtual void setVSyncEnabled(bool enable) {
447        // Do NOT lock the mutex here so as to avoid any mutex ordering issues
448        // with locking it in the onDispSyncEvent callback.
449        if (enable) {
450            status_t err = mDispSync->addEventListener(vsyncPhaseOffsetNs,
451                    static_cast<DispSync::Callback*>(this));
452            if (err != NO_ERROR) {
453                ALOGE("error registering vsync callback: %s (%d)",
454                        strerror(-err), err);
455            }
456            ATRACE_INT("VsyncOn", 1);
457        } else {
458            status_t err = mDispSync->removeEventListener(
459                    static_cast<DispSync::Callback*>(this));
460            if (err != NO_ERROR) {
461                ALOGE("error unregistering vsync callback: %s (%d)",
462                        strerror(-err), err);
463            }
464            ATRACE_INT("VsyncOn", 0);
465        }
466    }
467
468    virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
469        Mutex::Autolock lock(mMutex);
470        mCallback = callback;
471    }
472
473private:
474    virtual void onDispSyncEvent(nsecs_t when) {
475        sp<VSyncSource::Callback> callback;
476        {
477            Mutex::Autolock lock(mMutex);
478            callback = mCallback;
479
480            mValue = (mValue + 1) % 2;
481            ATRACE_INT("VSYNC", mValue);
482        }
483
484        if (callback != NULL) {
485            callback->onVSyncEvent(when);
486        }
487    }
488
489    int mValue;
490
491    DispSync* mDispSync;
492    sp<VSyncSource::Callback> mCallback;
493    Mutex mMutex;
494};
495
496void SurfaceFlinger::init() {
497    ALOGI(  "SurfaceFlinger's main thread ready to run. "
498            "Initializing graphics H/W...");
499
500    status_t err;
501    Mutex::Autolock _l(mStateLock);
502
503    // initialize EGL for the default display
504    mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
505    eglInitialize(mEGLDisplay, NULL, NULL);
506
507    // Initialize the H/W composer object.  There may or may not be an
508    // actual hardware composer underneath.
509    mHwc = new HWComposer(this,
510            *static_cast<HWComposer::EventHandler *>(this));
511
512    // First try to get an ES2 config
513    err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(), EGL_OPENGL_ES2_BIT,
514            &mEGLConfig);
515
516    if (err != NO_ERROR) {
517        // If ES2 fails, try ES1
518        err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(),
519                EGL_OPENGL_ES_BIT, &mEGLConfig);
520    }
521
522    if (err != NO_ERROR) {
523        // still didn't work, probably because we're on the emulator...
524        // try a simplified query
525        ALOGW("no suitable EGLConfig found, trying a simpler query");
526        err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(), 0, &mEGLConfig);
527    }
528
529    if (err != NO_ERROR) {
530        // this EGL is too lame for android
531        LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
532    }
533
534    // print some debugging info
535    EGLint r,g,b,a;
536    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_RED_SIZE,   &r);
537    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_GREEN_SIZE, &g);
538    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_BLUE_SIZE,  &b);
539    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_ALPHA_SIZE, &a);
540    ALOGI("EGL informations:");
541    ALOGI("vendor    : %s", eglQueryString(mEGLDisplay, EGL_VENDOR));
542    ALOGI("version   : %s", eglQueryString(mEGLDisplay, EGL_VERSION));
543    ALOGI("extensions: %s", eglQueryString(mEGLDisplay, EGL_EXTENSIONS));
544    ALOGI("Client API: %s", eglQueryString(mEGLDisplay, EGL_CLIENT_APIS)?:"Not Supported");
545    ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
546
547    // get a RenderEngine for the given display / config (can't fail)
548    mRenderEngine = RenderEngine::create(mEGLDisplay, mEGLConfig);
549
550    // retrieve the EGL context that was selected/created
551    mEGLContext = mRenderEngine->getEGLContext();
552
553    // figure out which format we got
554    eglGetConfigAttrib(mEGLDisplay, mEGLConfig,
555            EGL_NATIVE_VISUAL_ID, &mEGLNativeVisualId);
556
557    LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
558            "couldn't create EGLContext");
559
560    // initialize our non-virtual displays
561    for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
562        DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
563        // set-up the displays that are already connected
564        if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
565            // All non-virtual displays are currently considered secure.
566            bool isSecure = true;
567            createBuiltinDisplayLocked(type);
568            wp<IBinder> token = mBuiltinDisplays[i];
569
570            sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc());
571            sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i, bq);
572            sp<DisplayDevice> hw = new DisplayDevice(this,
573                    type, allocateHwcDisplayId(type), isSecure, token,
574                    fbs, bq,
575                    mEGLConfig);
576            if (i > DisplayDevice::DISPLAY_PRIMARY) {
577                // FIXME: currently we don't get blank/unblank requests
578                // for displays other than the main display, so we always
579                // assume a connected display is unblanked.
580                ALOGD("marking display %d as acquired/unblanked", i);
581                hw->acquireScreen();
582            }
583            mDisplays.add(token, hw);
584        }
585    }
586
587    // make the GLContext current so that we can create textures when creating Layers
588    // (which may happens before we render something)
589    getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
590
591    // start the EventThread
592    sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync);
593    mEventThread = new EventThread(vsyncSrc);
594    mEventQueue.setEventThread(mEventThread);
595
596    // set a fake vsync period if there is no HWComposer
597    if (mHwc->initCheck() != NO_ERROR) {
598        mPrimaryDispSync.setPeriod(16666667);
599    }
600
601    // initialize our drawing state
602    mDrawingState = mCurrentState;
603
604    // set initial conditions (e.g. unblank default device)
605    initializeDisplays();
606
607    // start boot animation
608    startBootAnim();
609}
610
611int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
612    return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
613            type : mHwc->allocateDisplayId();
614}
615
616void SurfaceFlinger::startBootAnim() {
617    // start boot animation
618    property_set("service.bootanim.exit", "0");
619    property_set("ctl.start", "bootanim");
620}
621
622size_t SurfaceFlinger::getMaxTextureSize() const {
623    return mRenderEngine->getMaxTextureSize();
624}
625
626size_t SurfaceFlinger::getMaxViewportDims() const {
627    return mRenderEngine->getMaxViewportDims();
628}
629
630// ----------------------------------------------------------------------------
631
632bool SurfaceFlinger::authenticateSurfaceTexture(
633        const sp<IGraphicBufferProducer>& bufferProducer) const {
634    Mutex::Autolock _l(mStateLock);
635    sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder());
636    return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
637}
638
639status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
640    int32_t type = NAME_NOT_FOUND;
641    for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
642        if (display == mBuiltinDisplays[i]) {
643            type = i;
644            break;
645        }
646    }
647
648    if (type < 0) {
649        return type;
650    }
651
652    const HWComposer& hwc(getHwComposer());
653    float xdpi = hwc.getDpiX(type);
654    float ydpi = hwc.getDpiY(type);
655
656    // TODO: Not sure if display density should handled by SF any longer
657    class Density {
658        static int getDensityFromProperty(char const* propName) {
659            char property[PROPERTY_VALUE_MAX];
660            int density = 0;
661            if (property_get(propName, property, NULL) > 0) {
662                density = atoi(property);
663            }
664            return density;
665        }
666    public:
667        static int getEmuDensity() {
668            return getDensityFromProperty("qemu.sf.lcd_density"); }
669        static int getBuildDensity()  {
670            return getDensityFromProperty("ro.sf.lcd_density"); }
671    };
672
673    if (type == DisplayDevice::DISPLAY_PRIMARY) {
674        // The density of the device is provided by a build property
675        float density = Density::getBuildDensity() / 160.0f;
676        if (density == 0) {
677            // the build doesn't provide a density -- this is wrong!
678            // use xdpi instead
679            ALOGE("ro.sf.lcd_density must be defined as a build property");
680            density = xdpi / 160.0f;
681        }
682        if (Density::getEmuDensity()) {
683            // if "qemu.sf.lcd_density" is specified, it overrides everything
684            xdpi = ydpi = density = Density::getEmuDensity();
685            density /= 160.0f;
686        }
687        info->density = density;
688
689        // TODO: this needs to go away (currently needed only by webkit)
690        sp<const DisplayDevice> hw(getDefaultDisplayDevice());
691        info->orientation = hw->getOrientation();
692    } else {
693        // TODO: where should this value come from?
694        static const int TV_DENSITY = 213;
695        info->density = TV_DENSITY / 160.0f;
696        info->orientation = 0;
697    }
698
699    info->w = hwc.getWidth(type);
700    info->h = hwc.getHeight(type);
701    info->xdpi = xdpi;
702    info->ydpi = ydpi;
703    info->fps = float(1e9 / hwc.getRefreshPeriod(type));
704
705    // All non-virtual displays are currently considered secure.
706    info->secure = true;
707
708    return NO_ERROR;
709}
710
711// ----------------------------------------------------------------------------
712
713sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
714    return mEventThread->createEventConnection();
715}
716
717// ----------------------------------------------------------------------------
718
719void SurfaceFlinger::waitForEvent() {
720    mEventQueue.waitMessage();
721}
722
723void SurfaceFlinger::signalTransaction() {
724    mEventQueue.invalidate();
725}
726
727void SurfaceFlinger::signalLayerUpdate() {
728    mEventQueue.invalidate();
729}
730
731void SurfaceFlinger::signalRefresh() {
732    mEventQueue.refresh();
733}
734
735status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
736        nsecs_t reltime, uint32_t flags) {
737    return mEventQueue.postMessage(msg, reltime);
738}
739
740status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
741        nsecs_t reltime, uint32_t flags) {
742    status_t res = mEventQueue.postMessage(msg, reltime);
743    if (res == NO_ERROR) {
744        msg->wait();
745    }
746    return res;
747}
748
749void SurfaceFlinger::run() {
750    do {
751        waitForEvent();
752    } while (true);
753}
754
755void SurfaceFlinger::enableHardwareVsync() {
756    Mutex::Autolock _l(mHWVsyncLock);
757    if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
758        mPrimaryDispSync.beginResync();
759        eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
760        mPrimaryHWVsyncEnabled = true;
761    }
762}
763
764void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
765    Mutex::Autolock _l(mHWVsyncLock);
766
767    if (makeAvailable) {
768        mHWVsyncAvailable = true;
769    } else if (!mHWVsyncAvailable) {
770        ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
771        return;
772    }
773
774    const nsecs_t period =
775            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
776
777    mPrimaryDispSync.reset();
778    mPrimaryDispSync.setPeriod(period);
779
780    if (!mPrimaryHWVsyncEnabled) {
781        mPrimaryDispSync.beginResync();
782        eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
783        mPrimaryHWVsyncEnabled = true;
784    }
785}
786
787void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
788    Mutex::Autolock _l(mHWVsyncLock);
789    if (mPrimaryHWVsyncEnabled) {
790        eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
791        mPrimaryDispSync.endResync();
792        mPrimaryHWVsyncEnabled = false;
793    }
794    if (makeUnavailable) {
795        mHWVsyncAvailable = false;
796    }
797}
798
799void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
800    if (type == 0) {
801        bool needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
802
803        if (needsHwVsync) {
804            enableHardwareVsync();
805        } else {
806            disableHardwareVsync(false);
807        }
808    }
809}
810
811void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
812    if (mEventThread == NULL) {
813        // This is a temporary workaround for b/7145521.  A non-null pointer
814        // does not mean EventThread has finished initializing, so this
815        // is not a correct fix.
816        ALOGW("WARNING: EventThread not started, ignoring hotplug");
817        return;
818    }
819
820    if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
821        Mutex::Autolock _l(mStateLock);
822        if (connected) {
823            createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
824        } else {
825            mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
826            mBuiltinDisplays[type].clear();
827        }
828        setTransactionFlags(eDisplayTransactionNeeded);
829
830        // Defer EventThread notification until SF has updated mDisplays.
831    }
832}
833
834void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
835    ATRACE_CALL();
836    getHwComposer().eventControl(disp, event, enabled);
837}
838
839void SurfaceFlinger::onMessageReceived(int32_t what) {
840    ATRACE_CALL();
841    switch (what) {
842    case MessageQueue::TRANSACTION:
843        handleMessageTransaction();
844        break;
845    case MessageQueue::INVALIDATE:
846        handleMessageTransaction();
847        handleMessageInvalidate();
848        signalRefresh();
849        break;
850    case MessageQueue::REFRESH:
851        handleMessageRefresh();
852        break;
853    }
854}
855
856void SurfaceFlinger::handleMessageTransaction() {
857    uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
858    if (transactionFlags) {
859        handleTransaction(transactionFlags);
860    }
861}
862
863void SurfaceFlinger::handleMessageInvalidate() {
864    ATRACE_CALL();
865    handlePageFlip();
866}
867
868void SurfaceFlinger::handleMessageRefresh() {
869    ATRACE_CALL();
870    preComposition();
871    rebuildLayerStacks();
872    setUpHWComposer();
873    doDebugFlashRegions();
874    doComposition();
875    postComposition();
876}
877
878void SurfaceFlinger::doDebugFlashRegions()
879{
880    // is debugging enabled
881    if (CC_LIKELY(!mDebugRegion))
882        return;
883
884    const bool repaintEverything = mRepaintEverything;
885    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
886        const sp<DisplayDevice>& hw(mDisplays[dpy]);
887        if (hw->canDraw()) {
888            // transform the dirty region into this screen's coordinate space
889            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
890            if (!dirtyRegion.isEmpty()) {
891                // redraw the whole screen
892                doComposeSurfaces(hw, Region(hw->bounds()));
893
894                // and draw the dirty region
895                const int32_t height = hw->getHeight();
896                RenderEngine& engine(getRenderEngine());
897                engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
898
899                hw->compositionComplete();
900                hw->swapBuffers(getHwComposer());
901            }
902        }
903    }
904
905    postFramebuffer();
906
907    if (mDebugRegion > 1) {
908        usleep(mDebugRegion * 1000);
909    }
910
911    HWComposer& hwc(getHwComposer());
912    if (hwc.initCheck() == NO_ERROR) {
913        status_t err = hwc.prepare();
914        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
915    }
916}
917
918void SurfaceFlinger::preComposition()
919{
920    bool needExtraInvalidate = false;
921    const LayerVector& layers(mDrawingState.layersSortedByZ);
922    const size_t count = layers.size();
923    for (size_t i=0 ; i<count ; i++) {
924        if (layers[i]->onPreComposition()) {
925            needExtraInvalidate = true;
926        }
927    }
928    if (needExtraInvalidate) {
929        signalLayerUpdate();
930    }
931}
932
933void SurfaceFlinger::postComposition()
934{
935    const LayerVector& layers(mDrawingState.layersSortedByZ);
936    const size_t count = layers.size();
937    for (size_t i=0 ; i<count ; i++) {
938        layers[i]->onPostComposition();
939    }
940
941    const HWComposer& hwc = getHwComposer();
942    sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
943
944    if (presentFence->isValid()) {
945        if (mPrimaryDispSync.addPresentFence(presentFence)) {
946            enableHardwareVsync();
947        } else {
948            disableHardwareVsync(false);
949        }
950    }
951
952    if (runningWithoutSyncFramework) {
953        const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
954        if (hw->isScreenAcquired()) {
955            enableHardwareVsync();
956        }
957    }
958
959    if (mAnimCompositionPending) {
960        mAnimCompositionPending = false;
961
962        if (presentFence->isValid()) {
963            mAnimFrameTracker.setActualPresentFence(presentFence);
964        } else {
965            // The HWC doesn't support present fences, so use the refresh
966            // timestamp instead.
967            nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
968            mAnimFrameTracker.setActualPresentTime(presentTime);
969        }
970        mAnimFrameTracker.advanceFrame();
971    }
972}
973
974void SurfaceFlinger::rebuildLayerStacks() {
975    // rebuild the visible layer list per screen
976    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
977        ATRACE_CALL();
978        mVisibleRegionsDirty = false;
979        invalidateHwcGeometry();
980
981        const LayerVector& layers(mDrawingState.layersSortedByZ);
982        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
983            Region opaqueRegion;
984            Region dirtyRegion;
985            Vector< sp<Layer> > layersSortedByZ;
986            const sp<DisplayDevice>& hw(mDisplays[dpy]);
987            const Transform& tr(hw->getTransform());
988            const Rect bounds(hw->getBounds());
989            if (hw->canDraw()) {
990                SurfaceFlinger::computeVisibleRegions(layers,
991                        hw->getLayerStack(), dirtyRegion, opaqueRegion);
992
993                const size_t count = layers.size();
994                for (size_t i=0 ; i<count ; i++) {
995                    const sp<Layer>& layer(layers[i]);
996                    const Layer::State& s(layer->getDrawingState());
997                    if (s.layerStack == hw->getLayerStack()) {
998                        Region drawRegion(tr.transform(
999                                layer->visibleNonTransparentRegion));
1000                        drawRegion.andSelf(bounds);
1001                        if (!drawRegion.isEmpty()) {
1002                            layersSortedByZ.add(layer);
1003                        }
1004                    }
1005                }
1006            }
1007            hw->setVisibleLayersSortedByZ(layersSortedByZ);
1008            hw->undefinedRegion.set(bounds);
1009            hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1010            hw->dirtyRegion.orSelf(dirtyRegion);
1011        }
1012    }
1013}
1014
1015void SurfaceFlinger::setUpHWComposer() {
1016    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1017        mDisplays[dpy]->beginFrame();
1018    }
1019
1020    HWComposer& hwc(getHwComposer());
1021    if (hwc.initCheck() == NO_ERROR) {
1022        // build the h/w work list
1023        if (CC_UNLIKELY(mHwWorkListDirty)) {
1024            mHwWorkListDirty = false;
1025            for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1026                sp<const DisplayDevice> hw(mDisplays[dpy]);
1027                const int32_t id = hw->getHwcDisplayId();
1028                if (id >= 0) {
1029                    const Vector< sp<Layer> >& currentLayers(
1030                        hw->getVisibleLayersSortedByZ());
1031                    const size_t count = currentLayers.size();
1032                    if (hwc.createWorkList(id, count) == NO_ERROR) {
1033                        HWComposer::LayerListIterator cur = hwc.begin(id);
1034                        const HWComposer::LayerListIterator end = hwc.end(id);
1035                        for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1036                            const sp<Layer>& layer(currentLayers[i]);
1037                            layer->setGeometry(hw, *cur);
1038                            if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1039                                cur->setSkip(true);
1040                            }
1041                        }
1042                    }
1043                }
1044            }
1045        }
1046
1047        // set the per-frame data
1048        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1049            sp<const DisplayDevice> hw(mDisplays[dpy]);
1050            const int32_t id = hw->getHwcDisplayId();
1051            if (id >= 0) {
1052                const Vector< sp<Layer> >& currentLayers(
1053                    hw->getVisibleLayersSortedByZ());
1054                const size_t count = currentLayers.size();
1055                HWComposer::LayerListIterator cur = hwc.begin(id);
1056                const HWComposer::LayerListIterator end = hwc.end(id);
1057                for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1058                    /*
1059                     * update the per-frame h/w composer data for each layer
1060                     * and build the transparent region of the FB
1061                     */
1062                    const sp<Layer>& layer(currentLayers[i]);
1063                    layer->setPerFrameData(hw, *cur);
1064                }
1065            }
1066        }
1067
1068        status_t err = hwc.prepare();
1069        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1070
1071        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1072            sp<const DisplayDevice> hw(mDisplays[dpy]);
1073            hw->prepareFrame(hwc);
1074        }
1075    }
1076}
1077
1078void SurfaceFlinger::doComposition() {
1079    ATRACE_CALL();
1080    const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1081    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1082        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1083        if (hw->canDraw()) {
1084            // transform the dirty region into this screen's coordinate space
1085            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1086
1087            // repaint the framebuffer (if needed)
1088            doDisplayComposition(hw, dirtyRegion);
1089
1090            hw->dirtyRegion.clear();
1091            hw->flip(hw->swapRegion);
1092            hw->swapRegion.clear();
1093        }
1094        // inform the h/w that we're done compositing
1095        hw->compositionComplete();
1096    }
1097    postFramebuffer();
1098}
1099
1100void SurfaceFlinger::postFramebuffer()
1101{
1102    ATRACE_CALL();
1103
1104    const nsecs_t now = systemTime();
1105    mDebugInSwapBuffers = now;
1106
1107    HWComposer& hwc(getHwComposer());
1108    if (hwc.initCheck() == NO_ERROR) {
1109        if (!hwc.supportsFramebufferTarget()) {
1110            // EGL spec says:
1111            //   "surface must be bound to the calling thread's current context,
1112            //    for the current rendering API."
1113            getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1114        }
1115        hwc.commit();
1116    }
1117
1118    // make the default display current because the VirtualDisplayDevice code cannot
1119    // deal with dequeueBuffer() being called outside of the composition loop; however
1120    // the code below can call glFlush() which is allowed (and does in some case) call
1121    // dequeueBuffer().
1122    getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1123
1124    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1125        sp<const DisplayDevice> hw(mDisplays[dpy]);
1126        const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1127        hw->onSwapBuffersCompleted(hwc);
1128        const size_t count = currentLayers.size();
1129        int32_t id = hw->getHwcDisplayId();
1130        if (id >=0 && hwc.initCheck() == NO_ERROR) {
1131            HWComposer::LayerListIterator cur = hwc.begin(id);
1132            const HWComposer::LayerListIterator end = hwc.end(id);
1133            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1134                currentLayers[i]->onLayerDisplayed(hw, &*cur);
1135            }
1136        } else {
1137            for (size_t i = 0; i < count; i++) {
1138                currentLayers[i]->onLayerDisplayed(hw, NULL);
1139            }
1140        }
1141    }
1142
1143    mLastSwapBufferTime = systemTime() - now;
1144    mDebugInSwapBuffers = 0;
1145
1146    uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1147    if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1148        logFrameStats();
1149    }
1150}
1151
1152void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1153{
1154    ATRACE_CALL();
1155
1156    // here we keep a copy of the drawing state (that is the state that's
1157    // going to be overwritten by handleTransactionLocked()) outside of
1158    // mStateLock so that the side-effects of the State assignment
1159    // don't happen with mStateLock held (which can cause deadlocks).
1160    State drawingState(mDrawingState);
1161
1162    Mutex::Autolock _l(mStateLock);
1163    const nsecs_t now = systemTime();
1164    mDebugInTransaction = now;
1165
1166    // Here we're guaranteed that some transaction flags are set
1167    // so we can call handleTransactionLocked() unconditionally.
1168    // We call getTransactionFlags(), which will also clear the flags,
1169    // with mStateLock held to guarantee that mCurrentState won't change
1170    // until the transaction is committed.
1171
1172    transactionFlags = getTransactionFlags(eTransactionMask);
1173    handleTransactionLocked(transactionFlags);
1174
1175    mLastTransactionTime = systemTime() - now;
1176    mDebugInTransaction = 0;
1177    invalidateHwcGeometry();
1178    // here the transaction has been committed
1179}
1180
1181void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1182{
1183    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1184    const size_t count = currentLayers.size();
1185
1186    /*
1187     * Traversal of the children
1188     * (perform the transaction for each of them if needed)
1189     */
1190
1191    if (transactionFlags & eTraversalNeeded) {
1192        for (size_t i=0 ; i<count ; i++) {
1193            const sp<Layer>& layer(currentLayers[i]);
1194            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1195            if (!trFlags) continue;
1196
1197            const uint32_t flags = layer->doTransaction(0);
1198            if (flags & Layer::eVisibleRegion)
1199                mVisibleRegionsDirty = true;
1200        }
1201    }
1202
1203    /*
1204     * Perform display own transactions if needed
1205     */
1206
1207    if (transactionFlags & eDisplayTransactionNeeded) {
1208        // here we take advantage of Vector's copy-on-write semantics to
1209        // improve performance by skipping the transaction entirely when
1210        // know that the lists are identical
1211        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1212        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1213        if (!curr.isIdenticalTo(draw)) {
1214            mVisibleRegionsDirty = true;
1215            const size_t cc = curr.size();
1216                  size_t dc = draw.size();
1217
1218            // find the displays that were removed
1219            // (ie: in drawing state but not in current state)
1220            // also handle displays that changed
1221            // (ie: displays that are in both lists)
1222            for (size_t i=0 ; i<dc ; i++) {
1223                const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1224                if (j < 0) {
1225                    // in drawing state but not in current state
1226                    if (!draw[i].isMainDisplay()) {
1227                        // Call makeCurrent() on the primary display so we can
1228                        // be sure that nothing associated with this display
1229                        // is current.
1230                        const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1231                        defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1232                        sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1233                        if (hw != NULL)
1234                            hw->disconnect(getHwComposer());
1235                        if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1236                            mEventThread->onHotplugReceived(draw[i].type, false);
1237                        mDisplays.removeItem(draw.keyAt(i));
1238                    } else {
1239                        ALOGW("trying to remove the main display");
1240                    }
1241                } else {
1242                    // this display is in both lists. see if something changed.
1243                    const DisplayDeviceState& state(curr[j]);
1244                    const wp<IBinder>& display(curr.keyAt(j));
1245                    if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1246                        // changing the surface is like destroying and
1247                        // recreating the DisplayDevice, so we just remove it
1248                        // from the drawing state, so that it get re-added
1249                        // below.
1250                        sp<DisplayDevice> hw(getDisplayDevice(display));
1251                        if (hw != NULL)
1252                            hw->disconnect(getHwComposer());
1253                        mDisplays.removeItem(display);
1254                        mDrawingState.displays.removeItemsAt(i);
1255                        dc--; i--;
1256                        // at this point we must loop to the next item
1257                        continue;
1258                    }
1259
1260                    const sp<DisplayDevice> disp(getDisplayDevice(display));
1261                    if (disp != NULL) {
1262                        if (state.layerStack != draw[i].layerStack) {
1263                            disp->setLayerStack(state.layerStack);
1264                        }
1265                        if ((state.orientation != draw[i].orientation)
1266                                || (state.viewport != draw[i].viewport)
1267                                || (state.frame != draw[i].frame))
1268                        {
1269                            disp->setProjection(state.orientation,
1270                                    state.viewport, state.frame);
1271                        }
1272                    }
1273                }
1274            }
1275
1276            // find displays that were added
1277            // (ie: in current state but not in drawing state)
1278            for (size_t i=0 ; i<cc ; i++) {
1279                if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1280                    const DisplayDeviceState& state(curr[i]);
1281
1282                    sp<DisplaySurface> dispSurface;
1283                    sp<IGraphicBufferProducer> producer;
1284                    sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc());
1285
1286                    int32_t hwcDisplayId = -1;
1287                    if (state.isVirtualDisplay()) {
1288                        // Virtual displays without a surface are dormant:
1289                        // they have external state (layer stack, projection,
1290                        // etc.) but no internal state (i.e. a DisplayDevice).
1291                        if (state.surface != NULL) {
1292
1293                            hwcDisplayId = allocateHwcDisplayId(state.type);
1294                            sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1295                                    *mHwc, hwcDisplayId, state.surface, bq,
1296                                    state.displayName);
1297
1298                            dispSurface = vds;
1299                            if (hwcDisplayId >= 0) {
1300                                producer = vds;
1301                            } else {
1302                                // There won't be any interaction with HWC for this virtual display,
1303                                // so the GLES driver can pass buffers directly to the sink.
1304                                producer = state.surface;
1305                            }
1306                        }
1307                    } else {
1308                        ALOGE_IF(state.surface!=NULL,
1309                                "adding a supported display, but rendering "
1310                                "surface is provided (%p), ignoring it",
1311                                state.surface.get());
1312                        hwcDisplayId = allocateHwcDisplayId(state.type);
1313                        // for supported (by hwc) displays we provide our
1314                        // own rendering surface
1315                        dispSurface = new FramebufferSurface(*mHwc, state.type, bq);
1316                        producer = bq;
1317                    }
1318
1319                    const wp<IBinder>& display(curr.keyAt(i));
1320                    if (dispSurface != NULL) {
1321                        sp<DisplayDevice> hw = new DisplayDevice(this,
1322                                state.type, hwcDisplayId, state.isSecure,
1323                                display, dispSurface, producer, mEGLConfig);
1324                        hw->setLayerStack(state.layerStack);
1325                        hw->setProjection(state.orientation,
1326                                state.viewport, state.frame);
1327                        hw->setDisplayName(state.displayName);
1328                        mDisplays.add(display, hw);
1329                        if (state.isVirtualDisplay()) {
1330                            if (hwcDisplayId >= 0) {
1331                                mHwc->setVirtualDisplayProperties(hwcDisplayId,
1332                                        hw->getWidth(), hw->getHeight(),
1333                                        hw->getFormat());
1334                            }
1335                        } else {
1336                            mEventThread->onHotplugReceived(state.type, true);
1337                        }
1338                    }
1339                }
1340            }
1341        }
1342    }
1343
1344    if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1345        // The transform hint might have changed for some layers
1346        // (either because a display has changed, or because a layer
1347        // as changed).
1348        //
1349        // Walk through all the layers in currentLayers,
1350        // and update their transform hint.
1351        //
1352        // If a layer is visible only on a single display, then that
1353        // display is used to calculate the hint, otherwise we use the
1354        // default display.
1355        //
1356        // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1357        // the hint is set before we acquire a buffer from the surface texture.
1358        //
1359        // NOTE: layer transactions have taken place already, so we use their
1360        // drawing state. However, SurfaceFlinger's own transaction has not
1361        // happened yet, so we must use the current state layer list
1362        // (soon to become the drawing state list).
1363        //
1364        sp<const DisplayDevice> disp;
1365        uint32_t currentlayerStack = 0;
1366        for (size_t i=0; i<count; i++) {
1367            // NOTE: we rely on the fact that layers are sorted by
1368            // layerStack first (so we don't have to traverse the list
1369            // of displays for every layer).
1370            const sp<Layer>& layer(currentLayers[i]);
1371            uint32_t layerStack = layer->getDrawingState().layerStack;
1372            if (i==0 || currentlayerStack != layerStack) {
1373                currentlayerStack = layerStack;
1374                // figure out if this layerstack is mirrored
1375                // (more than one display) if so, pick the default display,
1376                // if not, pick the only display it's on.
1377                disp.clear();
1378                for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1379                    sp<const DisplayDevice> hw(mDisplays[dpy]);
1380                    if (hw->getLayerStack() == currentlayerStack) {
1381                        if (disp == NULL) {
1382                            disp = hw;
1383                        } else {
1384                            disp = NULL;
1385                            break;
1386                        }
1387                    }
1388                }
1389            }
1390            if (disp == NULL) {
1391                // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1392                // redraw after transform hint changes. See bug 8508397.
1393
1394                // could be null when this layer is using a layerStack
1395                // that is not visible on any display. Also can occur at
1396                // screen off/on times.
1397                disp = getDefaultDisplayDevice();
1398            }
1399            layer->updateTransformHint(disp);
1400        }
1401    }
1402
1403
1404    /*
1405     * Perform our own transaction if needed
1406     */
1407
1408    const LayerVector& layers(mDrawingState.layersSortedByZ);
1409    if (currentLayers.size() > layers.size()) {
1410        // layers have been added
1411        mVisibleRegionsDirty = true;
1412    }
1413
1414    // some layers might have been removed, so
1415    // we need to update the regions they're exposing.
1416    if (mLayersRemoved) {
1417        mLayersRemoved = false;
1418        mVisibleRegionsDirty = true;
1419        const size_t count = layers.size();
1420        for (size_t i=0 ; i<count ; i++) {
1421            const sp<Layer>& layer(layers[i]);
1422            if (currentLayers.indexOf(layer) < 0) {
1423                // this layer is not visible anymore
1424                // TODO: we could traverse the tree from front to back and
1425                //       compute the actual visible region
1426                // TODO: we could cache the transformed region
1427                const Layer::State& s(layer->getDrawingState());
1428                Region visibleReg = s.transform.transform(
1429                        Region(Rect(s.active.w, s.active.h)));
1430                invalidateLayerStack(s.layerStack, visibleReg);
1431            }
1432        }
1433    }
1434
1435    commitTransaction();
1436}
1437
1438void SurfaceFlinger::commitTransaction()
1439{
1440    if (!mLayersPendingRemoval.isEmpty()) {
1441        // Notify removed layers now that they can't be drawn from
1442        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1443            mLayersPendingRemoval[i]->onRemoved();
1444        }
1445        mLayersPendingRemoval.clear();
1446    }
1447
1448    // If this transaction is part of a window animation then the next frame
1449    // we composite should be considered an animation as well.
1450    mAnimCompositionPending = mAnimTransactionPending;
1451
1452    mDrawingState = mCurrentState;
1453    mTransactionPending = false;
1454    mAnimTransactionPending = false;
1455    mTransactionCV.broadcast();
1456}
1457
1458void SurfaceFlinger::computeVisibleRegions(
1459        const LayerVector& currentLayers, uint32_t layerStack,
1460        Region& outDirtyRegion, Region& outOpaqueRegion)
1461{
1462    ATRACE_CALL();
1463
1464    Region aboveOpaqueLayers;
1465    Region aboveCoveredLayers;
1466    Region dirty;
1467
1468    outDirtyRegion.clear();
1469
1470    size_t i = currentLayers.size();
1471    while (i--) {
1472        const sp<Layer>& layer = currentLayers[i];
1473
1474        // start with the whole surface at its current location
1475        const Layer::State& s(layer->getDrawingState());
1476
1477        // only consider the layers on the given layer stack
1478        if (s.layerStack != layerStack)
1479            continue;
1480
1481        /*
1482         * opaqueRegion: area of a surface that is fully opaque.
1483         */
1484        Region opaqueRegion;
1485
1486        /*
1487         * visibleRegion: area of a surface that is visible on screen
1488         * and not fully transparent. This is essentially the layer's
1489         * footprint minus the opaque regions above it.
1490         * Areas covered by a translucent surface are considered visible.
1491         */
1492        Region visibleRegion;
1493
1494        /*
1495         * coveredRegion: area of a surface that is covered by all
1496         * visible regions above it (which includes the translucent areas).
1497         */
1498        Region coveredRegion;
1499
1500        /*
1501         * transparentRegion: area of a surface that is hinted to be completely
1502         * transparent. This is only used to tell when the layer has no visible
1503         * non-transparent regions and can be removed from the layer list. It
1504         * does not affect the visibleRegion of this layer or any layers
1505         * beneath it. The hint may not be correct if apps don't respect the
1506         * SurfaceView restrictions (which, sadly, some don't).
1507         */
1508        Region transparentRegion;
1509
1510
1511        // handle hidden surfaces by setting the visible region to empty
1512        if (CC_LIKELY(layer->isVisible())) {
1513            const bool translucent = !layer->isOpaque();
1514            Rect bounds(s.transform.transform(layer->computeBounds()));
1515            visibleRegion.set(bounds);
1516            if (!visibleRegion.isEmpty()) {
1517                // Remove the transparent area from the visible region
1518                if (translucent) {
1519                    const Transform tr(s.transform);
1520                    if (tr.transformed()) {
1521                        if (tr.preserveRects()) {
1522                            // transform the transparent region
1523                            transparentRegion = tr.transform(s.activeTransparentRegion);
1524                        } else {
1525                            // transformation too complex, can't do the
1526                            // transparent region optimization.
1527                            transparentRegion.clear();
1528                        }
1529                    } else {
1530                        transparentRegion = s.activeTransparentRegion;
1531                    }
1532                }
1533
1534                // compute the opaque region
1535                const int32_t layerOrientation = s.transform.getOrientation();
1536                if (s.alpha==255 && !translucent &&
1537                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
1538                    // the opaque region is the layer's footprint
1539                    opaqueRegion = visibleRegion;
1540                }
1541            }
1542        }
1543
1544        // Clip the covered region to the visible region
1545        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1546
1547        // Update aboveCoveredLayers for next (lower) layer
1548        aboveCoveredLayers.orSelf(visibleRegion);
1549
1550        // subtract the opaque region covered by the layers above us
1551        visibleRegion.subtractSelf(aboveOpaqueLayers);
1552
1553        // compute this layer's dirty region
1554        if (layer->contentDirty) {
1555            // we need to invalidate the whole region
1556            dirty = visibleRegion;
1557            // as well, as the old visible region
1558            dirty.orSelf(layer->visibleRegion);
1559            layer->contentDirty = false;
1560        } else {
1561            /* compute the exposed region:
1562             *   the exposed region consists of two components:
1563             *   1) what's VISIBLE now and was COVERED before
1564             *   2) what's EXPOSED now less what was EXPOSED before
1565             *
1566             * note that (1) is conservative, we start with the whole
1567             * visible region but only keep what used to be covered by
1568             * something -- which mean it may have been exposed.
1569             *
1570             * (2) handles areas that were not covered by anything but got
1571             * exposed because of a resize.
1572             */
1573            const Region newExposed = visibleRegion - coveredRegion;
1574            const Region oldVisibleRegion = layer->visibleRegion;
1575            const Region oldCoveredRegion = layer->coveredRegion;
1576            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1577            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1578        }
1579        dirty.subtractSelf(aboveOpaqueLayers);
1580
1581        // accumulate to the screen dirty region
1582        outDirtyRegion.orSelf(dirty);
1583
1584        // Update aboveOpaqueLayers for next (lower) layer
1585        aboveOpaqueLayers.orSelf(opaqueRegion);
1586
1587        // Store the visible region in screen space
1588        layer->setVisibleRegion(visibleRegion);
1589        layer->setCoveredRegion(coveredRegion);
1590        layer->setVisibleNonTransparentRegion(
1591                visibleRegion.subtract(transparentRegion));
1592    }
1593
1594    outOpaqueRegion = aboveOpaqueLayers;
1595}
1596
1597void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1598        const Region& dirty) {
1599    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1600        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1601        if (hw->getLayerStack() == layerStack) {
1602            hw->dirtyRegion.orSelf(dirty);
1603        }
1604    }
1605}
1606
1607void SurfaceFlinger::handlePageFlip()
1608{
1609    Region dirtyRegion;
1610
1611    bool visibleRegions = false;
1612    const LayerVector& layers(mDrawingState.layersSortedByZ);
1613    const size_t count = layers.size();
1614    for (size_t i=0 ; i<count ; i++) {
1615        const sp<Layer>& layer(layers[i]);
1616        const Region dirty(layer->latchBuffer(visibleRegions));
1617        const Layer::State& s(layer->getDrawingState());
1618        invalidateLayerStack(s.layerStack, dirty);
1619    }
1620
1621    mVisibleRegionsDirty |= visibleRegions;
1622}
1623
1624void SurfaceFlinger::invalidateHwcGeometry()
1625{
1626    mHwWorkListDirty = true;
1627}
1628
1629
1630void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1631        const Region& inDirtyRegion)
1632{
1633    Region dirtyRegion(inDirtyRegion);
1634
1635    // compute the invalid region
1636    hw->swapRegion.orSelf(dirtyRegion);
1637
1638    uint32_t flags = hw->getFlags();
1639    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1640        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1641        // takes a rectangle, we must make sure to update that whole
1642        // rectangle in that case
1643        dirtyRegion.set(hw->swapRegion.bounds());
1644    } else {
1645        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1646            // We need to redraw the rectangle that will be updated
1647            // (pushed to the framebuffer).
1648            // This is needed because PARTIAL_UPDATES only takes one
1649            // rectangle instead of a region (see DisplayDevice::flip())
1650            dirtyRegion.set(hw->swapRegion.bounds());
1651        } else {
1652            // we need to redraw everything (the whole screen)
1653            dirtyRegion.set(hw->bounds());
1654            hw->swapRegion = dirtyRegion;
1655        }
1656    }
1657
1658    if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1659        doComposeSurfaces(hw, dirtyRegion);
1660    } else {
1661        RenderEngine& engine(getRenderEngine());
1662        mat4 colorMatrix = mColorMatrix;
1663        if (mDaltonize) {
1664            colorMatrix = colorMatrix * mDaltonizer();
1665        }
1666        engine.beginGroup(colorMatrix);
1667        doComposeSurfaces(hw, dirtyRegion);
1668        engine.endGroup();
1669    }
1670
1671    // update the swap region and clear the dirty region
1672    hw->swapRegion.orSelf(dirtyRegion);
1673
1674    // swap buffers (presentation)
1675    hw->swapBuffers(getHwComposer());
1676}
1677
1678void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1679{
1680    RenderEngine& engine(getRenderEngine());
1681    const int32_t id = hw->getHwcDisplayId();
1682    HWComposer& hwc(getHwComposer());
1683    HWComposer::LayerListIterator cur = hwc.begin(id);
1684    const HWComposer::LayerListIterator end = hwc.end(id);
1685
1686    bool hasGlesComposition = hwc.hasGlesComposition(id);
1687    if (hasGlesComposition) {
1688        if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1689            ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1690                  hw->getDisplayName().string());
1691            return;
1692        }
1693
1694        // Never touch the framebuffer if we don't have any framebuffer layers
1695        const bool hasHwcComposition = hwc.hasHwcComposition(id);
1696        if (hasHwcComposition) {
1697            // when using overlays, we assume a fully transparent framebuffer
1698            // NOTE: we could reduce how much we need to clear, for instance
1699            // remove where there are opaque FB layers. however, on some
1700            // GPUs doing a "clean slate" clear might be more efficient.
1701            // We'll revisit later if needed.
1702            engine.clearWithColor(0, 0, 0, 0);
1703        } else {
1704            // we start with the whole screen area
1705            const Region bounds(hw->getBounds());
1706
1707            // we remove the scissor part
1708            // we're left with the letterbox region
1709            // (common case is that letterbox ends-up being empty)
1710            const Region letterbox(bounds.subtract(hw->getScissor()));
1711
1712            // compute the area to clear
1713            Region region(hw->undefinedRegion.merge(letterbox));
1714
1715            // but limit it to the dirty region
1716            region.andSelf(dirty);
1717
1718            // screen is already cleared here
1719            if (!region.isEmpty()) {
1720                // can happen with SurfaceView
1721                drawWormhole(hw, region);
1722            }
1723        }
1724
1725        if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1726            // just to be on the safe side, we don't set the
1727            // scissor on the main display. It should never be needed
1728            // anyways (though in theory it could since the API allows it).
1729            const Rect& bounds(hw->getBounds());
1730            const Rect& scissor(hw->getScissor());
1731            if (scissor != bounds) {
1732                // scissor doesn't match the screen's dimensions, so we
1733                // need to clear everything outside of it and enable
1734                // the GL scissor so we don't draw anything where we shouldn't
1735
1736                // enable scissor for this frame
1737                const uint32_t height = hw->getHeight();
1738                engine.setScissor(scissor.left, height - scissor.bottom,
1739                        scissor.getWidth(), scissor.getHeight());
1740            }
1741        }
1742    }
1743
1744    /*
1745     * and then, render the layers targeted at the framebuffer
1746     */
1747
1748    const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1749    const size_t count = layers.size();
1750    const Transform& tr = hw->getTransform();
1751    if (cur != end) {
1752        // we're using h/w composer
1753        for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1754            const sp<Layer>& layer(layers[i]);
1755            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1756            if (!clip.isEmpty()) {
1757                switch (cur->getCompositionType()) {
1758                    case HWC_OVERLAY: {
1759                        const Layer::State& state(layer->getDrawingState());
1760                        if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1761                                && i
1762                                && layer->isOpaque() && (state.alpha == 0xFF)
1763                                && hasGlesComposition) {
1764                            // never clear the very first layer since we're
1765                            // guaranteed the FB is already cleared
1766                            layer->clearWithOpenGL(hw, clip);
1767                        }
1768                        break;
1769                    }
1770                    case HWC_FRAMEBUFFER: {
1771                        layer->draw(hw, clip);
1772                        break;
1773                    }
1774                    case HWC_FRAMEBUFFER_TARGET: {
1775                        // this should not happen as the iterator shouldn't
1776                        // let us get there.
1777                        ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i);
1778                        break;
1779                    }
1780                }
1781            }
1782            layer->setAcquireFence(hw, *cur);
1783        }
1784    } else {
1785        // we're not using h/w composer
1786        for (size_t i=0 ; i<count ; ++i) {
1787            const sp<Layer>& layer(layers[i]);
1788            const Region clip(dirty.intersect(
1789                    tr.transform(layer->visibleRegion)));
1790            if (!clip.isEmpty()) {
1791                layer->draw(hw, clip);
1792            }
1793        }
1794    }
1795
1796    // disable scissor at the end of the frame
1797    engine.disableScissor();
1798}
1799
1800void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
1801    const int32_t height = hw->getHeight();
1802    RenderEngine& engine(getRenderEngine());
1803    engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
1804}
1805
1806void SurfaceFlinger::addClientLayer(const sp<Client>& client,
1807        const sp<IBinder>& handle,
1808        const sp<IGraphicBufferProducer>& gbc,
1809        const sp<Layer>& lbc)
1810{
1811    // attach this layer to the client
1812    client->attachLayer(handle, lbc);
1813
1814    // add this layer to the current state list
1815    Mutex::Autolock _l(mStateLock);
1816    mCurrentState.layersSortedByZ.add(lbc);
1817    mGraphicBufferProducerList.add(gbc->asBinder());
1818}
1819
1820status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
1821    Mutex::Autolock _l(mStateLock);
1822    ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
1823    if (index >= 0) {
1824        mLayersPendingRemoval.push(layer);
1825        mLayersRemoved = true;
1826        setTransactionFlags(eTransactionNeeded);
1827        return NO_ERROR;
1828    }
1829    return status_t(index);
1830}
1831
1832uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) {
1833    return android_atomic_release_load(&mTransactionFlags);
1834}
1835
1836uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
1837    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1838}
1839
1840uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
1841    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1842    if ((old & flags)==0) { // wake the server up
1843        signalTransaction();
1844    }
1845    return old;
1846}
1847
1848void SurfaceFlinger::setTransactionState(
1849        const Vector<ComposerState>& state,
1850        const Vector<DisplayState>& displays,
1851        uint32_t flags)
1852{
1853    ATRACE_CALL();
1854    Mutex::Autolock _l(mStateLock);
1855    uint32_t transactionFlags = 0;
1856
1857    if (flags & eAnimation) {
1858        // For window updates that are part of an animation we must wait for
1859        // previous animation "frames" to be handled.
1860        while (mAnimTransactionPending) {
1861            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1862            if (CC_UNLIKELY(err != NO_ERROR)) {
1863                // just in case something goes wrong in SF, return to the
1864                // caller after a few seconds.
1865                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
1866                        "waiting for previous animation frame");
1867                mAnimTransactionPending = false;
1868                break;
1869            }
1870        }
1871    }
1872
1873    size_t count = displays.size();
1874    for (size_t i=0 ; i<count ; i++) {
1875        const DisplayState& s(displays[i]);
1876        transactionFlags |= setDisplayStateLocked(s);
1877    }
1878
1879    count = state.size();
1880    for (size_t i=0 ; i<count ; i++) {
1881        const ComposerState& s(state[i]);
1882        // Here we need to check that the interface we're given is indeed
1883        // one of our own. A malicious client could give us a NULL
1884        // IInterface, or one of its own or even one of our own but a
1885        // different type. All these situations would cause us to crash.
1886        //
1887        // NOTE: it would be better to use RTTI as we could directly check
1888        // that we have a Client*. however, RTTI is disabled in Android.
1889        if (s.client != NULL) {
1890            sp<IBinder> binder = s.client->asBinder();
1891            if (binder != NULL) {
1892                String16 desc(binder->getInterfaceDescriptor());
1893                if (desc == ISurfaceComposerClient::descriptor) {
1894                    sp<Client> client( static_cast<Client *>(s.client.get()) );
1895                    transactionFlags |= setClientStateLocked(client, s.state);
1896                }
1897            }
1898        }
1899    }
1900
1901    if (transactionFlags) {
1902        // this triggers the transaction
1903        setTransactionFlags(transactionFlags);
1904
1905        // if this is a synchronous transaction, wait for it to take effect
1906        // before returning.
1907        if (flags & eSynchronous) {
1908            mTransactionPending = true;
1909        }
1910        if (flags & eAnimation) {
1911            mAnimTransactionPending = true;
1912        }
1913        while (mTransactionPending) {
1914            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1915            if (CC_UNLIKELY(err != NO_ERROR)) {
1916                // just in case something goes wrong in SF, return to the
1917                // called after a few seconds.
1918                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
1919                mTransactionPending = false;
1920                break;
1921            }
1922        }
1923    }
1924}
1925
1926uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1927{
1928    ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
1929    if (dpyIdx < 0)
1930        return 0;
1931
1932    uint32_t flags = 0;
1933    DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
1934    if (disp.isValid()) {
1935        const uint32_t what = s.what;
1936        if (what & DisplayState::eSurfaceChanged) {
1937            if (disp.surface->asBinder() != s.surface->asBinder()) {
1938                disp.surface = s.surface;
1939                flags |= eDisplayTransactionNeeded;
1940            }
1941        }
1942        if (what & DisplayState::eLayerStackChanged) {
1943            if (disp.layerStack != s.layerStack) {
1944                disp.layerStack = s.layerStack;
1945                flags |= eDisplayTransactionNeeded;
1946            }
1947        }
1948        if (what & DisplayState::eDisplayProjectionChanged) {
1949            if (disp.orientation != s.orientation) {
1950                disp.orientation = s.orientation;
1951                flags |= eDisplayTransactionNeeded;
1952            }
1953            if (disp.frame != s.frame) {
1954                disp.frame = s.frame;
1955                flags |= eDisplayTransactionNeeded;
1956            }
1957            if (disp.viewport != s.viewport) {
1958                disp.viewport = s.viewport;
1959                flags |= eDisplayTransactionNeeded;
1960            }
1961        }
1962    }
1963    return flags;
1964}
1965
1966uint32_t SurfaceFlinger::setClientStateLocked(
1967        const sp<Client>& client,
1968        const layer_state_t& s)
1969{
1970    uint32_t flags = 0;
1971    sp<Layer> layer(client->getLayerUser(s.surface));
1972    if (layer != 0) {
1973        const uint32_t what = s.what;
1974        if (what & layer_state_t::ePositionChanged) {
1975            if (layer->setPosition(s.x, s.y))
1976                flags |= eTraversalNeeded;
1977        }
1978        if (what & layer_state_t::eLayerChanged) {
1979            // NOTE: index needs to be calculated before we update the state
1980            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1981            if (layer->setLayer(s.z)) {
1982                mCurrentState.layersSortedByZ.removeAt(idx);
1983                mCurrentState.layersSortedByZ.add(layer);
1984                // we need traversal (state changed)
1985                // AND transaction (list changed)
1986                flags |= eTransactionNeeded|eTraversalNeeded;
1987            }
1988        }
1989        if (what & layer_state_t::eSizeChanged) {
1990            if (layer->setSize(s.w, s.h)) {
1991                flags |= eTraversalNeeded;
1992            }
1993        }
1994        if (what & layer_state_t::eAlphaChanged) {
1995            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1996                flags |= eTraversalNeeded;
1997        }
1998        if (what & layer_state_t::eMatrixChanged) {
1999            if (layer->setMatrix(s.matrix))
2000                flags |= eTraversalNeeded;
2001        }
2002        if (what & layer_state_t::eTransparentRegionChanged) {
2003            if (layer->setTransparentRegionHint(s.transparentRegion))
2004                flags |= eTraversalNeeded;
2005        }
2006        if (what & layer_state_t::eVisibilityChanged) {
2007            if (layer->setFlags(s.flags, s.mask))
2008                flags |= eTraversalNeeded;
2009        }
2010        if (what & layer_state_t::eCropChanged) {
2011            if (layer->setCrop(s.crop))
2012                flags |= eTraversalNeeded;
2013        }
2014        if (what & layer_state_t::eLayerStackChanged) {
2015            // NOTE: index needs to be calculated before we update the state
2016            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2017            if (layer->setLayerStack(s.layerStack)) {
2018                mCurrentState.layersSortedByZ.removeAt(idx);
2019                mCurrentState.layersSortedByZ.add(layer);
2020                // we need traversal (state changed)
2021                // AND transaction (list changed)
2022                flags |= eTransactionNeeded|eTraversalNeeded;
2023            }
2024        }
2025    }
2026    return flags;
2027}
2028
2029status_t SurfaceFlinger::createLayer(
2030        const String8& name,
2031        const sp<Client>& client,
2032        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2033        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2034{
2035    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2036    if (int32_t(w|h) < 0) {
2037        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2038                int(w), int(h));
2039        return BAD_VALUE;
2040    }
2041
2042    status_t result = NO_ERROR;
2043
2044    sp<Layer> layer;
2045
2046    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2047        case ISurfaceComposerClient::eFXSurfaceNormal:
2048            result = createNormalLayer(client,
2049                    name, w, h, flags, format,
2050                    handle, gbp, &layer);
2051            break;
2052        case ISurfaceComposerClient::eFXSurfaceDim:
2053            result = createDimLayer(client,
2054                    name, w, h, flags,
2055                    handle, gbp, &layer);
2056            break;
2057        default:
2058            result = BAD_VALUE;
2059            break;
2060    }
2061
2062    if (result == NO_ERROR) {
2063        addClientLayer(client, *handle, *gbp, layer);
2064        setTransactionFlags(eTransactionNeeded);
2065    }
2066    return result;
2067}
2068
2069status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2070        const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2071        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2072{
2073    // initialize the surfaces
2074    switch (format) {
2075    case PIXEL_FORMAT_TRANSPARENT:
2076    case PIXEL_FORMAT_TRANSLUCENT:
2077        format = PIXEL_FORMAT_RGBA_8888;
2078        break;
2079    case PIXEL_FORMAT_OPAQUE:
2080#ifdef NO_RGBX_8888
2081        format = PIXEL_FORMAT_RGB_565;
2082#else
2083        format = PIXEL_FORMAT_RGBX_8888;
2084#endif
2085        break;
2086    }
2087
2088#ifdef NO_RGBX_8888
2089    if (format == PIXEL_FORMAT_RGBX_8888)
2090        format = PIXEL_FORMAT_RGBA_8888;
2091#endif
2092
2093    *outLayer = new Layer(this, client, name, w, h, flags);
2094    status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2095    if (err == NO_ERROR) {
2096        *handle = (*outLayer)->getHandle();
2097        *gbp = (*outLayer)->getBufferQueue();
2098    }
2099
2100    ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2101    return err;
2102}
2103
2104status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2105        const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2106        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2107{
2108    *outLayer = new LayerDim(this, client, name, w, h, flags);
2109    *handle = (*outLayer)->getHandle();
2110    *gbp = (*outLayer)->getBufferQueue();
2111    return NO_ERROR;
2112}
2113
2114status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2115{
2116    // called by the window manager when it wants to remove a Layer
2117    status_t err = NO_ERROR;
2118    sp<Layer> l(client->getLayerUser(handle));
2119    if (l != NULL) {
2120        err = removeLayer(l);
2121        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2122                "error removing layer=%p (%s)", l.get(), strerror(-err));
2123    }
2124    return err;
2125}
2126
2127status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2128{
2129    // called by ~LayerCleaner() when all references to the IBinder (handle)
2130    // are gone
2131    status_t err = NO_ERROR;
2132    sp<Layer> l(layer.promote());
2133    if (l != NULL) {
2134        err = removeLayer(l);
2135        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2136                "error removing layer=%p (%s)", l.get(), strerror(-err));
2137    }
2138    return err;
2139}
2140
2141// ---------------------------------------------------------------------------
2142
2143void SurfaceFlinger::onInitializeDisplays() {
2144    // reset screen orientation and use primary layer stack
2145    Vector<ComposerState> state;
2146    Vector<DisplayState> displays;
2147    DisplayState d;
2148    d.what = DisplayState::eDisplayProjectionChanged |
2149             DisplayState::eLayerStackChanged;
2150    d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2151    d.layerStack = 0;
2152    d.orientation = DisplayState::eOrientationDefault;
2153    d.frame.makeInvalid();
2154    d.viewport.makeInvalid();
2155    displays.add(d);
2156    setTransactionState(state, displays, 0);
2157    onScreenAcquired(getDefaultDisplayDevice());
2158
2159    const nsecs_t period =
2160            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2161    mAnimFrameTracker.setDisplayRefreshPeriod(period);
2162}
2163
2164void SurfaceFlinger::initializeDisplays() {
2165    class MessageScreenInitialized : public MessageBase {
2166        SurfaceFlinger* flinger;
2167    public:
2168        MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2169        virtual bool handler() {
2170            flinger->onInitializeDisplays();
2171            return true;
2172        }
2173    };
2174    sp<MessageBase> msg = new MessageScreenInitialized(this);
2175    postMessageAsync(msg);  // we may be called from main thread, use async message
2176}
2177
2178
2179void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) {
2180    ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this);
2181    if (hw->isScreenAcquired()) {
2182        // this is expected, e.g. when power manager wakes up during boot
2183        ALOGD(" screen was previously acquired");
2184        return;
2185    }
2186
2187    hw->acquireScreen();
2188    int32_t type = hw->getDisplayType();
2189    if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2190        // built-in display, tell the HWC
2191        getHwComposer().acquire(type);
2192
2193        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2194            // FIXME: eventthread only knows about the main display right now
2195            mEventThread->onScreenAcquired();
2196
2197            resyncToHardwareVsync(true);
2198        }
2199    }
2200    mVisibleRegionsDirty = true;
2201    repaintEverything();
2202}
2203
2204void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) {
2205    ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this);
2206    if (!hw->isScreenAcquired()) {
2207        ALOGD(" screen was previously released");
2208        return;
2209    }
2210
2211    hw->releaseScreen();
2212    int32_t type = hw->getDisplayType();
2213    if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2214        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2215            disableHardwareVsync(true); // also cancels any in-progress resync
2216
2217            // FIXME: eventthread only knows about the main display right now
2218            mEventThread->onScreenReleased();
2219        }
2220
2221        // built-in display, tell the HWC
2222        getHwComposer().release(type);
2223    }
2224    mVisibleRegionsDirty = true;
2225    // from this point on, SF will stop drawing on this display
2226}
2227
2228void SurfaceFlinger::unblank(const sp<IBinder>& display) {
2229    class MessageScreenAcquired : public MessageBase {
2230        SurfaceFlinger& mFlinger;
2231        sp<IBinder> mDisplay;
2232    public:
2233        MessageScreenAcquired(SurfaceFlinger& flinger,
2234                const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2235        virtual bool handler() {
2236            const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2237            if (hw == NULL) {
2238                ALOGE("Attempt to unblank null display %p", mDisplay.get());
2239            } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2240                ALOGW("Attempt to unblank virtual display");
2241            } else {
2242                mFlinger.onScreenAcquired(hw);
2243            }
2244            return true;
2245        }
2246    };
2247    sp<MessageBase> msg = new MessageScreenAcquired(*this, display);
2248    postMessageSync(msg);
2249}
2250
2251void SurfaceFlinger::blank(const sp<IBinder>& display) {
2252    class MessageScreenReleased : public MessageBase {
2253        SurfaceFlinger& mFlinger;
2254        sp<IBinder> mDisplay;
2255    public:
2256        MessageScreenReleased(SurfaceFlinger& flinger,
2257                const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2258        virtual bool handler() {
2259            const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2260            if (hw == NULL) {
2261                ALOGE("Attempt to blank null display %p", mDisplay.get());
2262            } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2263                ALOGW("Attempt to blank virtual display");
2264            } else {
2265                mFlinger.onScreenReleased(hw);
2266            }
2267            return true;
2268        }
2269    };
2270    sp<MessageBase> msg = new MessageScreenReleased(*this, display);
2271    postMessageSync(msg);
2272}
2273
2274// ---------------------------------------------------------------------------
2275
2276status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2277{
2278    String8 result;
2279
2280    IPCThreadState* ipc = IPCThreadState::self();
2281    const int pid = ipc->getCallingPid();
2282    const int uid = ipc->getCallingUid();
2283    if ((uid != AID_SHELL) &&
2284            !PermissionCache::checkPermission(sDump, pid, uid)) {
2285        result.appendFormat("Permission Denial: "
2286                "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2287    } else {
2288        // Try to get the main lock, but don't insist if we can't
2289        // (this would indicate SF is stuck, but we want to be able to
2290        // print something in dumpsys).
2291        int retry = 3;
2292        while (mStateLock.tryLock()<0 && --retry>=0) {
2293            usleep(1000000);
2294        }
2295        const bool locked(retry >= 0);
2296        if (!locked) {
2297            result.append(
2298                    "SurfaceFlinger appears to be unresponsive, "
2299                    "dumping anyways (no locks held)\n");
2300        }
2301
2302        bool dumpAll = true;
2303        size_t index = 0;
2304        size_t numArgs = args.size();
2305        if (numArgs) {
2306            if ((index < numArgs) &&
2307                    (args[index] == String16("--list"))) {
2308                index++;
2309                listLayersLocked(args, index, result);
2310                dumpAll = false;
2311            }
2312
2313            if ((index < numArgs) &&
2314                    (args[index] == String16("--latency"))) {
2315                index++;
2316                dumpStatsLocked(args, index, result);
2317                dumpAll = false;
2318            }
2319
2320            if ((index < numArgs) &&
2321                    (args[index] == String16("--latency-clear"))) {
2322                index++;
2323                clearStatsLocked(args, index, result);
2324                dumpAll = false;
2325            }
2326        }
2327
2328        if (dumpAll) {
2329            dumpAllLocked(args, index, result);
2330        }
2331
2332        if (locked) {
2333            mStateLock.unlock();
2334        }
2335    }
2336    write(fd, result.string(), result.size());
2337    return NO_ERROR;
2338}
2339
2340void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
2341        String8& result) const
2342{
2343    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2344    const size_t count = currentLayers.size();
2345    for (size_t i=0 ; i<count ; i++) {
2346        const sp<Layer>& layer(currentLayers[i]);
2347        result.appendFormat("%s\n", layer->getName().string());
2348    }
2349}
2350
2351void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2352        String8& result) const
2353{
2354    String8 name;
2355    if (index < args.size()) {
2356        name = String8(args[index]);
2357        index++;
2358    }
2359
2360    const nsecs_t period =
2361            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2362    result.appendFormat("%lld\n", period);
2363
2364    if (name.isEmpty()) {
2365        mAnimFrameTracker.dump(result);
2366    } else {
2367        const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2368        const size_t count = currentLayers.size();
2369        for (size_t i=0 ; i<count ; i++) {
2370            const sp<Layer>& layer(currentLayers[i]);
2371            if (name == layer->getName()) {
2372                layer->dumpStats(result);
2373            }
2374        }
2375    }
2376}
2377
2378void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2379        String8& result)
2380{
2381    String8 name;
2382    if (index < args.size()) {
2383        name = String8(args[index]);
2384        index++;
2385    }
2386
2387    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2388    const size_t count = currentLayers.size();
2389    for (size_t i=0 ; i<count ; i++) {
2390        const sp<Layer>& layer(currentLayers[i]);
2391        if (name.isEmpty() || (name == layer->getName())) {
2392            layer->clearStats();
2393        }
2394    }
2395
2396    mAnimFrameTracker.clear();
2397}
2398
2399// This should only be called from the main thread.  Otherwise it would need
2400// the lock and should use mCurrentState rather than mDrawingState.
2401void SurfaceFlinger::logFrameStats() {
2402    const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2403    const size_t count = drawingLayers.size();
2404    for (size_t i=0 ; i<count ; i++) {
2405        const sp<Layer>& layer(drawingLayers[i]);
2406        layer->logFrameStats();
2407    }
2408
2409    mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2410}
2411
2412/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2413{
2414    static const char* config =
2415            " [sf"
2416#ifdef NO_RGBX_8888
2417            " NO_RGBX_8888"
2418#endif
2419#ifdef HAS_CONTEXT_PRIORITY
2420            " HAS_CONTEXT_PRIORITY"
2421#endif
2422#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2423            " NEVER_DEFAULT_TO_ASYNC_MODE"
2424#endif
2425#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2426            " TARGET_DISABLE_TRIPLE_BUFFERING"
2427#endif
2428            "]";
2429    result.append(config);
2430}
2431
2432void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2433        String8& result) const
2434{
2435    bool colorize = false;
2436    if (index < args.size()
2437            && (args[index] == String16("--color"))) {
2438        colorize = true;
2439        index++;
2440    }
2441
2442    Colorizer colorizer(colorize);
2443
2444    // figure out if we're stuck somewhere
2445    const nsecs_t now = systemTime();
2446    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2447    const nsecs_t inTransaction(mDebugInTransaction);
2448    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2449    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2450
2451    /*
2452     * Dump library configuration.
2453     */
2454
2455    colorizer.bold(result);
2456    result.append("Build configuration:");
2457    colorizer.reset(result);
2458    appendSfConfigString(result);
2459    appendUiConfigString(result);
2460    appendGuiConfigString(result);
2461    result.append("\n");
2462
2463    colorizer.bold(result);
2464    result.append("Sync configuration: ");
2465    colorizer.reset(result);
2466    result.append(SyncFeatures::getInstance().toString());
2467    result.append("\n");
2468
2469    /*
2470     * Dump the visible layer list
2471     */
2472    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2473    const size_t count = currentLayers.size();
2474    colorizer.bold(result);
2475    result.appendFormat("Visible layers (count = %d)\n", count);
2476    colorizer.reset(result);
2477    for (size_t i=0 ; i<count ; i++) {
2478        const sp<Layer>& layer(currentLayers[i]);
2479        layer->dump(result, colorizer);
2480    }
2481
2482    /*
2483     * Dump Display state
2484     */
2485
2486    colorizer.bold(result);
2487    result.appendFormat("Displays (%d entries)\n", mDisplays.size());
2488    colorizer.reset(result);
2489    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2490        const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2491        hw->dump(result);
2492    }
2493
2494    /*
2495     * Dump SurfaceFlinger global state
2496     */
2497
2498    colorizer.bold(result);
2499    result.append("SurfaceFlinger global state:\n");
2500    colorizer.reset(result);
2501
2502    HWComposer& hwc(getHwComposer());
2503    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2504
2505    colorizer.bold(result);
2506    result.appendFormat("EGL implementation : %s\n",
2507            eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2508    colorizer.reset(result);
2509    result.appendFormat("%s\n",
2510            eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2511
2512    mRenderEngine->dump(result);
2513
2514    hw->undefinedRegion.dump(result, "undefinedRegion");
2515    result.appendFormat("  orientation=%d, canDraw=%d\n",
2516            hw->getOrientation(), hw->canDraw());
2517    result.appendFormat(
2518            "  last eglSwapBuffers() time: %f us\n"
2519            "  last transaction time     : %f us\n"
2520            "  transaction-flags         : %08x\n"
2521            "  refresh-rate              : %f fps\n"
2522            "  x-dpi                     : %f\n"
2523            "  y-dpi                     : %f\n"
2524            "  EGL_NATIVE_VISUAL_ID      : %d\n"
2525            "  gpu_to_cpu_unsupported    : %d\n"
2526            ,
2527            mLastSwapBufferTime/1000.0,
2528            mLastTransactionTime/1000.0,
2529            mTransactionFlags,
2530            1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2531            hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2532            hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2533            mEGLNativeVisualId,
2534            !mGpuToCpuSupported);
2535
2536    result.appendFormat("  eglSwapBuffers time: %f us\n",
2537            inSwapBuffersDuration/1000.0);
2538
2539    result.appendFormat("  transaction time: %f us\n",
2540            inTransactionDuration/1000.0);
2541
2542    /*
2543     * VSYNC state
2544     */
2545    mEventThread->dump(result);
2546
2547    /*
2548     * Dump HWComposer state
2549     */
2550    colorizer.bold(result);
2551    result.append("h/w composer state:\n");
2552    colorizer.reset(result);
2553    result.appendFormat("  h/w composer %s and %s\n",
2554            hwc.initCheck()==NO_ERROR ? "present" : "not present",
2555                    (mDebugDisableHWC || mDebugRegion || mDaltonize
2556                            || mHasColorMatrix) ? "disabled" : "enabled");
2557    hwc.dump(result);
2558
2559    /*
2560     * Dump gralloc state
2561     */
2562    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2563    alloc.dump(result);
2564}
2565
2566const Vector< sp<Layer> >&
2567SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2568    // Note: mStateLock is held here
2569    wp<IBinder> dpy;
2570    for (size_t i=0 ; i<mDisplays.size() ; i++) {
2571        if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2572            dpy = mDisplays.keyAt(i);
2573            break;
2574        }
2575    }
2576    if (dpy == NULL) {
2577        ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2578        // Just use the primary display so we have something to return
2579        dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2580    }
2581    return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2582}
2583
2584bool SurfaceFlinger::startDdmConnection()
2585{
2586    void* libddmconnection_dso =
2587            dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2588    if (!libddmconnection_dso) {
2589        return false;
2590    }
2591    void (*DdmConnection_start)(const char* name);
2592    DdmConnection_start =
2593            (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2594    if (!DdmConnection_start) {
2595        dlclose(libddmconnection_dso);
2596        return false;
2597    }
2598    (*DdmConnection_start)(getServiceName());
2599    return true;
2600}
2601
2602status_t SurfaceFlinger::onTransact(
2603    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2604{
2605    switch (code) {
2606        case CREATE_CONNECTION:
2607        case CREATE_DISPLAY:
2608        case SET_TRANSACTION_STATE:
2609        case BOOT_FINISHED:
2610        case BLANK:
2611        case UNBLANK:
2612        {
2613            // codes that require permission check
2614            IPCThreadState* ipc = IPCThreadState::self();
2615            const int pid = ipc->getCallingPid();
2616            const int uid = ipc->getCallingUid();
2617            if ((uid != AID_GRAPHICS) &&
2618                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2619                ALOGE("Permission Denial: "
2620                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2621                return PERMISSION_DENIED;
2622            }
2623            break;
2624        }
2625        case CAPTURE_SCREEN:
2626        {
2627            // codes that require permission check
2628            IPCThreadState* ipc = IPCThreadState::self();
2629            const int pid = ipc->getCallingPid();
2630            const int uid = ipc->getCallingUid();
2631            if ((uid != AID_GRAPHICS) &&
2632                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2633                ALOGE("Permission Denial: "
2634                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
2635                return PERMISSION_DENIED;
2636            }
2637            break;
2638        }
2639    }
2640
2641    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2642    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2643        CHECK_INTERFACE(ISurfaceComposer, data, reply);
2644        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2645            IPCThreadState* ipc = IPCThreadState::self();
2646            const int pid = ipc->getCallingPid();
2647            const int uid = ipc->getCallingUid();
2648            ALOGE("Permission Denial: "
2649                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2650            return PERMISSION_DENIED;
2651        }
2652        int n;
2653        switch (code) {
2654            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2655            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2656                return NO_ERROR;
2657            case 1002:  // SHOW_UPDATES
2658                n = data.readInt32();
2659                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2660                invalidateHwcGeometry();
2661                repaintEverything();
2662                return NO_ERROR;
2663            case 1004:{ // repaint everything
2664                repaintEverything();
2665                return NO_ERROR;
2666            }
2667            case 1005:{ // force transaction
2668                setTransactionFlags(
2669                        eTransactionNeeded|
2670                        eDisplayTransactionNeeded|
2671                        eTraversalNeeded);
2672                return NO_ERROR;
2673            }
2674            case 1006:{ // send empty update
2675                signalRefresh();
2676                return NO_ERROR;
2677            }
2678            case 1008:  // toggle use of hw composer
2679                n = data.readInt32();
2680                mDebugDisableHWC = n ? 1 : 0;
2681                invalidateHwcGeometry();
2682                repaintEverything();
2683                return NO_ERROR;
2684            case 1009:  // toggle use of transform hint
2685                n = data.readInt32();
2686                mDebugDisableTransformHint = n ? 1 : 0;
2687                invalidateHwcGeometry();
2688                repaintEverything();
2689                return NO_ERROR;
2690            case 1010:  // interrogate.
2691                reply->writeInt32(0);
2692                reply->writeInt32(0);
2693                reply->writeInt32(mDebugRegion);
2694                reply->writeInt32(0);
2695                reply->writeInt32(mDebugDisableHWC);
2696                return NO_ERROR;
2697            case 1013: {
2698                Mutex::Autolock _l(mStateLock);
2699                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2700                reply->writeInt32(hw->getPageFlipCount());
2701                return NO_ERROR;
2702            }
2703            case 1014: {
2704                // daltonize
2705                n = data.readInt32();
2706                switch (n % 10) {
2707                    case 1: mDaltonizer.setType(Daltonizer::protanomaly);   break;
2708                    case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2709                    case 3: mDaltonizer.setType(Daltonizer::tritanomaly);   break;
2710                }
2711                if (n >= 10) {
2712                    mDaltonizer.setMode(Daltonizer::correction);
2713                } else {
2714                    mDaltonizer.setMode(Daltonizer::simulation);
2715                }
2716                mDaltonize = n > 0;
2717                invalidateHwcGeometry();
2718                repaintEverything();
2719                return NO_ERROR;
2720            }
2721            case 1015: {
2722                // apply a color matrix
2723                n = data.readInt32();
2724                mHasColorMatrix = n ? 1 : 0;
2725                if (n) {
2726                    // color matrix is sent as mat3 matrix followed by vec3
2727                    // offset, then packed into a mat4 where the last row is
2728                    // the offset and extra values are 0
2729                    for (size_t i = 0 ; i < 4; i++) {
2730                      for (size_t j = 0; j < 4; j++) {
2731                          mColorMatrix[i][j] = data.readFloat();
2732                      }
2733                    }
2734                } else {
2735                    mColorMatrix = mat4();
2736                }
2737                invalidateHwcGeometry();
2738                repaintEverything();
2739                return NO_ERROR;
2740            }
2741        }
2742    }
2743    return err;
2744}
2745
2746void SurfaceFlinger::repaintEverything() {
2747    android_atomic_or(1, &mRepaintEverything);
2748    signalTransaction();
2749}
2750
2751// ---------------------------------------------------------------------------
2752// Capture screen into an IGraphiBufferProducer
2753// ---------------------------------------------------------------------------
2754
2755/* The code below is here to handle b/8734824
2756 *
2757 * We create a IGraphicBufferProducer wrapper that forwards all calls
2758 * to the calling binder thread, where they are executed. This allows
2759 * the calling thread to be reused (on the other side) and not
2760 * depend on having "enough" binder threads to handle the requests.
2761 *
2762 */
2763
2764class GraphicProducerWrapper : public BBinder, public MessageHandler {
2765    sp<IGraphicBufferProducer> impl;
2766    sp<Looper> looper;
2767    status_t result;
2768    bool exitPending;
2769    bool exitRequested;
2770    mutable Barrier barrier;
2771    volatile int32_t memoryBarrier;
2772    uint32_t code;
2773    Parcel const* data;
2774    Parcel* reply;
2775
2776    enum {
2777        MSG_API_CALL,
2778        MSG_EXIT
2779    };
2780
2781    /*
2782     * this is called by our "fake" BpGraphicBufferProducer. We package the
2783     * data and reply Parcel and forward them to the calling thread.
2784     */
2785    virtual status_t transact(uint32_t code,
2786            const Parcel& data, Parcel* reply, uint32_t flags) {
2787        this->code = code;
2788        this->data = &data;
2789        this->reply = reply;
2790        android_atomic_acquire_store(0, &memoryBarrier);
2791        if (exitPending) {
2792            // if we've exited, we run the message synchronously right here
2793            handleMessage(Message(MSG_API_CALL));
2794        } else {
2795            barrier.close();
2796            looper->sendMessage(this, Message(MSG_API_CALL));
2797            barrier.wait();
2798        }
2799        return NO_ERROR;
2800    }
2801
2802    /*
2803     * here we run on the binder calling thread. All we've got to do is
2804     * call the real BpGraphicBufferProducer.
2805     */
2806    virtual void handleMessage(const Message& message) {
2807        android_atomic_release_load(&memoryBarrier);
2808        if (message.what == MSG_API_CALL) {
2809            impl->asBinder()->transact(code, data[0], reply);
2810            barrier.open();
2811        } else if (message.what == MSG_EXIT) {
2812            exitRequested = true;
2813        }
2814    }
2815
2816public:
2817    GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl) :
2818        impl(impl), looper(new Looper(true)), result(NO_ERROR),
2819        exitPending(false), exitRequested(false) {
2820    }
2821
2822    status_t waitForResponse() {
2823        do {
2824            looper->pollOnce(-1);
2825        } while (!exitRequested);
2826        return result;
2827    }
2828
2829    void exit(status_t result) {
2830        this->result = result;
2831        exitPending = true;
2832        looper->sendMessage(this, Message(MSG_EXIT));
2833    }
2834};
2835
2836
2837status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2838        const sp<IGraphicBufferProducer>& producer,
2839        uint32_t reqWidth, uint32_t reqHeight,
2840        uint32_t minLayerZ, uint32_t maxLayerZ) {
2841
2842    if (CC_UNLIKELY(display == 0))
2843        return BAD_VALUE;
2844
2845    if (CC_UNLIKELY(producer == 0))
2846        return BAD_VALUE;
2847
2848    // if we have secure windows on this display, never allow the screen capture
2849    // unless the producer interface is local (i.e.: we can take a screenshot for
2850    // ourselves).
2851    if (!producer->asBinder()->localBinder()) {
2852        Mutex::Autolock _l(mStateLock);
2853        sp<const DisplayDevice> hw(getDisplayDevice(display));
2854        if (hw->getSecureLayerVisible()) {
2855            ALOGW("FB is protected: PERMISSION_DENIED");
2856            return PERMISSION_DENIED;
2857        }
2858    }
2859
2860    class MessageCaptureScreen : public MessageBase {
2861        SurfaceFlinger* flinger;
2862        sp<IBinder> display;
2863        sp<IGraphicBufferProducer> producer;
2864        uint32_t reqWidth, reqHeight;
2865        uint32_t minLayerZ,maxLayerZ;
2866        status_t result;
2867    public:
2868        MessageCaptureScreen(SurfaceFlinger* flinger,
2869                const sp<IBinder>& display,
2870                const sp<IGraphicBufferProducer>& producer,
2871                uint32_t reqWidth, uint32_t reqHeight,
2872                uint32_t minLayerZ, uint32_t maxLayerZ)
2873            : flinger(flinger), display(display), producer(producer),
2874              reqWidth(reqWidth), reqHeight(reqHeight),
2875              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2876              result(PERMISSION_DENIED)
2877        {
2878        }
2879        status_t getResult() const {
2880            return result;
2881        }
2882        virtual bool handler() {
2883            Mutex::Autolock _l(flinger->mStateLock);
2884            sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
2885            result = flinger->captureScreenImplLocked(hw,
2886                    producer, reqWidth, reqHeight, minLayerZ, maxLayerZ);
2887            static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result);
2888            return true;
2889        }
2890    };
2891
2892    // make sure to process transactions before screenshots -- a transaction
2893    // might already be pending but scheduled for VSYNC; this guarantees we
2894    // will handle it before the screenshot. When VSYNC finally arrives
2895    // the scheduled transaction will be a no-op. If no transactions are
2896    // scheduled at this time, this will end-up being a no-op as well.
2897    mEventQueue.invalidateTransactionNow();
2898
2899    // this creates a "fake" BBinder which will serve as a "fake" remote
2900    // binder to receive the marshaled calls and forward them to the
2901    // real remote (a BpGraphicBufferProducer)
2902    sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
2903
2904    // the asInterface() call below creates our "fake" BpGraphicBufferProducer
2905    // which does the marshaling work forwards to our "fake remote" above.
2906    sp<MessageBase> msg = new MessageCaptureScreen(this,
2907            display, IGraphicBufferProducer::asInterface( wrapper ),
2908            reqWidth, reqHeight, minLayerZ, maxLayerZ);
2909
2910    status_t res = postMessageAsync(msg);
2911    if (res == NO_ERROR) {
2912        res = wrapper->waitForResponse();
2913    }
2914    return res;
2915}
2916
2917
2918void SurfaceFlinger::renderScreenImplLocked(
2919        const sp<const DisplayDevice>& hw,
2920        uint32_t reqWidth, uint32_t reqHeight,
2921        uint32_t minLayerZ, uint32_t maxLayerZ,
2922        bool yswap)
2923{
2924    ATRACE_CALL();
2925    RenderEngine& engine(getRenderEngine());
2926
2927    // get screen geometry
2928    const uint32_t hw_w = hw->getWidth();
2929    const uint32_t hw_h = hw->getHeight();
2930    const bool filtering = reqWidth != hw_w || reqWidth != hw_h;
2931
2932    // make sure to clear all GL error flags
2933    engine.checkErrors();
2934
2935    // set-up our viewport
2936    engine.setViewportAndProjection(reqWidth, reqHeight, hw_w, hw_h, yswap);
2937    engine.disableTexturing();
2938
2939    // redraw the screen entirely...
2940    engine.clearWithColor(0, 0, 0, 1);
2941
2942    const LayerVector& layers( mDrawingState.layersSortedByZ );
2943    const size_t count = layers.size();
2944    for (size_t i=0 ; i<count ; ++i) {
2945        const sp<Layer>& layer(layers[i]);
2946        const Layer::State& state(layer->getDrawingState());
2947        if (state.layerStack == hw->getLayerStack()) {
2948            if (state.z >= minLayerZ && state.z <= maxLayerZ) {
2949                if (layer->isVisible()) {
2950                    if (filtering) layer->setFiltering(true);
2951                    layer->draw(hw);
2952                    if (filtering) layer->setFiltering(false);
2953                }
2954            }
2955        }
2956    }
2957
2958    // compositionComplete is needed for older driver
2959    hw->compositionComplete();
2960    hw->setViewportAndProjection();
2961}
2962
2963
2964status_t SurfaceFlinger::captureScreenImplLocked(
2965        const sp<const DisplayDevice>& hw,
2966        const sp<IGraphicBufferProducer>& producer,
2967        uint32_t reqWidth, uint32_t reqHeight,
2968        uint32_t minLayerZ, uint32_t maxLayerZ)
2969{
2970    ATRACE_CALL();
2971
2972    // get screen geometry
2973    const uint32_t hw_w = hw->getWidth();
2974    const uint32_t hw_h = hw->getHeight();
2975
2976    if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
2977        ALOGE("size mismatch (%d, %d) > (%d, %d)",
2978                reqWidth, reqHeight, hw_w, hw_h);
2979        return BAD_VALUE;
2980    }
2981
2982    reqWidth  = (!reqWidth)  ? hw_w : reqWidth;
2983    reqHeight = (!reqHeight) ? hw_h : reqHeight;
2984
2985    // create a surface (because we're a producer, and we need to
2986    // dequeue/queue a buffer)
2987    sp<Surface> sur = new Surface(producer, false);
2988    ANativeWindow* window = sur.get();
2989
2990    status_t result = NO_ERROR;
2991    if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) {
2992        uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
2993                        GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
2994
2995        int err = 0;
2996        err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
2997        err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
2998        err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
2999        err |= native_window_set_usage(window, usage);
3000
3001        if (err == NO_ERROR) {
3002            ANativeWindowBuffer* buffer;
3003            /* TODO: Once we have the sync framework everywhere this can use
3004             * server-side waits on the fence that dequeueBuffer returns.
3005             */
3006            result = native_window_dequeue_buffer_and_wait(window,  &buffer);
3007            if (result == NO_ERROR) {
3008                // create an EGLImage from the buffer so we can later
3009                // turn it into a texture
3010                EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3011                        EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3012                if (image != EGL_NO_IMAGE_KHR) {
3013                    // this binds the given EGLImage as a framebuffer for the
3014                    // duration of this scope.
3015                    RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3016                    if (imageBond.getStatus() == NO_ERROR) {
3017                        // this will in fact render into our dequeued buffer
3018                        // via an FBO, which means we didn't have to create
3019                        // an EGLSurface and therefore we're not
3020                        // dependent on the context's EGLConfig.
3021                        renderScreenImplLocked(hw, reqWidth, reqHeight,
3022                                minLayerZ, maxLayerZ, true);
3023
3024                        // Create a sync point and wait on it, so we know the buffer is
3025                        // ready before we pass it along.  We can't trivially call glFlush(),
3026                        // so we use a wait flag instead.
3027                        // TODO: pass a sync fd to queueBuffer() and let the consumer wait.
3028                        EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3029                        if (sync != EGL_NO_SYNC_KHR) {
3030                            EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3031                                    EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3032                            EGLint eglErr = eglGetError();
3033                            eglDestroySyncKHR(mEGLDisplay, sync);
3034                            if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3035                                ALOGW("captureScreen: fence wait timed out");
3036                            } else {
3037                                ALOGW_IF(eglErr != EGL_SUCCESS,
3038                                        "captureScreen: error waiting on EGL fence: %#x", eglErr);
3039                            }
3040                        } else {
3041                            ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3042                            // not fatal
3043                        }
3044
3045                        if (DEBUG_SCREENSHOTS) {
3046                            uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3047                            getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3048                            checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3049                                    hw, minLayerZ, maxLayerZ);
3050                            delete [] pixels;
3051                        }
3052
3053                    } else {
3054                        ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3055                        result = INVALID_OPERATION;
3056                    }
3057                    // destroy our image
3058                    eglDestroyImageKHR(mEGLDisplay, image);
3059                } else {
3060                    result = BAD_VALUE;
3061                }
3062                window->queueBuffer(window, buffer, -1);
3063            }
3064        } else {
3065            result = BAD_VALUE;
3066        }
3067        native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3068    }
3069
3070    return result;
3071}
3072
3073void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3074        const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3075    if (DEBUG_SCREENSHOTS) {
3076        for (size_t y=0 ; y<h ; y++) {
3077            uint32_t const * p = (uint32_t const *)vaddr + y*s;
3078            for (size_t x=0 ; x<w ; x++) {
3079                if (p[x] != 0xFF000000) return;
3080            }
3081        }
3082        ALOGE("*** we just took a black screenshot ***\n"
3083                "requested minz=%d, maxz=%d, layerStack=%d",
3084                minLayerZ, maxLayerZ, hw->getLayerStack());
3085        const LayerVector& layers( mDrawingState.layersSortedByZ );
3086        const size_t count = layers.size();
3087        for (size_t i=0 ; i<count ; ++i) {
3088            const sp<Layer>& layer(layers[i]);
3089            const Layer::State& state(layer->getDrawingState());
3090            const bool visible = (state.layerStack == hw->getLayerStack())
3091                                && (state.z >= minLayerZ && state.z <= maxLayerZ)
3092                                && (layer->isVisible());
3093            ALOGE("%c index=%d, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3094                    visible ? '+' : '-',
3095                            i, layer->getName().string(), state.layerStack, state.z,
3096                            layer->isVisible(), state.flags, state.alpha);
3097        }
3098    }
3099}
3100
3101// ---------------------------------------------------------------------------
3102
3103SurfaceFlinger::LayerVector::LayerVector() {
3104}
3105
3106SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3107    : SortedVector<sp<Layer> >(rhs) {
3108}
3109
3110int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3111    const void* rhs) const
3112{
3113    // sort layers per layer-stack, then by z-order and finally by sequence
3114    const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3115    const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3116
3117    uint32_t ls = l->getCurrentState().layerStack;
3118    uint32_t rs = r->getCurrentState().layerStack;
3119    if (ls != rs)
3120        return ls - rs;
3121
3122    uint32_t lz = l->getCurrentState().z;
3123    uint32_t rz = r->getCurrentState().z;
3124    if (lz != rz)
3125        return lz - rz;
3126
3127    return l->sequence - r->sequence;
3128}
3129
3130// ---------------------------------------------------------------------------
3131
3132SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3133    : type(DisplayDevice::DISPLAY_ID_INVALID) {
3134}
3135
3136SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
3137    : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0) {
3138    viewport.makeInvalid();
3139    frame.makeInvalid();
3140}
3141
3142// ---------------------------------------------------------------------------
3143
3144}; // namespace android
3145
3146
3147#if defined(__gl_h_)
3148#error "don't include gl/gl.h in this file"
3149#endif
3150
3151#if defined(__gl2_h_)
3152#error "don't include gl2/gl2.h in this file"
3153#endif
3154