Layer.cpp revision 503d2bd9a0c64f90fc321f9d65fc65e592f1fa2b
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 LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "Layer"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22#include <math.h>
23#include <stdint.h>
24#include <stdlib.h>
25#include <sys/types.h>
26
27#include <cutils/compiler.h>
28#include <cutils/native_handle.h>
29#include <cutils/properties.h>
30
31#include <utils/Errors.h>
32#include <utils/Log.h>
33#include <utils/NativeHandle.h>
34#include <utils/StopWatch.h>
35#include <utils/Trace.h>
36
37#include <ui/DebugUtils.h>
38#include <ui/GraphicBuffer.h>
39#include <ui/PixelFormat.h>
40
41#include <gui/BufferItem.h>
42#include <gui/BufferQueue.h>
43#include <gui/LayerDebugInfo.h>
44#include <gui/Surface.h>
45
46#include "Colorizer.h"
47#include "DisplayDevice.h"
48#include "Layer.h"
49#include "LayerRejecter.h"
50#include "MonitoredProducer.h"
51#include "SurfaceFlinger.h"
52#include "clz.h"
53
54#include "DisplayHardware/HWComposer.h"
55
56#include "RenderEngine/RenderEngine.h"
57
58#include <mutex>
59#include "LayerProtoHelper.h"
60
61#define DEBUG_RESIZE 0
62
63namespace android {
64
65LayerBE::LayerBE()
66      : mBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
67        mBuffer(nullptr),
68        mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2) {
69}
70
71
72int32_t Layer::sSequence = 1;
73
74Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client, const String8& name, uint32_t w,
75             uint32_t h, uint32_t flags)
76      : contentDirty(false),
77        sequence(uint32_t(android_atomic_inc(&sSequence))),
78        mFlinger(flinger),
79        mPremultipliedAlpha(true),
80        mName(name),
81        mTransactionFlags(0),
82        mPendingStateMutex(),
83        mPendingStates(),
84        mQueuedFrames(0),
85        mSidebandStreamChanged(false),
86        mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
87        mCurrentTransform(0),
88        mOverrideScalingMode(-1),
89        mCurrentOpacity(true),
90        mCurrentFrameNumber(0),
91        mFrameLatencyNeeded(false),
92        mFiltering(false),
93        mNeedsFiltering(false),
94        mProtectedByApp(false),
95        mClientRef(client),
96        mPotentialCursor(false),
97        mQueueItemLock(),
98        mQueueItemCondition(),
99        mQueueItems(),
100        mLastFrameNumberReceived(0),
101        mAutoRefresh(false),
102        mFreezeGeometryUpdates(false) {
103
104    mCurrentCrop.makeInvalid();
105
106    uint32_t layerFlags = 0;
107    if (flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
108    if (flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
109    if (flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
110
111    mName = name;
112    mTransactionName = String8("TX - ") + mName;
113
114    mCurrentState.active.w = w;
115    mCurrentState.active.h = h;
116    mCurrentState.flags = layerFlags;
117    mCurrentState.active.transform.set(0, 0);
118    mCurrentState.crop.makeInvalid();
119    mCurrentState.finalCrop.makeInvalid();
120    mCurrentState.requestedFinalCrop = mCurrentState.finalCrop;
121    mCurrentState.requestedCrop = mCurrentState.crop;
122    mCurrentState.z = 0;
123    mCurrentState.color.a = 1.0f;
124    mCurrentState.layerStack = 0;
125    mCurrentState.sequence = 0;
126    mCurrentState.requested = mCurrentState.active;
127    mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
128    mCurrentState.appId = 0;
129    mCurrentState.type = 0;
130
131    // drawing state & current state are identical
132    mDrawingState = mCurrentState;
133
134    const auto& hwc = flinger->getHwComposer();
135    const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
136    nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
137    mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
138
139    CompositorTiming compositorTiming;
140    flinger->getCompositorTiming(&compositorTiming);
141    mFrameEventHistory.initializeCompositorTiming(compositorTiming);
142
143}
144
145void Layer::onFirstRef() {}
146
147Layer::~Layer() {
148    mFrameTracker.logAndResetStats(mName);
149}
150
151// ---------------------------------------------------------------------------
152// callbacks
153// ---------------------------------------------------------------------------
154
155/*
156 * onLayerDisplayed is only meaningful for BufferLayer, but, is called through
157 * Layer.  So, the implementation is done in BufferLayer.  When called on a
158 * ColorLayer object, it's essentially a NOP.
159 */
160void Layer::onLayerDisplayed(const sp<Fence>& /*releaseFence*/) {}
161
162void Layer::onRemovedFromCurrentState() {
163    // the layer is removed from SF mCurrentState to mLayersPendingRemoval
164
165    mPendingRemoval = true;
166
167    if (mCurrentState.zOrderRelativeOf != nullptr) {
168        sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
169        if (strongRelative != nullptr) {
170            strongRelative->removeZOrderRelative(this);
171            mFlinger->setTransactionFlags(eTraversalNeeded);
172        }
173        mCurrentState.zOrderRelativeOf = nullptr;
174    }
175
176    for (const auto& child : mCurrentChildren) {
177        child->onRemovedFromCurrentState();
178    }
179}
180
181void Layer::onRemoved() {
182    // the layer is removed from SF mLayersPendingRemoval
183    abandon();
184
185    destroyAllHwcLayers();
186
187    for (const auto& child : mCurrentChildren) {
188        child->onRemoved();
189    }
190}
191
192// ---------------------------------------------------------------------------
193// set-up
194// ---------------------------------------------------------------------------
195
196const String8& Layer::getName() const {
197    return mName;
198}
199
200bool Layer::getPremultipledAlpha() const {
201    return mPremultipliedAlpha;
202}
203
204sp<IBinder> Layer::getHandle() {
205    Mutex::Autolock _l(mLock);
206    return new Handle(mFlinger, this);
207}
208
209// ---------------------------------------------------------------------------
210// h/w composer set-up
211// ---------------------------------------------------------------------------
212
213bool Layer::createHwcLayer(HWComposer* hwc, int32_t hwcId) {
214    LOG_ALWAYS_FATAL_IF(getBE().mHwcLayers.count(hwcId) != 0,
215                        "Already have a layer for hwcId %d", hwcId);
216    HWC2::Layer* layer = hwc->createLayer(hwcId);
217    if (!layer) {
218        return false;
219    }
220    LayerBE::HWCInfo& hwcInfo = getBE().mHwcLayers[hwcId];
221    hwcInfo.hwc = hwc;
222    hwcInfo.layer = layer;
223    layer->setLayerDestroyedListener(
224            [this, hwcId](HWC2::Layer* /*layer*/) { getBE().mHwcLayers.erase(hwcId); });
225    return true;
226}
227
228bool Layer::destroyHwcLayer(int32_t hwcId) {
229    if (getBE().mHwcLayers.count(hwcId) == 0) {
230        return false;
231    }
232    auto& hwcInfo = getBE().mHwcLayers[hwcId];
233    LOG_ALWAYS_FATAL_IF(hwcInfo.layer == nullptr, "Attempt to destroy null layer");
234    LOG_ALWAYS_FATAL_IF(hwcInfo.hwc == nullptr, "Missing HWComposer");
235    hwcInfo.hwc->destroyLayer(hwcId, hwcInfo.layer);
236    // The layer destroyed listener should have cleared the entry from
237    // mHwcLayers. Verify that.
238    LOG_ALWAYS_FATAL_IF(getBE().mHwcLayers.count(hwcId) != 0,
239                        "Stale layer entry in getBE().mHwcLayers");
240    return true;
241}
242
243void Layer::destroyAllHwcLayers() {
244    size_t numLayers = getBE().mHwcLayers.size();
245    for (size_t i = 0; i < numLayers; ++i) {
246        LOG_ALWAYS_FATAL_IF(getBE().mHwcLayers.empty(), "destroyAllHwcLayers failed");
247        destroyHwcLayer(getBE().mHwcLayers.begin()->first);
248    }
249    LOG_ALWAYS_FATAL_IF(!getBE().mHwcLayers.empty(),
250                        "All hardware composer layers should have been destroyed");
251}
252
253Rect Layer::getContentCrop() const {
254    // this is the crop rectangle that applies to the buffer
255    // itself (as opposed to the window)
256    Rect crop;
257    if (!mCurrentCrop.isEmpty()) {
258        // if the buffer crop is defined, we use that
259        crop = mCurrentCrop;
260    } else if (getBE().mBuffer != NULL) {
261        // otherwise we use the whole buffer
262        crop = getBE().mBuffer->getBounds();
263    } else {
264        // if we don't have a buffer yet, we use an empty/invalid crop
265        crop.makeInvalid();
266    }
267    return crop;
268}
269
270static Rect reduce(const Rect& win, const Region& exclude) {
271    if (CC_LIKELY(exclude.isEmpty())) {
272        return win;
273    }
274    if (exclude.isRect()) {
275        return win.reduce(exclude.getBounds());
276    }
277    return Region(win).subtract(exclude).getBounds();
278}
279
280Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
281    const Layer::State& s(getDrawingState());
282    Rect win(s.active.w, s.active.h);
283
284    if (!s.crop.isEmpty()) {
285        win.intersect(s.crop, &win);
286    }
287
288    Transform t = getTransform();
289    win = t.transform(win);
290
291    if (!s.finalCrop.isEmpty()) {
292        win.intersect(s.finalCrop, &win);
293    }
294
295    const sp<Layer>& p = mDrawingParent.promote();
296    // Now we need to calculate the parent bounds, so we can clip ourselves to those.
297    // When calculating the parent bounds for purposes of clipping,
298    // we don't need to constrain the parent to its transparent region.
299    // The transparent region is an optimization based on the
300    // buffer contents of the layer, but does not affect the space allocated to
301    // it by policy, and thus children should be allowed to extend into the
302    // parent's transparent region. In fact one of the main uses, is to reduce
303    // buffer allocation size in cases where a child window sits behind a main window
304    // (by marking the hole in the parent window as a transparent region)
305    if (p != nullptr) {
306        Rect bounds = p->computeScreenBounds(false);
307        bounds.intersect(win, &win);
308    }
309
310    if (reduceTransparentRegion) {
311        auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
312        win = reduce(win, screenTransparentRegion);
313    }
314
315    return win;
316}
317
318Rect Layer::computeBounds() const {
319    const Layer::State& s(getDrawingState());
320    return computeBounds(s.activeTransparentRegion);
321}
322
323Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
324    const Layer::State& s(getDrawingState());
325    Rect win(s.active.w, s.active.h);
326
327    if (!s.crop.isEmpty()) {
328        win.intersect(s.crop, &win);
329    }
330
331    Rect bounds = win;
332    const auto& p = mDrawingParent.promote();
333    if (p != nullptr) {
334        // Look in computeScreenBounds recursive call for explanation of
335        // why we pass false here.
336        bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
337    }
338
339    Transform t = getTransform();
340    if (p != nullptr) {
341        win = t.transform(win);
342        win.intersect(bounds, &win);
343        win = t.inverse().transform(win);
344    }
345
346    // subtract the transparent region and snap to the bounds
347    return reduce(win, activeTransparentRegion);
348}
349
350Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
351    // the crop is the area of the window that gets cropped, but not
352    // scaled in any ways.
353    const State& s(getDrawingState());
354
355    // apply the projection's clipping to the window crop in
356    // layerstack space, and convert-back to layer space.
357    // if there are no window scaling involved, this operation will map to full
358    // pixels in the buffer.
359    // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
360    // a viewport clipping and a window transform. we should use floating point to fix this.
361
362    Rect activeCrop(s.active.w, s.active.h);
363    if (!s.crop.isEmpty()) {
364        activeCrop.intersect(s.crop, &activeCrop);
365    }
366
367    Transform t = getTransform();
368    activeCrop = t.transform(activeCrop);
369    if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
370        activeCrop.clear();
371    }
372    if (!s.finalCrop.isEmpty()) {
373        if (!activeCrop.intersect(s.finalCrop, &activeCrop)) {
374            activeCrop.clear();
375        }
376    }
377
378    const auto& p = mDrawingParent.promote();
379    if (p != nullptr) {
380        auto parentCrop = p->computeInitialCrop(hw);
381        activeCrop.intersect(parentCrop, &activeCrop);
382    }
383
384    return activeCrop;
385}
386
387FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
388    // the content crop is the area of the content that gets scaled to the
389    // layer's size. This is in buffer space.
390    FloatRect crop = getContentCrop().toFloatRect();
391
392    // In addition there is a WM-specified crop we pull from our drawing state.
393    const State& s(getDrawingState());
394
395    // Screen space to make reduction to parent crop clearer.
396    Rect activeCrop = computeInitialCrop(hw);
397    Transform t = getTransform();
398    // Back to layer space to work with the content crop.
399    activeCrop = t.inverse().transform(activeCrop);
400
401    // This needs to be here as transform.transform(Rect) computes the
402    // transformed rect and then takes the bounding box of the result before
403    // returning. This means
404    // transform.inverse().transform(transform.transform(Rect)) != Rect
405    // in which case we need to make sure the final rect is clipped to the
406    // display bounds.
407    if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
408        activeCrop.clear();
409    }
410
411    // subtract the transparent region and snap to the bounds
412    activeCrop = reduce(activeCrop, s.activeTransparentRegion);
413
414    // Transform the window crop to match the buffer coordinate system,
415    // which means using the inverse of the current transform set on the
416    // SurfaceFlingerConsumer.
417    uint32_t invTransform = mCurrentTransform;
418    if (getTransformToDisplayInverse()) {
419        /*
420         * the code below applies the primary display's inverse transform to the
421         * buffer
422         */
423        uint32_t invTransformOrient = DisplayDevice::getPrimaryDisplayOrientationTransform();
424        // calculate the inverse transform
425        if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
426            invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_FLIP_H;
427        }
428        // and apply to the current transform
429        invTransform = (Transform(invTransformOrient) * Transform(invTransform)).getOrientation();
430    }
431
432    int winWidth = s.active.w;
433    int winHeight = s.active.h;
434    if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
435        // If the activeCrop has been rotate the ends are rotated but not
436        // the space itself so when transforming ends back we can't rely on
437        // a modification of the axes of rotation. To account for this we
438        // need to reorient the inverse rotation in terms of the current
439        // axes of rotation.
440        bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
441        bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
442        if (is_h_flipped == is_v_flipped) {
443            invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_FLIP_H;
444        }
445        winWidth = s.active.h;
446        winHeight = s.active.w;
447    }
448    const Rect winCrop = activeCrop.transform(invTransform, s.active.w, s.active.h);
449
450    // below, crop is intersected with winCrop expressed in crop's coordinate space
451    float xScale = crop.getWidth() / float(winWidth);
452    float yScale = crop.getHeight() / float(winHeight);
453
454    float insetL = winCrop.left * xScale;
455    float insetT = winCrop.top * yScale;
456    float insetR = (winWidth - winCrop.right) * xScale;
457    float insetB = (winHeight - winCrop.bottom) * yScale;
458
459    crop.left += insetL;
460    crop.top += insetT;
461    crop.right -= insetR;
462    crop.bottom -= insetB;
463
464    return crop;
465}
466
467void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
468{
469    const auto hwcId = displayDevice->getHwcDisplayId();
470    auto& hwcInfo = getBE().mHwcLayers[hwcId];
471
472    // enable this layer
473    hwcInfo.forceClientComposition = false;
474
475    if (isSecure() && !displayDevice->isSecure()) {
476        hwcInfo.forceClientComposition = true;
477    }
478
479    auto& hwcLayer = hwcInfo.layer;
480
481    // this gives us only the "orientation" component of the transform
482    const State& s(getDrawingState());
483    auto blendMode = HWC2::BlendMode::None;
484    if (!isOpaque(s) || getAlpha() != 1.0f) {
485        blendMode =
486                mPremultipliedAlpha ? HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
487    }
488    auto error = hwcLayer->setBlendMode(blendMode);
489    ALOGE_IF(error != HWC2::Error::None,
490             "[%s] Failed to set blend mode %s:"
491             " %s (%d)",
492             mName.string(), to_string(blendMode).c_str(), to_string(error).c_str(),
493             static_cast<int32_t>(error));
494
495    // apply the layer's transform, followed by the display's global transform
496    // here we're guaranteed that the layer's transform preserves rects
497    Region activeTransparentRegion(s.activeTransparentRegion);
498    Transform t = getTransform();
499    if (!s.crop.isEmpty()) {
500        Rect activeCrop(s.crop);
501        activeCrop = t.transform(activeCrop);
502        if (!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
503            activeCrop.clear();
504        }
505        activeCrop = t.inverse().transform(activeCrop, true);
506        // This needs to be here as transform.transform(Rect) computes the
507        // transformed rect and then takes the bounding box of the result before
508        // returning. This means
509        // transform.inverse().transform(transform.transform(Rect)) != Rect
510        // in which case we need to make sure the final rect is clipped to the
511        // display bounds.
512        if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
513            activeCrop.clear();
514        }
515        // mark regions outside the crop as transparent
516        activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
517        activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom, s.active.w, s.active.h));
518        activeTransparentRegion.orSelf(Rect(0, activeCrop.top, activeCrop.left, activeCrop.bottom));
519        activeTransparentRegion.orSelf(
520                Rect(activeCrop.right, activeCrop.top, s.active.w, activeCrop.bottom));
521    }
522
523    Rect frame(t.transform(computeBounds(activeTransparentRegion)));
524    if (!s.finalCrop.isEmpty()) {
525        if (!frame.intersect(s.finalCrop, &frame)) {
526            frame.clear();
527        }
528    }
529    if (!frame.intersect(displayDevice->getViewport(), &frame)) {
530        frame.clear();
531    }
532    const Transform& tr(displayDevice->getTransform());
533    Rect transformedFrame = tr.transform(frame);
534    error = hwcLayer->setDisplayFrame(transformedFrame);
535    if (error != HWC2::Error::None) {
536        ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)", mName.string(),
537              transformedFrame.left, transformedFrame.top, transformedFrame.right,
538              transformedFrame.bottom, to_string(error).c_str(), static_cast<int32_t>(error));
539    } else {
540        hwcInfo.displayFrame = transformedFrame;
541    }
542
543    FloatRect sourceCrop = computeCrop(displayDevice);
544    error = hwcLayer->setSourceCrop(sourceCrop);
545    if (error != HWC2::Error::None) {
546        ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
547              "%s (%d)",
548              mName.string(), sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom,
549              to_string(error).c_str(), static_cast<int32_t>(error));
550    } else {
551        hwcInfo.sourceCrop = sourceCrop;
552    }
553
554    float alpha = static_cast<float>(getAlpha());
555    error = hwcLayer->setPlaneAlpha(alpha);
556    ALOGE_IF(error != HWC2::Error::None,
557             "[%s] Failed to set plane alpha %.3f: "
558             "%s (%d)",
559             mName.string(), alpha, to_string(error).c_str(), static_cast<int32_t>(error));
560
561    error = hwcLayer->setZOrder(z);
562    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)", mName.string(), z,
563             to_string(error).c_str(), static_cast<int32_t>(error));
564
565    int type = s.type;
566    int appId = s.appId;
567    sp<Layer> parent = mDrawingParent.promote();
568    if (parent.get()) {
569        auto& parentState = parent->getDrawingState();
570        type = parentState.type;
571        appId = parentState.appId;
572    }
573
574    error = hwcLayer->setInfo(type, appId);
575    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)", mName.string(),
576             static_cast<int32_t>(error));
577
578    /*
579     * Transformations are applied in this order:
580     * 1) buffer orientation/flip/mirror
581     * 2) state transformation (window manager)
582     * 3) layer orientation (screen orientation)
583     * (NOTE: the matrices are multiplied in reverse order)
584     */
585
586    const Transform bufferOrientation(mCurrentTransform);
587    Transform transform(tr * t * bufferOrientation);
588
589    if (getTransformToDisplayInverse()) {
590        /*
591         * the code below applies the primary display's inverse transform to the
592         * buffer
593         */
594        uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
595        // calculate the inverse transform
596        if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
597            invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_FLIP_H;
598        }
599
600        /*
601         * Here we cancel out the orientation component of the WM transform.
602         * The scaling and translate components are already included in our bounds
603         * computation so it's enough to just omit it in the composition.
604         * See comment in onDraw with ref to b/36727915 for why.
605         */
606        transform = Transform(invTransform) * tr * bufferOrientation;
607    }
608
609    // this gives us only the "orientation" component of the transform
610    const uint32_t orientation = transform.getOrientation();
611    if (orientation & Transform::ROT_INVALID) {
612        // we can only handle simple transformation
613        hwcInfo.forceClientComposition = true;
614    } else {
615        auto transform = static_cast<HWC2::Transform>(orientation);
616        auto error = hwcLayer->setTransform(transform);
617        ALOGE_IF(error != HWC2::Error::None,
618                 "[%s] Failed to set transform %s: "
619                 "%s (%d)",
620                 mName.string(), to_string(transform).c_str(), to_string(error).c_str(),
621                 static_cast<int32_t>(error));
622    }
623}
624
625void Layer::forceClientComposition(int32_t hwcId) {
626    if (getBE().mHwcLayers.count(hwcId) == 0) {
627        ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
628        return;
629    }
630
631    getBE().mHwcLayers[hwcId].forceClientComposition = true;
632}
633
634bool Layer::getForceClientComposition(int32_t hwcId) {
635    if (getBE().mHwcLayers.count(hwcId) == 0) {
636        ALOGE("getForceClientComposition: no HWC layer found (%d)", hwcId);
637        return false;
638    }
639
640    return getBE().mHwcLayers[hwcId].forceClientComposition;
641}
642
643void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
644    auto hwcId = displayDevice->getHwcDisplayId();
645    if (getBE().mHwcLayers.count(hwcId) == 0 ||
646        getCompositionType(hwcId) != HWC2::Composition::Cursor) {
647        return;
648    }
649
650    // This gives us only the "orientation" component of the transform
651    const State& s(getCurrentState());
652
653    // Apply the layer's transform, followed by the display's global transform
654    // Here we're guaranteed that the layer's transform preserves rects
655    Rect win(s.active.w, s.active.h);
656    if (!s.crop.isEmpty()) {
657        win.intersect(s.crop, &win);
658    }
659    // Subtract the transparent region and snap to the bounds
660    Rect bounds = reduce(win, s.activeTransparentRegion);
661    Rect frame(getTransform().transform(bounds));
662    frame.intersect(displayDevice->getViewport(), &frame);
663    if (!s.finalCrop.isEmpty()) {
664        frame.intersect(s.finalCrop, &frame);
665    }
666    auto& displayTransform(displayDevice->getTransform());
667    auto position = displayTransform.transform(frame);
668
669    auto error = getBE().mHwcLayers[hwcId].layer->setCursorPosition(position.left,
670                                                                              position.top);
671    ALOGE_IF(error != HWC2::Error::None,
672             "[%s] Failed to set cursor position "
673             "to (%d, %d): %s (%d)",
674             mName.string(), position.left, position.top, to_string(error).c_str(),
675             static_cast<int32_t>(error));
676}
677
678// ---------------------------------------------------------------------------
679// drawing...
680// ---------------------------------------------------------------------------
681
682void Layer::draw(const RenderArea& renderArea, const Region& clip) const {
683    onDraw(renderArea, clip, false);
684}
685
686void Layer::draw(const RenderArea& renderArea, bool useIdentityTransform) const {
687    onDraw(renderArea, Region(renderArea.getBounds()), useIdentityTransform);
688}
689
690void Layer::draw(const RenderArea& renderArea) const {
691    onDraw(renderArea, Region(renderArea.getBounds()), false);
692}
693
694void Layer::clearWithOpenGL(const RenderArea& renderArea, float red, float green, float blue,
695                            float alpha) const {
696    RenderEngine& engine(mFlinger->getRenderEngine());
697    computeGeometry(renderArea, getBE().mMesh, false);
698    engine.setupFillWithColor(red, green, blue, alpha);
699    engine.drawMesh(getBE().mMesh);
700}
701
702void Layer::clearWithOpenGL(const RenderArea& renderArea) const {
703    clearWithOpenGL(renderArea, 0, 0, 0, 0);
704}
705
706void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type, bool callIntoHwc) {
707    if (getBE().mHwcLayers.count(hwcId) == 0) {
708        ALOGE("setCompositionType called without a valid HWC layer");
709        return;
710    }
711    auto& hwcInfo = getBE().mHwcLayers[hwcId];
712    auto& hwcLayer = hwcInfo.layer;
713    ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(), to_string(type).c_str(),
714          static_cast<int>(callIntoHwc));
715    if (hwcInfo.compositionType != type) {
716        ALOGV("    actually setting");
717        hwcInfo.compositionType = type;
718        if (callIntoHwc) {
719            auto error = hwcLayer->setCompositionType(type);
720            ALOGE_IF(error != HWC2::Error::None,
721                     "[%s] Failed to set "
722                     "composition type %s: %s (%d)",
723                     mName.string(), to_string(type).c_str(), to_string(error).c_str(),
724                     static_cast<int32_t>(error));
725        }
726    }
727}
728
729HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
730    if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
731        // If we're querying the composition type for a display that does not
732        // have a HWC counterpart, then it will always be Client
733        return HWC2::Composition::Client;
734    }
735    if (getBE().mHwcLayers.count(hwcId) == 0) {
736        ALOGE("getCompositionType called with an invalid HWC layer");
737        return HWC2::Composition::Invalid;
738    }
739    return getBE().mHwcLayers.at(hwcId).compositionType;
740}
741
742void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
743    if (getBE().mHwcLayers.count(hwcId) == 0) {
744        ALOGE("setClearClientTarget called without a valid HWC layer");
745        return;
746    }
747    getBE().mHwcLayers[hwcId].clearClientTarget = clear;
748}
749
750bool Layer::getClearClientTarget(int32_t hwcId) const {
751    if (getBE().mHwcLayers.count(hwcId) == 0) {
752        ALOGE("getClearClientTarget called without a valid HWC layer");
753        return false;
754    }
755    return getBE().mHwcLayers.at(hwcId).clearClientTarget;
756}
757
758bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
759    if (point->getFrameNumber() <= mCurrentFrameNumber) {
760        // Don't bother with a SyncPoint, since we've already latched the
761        // relevant frame
762        return false;
763    }
764
765    Mutex::Autolock lock(mLocalSyncPointMutex);
766    mLocalSyncPoints.push_back(point);
767    return true;
768}
769
770void Layer::setFiltering(bool filtering) {
771    mFiltering = filtering;
772}
773
774bool Layer::getFiltering() const {
775    return mFiltering;
776}
777
778// ----------------------------------------------------------------------------
779// local state
780// ----------------------------------------------------------------------------
781
782static void boundPoint(vec2* point, const Rect& crop) {
783    if (point->x < crop.left) {
784        point->x = crop.left;
785    }
786    if (point->x > crop.right) {
787        point->x = crop.right;
788    }
789    if (point->y < crop.top) {
790        point->y = crop.top;
791    }
792    if (point->y > crop.bottom) {
793        point->y = crop.bottom;
794    }
795}
796
797void Layer::computeGeometry(const RenderArea& renderArea, Mesh& mesh,
798                            bool useIdentityTransform) const {
799    const Layer::State& s(getDrawingState());
800    const Transform renderAreaTransform(renderArea.getTransform());
801    const uint32_t height = renderArea.getHeight();
802    Rect win = computeBounds();
803
804    vec2 lt = vec2(win.left, win.top);
805    vec2 lb = vec2(win.left, win.bottom);
806    vec2 rb = vec2(win.right, win.bottom);
807    vec2 rt = vec2(win.right, win.top);
808
809    Transform layerTransform = getTransform();
810    if (!useIdentityTransform) {
811        lt = layerTransform.transform(lt);
812        lb = layerTransform.transform(lb);
813        rb = layerTransform.transform(rb);
814        rt = layerTransform.transform(rt);
815    }
816
817    if (!s.finalCrop.isEmpty()) {
818        boundPoint(&lt, s.finalCrop);
819        boundPoint(&lb, s.finalCrop);
820        boundPoint(&rb, s.finalCrop);
821        boundPoint(&rt, s.finalCrop);
822    }
823
824    Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
825    position[0] = renderAreaTransform.transform(lt);
826    position[1] = renderAreaTransform.transform(lb);
827    position[2] = renderAreaTransform.transform(rb);
828    position[3] = renderAreaTransform.transform(rt);
829    for (size_t i = 0; i < 4; i++) {
830        position[i].y = height - position[i].y;
831    }
832}
833
834bool Layer::isSecure() const {
835    const Layer::State& s(mDrawingState);
836    return (s.flags & layer_state_t::eLayerSecure);
837}
838
839void Layer::setVisibleRegion(const Region& visibleRegion) {
840    // always called from main thread
841    this->visibleRegion = visibleRegion;
842}
843
844void Layer::setCoveredRegion(const Region& coveredRegion) {
845    // always called from main thread
846    this->coveredRegion = coveredRegion;
847}
848
849void Layer::setVisibleNonTransparentRegion(const Region& setVisibleNonTransparentRegion) {
850    // always called from main thread
851    this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
852}
853
854// ----------------------------------------------------------------------------
855// transaction
856// ----------------------------------------------------------------------------
857
858void Layer::pushPendingState() {
859    if (!mCurrentState.modified) {
860        return;
861    }
862
863    // If this transaction is waiting on the receipt of a frame, generate a sync
864    // point and send it to the remote layer.
865    if (mCurrentState.barrierLayer != nullptr) {
866        sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
867        if (barrierLayer == nullptr) {
868            ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
869            // If we can't promote the layer we are intended to wait on,
870            // then it is expired or otherwise invalid. Allow this transaction
871            // to be applied as per normal (no synchronization).
872            mCurrentState.barrierLayer = nullptr;
873        } else {
874            auto syncPoint = std::make_shared<SyncPoint>(mCurrentState.frameNumber);
875            if (barrierLayer->addSyncPoint(syncPoint)) {
876                mRemoteSyncPoints.push_back(std::move(syncPoint));
877            } else {
878                // We already missed the frame we're supposed to synchronize
879                // on, so go ahead and apply the state update
880                mCurrentState.barrierLayer = nullptr;
881            }
882        }
883
884        // Wake us up to check if the frame has been received
885        setTransactionFlags(eTransactionNeeded);
886        mFlinger->setTransactionFlags(eTraversalNeeded);
887    }
888    mPendingStates.push_back(mCurrentState);
889    ATRACE_INT(mTransactionName.string(), mPendingStates.size());
890}
891
892void Layer::popPendingState(State* stateToCommit) {
893    auto oldFlags = stateToCommit->flags;
894    *stateToCommit = mPendingStates[0];
895    stateToCommit->flags =
896            (oldFlags & ~stateToCommit->mask) | (stateToCommit->flags & stateToCommit->mask);
897
898    mPendingStates.removeAt(0);
899    ATRACE_INT(mTransactionName.string(), mPendingStates.size());
900}
901
902bool Layer::applyPendingStates(State* stateToCommit) {
903    bool stateUpdateAvailable = false;
904    while (!mPendingStates.empty()) {
905        if (mPendingStates[0].barrierLayer != nullptr) {
906            if (mRemoteSyncPoints.empty()) {
907                // If we don't have a sync point for this, apply it anyway. It
908                // will be visually wrong, but it should keep us from getting
909                // into too much trouble.
910                ALOGE("[%s] No local sync point found", mName.string());
911                popPendingState(stateToCommit);
912                stateUpdateAvailable = true;
913                continue;
914            }
915
916            if (mRemoteSyncPoints.front()->getFrameNumber() != mPendingStates[0].frameNumber) {
917                ALOGE("[%s] Unexpected sync point frame number found", mName.string());
918
919                // Signal our end of the sync point and then dispose of it
920                mRemoteSyncPoints.front()->setTransactionApplied();
921                mRemoteSyncPoints.pop_front();
922                continue;
923            }
924
925            if (mRemoteSyncPoints.front()->frameIsAvailable()) {
926                // Apply the state update
927                popPendingState(stateToCommit);
928                stateUpdateAvailable = true;
929
930                // Signal our end of the sync point and then dispose of it
931                mRemoteSyncPoints.front()->setTransactionApplied();
932                mRemoteSyncPoints.pop_front();
933            } else {
934                break;
935            }
936        } else {
937            popPendingState(stateToCommit);
938            stateUpdateAvailable = true;
939        }
940    }
941
942    // If we still have pending updates, wake SurfaceFlinger back up and point
943    // it at this layer so we can process them
944    if (!mPendingStates.empty()) {
945        setTransactionFlags(eTransactionNeeded);
946        mFlinger->setTransactionFlags(eTraversalNeeded);
947    }
948
949    mCurrentState.modified = false;
950    return stateUpdateAvailable;
951}
952
953uint32_t Layer::doTransaction(uint32_t flags) {
954    ATRACE_CALL();
955
956    pushPendingState();
957    Layer::State c = getCurrentState();
958    if (!applyPendingStates(&c)) {
959        return 0;
960    }
961
962    const Layer::State& s(getDrawingState());
963
964    const bool sizeChanged = (c.requested.w != s.requested.w) || (c.requested.h != s.requested.h);
965
966    if (sizeChanged) {
967        // the size changed, we need to ask our client to request a new buffer
968        ALOGD_IF(DEBUG_RESIZE,
969                 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
970                 "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
971                 "            requested={ wh={%4u,%4u} }}\n"
972                 "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
973                 "            requested={ wh={%4u,%4u} }}\n",
974                 this, getName().string(), mCurrentTransform,
975                 getEffectiveScalingMode(), c.active.w, c.active.h, c.crop.left, c.crop.top,
976                 c.crop.right, c.crop.bottom, c.crop.getWidth(), c.crop.getHeight(), c.requested.w,
977                 c.requested.h, s.active.w, s.active.h, s.crop.left, s.crop.top, s.crop.right,
978                 s.crop.bottom, s.crop.getWidth(), s.crop.getHeight(), s.requested.w,
979                 s.requested.h);
980
981        // record the new size, form this point on, when the client request
982        // a buffer, it'll get the new size.
983        setDefaultBufferSize(c.requested.w, c.requested.h);
984    }
985
986    // Don't let Layer::doTransaction update the drawing state
987    // if we have a pending resize, unless we are in fixed-size mode.
988    // the drawing state will be updated only once we receive a buffer
989    // with the correct size.
990    //
991    // In particular, we want to make sure the clip (which is part
992    // of the geometry state) is latched together with the size but is
993    // latched immediately when no resizing is involved.
994    //
995    // If a sideband stream is attached, however, we want to skip this
996    // optimization so that transactions aren't missed when a buffer
997    // never arrives
998    //
999    // In the case that we don't have a buffer we ignore other factors
1000    // and avoid entering the resizePending state. At a high level the
1001    // resizePending state is to avoid applying the state of the new buffer
1002    // to the old buffer. However in the state where we don't have an old buffer
1003    // there is no such concern but we may still be being used as a parent layer.
1004    const bool resizePending = ((c.requested.w != c.active.w) || (c.requested.h != c.active.h)) &&
1005            (getBE().mBuffer != nullptr);
1006    if (!isFixedSize()) {
1007        if (resizePending && getBE().mSidebandStream == NULL) {
1008            flags |= eDontUpdateGeometryState;
1009        }
1010    }
1011
1012    // Here we apply various requested geometry states, depending on our
1013    // latching configuration. See Layer.h for a detailed discussion of
1014    // how geometry latching is controlled.
1015    if (!(flags & eDontUpdateGeometryState)) {
1016        Layer::State& editCurrentState(getCurrentState());
1017
1018        // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1019        // mode, which causes attributes which normally latch regardless of scaling mode,
1020        // to be delayed. We copy the requested state to the active state making sure
1021        // to respect these rules (again see Layer.h for a detailed discussion).
1022        //
1023        // There is an awkward asymmetry in the handling of the crop states in the position
1024        // states, as can be seen below. Largely this arises from position and transform
1025        // being stored in the same data structure while having different latching rules.
1026        // b/38182305
1027        //
1028        // Careful that "c" and editCurrentState may not begin as equivalent due to
1029        // applyPendingStates in the presence of deferred transactions.
1030        if (mFreezeGeometryUpdates) {
1031            float tx = c.active.transform.tx();
1032            float ty = c.active.transform.ty();
1033            c.active = c.requested;
1034            c.active.transform.set(tx, ty);
1035            editCurrentState.active = c.active;
1036        } else {
1037            editCurrentState.active = editCurrentState.requested;
1038            c.active = c.requested;
1039        }
1040    }
1041
1042    if (s.active != c.active) {
1043        // invalidate and recompute the visible regions if needed
1044        flags |= Layer::eVisibleRegion;
1045    }
1046
1047    if (c.sequence != s.sequence) {
1048        // invalidate and recompute the visible regions if needed
1049        flags |= eVisibleRegion;
1050        this->contentDirty = true;
1051
1052        // we may use linear filtering, if the matrix scales us
1053        const uint8_t type = c.active.transform.getType();
1054        mNeedsFiltering = (!c.active.transform.preserveRects() || (type >= Transform::SCALE));
1055    }
1056
1057    // If the layer is hidden, signal and clear out all local sync points so
1058    // that transactions for layers depending on this layer's frames becoming
1059    // visible are not blocked
1060    if (c.flags & layer_state_t::eLayerHidden) {
1061        clearSyncPoints();
1062    }
1063
1064    // Commit the transaction
1065    commitTransaction(c);
1066    return flags;
1067}
1068
1069void Layer::commitTransaction(const State& stateToCommit) {
1070    mDrawingState = stateToCommit;
1071}
1072
1073uint32_t Layer::getTransactionFlags(uint32_t flags) {
1074    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1075}
1076
1077uint32_t Layer::setTransactionFlags(uint32_t flags) {
1078    return android_atomic_or(flags, &mTransactionFlags);
1079}
1080
1081bool Layer::setPosition(float x, float y, bool immediate) {
1082    if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1083        return false;
1084    mCurrentState.sequence++;
1085
1086    // We update the requested and active position simultaneously because
1087    // we want to apply the position portion of the transform matrix immediately,
1088    // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1089    mCurrentState.requested.transform.set(x, y);
1090    if (immediate && !mFreezeGeometryUpdates) {
1091        // Here we directly update the active state
1092        // unlike other setters, because we store it within
1093        // the transform, but use different latching rules.
1094        // b/38182305
1095        mCurrentState.active.transform.set(x, y);
1096    }
1097    mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1098
1099    mCurrentState.modified = true;
1100    setTransactionFlags(eTransactionNeeded);
1101    return true;
1102}
1103
1104bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1105    ssize_t idx = mCurrentChildren.indexOf(childLayer);
1106    if (idx < 0) {
1107        return false;
1108    }
1109    if (childLayer->setLayer(z)) {
1110        mCurrentChildren.removeAt(idx);
1111        mCurrentChildren.add(childLayer);
1112        return true;
1113    }
1114    return false;
1115}
1116
1117bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
1118        const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
1119    ssize_t idx = mCurrentChildren.indexOf(childLayer);
1120    if (idx < 0) {
1121        return false;
1122    }
1123    if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
1124        mCurrentChildren.removeAt(idx);
1125        mCurrentChildren.add(childLayer);
1126        return true;
1127    }
1128    return false;
1129}
1130
1131bool Layer::setLayer(int32_t z) {
1132    if (mCurrentState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
1133    mCurrentState.sequence++;
1134    mCurrentState.z = z;
1135    mCurrentState.modified = true;
1136
1137    // Discard all relative layering.
1138    if (mCurrentState.zOrderRelativeOf != nullptr) {
1139        sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1140        if (strongRelative != nullptr) {
1141            strongRelative->removeZOrderRelative(this);
1142        }
1143        mCurrentState.zOrderRelativeOf = nullptr;
1144    }
1145    setTransactionFlags(eTransactionNeeded);
1146    return true;
1147}
1148
1149void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1150    mCurrentState.zOrderRelatives.remove(relative);
1151    mCurrentState.sequence++;
1152    mCurrentState.modified = true;
1153    setTransactionFlags(eTransactionNeeded);
1154}
1155
1156void Layer::addZOrderRelative(const wp<Layer>& relative) {
1157    mCurrentState.zOrderRelatives.add(relative);
1158    mCurrentState.modified = true;
1159    mCurrentState.sequence++;
1160    setTransactionFlags(eTransactionNeeded);
1161}
1162
1163bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
1164    sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1165    if (handle == nullptr) {
1166        return false;
1167    }
1168    sp<Layer> relative = handle->owner.promote();
1169    if (relative == nullptr) {
1170        return false;
1171    }
1172
1173    if (mCurrentState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
1174            mCurrentState.zOrderRelativeOf == relative) {
1175        return false;
1176    }
1177
1178    mCurrentState.sequence++;
1179    mCurrentState.modified = true;
1180    mCurrentState.z = relativeZ;
1181
1182    auto oldZOrderRelativeOf = mCurrentState.zOrderRelativeOf.promote();
1183    if (oldZOrderRelativeOf != nullptr) {
1184        oldZOrderRelativeOf->removeZOrderRelative(this);
1185    }
1186    mCurrentState.zOrderRelativeOf = relative;
1187    relative->addZOrderRelative(this);
1188
1189    setTransactionFlags(eTransactionNeeded);
1190
1191    return true;
1192}
1193
1194bool Layer::setSize(uint32_t w, uint32_t h) {
1195    if (mCurrentState.requested.w == w && mCurrentState.requested.h == h) return false;
1196    mCurrentState.requested.w = w;
1197    mCurrentState.requested.h = h;
1198    mCurrentState.modified = true;
1199    setTransactionFlags(eTransactionNeeded);
1200    return true;
1201}
1202bool Layer::setAlpha(float alpha) {
1203    if (mCurrentState.color.a == alpha) return false;
1204    mCurrentState.sequence++;
1205    mCurrentState.color.a = alpha;
1206    mCurrentState.modified = true;
1207    setTransactionFlags(eTransactionNeeded);
1208    return true;
1209}
1210
1211bool Layer::setColor(const half3& color) {
1212    if (color.r == mCurrentState.color.r && color.g == mCurrentState.color.g &&
1213        color.b == mCurrentState.color.b)
1214        return false;
1215
1216    mCurrentState.sequence++;
1217    mCurrentState.color.r = color.r;
1218    mCurrentState.color.g = color.g;
1219    mCurrentState.color.b = color.b;
1220    mCurrentState.modified = true;
1221    setTransactionFlags(eTransactionNeeded);
1222    return true;
1223}
1224
1225bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1226    mCurrentState.sequence++;
1227    mCurrentState.requested.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
1228    mCurrentState.modified = true;
1229    setTransactionFlags(eTransactionNeeded);
1230    return true;
1231}
1232bool Layer::setTransparentRegionHint(const Region& transparent) {
1233    mCurrentState.requestedTransparentRegion = transparent;
1234    mCurrentState.modified = true;
1235    setTransactionFlags(eTransactionNeeded);
1236    return true;
1237}
1238bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1239    const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1240    if (mCurrentState.flags == newFlags) return false;
1241    mCurrentState.sequence++;
1242    mCurrentState.flags = newFlags;
1243    mCurrentState.mask = mask;
1244    mCurrentState.modified = true;
1245    setTransactionFlags(eTransactionNeeded);
1246    return true;
1247}
1248
1249bool Layer::setCrop(const Rect& crop, bool immediate) {
1250    if (mCurrentState.requestedCrop == crop) return false;
1251    mCurrentState.sequence++;
1252    mCurrentState.requestedCrop = crop;
1253    if (immediate && !mFreezeGeometryUpdates) {
1254        mCurrentState.crop = crop;
1255    }
1256    mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1257
1258    mCurrentState.modified = true;
1259    setTransactionFlags(eTransactionNeeded);
1260    return true;
1261}
1262
1263bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
1264    if (mCurrentState.requestedFinalCrop == crop) return false;
1265    mCurrentState.sequence++;
1266    mCurrentState.requestedFinalCrop = crop;
1267    if (immediate && !mFreezeGeometryUpdates) {
1268        mCurrentState.finalCrop = crop;
1269    }
1270    mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1271
1272    mCurrentState.modified = true;
1273    setTransactionFlags(eTransactionNeeded);
1274    return true;
1275}
1276
1277bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1278    if (scalingMode == mOverrideScalingMode) return false;
1279    mOverrideScalingMode = scalingMode;
1280    setTransactionFlags(eTransactionNeeded);
1281    return true;
1282}
1283
1284void Layer::setInfo(uint32_t type, uint32_t appId) {
1285    mCurrentState.appId = appId;
1286    mCurrentState.type = type;
1287    mCurrentState.modified = true;
1288    setTransactionFlags(eTransactionNeeded);
1289}
1290
1291bool Layer::setLayerStack(uint32_t layerStack) {
1292    if (mCurrentState.layerStack == layerStack) return false;
1293    mCurrentState.sequence++;
1294    mCurrentState.layerStack = layerStack;
1295    mCurrentState.modified = true;
1296    setTransactionFlags(eTransactionNeeded);
1297    return true;
1298}
1299
1300bool Layer::setDataSpace(android_dataspace dataSpace) {
1301    if (mCurrentState.dataSpace == dataSpace) return false;
1302    mCurrentState.sequence++;
1303    mCurrentState.dataSpace = dataSpace;
1304    mCurrentState.modified = true;
1305    setTransactionFlags(eTransactionNeeded);
1306    return true;
1307}
1308
1309android_dataspace Layer::getDataSpace() const {
1310    return mCurrentState.dataSpace;
1311}
1312
1313uint32_t Layer::getLayerStack() const {
1314    auto p = mDrawingParent.promote();
1315    if (p == nullptr) {
1316        return getDrawingState().layerStack;
1317    }
1318    return p->getLayerStack();
1319}
1320
1321void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer, uint64_t frameNumber) {
1322    mCurrentState.barrierLayer = barrierLayer;
1323    mCurrentState.frameNumber = frameNumber;
1324    // We don't set eTransactionNeeded, because just receiving a deferral
1325    // request without any other state updates shouldn't actually induce a delay
1326    mCurrentState.modified = true;
1327    pushPendingState();
1328    mCurrentState.barrierLayer = nullptr;
1329    mCurrentState.frameNumber = 0;
1330    mCurrentState.modified = false;
1331}
1332
1333void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle, uint64_t frameNumber) {
1334    sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1335    deferTransactionUntil(handle->owner.promote(), frameNumber);
1336}
1337
1338
1339// ----------------------------------------------------------------------------
1340// pageflip handling...
1341// ----------------------------------------------------------------------------
1342
1343bool Layer::isHiddenByPolicy() const {
1344    const Layer::State& s(mDrawingState);
1345    const auto& parent = mDrawingParent.promote();
1346    if (parent != nullptr && parent->isHiddenByPolicy()) {
1347        return true;
1348    }
1349    return s.flags & layer_state_t::eLayerHidden;
1350}
1351
1352uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
1353    // TODO: should we do something special if mSecure is set?
1354    if (mProtectedByApp) {
1355        // need a hardware-protected path to external video sink
1356        usage |= GraphicBuffer::USAGE_PROTECTED;
1357    }
1358    if (mPotentialCursor) {
1359        usage |= GraphicBuffer::USAGE_CURSOR;
1360    }
1361    usage |= GraphicBuffer::USAGE_HW_COMPOSER;
1362    return usage;
1363}
1364
1365void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
1366    uint32_t orientation = 0;
1367    if (!mFlinger->mDebugDisableTransformHint) {
1368        // The transform hint is used to improve performance, but we can
1369        // only have a single transform hint, it cannot
1370        // apply to all displays.
1371        const Transform& planeTransform(hw->getTransform());
1372        orientation = planeTransform.getOrientation();
1373        if (orientation & Transform::ROT_INVALID) {
1374            orientation = 0;
1375        }
1376    }
1377    setTransformHint(orientation);
1378}
1379
1380// ----------------------------------------------------------------------------
1381// debugging
1382// ----------------------------------------------------------------------------
1383
1384LayerDebugInfo Layer::getLayerDebugInfo() const {
1385    LayerDebugInfo info;
1386    const Layer::State& ds = getDrawingState();
1387    info.mName = getName();
1388    sp<Layer> parent = getParent();
1389    info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
1390    info.mType = String8(getTypeId());
1391    info.mTransparentRegion = ds.activeTransparentRegion;
1392    info.mVisibleRegion = visibleRegion;
1393    info.mSurfaceDamageRegion = surfaceDamageRegion;
1394    info.mLayerStack = getLayerStack();
1395    info.mX = ds.active.transform.tx();
1396    info.mY = ds.active.transform.ty();
1397    info.mZ = ds.z;
1398    info.mWidth = ds.active.w;
1399    info.mHeight = ds.active.h;
1400    info.mCrop = ds.crop;
1401    info.mFinalCrop = ds.finalCrop;
1402    info.mColor = ds.color;
1403    info.mFlags = ds.flags;
1404    info.mPixelFormat = getPixelFormat();
1405    info.mDataSpace = getDataSpace();
1406    info.mMatrix[0][0] = ds.active.transform[0][0];
1407    info.mMatrix[0][1] = ds.active.transform[0][1];
1408    info.mMatrix[1][0] = ds.active.transform[1][0];
1409    info.mMatrix[1][1] = ds.active.transform[1][1];
1410    {
1411        sp<const GraphicBuffer> buffer = getBE().mBuffer;
1412        if (buffer != 0) {
1413            info.mActiveBufferWidth = buffer->getWidth();
1414            info.mActiveBufferHeight = buffer->getHeight();
1415            info.mActiveBufferStride = buffer->getStride();
1416            info.mActiveBufferFormat = buffer->format;
1417        } else {
1418            info.mActiveBufferWidth = 0;
1419            info.mActiveBufferHeight = 0;
1420            info.mActiveBufferStride = 0;
1421            info.mActiveBufferFormat = 0;
1422        }
1423    }
1424    info.mNumQueuedFrames = getQueuedFrameCount();
1425    info.mRefreshPending = isBufferLatched();
1426    info.mIsOpaque = isOpaque(ds);
1427    info.mContentDirty = contentDirty;
1428    return info;
1429}
1430
1431void Layer::miniDumpHeader(String8& result) {
1432    result.append("----------------------------------------");
1433    result.append("---------------------------------------\n");
1434    result.append(" Layer name\n");
1435    result.append("           Z | ");
1436    result.append(" Comp Type | ");
1437    result.append("  Disp Frame (LTRB) | ");
1438    result.append("         Source Crop (LTRB)\n");
1439    result.append("----------------------------------------");
1440    result.append("---------------------------------------\n");
1441}
1442
1443void Layer::miniDump(String8& result, int32_t hwcId) const {
1444    if (getBE().mHwcLayers.count(hwcId) == 0) {
1445        return;
1446    }
1447
1448    String8 name;
1449    if (mName.length() > 77) {
1450        std::string shortened;
1451        shortened.append(mName.string(), 36);
1452        shortened.append("[...]");
1453        shortened.append(mName.string() + (mName.length() - 36), 36);
1454        name = shortened.c_str();
1455    } else {
1456        name = mName;
1457    }
1458
1459    result.appendFormat(" %s\n", name.string());
1460
1461    const Layer::State& layerState(getDrawingState());
1462    const LayerBE::HWCInfo& hwcInfo = getBE().mHwcLayers.at(hwcId);
1463    result.appendFormat("  %10d | ", layerState.z);
1464    result.appendFormat("%10s | ", to_string(getCompositionType(hwcId)).c_str());
1465    const Rect& frame = hwcInfo.displayFrame;
1466    result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1467    const FloatRect& crop = hwcInfo.sourceCrop;
1468    result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, crop.right, crop.bottom);
1469
1470    result.append("- - - - - - - - - - - - - - - - - - - - ");
1471    result.append("- - - - - - - - - - - - - - - - - - - -\n");
1472}
1473
1474void Layer::dumpFrameStats(String8& result) const {
1475    mFrameTracker.dumpStats(result);
1476}
1477
1478void Layer::clearFrameStats() {
1479    mFrameTracker.clearStats();
1480}
1481
1482void Layer::logFrameStats() {
1483    mFrameTracker.logAndResetStats(mName);
1484}
1485
1486void Layer::getFrameStats(FrameStats* outStats) const {
1487    mFrameTracker.getStats(outStats);
1488}
1489
1490void Layer::dumpFrameEvents(String8& result) {
1491    result.appendFormat("- Layer %s (%s, %p)\n", getName().string(), getTypeId(), this);
1492    Mutex::Autolock lock(mFrameEventHistoryMutex);
1493    mFrameEventHistory.checkFencesForCompletion();
1494    mFrameEventHistory.dump(result);
1495}
1496
1497void Layer::onDisconnect() {
1498    Mutex::Autolock lock(mFrameEventHistoryMutex);
1499    mFrameEventHistory.onDisconnect();
1500}
1501
1502void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
1503                                     FrameEventHistoryDelta* outDelta) {
1504    Mutex::Autolock lock(mFrameEventHistoryMutex);
1505    if (newTimestamps) {
1506        // If there are any unsignaled fences in the aquire timeline at this
1507        // point, the previously queued frame hasn't been latched yet. Go ahead
1508        // and try to get the signal time here so the syscall is taken out of
1509        // the main thread's critical path.
1510        mAcquireTimeline.updateSignalTimes();
1511        // Push the new fence after updating since it's likely still pending.
1512        mAcquireTimeline.push(newTimestamps->acquireFence);
1513        mFrameEventHistory.addQueue(*newTimestamps);
1514    }
1515
1516    if (outDelta) {
1517        mFrameEventHistory.getAndResetDelta(outDelta);
1518    }
1519}
1520
1521size_t Layer::getChildrenCount() const {
1522    size_t count = 0;
1523    for (const sp<Layer>& child : mCurrentChildren) {
1524        count += 1 + child->getChildrenCount();
1525    }
1526    return count;
1527}
1528
1529void Layer::addChild(const sp<Layer>& layer) {
1530    mCurrentChildren.add(layer);
1531    layer->setParent(this);
1532}
1533
1534ssize_t Layer::removeChild(const sp<Layer>& layer) {
1535    layer->setParent(nullptr);
1536    return mCurrentChildren.remove(layer);
1537}
1538
1539bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
1540    sp<Handle> handle = nullptr;
1541    sp<Layer> newParent = nullptr;
1542    if (newParentHandle == nullptr) {
1543        return false;
1544    }
1545    handle = static_cast<Handle*>(newParentHandle.get());
1546    newParent = handle->owner.promote();
1547    if (newParent == nullptr) {
1548        ALOGE("Unable to promote Layer handle");
1549        return false;
1550    }
1551
1552    for (const sp<Layer>& child : mCurrentChildren) {
1553        newParent->addChild(child);
1554
1555        sp<Client> client(child->mClientRef.promote());
1556        if (client != nullptr) {
1557            client->setParentLayer(newParent);
1558        }
1559    }
1560    mCurrentChildren.clear();
1561
1562    return true;
1563}
1564
1565bool Layer::reparent(const sp<IBinder>& newParentHandle) {
1566    if (newParentHandle == nullptr) {
1567        return false;
1568    }
1569
1570    auto handle = static_cast<Handle*>(newParentHandle.get());
1571    sp<Layer> newParent = handle->owner.promote();
1572    if (newParent == nullptr) {
1573        ALOGE("Unable to promote Layer handle");
1574        return false;
1575    }
1576
1577    sp<Layer> parent = getParent();
1578    if (parent != nullptr) {
1579        parent->removeChild(this);
1580    }
1581    newParent->addChild(this);
1582
1583    sp<Client> client(mClientRef.promote());
1584    sp<Client> newParentClient(newParent->mClientRef.promote());
1585
1586    if (client != newParentClient) {
1587        client->setParentLayer(newParent);
1588    }
1589
1590    return true;
1591}
1592
1593bool Layer::detachChildren() {
1594    for (const sp<Layer>& child : mCurrentChildren) {
1595        sp<Client> parentClient = mClientRef.promote();
1596        sp<Client> client(child->mClientRef.promote());
1597        if (client != nullptr && parentClient != client) {
1598            client->detachLayer(child.get());
1599            child->detachChildren();
1600        }
1601    }
1602
1603    return true;
1604}
1605
1606void Layer::setParent(const sp<Layer>& layer) {
1607    mCurrentParent = layer;
1608}
1609
1610void Layer::clearSyncPoints() {
1611    for (const auto& child : mCurrentChildren) {
1612        child->clearSyncPoints();
1613    }
1614
1615    Mutex::Autolock lock(mLocalSyncPointMutex);
1616    for (auto& point : mLocalSyncPoints) {
1617        point->setFrameAvailable();
1618    }
1619    mLocalSyncPoints.clear();
1620}
1621
1622int32_t Layer::getZ() const {
1623    return mDrawingState.z;
1624}
1625
1626bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) {
1627    const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1628    const State& state = useDrawing ? mDrawingState : mCurrentState;
1629    return state.zOrderRelativeOf != nullptr;
1630}
1631
1632__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
1633        LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
1634    LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1635                        "makeTraversalList received invalid stateSet");
1636    const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1637    const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1638    const State& state = useDrawing ? mDrawingState : mCurrentState;
1639
1640    if (state.zOrderRelatives.size() == 0) {
1641        *outSkipRelativeZUsers = true;
1642        return children;
1643    }
1644
1645    LayerVector traverse;
1646    for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1647        sp<Layer> strongRelative = weakRelative.promote();
1648        if (strongRelative != nullptr) {
1649            traverse.add(strongRelative);
1650        }
1651    }
1652
1653    for (const sp<Layer>& child : children) {
1654        const State& childState = useDrawing ? child->mDrawingState : child->mCurrentState;
1655        if (childState.zOrderRelativeOf != nullptr) {
1656            continue;
1657        }
1658        traverse.add(child);
1659    }
1660
1661    return traverse;
1662}
1663
1664/**
1665 * Negatively signed relatives are before 'this' in Z-order.
1666 */
1667void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
1668    // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1669    // produce a new list for traversing, including our relatives, and not including our children
1670    // who are relatives of another surface. In the case that there are no relative Z,
1671    // makeTraversalList returns our children directly to avoid significant overhead.
1672    // However in this case we need to take the responsibility for filtering children which
1673    // are relatives of another surface here.
1674    bool skipRelativeZUsers = false;
1675    const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
1676
1677    size_t i = 0;
1678    for (; i < list.size(); i++) {
1679        const auto& relative = list[i];
1680        if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1681            continue;
1682        }
1683
1684        if (relative->getZ() >= 0) {
1685            break;
1686        }
1687        relative->traverseInZOrder(stateSet, visitor);
1688    }
1689
1690    visitor(this);
1691    for (; i < list.size(); i++) {
1692        const auto& relative = list[i];
1693
1694        if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1695            continue;
1696        }
1697        relative->traverseInZOrder(stateSet, visitor);
1698    }
1699}
1700
1701/**
1702 * Positively signed relatives are before 'this' in reverse Z-order.
1703 */
1704void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1705                                    const LayerVector::Visitor& visitor) {
1706    // See traverseInZOrder for documentation.
1707    bool skipRelativeZUsers = false;
1708    LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
1709
1710    int32_t i = 0;
1711    for (i = int32_t(list.size()) - 1; i >= 0; i--) {
1712        const auto& relative = list[i];
1713
1714        if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1715            continue;
1716        }
1717
1718        if (relative->getZ() < 0) {
1719            break;
1720        }
1721        relative->traverseInReverseZOrder(stateSet, visitor);
1722    }
1723    visitor(this);
1724    for (; i >= 0; i--) {
1725        const auto& relative = list[i];
1726
1727        if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1728            continue;
1729        }
1730
1731        relative->traverseInReverseZOrder(stateSet, visitor);
1732    }
1733}
1734
1735/**
1736 * Traverse only children in z order, ignoring relative layers.
1737 */
1738void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1739                                     const LayerVector::Visitor& visitor) {
1740    const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1741    const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1742
1743    size_t i = 0;
1744    for (; i < children.size(); i++) {
1745        const auto& relative = children[i];
1746        if (relative->getZ() >= 0) {
1747            break;
1748        }
1749        relative->traverseChildrenInZOrder(stateSet, visitor);
1750    }
1751    visitor(this);
1752    for (; i < children.size(); i++) {
1753        const auto& relative = children[i];
1754        relative->traverseChildrenInZOrder(stateSet, visitor);
1755    }
1756}
1757
1758Transform Layer::getTransform() const {
1759    Transform t;
1760    const auto& p = mDrawingParent.promote();
1761    if (p != nullptr) {
1762        t = p->getTransform();
1763
1764        // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
1765        // it isFixedSize) then there may be additional scaling not accounted
1766        // for in the transform. We need to mirror this scaling in child surfaces
1767        // or we will break the contract where WM can treat child surfaces as
1768        // pixels in the parent surface.
1769        if (p->isFixedSize() && p->getBE().mBuffer != nullptr) {
1770            int bufferWidth;
1771            int bufferHeight;
1772            if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
1773                bufferWidth = p->getBE().mBuffer->getWidth();
1774                bufferHeight = p->getBE().mBuffer->getHeight();
1775            } else {
1776                bufferHeight = p->getBE().mBuffer->getWidth();
1777                bufferWidth = p->getBE().mBuffer->getHeight();
1778            }
1779            float sx = p->getDrawingState().active.w / static_cast<float>(bufferWidth);
1780            float sy = p->getDrawingState().active.h / static_cast<float>(bufferHeight);
1781            Transform extraParentScaling;
1782            extraParentScaling.set(sx, 0, 0, sy);
1783            t = t * extraParentScaling;
1784        }
1785    }
1786    return t * getDrawingState().active.transform;
1787}
1788
1789half Layer::getAlpha() const {
1790    const auto& p = mDrawingParent.promote();
1791
1792    half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1793    return parentAlpha * getDrawingState().color.a;
1794}
1795
1796half4 Layer::getColor() const {
1797    const half4 color(getDrawingState().color);
1798    return half4(color.r, color.g, color.b, getAlpha());
1799}
1800
1801void Layer::commitChildList() {
1802    for (size_t i = 0; i < mCurrentChildren.size(); i++) {
1803        const auto& child = mCurrentChildren[i];
1804        child->commitChildList();
1805    }
1806    mDrawingChildren = mCurrentChildren;
1807    mDrawingParent = mCurrentParent;
1808}
1809
1810void Layer::writeToProto(LayerProto* layerInfo, LayerVector::StateSet stateSet) {
1811    const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1812    const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1813    const State& state = useDrawing ? mDrawingState : mCurrentState;
1814
1815    Transform requestedTransform = state.active.transform;
1816    Transform transform = getTransform();
1817
1818    layerInfo->set_id(sequence);
1819    layerInfo->set_name(getName().c_str());
1820    layerInfo->set_type(String8(getTypeId()));
1821
1822    for (const auto& child : children) {
1823        layerInfo->add_children(child->sequence);
1824    }
1825
1826    for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1827        sp<Layer> strongRelative = weakRelative.promote();
1828        if (strongRelative != nullptr) {
1829            layerInfo->add_relatives(strongRelative->sequence);
1830        }
1831    }
1832
1833    LayerProtoHelper::writeToProto(state.activeTransparentRegion,
1834                                   layerInfo->mutable_transparent_region());
1835    LayerProtoHelper::writeToProto(visibleRegion, layerInfo->mutable_visible_region());
1836    LayerProtoHelper::writeToProto(surfaceDamageRegion, layerInfo->mutable_damage_region());
1837
1838    layerInfo->set_layer_stack(getLayerStack());
1839    layerInfo->set_z(state.z);
1840
1841    PositionProto* position = layerInfo->mutable_position();
1842    position->set_x(transform.tx());
1843    position->set_y(transform.ty());
1844
1845    PositionProto* requestedPosition = layerInfo->mutable_requested_position();
1846    requestedPosition->set_x(requestedTransform.tx());
1847    requestedPosition->set_y(requestedTransform.ty());
1848
1849    SizeProto* size = layerInfo->mutable_size();
1850    size->set_w(state.active.w);
1851    size->set_h(state.active.h);
1852
1853    LayerProtoHelper::writeToProto(state.crop, layerInfo->mutable_crop());
1854    LayerProtoHelper::writeToProto(state.finalCrop, layerInfo->mutable_final_crop());
1855
1856    layerInfo->set_is_opaque(isOpaque(state));
1857    layerInfo->set_invalidate(contentDirty);
1858    layerInfo->set_dataspace(dataspaceDetails(getDataSpace()));
1859    layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
1860    LayerProtoHelper::writeToProto(getColor(), layerInfo->mutable_color());
1861    LayerProtoHelper::writeToProto(state.color, layerInfo->mutable_requested_color());
1862    layerInfo->set_flags(state.flags);
1863
1864    LayerProtoHelper::writeToProto(transform, layerInfo->mutable_transform());
1865    LayerProtoHelper::writeToProto(requestedTransform, layerInfo->mutable_requested_transform());
1866
1867    auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1868    if (parent != nullptr) {
1869        layerInfo->set_parent(parent->sequence);
1870    }
1871
1872    auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
1873    if (zOrderRelativeOf != nullptr) {
1874        layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
1875    }
1876
1877    auto buffer = getBE().mBuffer;
1878    if (buffer != nullptr) {
1879        LayerProtoHelper::writeToProto(buffer, layerInfo->mutable_active_buffer());
1880    }
1881
1882    layerInfo->set_queued_frames(getQueuedFrameCount());
1883    layerInfo->set_refresh_pending(isBufferLatched());
1884}
1885
1886// ---------------------------------------------------------------------------
1887
1888}; // namespace android
1889
1890#if defined(__gl_h_)
1891#error "don't include gl/gl.h in this file"
1892#endif
1893
1894#if defined(__gl2_h_)
1895#error "don't include gl2/gl2.h in this file"
1896#endif
1897