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 "Layer.h"
23
24 #include <android-base/stringprintf.h>
25 #include <compositionengine/Display.h>
26 #include <compositionengine/Layer.h>
27 #include <compositionengine/LayerFECompositionState.h>
28 #include <compositionengine/OutputLayer.h>
29 #include <compositionengine/impl/LayerCompositionState.h>
30 #include <compositionengine/impl/OutputLayerCompositionState.h>
31 #include <cutils/compiler.h>
32 #include <cutils/native_handle.h>
33 #include <cutils/properties.h>
34 #include <gui/BufferItem.h>
35 #include <gui/LayerDebugInfo.h>
36 #include <gui/Surface.h>
37 #include <math.h>
38 #include <renderengine/RenderEngine.h>
39 #include <stdint.h>
40 #include <stdlib.h>
41 #include <sys/types.h>
42 #include <ui/DebugUtils.h>
43 #include <ui/GraphicBuffer.h>
44 #include <ui/PixelFormat.h>
45 #include <utils/Errors.h>
46 #include <utils/Log.h>
47 #include <utils/NativeHandle.h>
48 #include <utils/StopWatch.h>
49 #include <utils/Trace.h>
50
51 #include <algorithm>
52 #include <mutex>
53 #include <sstream>
54
55 #include "BufferLayer.h"
56 #include "ColorLayer.h"
57 #include "Colorizer.h"
58 #include "DisplayDevice.h"
59 #include "DisplayHardware/HWComposer.h"
60 #include "LayerProtoHelper.h"
61 #include "LayerRejecter.h"
62 #include "MonitoredProducer.h"
63 #include "SurfaceFlinger.h"
64 #include "TimeStats/TimeStats.h"
65
66 #define DEBUG_RESIZE 0
67
68 namespace android {
69
70 using base::StringAppendF;
71
72 std::atomic<int32_t> Layer::sSequence{1};
73
Layer(const LayerCreationArgs & args)74 Layer::Layer(const LayerCreationArgs& args)
75 : mFlinger(args.flinger),
76 mName(args.name),
77 mClientRef(args.client),
78 mWindowType(args.metadata.getInt32(METADATA_WINDOW_TYPE, 0)) {
79 mCurrentCrop.makeInvalid();
80
81 uint32_t layerFlags = 0;
82 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
83 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
84 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
85
86 mTransactionName = String8("TX - ") + mName;
87
88 mCurrentState.active_legacy.w = args.w;
89 mCurrentState.active_legacy.h = args.h;
90 mCurrentState.flags = layerFlags;
91 mCurrentState.active_legacy.transform.set(0, 0);
92 mCurrentState.crop_legacy.makeInvalid();
93 mCurrentState.requestedCrop_legacy = mCurrentState.crop_legacy;
94 mCurrentState.z = 0;
95 mCurrentState.color.a = 1.0f;
96 mCurrentState.layerStack = 0;
97 mCurrentState.sequence = 0;
98 mCurrentState.requested_legacy = mCurrentState.active_legacy;
99 mCurrentState.active.w = UINT32_MAX;
100 mCurrentState.active.h = UINT32_MAX;
101 mCurrentState.active.transform.set(0, 0);
102 mCurrentState.transform = 0;
103 mCurrentState.transformToDisplayInverse = false;
104 mCurrentState.crop.makeInvalid();
105 mCurrentState.acquireFence = new Fence(-1);
106 mCurrentState.dataspace = ui::Dataspace::UNKNOWN;
107 mCurrentState.hdrMetadata.validTypes = 0;
108 mCurrentState.surfaceDamageRegion.clear();
109 mCurrentState.cornerRadius = 0.0f;
110 mCurrentState.api = -1;
111 mCurrentState.hasColorTransform = false;
112 mCurrentState.colorSpaceAgnostic = false;
113 mCurrentState.metadata = args.metadata;
114
115 // drawing state & current state are identical
116 mDrawingState = mCurrentState;
117
118 CompositorTiming compositorTiming;
119 args.flinger->getCompositorTiming(&compositorTiming);
120 mFrameEventHistory.initializeCompositorTiming(compositorTiming);
121 mFrameTracker.setDisplayRefreshPeriod(compositorTiming.interval);
122
123 mSchedulerLayerHandle = mFlinger->mScheduler->registerLayer(mName.c_str(), mWindowType);
124
125 mFlinger->onLayerCreated();
126 }
127
~Layer()128 Layer::~Layer() {
129 sp<Client> c(mClientRef.promote());
130 if (c != 0) {
131 c->detachLayer(this);
132 }
133
134 mFrameTracker.logAndResetStats(mName);
135 mFlinger->onLayerDestroyed(this);
136 }
137
138 // ---------------------------------------------------------------------------
139 // callbacks
140 // ---------------------------------------------------------------------------
141
142 /*
143 * onLayerDisplayed is only meaningful for BufferLayer, but, is called through
144 * Layer. So, the implementation is done in BufferLayer. When called on a
145 * ColorLayer object, it's essentially a NOP.
146 */
onLayerDisplayed(const sp<Fence> &)147 void Layer::onLayerDisplayed(const sp<Fence>& /*releaseFence*/) {}
148
removeRemoteSyncPoints()149 void Layer::removeRemoteSyncPoints() {
150 for (auto& point : mRemoteSyncPoints) {
151 point->setTransactionApplied();
152 }
153 mRemoteSyncPoints.clear();
154
155 {
156 for (State pendingState : mPendingStates) {
157 pendingState.barrierLayer_legacy = nullptr;
158 }
159 }
160 }
161
removeRelativeZ(const std::vector<Layer * > & layersInTree)162 void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
163 if (mCurrentState.zOrderRelativeOf == nullptr) {
164 return;
165 }
166
167 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
168 if (strongRelative == nullptr) {
169 setZOrderRelativeOf(nullptr);
170 return;
171 }
172
173 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
174 strongRelative->removeZOrderRelative(this);
175 mFlinger->setTransactionFlags(eTraversalNeeded);
176 setZOrderRelativeOf(nullptr);
177 }
178 }
179
removeFromCurrentState()180 void Layer::removeFromCurrentState() {
181 mRemovedFromCurrentState = true;
182
183 // Since we are no longer reachable from CurrentState SurfaceFlinger
184 // will no longer invoke doTransaction for us, and so we will
185 // never finish applying transactions. We signal the sync point
186 // now so that another layer will not become indefinitely
187 // blocked.
188 removeRemoteSyncPoints();
189
190 {
191 Mutex::Autolock syncLock(mLocalSyncPointMutex);
192 for (auto& point : mLocalSyncPoints) {
193 point->setFrameAvailable();
194 }
195 mLocalSyncPoints.clear();
196 }
197
198 mFlinger->markLayerPendingRemovalLocked(this);
199 }
200
onRemovedFromCurrentState()201 void Layer::onRemovedFromCurrentState() {
202 auto layersInTree = getLayersInTree(LayerVector::StateSet::Current);
203 std::sort(layersInTree.begin(), layersInTree.end());
204 for (const auto& layer : layersInTree) {
205 layer->removeFromCurrentState();
206 layer->removeRelativeZ(layersInTree);
207 }
208 }
209
addToCurrentState()210 void Layer::addToCurrentState() {
211 mRemovedFromCurrentState = false;
212
213 for (const auto& child : mCurrentChildren) {
214 child->addToCurrentState();
215 }
216 }
217
218 // ---------------------------------------------------------------------------
219 // set-up
220 // ---------------------------------------------------------------------------
221
getName() const222 const String8& Layer::getName() const {
223 return mName;
224 }
225
getPremultipledAlpha() const226 bool Layer::getPremultipledAlpha() const {
227 return mPremultipliedAlpha;
228 }
229
getHandle()230 sp<IBinder> Layer::getHandle() {
231 Mutex::Autolock _l(mLock);
232 if (mGetHandleCalled) {
233 ALOGE("Get handle called twice" );
234 return nullptr;
235 }
236 mGetHandleCalled = true;
237 return new Handle(mFlinger, this);
238 }
239
240 // ---------------------------------------------------------------------------
241 // h/w composer set-up
242 // ---------------------------------------------------------------------------
243
hasHwcLayer(const sp<const DisplayDevice> & displayDevice)244 bool Layer::hasHwcLayer(const sp<const DisplayDevice>& displayDevice) {
245 auto outputLayer = findOutputLayerForDisplay(displayDevice);
246 LOG_FATAL_IF(!outputLayer);
247 return outputLayer->getState().hwc && (*outputLayer->getState().hwc).hwcLayer != nullptr;
248 }
249
getHwcLayer(const sp<const DisplayDevice> & displayDevice)250 HWC2::Layer* Layer::getHwcLayer(const sp<const DisplayDevice>& displayDevice) {
251 auto outputLayer = findOutputLayerForDisplay(displayDevice);
252 if (!outputLayer || !outputLayer->getState().hwc) {
253 return nullptr;
254 }
255 return (*outputLayer->getState().hwc).hwcLayer.get();
256 }
257
getContentCrop() const258 Rect Layer::getContentCrop() const {
259 // this is the crop rectangle that applies to the buffer
260 // itself (as opposed to the window)
261 Rect crop;
262 if (!mCurrentCrop.isEmpty()) {
263 // if the buffer crop is defined, we use that
264 crop = mCurrentCrop;
265 } else if (mActiveBuffer != nullptr) {
266 // otherwise we use the whole buffer
267 crop = mActiveBuffer->getBounds();
268 } else {
269 // if we don't have a buffer yet, we use an empty/invalid crop
270 crop.makeInvalid();
271 }
272 return crop;
273 }
274
reduce(const Rect & win,const Region & exclude)275 static Rect reduce(const Rect& win, const Region& exclude) {
276 if (CC_LIKELY(exclude.isEmpty())) {
277 return win;
278 }
279 if (exclude.isRect()) {
280 return win.reduce(exclude.getBounds());
281 }
282 return Region(win).subtract(exclude).getBounds();
283 }
284
reduce(const FloatRect & win,const Region & exclude)285 static FloatRect reduce(const FloatRect& win, const Region& exclude) {
286 if (CC_LIKELY(exclude.isEmpty())) {
287 return win;
288 }
289 // Convert through Rect (by rounding) for lack of FloatRegion
290 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
291 }
292
getScreenBounds(bool reduceTransparentRegion) const293 Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
294 if (!reduceTransparentRegion) {
295 return Rect{mScreenBounds};
296 }
297
298 FloatRect bounds = getBounds();
299 ui::Transform t = getTransform();
300 // Transform to screen space.
301 bounds = t.transform(bounds);
302 return Rect{bounds};
303 }
304
getBounds() const305 FloatRect Layer::getBounds() const {
306 const State& s(getDrawingState());
307 return getBounds(getActiveTransparentRegion(s));
308 }
309
getBounds(const Region & activeTransparentRegion) const310 FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
311 // Subtract the transparent region and snap to the bounds.
312 return reduce(mBounds, activeTransparentRegion);
313 }
314
getBufferScaleTransform() const315 ui::Transform Layer::getBufferScaleTransform() const {
316 // If the layer is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
317 // it isFixedSize) then there may be additional scaling not accounted
318 // for in the layer transform.
319 if (!isFixedSize() || !mActiveBuffer) {
320 return {};
321 }
322
323 // If the layer is a buffer state layer, the active width and height
324 // could be infinite. In that case, return the effective transform.
325 const uint32_t activeWidth = getActiveWidth(getDrawingState());
326 const uint32_t activeHeight = getActiveHeight(getDrawingState());
327 if (activeWidth >= UINT32_MAX && activeHeight >= UINT32_MAX) {
328 return {};
329 }
330
331 int bufferWidth = mActiveBuffer->getWidth();
332 int bufferHeight = mActiveBuffer->getHeight();
333
334 if (mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
335 std::swap(bufferWidth, bufferHeight);
336 }
337
338 float sx = activeWidth / static_cast<float>(bufferWidth);
339 float sy = activeHeight / static_cast<float>(bufferHeight);
340
341 ui::Transform extraParentScaling;
342 extraParentScaling.set(sx, 0, 0, sy);
343 return extraParentScaling;
344 }
345
getTransformWithScale(const ui::Transform & bufferScaleTransform) const346 ui::Transform Layer::getTransformWithScale(const ui::Transform& bufferScaleTransform) const {
347 // We need to mirror this scaling to child surfaces or we will break the contract where WM can
348 // treat child surfaces as pixels in the parent surface.
349 if (!isFixedSize() || !mActiveBuffer) {
350 return mEffectiveTransform;
351 }
352 return mEffectiveTransform * bufferScaleTransform;
353 }
354
getBoundsPreScaling(const ui::Transform & bufferScaleTransform) const355 FloatRect Layer::getBoundsPreScaling(const ui::Transform& bufferScaleTransform) const {
356 // We need the pre scaled layer bounds when computing child bounds to make sure the child is
357 // cropped to its parent layer after any buffer transform scaling is applied.
358 if (!isFixedSize() || !mActiveBuffer) {
359 return mBounds;
360 }
361 return bufferScaleTransform.inverse().transform(mBounds);
362 }
363
computeBounds(FloatRect parentBounds,ui::Transform parentTransform)364 void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform) {
365 const State& s(getDrawingState());
366
367 // Calculate effective layer transform
368 mEffectiveTransform = parentTransform * getActiveTransform(s);
369
370 // Transform parent bounds to layer space
371 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
372
373 // Calculate source bounds
374 mSourceBounds = computeSourceBounds(parentBounds);
375
376 // Calculate bounds by croping diplay frame with layer crop and parent bounds
377 FloatRect bounds = mSourceBounds;
378 const Rect layerCrop = getCrop(s);
379 if (!layerCrop.isEmpty()) {
380 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
381 }
382 bounds = bounds.intersect(parentBounds);
383
384 mBounds = bounds;
385 mScreenBounds = mEffectiveTransform.transform(mBounds);
386
387 // Add any buffer scaling to the layer's children.
388 ui::Transform bufferScaleTransform = getBufferScaleTransform();
389 for (const sp<Layer>& child : mDrawingChildren) {
390 child->computeBounds(getBoundsPreScaling(bufferScaleTransform),
391 getTransformWithScale(bufferScaleTransform));
392 }
393 }
394
getCroppedBufferSize(const State & s) const395 Rect Layer::getCroppedBufferSize(const State& s) const {
396 Rect size = getBufferSize(s);
397 Rect crop = getCrop(s);
398 if (!crop.isEmpty() && size.isValid()) {
399 size.intersect(crop, &size);
400 } else if (!crop.isEmpty()) {
401 size = crop;
402 }
403 return size;
404 }
405
setupRoundedCornersCropCoordinates(Rect win,const FloatRect & roundedCornersCrop) const406 void Layer::setupRoundedCornersCropCoordinates(Rect win,
407 const FloatRect& roundedCornersCrop) const {
408 // Translate win by the rounded corners rect coordinates, to have all values in
409 // layer coordinate space.
410 win.left -= roundedCornersCrop.left;
411 win.right -= roundedCornersCrop.left;
412 win.top -= roundedCornersCrop.top;
413 win.bottom -= roundedCornersCrop.top;
414 }
415
latchGeometry(compositionengine::LayerFECompositionState & compositionState) const416 void Layer::latchGeometry(compositionengine::LayerFECompositionState& compositionState) const {
417 const auto& drawingState{getDrawingState()};
418 auto alpha = static_cast<float>(getAlpha());
419 auto blendMode = HWC2::BlendMode::None;
420 if (!isOpaque(drawingState) || alpha != 1.0f) {
421 blendMode =
422 mPremultipliedAlpha ? HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
423 }
424
425 int type = drawingState.metadata.getInt32(METADATA_WINDOW_TYPE, 0);
426 int appId = drawingState.metadata.getInt32(METADATA_OWNER_UID, 0);
427 sp<Layer> parent = mDrawingParent.promote();
428 if (parent.get()) {
429 auto& parentState = parent->getDrawingState();
430 const int parentType = parentState.metadata.getInt32(METADATA_WINDOW_TYPE, 0);
431 const int parentAppId = parentState.metadata.getInt32(METADATA_OWNER_UID, 0);
432 if (parentType >= 0 || parentAppId >= 0) {
433 type = parentType;
434 appId = parentAppId;
435 }
436 }
437
438 compositionState.geomLayerTransform = getTransform();
439 compositionState.geomInverseLayerTransform = compositionState.geomLayerTransform.inverse();
440 compositionState.geomBufferSize = getBufferSize(drawingState);
441 compositionState.geomContentCrop = getContentCrop();
442 compositionState.geomCrop = getCrop(drawingState);
443 compositionState.geomBufferTransform = mCurrentTransform;
444 compositionState.geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
445 compositionState.geomActiveTransparentRegion = getActiveTransparentRegion(drawingState);
446 compositionState.geomLayerBounds = mBounds;
447 compositionState.geomUsesSourceCrop = usesSourceCrop();
448 compositionState.isSecure = isSecure();
449
450 compositionState.blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
451 compositionState.alpha = alpha;
452 compositionState.type = type;
453 compositionState.appId = appId;
454 }
455
latchCompositionState(compositionengine::LayerFECompositionState & compositionState,bool includeGeometry) const456 void Layer::latchCompositionState(compositionengine::LayerFECompositionState& compositionState,
457 bool includeGeometry) const {
458 if (includeGeometry) {
459 latchGeometry(compositionState);
460 }
461 }
462
getDebugName() const463 const char* Layer::getDebugName() const {
464 return mName.string();
465 }
466
forceClientComposition(const sp<DisplayDevice> & display)467 void Layer::forceClientComposition(const sp<DisplayDevice>& display) {
468 const auto outputLayer = findOutputLayerForDisplay(display);
469 LOG_FATAL_IF(!outputLayer);
470 outputLayer->editState().forceClientComposition = true;
471 }
472
getForceClientComposition(const sp<DisplayDevice> & display)473 bool Layer::getForceClientComposition(const sp<DisplayDevice>& display) {
474 const auto outputLayer = findOutputLayerForDisplay(display);
475 LOG_FATAL_IF(!outputLayer);
476 return outputLayer->getState().forceClientComposition;
477 }
478
updateCursorPosition(const sp<const DisplayDevice> & display)479 void Layer::updateCursorPosition(const sp<const DisplayDevice>& display) {
480 const auto outputLayer = findOutputLayerForDisplay(display);
481 LOG_FATAL_IF(!outputLayer);
482
483 if (!outputLayer->getState().hwc ||
484 (*outputLayer->getState().hwc).hwcCompositionType !=
485 Hwc2::IComposerClient::Composition::CURSOR) {
486 return;
487 }
488
489 // This gives us only the "orientation" component of the transform
490 const State& s(getDrawingState());
491
492 // Apply the layer's transform, followed by the display's global transform
493 // Here we're guaranteed that the layer's transform preserves rects
494 Rect win = getCroppedBufferSize(s);
495 // Subtract the transparent region and snap to the bounds
496 Rect bounds = reduce(win, getActiveTransparentRegion(s));
497 Rect frame(getTransform().transform(bounds));
498 frame.intersect(display->getViewport(), &frame);
499 auto& displayTransform = display->getTransform();
500 auto position = displayTransform.transform(frame);
501
502 auto error =
503 (*outputLayer->getState().hwc).hwcLayer->setCursorPosition(position.left, position.top);
504 ALOGE_IF(error != HWC2::Error::None,
505 "[%s] Failed to set cursor position "
506 "to (%d, %d): %s (%d)",
507 mName.string(), position.left, position.top, to_string(error).c_str(),
508 static_cast<int32_t>(error));
509 }
510
511 // ---------------------------------------------------------------------------
512 // drawing...
513 // ---------------------------------------------------------------------------
514
prepareClientLayer(const RenderArea & renderArea,const Region & clip,Region & clearRegion,const bool supportProtectedContent,renderengine::LayerSettings & layer)515 bool Layer::prepareClientLayer(const RenderArea& renderArea, const Region& clip,
516 Region& clearRegion, const bool supportProtectedContent,
517 renderengine::LayerSettings& layer) {
518 return prepareClientLayer(renderArea, clip, false, clearRegion, supportProtectedContent, layer);
519 }
520
prepareClientLayer(const RenderArea & renderArea,bool useIdentityTransform,Region & clearRegion,const bool supportProtectedContent,renderengine::LayerSettings & layer)521 bool Layer::prepareClientLayer(const RenderArea& renderArea, bool useIdentityTransform,
522 Region& clearRegion, const bool supportProtectedContent,
523 renderengine::LayerSettings& layer) {
524 return prepareClientLayer(renderArea, Region(renderArea.getBounds()), useIdentityTransform,
525 clearRegion, supportProtectedContent, layer);
526 }
527
prepareClientLayer(const RenderArea &,const Region &,bool useIdentityTransform,Region &,const bool,renderengine::LayerSettings & layer)528 bool Layer::prepareClientLayer(const RenderArea& /*renderArea*/, const Region& /*clip*/,
529 bool useIdentityTransform, Region& /*clearRegion*/,
530 const bool /*supportProtectedContent*/,
531 renderengine::LayerSettings& layer) {
532 FloatRect bounds = getBounds();
533 half alpha = getAlpha();
534 layer.geometry.boundaries = bounds;
535 if (useIdentityTransform) {
536 layer.geometry.positionTransform = mat4();
537 } else {
538 const ui::Transform transform = getTransform();
539 mat4 m;
540 m[0][0] = transform[0][0];
541 m[0][1] = transform[0][1];
542 m[0][3] = transform[0][2];
543 m[1][0] = transform[1][0];
544 m[1][1] = transform[1][1];
545 m[1][3] = transform[1][2];
546 m[3][0] = transform[2][0];
547 m[3][1] = transform[2][1];
548 m[3][3] = transform[2][2];
549 layer.geometry.positionTransform = m;
550 }
551
552 if (hasColorTransform()) {
553 layer.colorTransform = getColorTransform();
554 }
555
556 const auto roundedCornerState = getRoundedCornerState();
557 layer.geometry.roundedCornersRadius = roundedCornerState.radius;
558 layer.geometry.roundedCornersCrop = roundedCornerState.cropRect;
559
560 layer.alpha = alpha;
561 layer.sourceDataspace = mCurrentDataSpace;
562 return true;
563 }
564
setCompositionType(const sp<const DisplayDevice> & display,Hwc2::IComposerClient::Composition type)565 void Layer::setCompositionType(const sp<const DisplayDevice>& display,
566 Hwc2::IComposerClient::Composition type) {
567 const auto outputLayer = findOutputLayerForDisplay(display);
568 LOG_FATAL_IF(!outputLayer);
569 LOG_FATAL_IF(!outputLayer->getState().hwc);
570 auto& compositionState = outputLayer->editState();
571
572 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", ((*compositionState.hwc).hwcLayer)->getId(),
573 toString(type).c_str(), 1);
574 if ((*compositionState.hwc).hwcCompositionType != type) {
575 ALOGV(" actually setting");
576 (*compositionState.hwc).hwcCompositionType = type;
577
578 auto error = (*compositionState.hwc)
579 .hwcLayer->setCompositionType(static_cast<HWC2::Composition>(type));
580 ALOGE_IF(error != HWC2::Error::None,
581 "[%s] Failed to set "
582 "composition type %s: %s (%d)",
583 mName.string(), toString(type).c_str(), to_string(error).c_str(),
584 static_cast<int32_t>(error));
585 }
586 }
587
getCompositionType(const sp<const DisplayDevice> & display) const588 Hwc2::IComposerClient::Composition Layer::getCompositionType(
589 const sp<const DisplayDevice>& display) const {
590 const auto outputLayer = findOutputLayerForDisplay(display);
591 LOG_FATAL_IF(!outputLayer);
592 return outputLayer->getState().hwc ? (*outputLayer->getState().hwc).hwcCompositionType
593 : Hwc2::IComposerClient::Composition::CLIENT;
594 }
595
getClearClientTarget(const sp<const DisplayDevice> & display) const596 bool Layer::getClearClientTarget(const sp<const DisplayDevice>& display) const {
597 const auto outputLayer = findOutputLayerForDisplay(display);
598 LOG_FATAL_IF(!outputLayer);
599 return outputLayer->getState().clearClientTarget;
600 }
601
addSyncPoint(const std::shared_ptr<SyncPoint> & point)602 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
603 if (point->getFrameNumber() <= mCurrentFrameNumber) {
604 // Don't bother with a SyncPoint, since we've already latched the
605 // relevant frame
606 return false;
607 }
608 if (isRemovedFromCurrentState()) {
609 return false;
610 }
611
612 Mutex::Autolock lock(mLocalSyncPointMutex);
613 mLocalSyncPoints.push_back(point);
614 return true;
615 }
616
617 // ----------------------------------------------------------------------------
618 // local state
619 // ----------------------------------------------------------------------------
620
computeGeometry(const RenderArea & renderArea,renderengine::Mesh & mesh,bool useIdentityTransform) const621 void Layer::computeGeometry(const RenderArea& renderArea,
622 renderengine::Mesh& mesh,
623 bool useIdentityTransform) const {
624 const ui::Transform renderAreaTransform(renderArea.getTransform());
625 FloatRect win = getBounds();
626
627 vec2 lt = vec2(win.left, win.top);
628 vec2 lb = vec2(win.left, win.bottom);
629 vec2 rb = vec2(win.right, win.bottom);
630 vec2 rt = vec2(win.right, win.top);
631
632 ui::Transform layerTransform = getTransform();
633 if (!useIdentityTransform) {
634 lt = layerTransform.transform(lt);
635 lb = layerTransform.transform(lb);
636 rb = layerTransform.transform(rb);
637 rt = layerTransform.transform(rt);
638 }
639
640 renderengine::Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
641 position[0] = renderAreaTransform.transform(lt);
642 position[1] = renderAreaTransform.transform(lb);
643 position[2] = renderAreaTransform.transform(rb);
644 position[3] = renderAreaTransform.transform(rt);
645 }
646
isSecure() const647 bool Layer::isSecure() const {
648 const State& s(mDrawingState);
649 return (s.flags & layer_state_t::eLayerSecure);
650 }
651
setVisibleRegion(const Region & visibleRegion)652 void Layer::setVisibleRegion(const Region& visibleRegion) {
653 // always called from main thread
654 this->visibleRegion = visibleRegion;
655 }
656
setCoveredRegion(const Region & coveredRegion)657 void Layer::setCoveredRegion(const Region& coveredRegion) {
658 // always called from main thread
659 this->coveredRegion = coveredRegion;
660 }
661
setVisibleNonTransparentRegion(const Region & setVisibleNonTransparentRegion)662 void Layer::setVisibleNonTransparentRegion(const Region& setVisibleNonTransparentRegion) {
663 // always called from main thread
664 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
665 }
666
clearVisibilityRegions()667 void Layer::clearVisibilityRegions() {
668 visibleRegion.clear();
669 visibleNonTransparentRegion.clear();
670 coveredRegion.clear();
671 }
672
673 // ----------------------------------------------------------------------------
674 // transaction
675 // ----------------------------------------------------------------------------
676
pushPendingState()677 void Layer::pushPendingState() {
678 if (!mCurrentState.modified) {
679 return;
680 }
681 ATRACE_CALL();
682
683 // If this transaction is waiting on the receipt of a frame, generate a sync
684 // point and send it to the remote layer.
685 // We don't allow installing sync points after we are removed from the current state
686 // as we won't be able to signal our end.
687 if (mCurrentState.barrierLayer_legacy != nullptr && !isRemovedFromCurrentState()) {
688 sp<Layer> barrierLayer = mCurrentState.barrierLayer_legacy.promote();
689 if (barrierLayer == nullptr) {
690 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
691 // If we can't promote the layer we are intended to wait on,
692 // then it is expired or otherwise invalid. Allow this transaction
693 // to be applied as per normal (no synchronization).
694 mCurrentState.barrierLayer_legacy = nullptr;
695 } else {
696 auto syncPoint = std::make_shared<SyncPoint>(mCurrentState.frameNumber_legacy, this);
697 if (barrierLayer->addSyncPoint(syncPoint)) {
698 std::stringstream ss;
699 ss << "Adding sync point " << mCurrentState.frameNumber_legacy;
700 ATRACE_NAME(ss.str().c_str());
701 mRemoteSyncPoints.push_back(std::move(syncPoint));
702 } else {
703 // We already missed the frame we're supposed to synchronize
704 // on, so go ahead and apply the state update
705 mCurrentState.barrierLayer_legacy = nullptr;
706 }
707 }
708
709 // Wake us up to check if the frame has been received
710 setTransactionFlags(eTransactionNeeded);
711 mFlinger->setTransactionFlags(eTraversalNeeded);
712 }
713 mPendingStates.push_back(mCurrentState);
714 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
715 }
716
popPendingState(State * stateToCommit)717 void Layer::popPendingState(State* stateToCommit) {
718 ATRACE_CALL();
719 *stateToCommit = mPendingStates[0];
720
721 mPendingStates.removeAt(0);
722 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
723 }
724
applyPendingStates(State * stateToCommit)725 bool Layer::applyPendingStates(State* stateToCommit) {
726 bool stateUpdateAvailable = false;
727 while (!mPendingStates.empty()) {
728 if (mPendingStates[0].barrierLayer_legacy != nullptr) {
729 if (mRemoteSyncPoints.empty()) {
730 // If we don't have a sync point for this, apply it anyway. It
731 // will be visually wrong, but it should keep us from getting
732 // into too much trouble.
733 ALOGE("[%s] No local sync point found", mName.string());
734 popPendingState(stateToCommit);
735 stateUpdateAvailable = true;
736 continue;
737 }
738
739 if (mRemoteSyncPoints.front()->getFrameNumber() !=
740 mPendingStates[0].frameNumber_legacy) {
741 ALOGE("[%s] Unexpected sync point frame number found", mName.string());
742
743 // Signal our end of the sync point and then dispose of it
744 mRemoteSyncPoints.front()->setTransactionApplied();
745 mRemoteSyncPoints.pop_front();
746 continue;
747 }
748
749 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
750 ATRACE_NAME("frameIsAvailable");
751 // Apply the state update
752 popPendingState(stateToCommit);
753 stateUpdateAvailable = true;
754
755 // Signal our end of the sync point and then dispose of it
756 mRemoteSyncPoints.front()->setTransactionApplied();
757 mRemoteSyncPoints.pop_front();
758 } else {
759 ATRACE_NAME("!frameIsAvailable");
760 break;
761 }
762 } else {
763 popPendingState(stateToCommit);
764 stateUpdateAvailable = true;
765 }
766 }
767
768 // If we still have pending updates, wake SurfaceFlinger back up and point
769 // it at this layer so we can process them
770 if (!mPendingStates.empty()) {
771 setTransactionFlags(eTransactionNeeded);
772 mFlinger->setTransactionFlags(eTraversalNeeded);
773 }
774
775 mCurrentState.modified = false;
776 return stateUpdateAvailable;
777 }
778
doTransactionResize(uint32_t flags,State * stateToCommit)779 uint32_t Layer::doTransactionResize(uint32_t flags, State* stateToCommit) {
780 const State& s(getDrawingState());
781
782 const bool sizeChanged = (stateToCommit->requested_legacy.w != s.requested_legacy.w) ||
783 (stateToCommit->requested_legacy.h != s.requested_legacy.h);
784
785 if (sizeChanged) {
786 // the size changed, we need to ask our client to request a new buffer
787 ALOGD_IF(DEBUG_RESIZE,
788 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
789 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
790 " requested={ wh={%4u,%4u} }}\n"
791 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
792 " requested={ wh={%4u,%4u} }}\n",
793 this, getName().string(), mCurrentTransform, getEffectiveScalingMode(),
794 stateToCommit->active_legacy.w, stateToCommit->active_legacy.h,
795 stateToCommit->crop_legacy.left, stateToCommit->crop_legacy.top,
796 stateToCommit->crop_legacy.right, stateToCommit->crop_legacy.bottom,
797 stateToCommit->crop_legacy.getWidth(), stateToCommit->crop_legacy.getHeight(),
798 stateToCommit->requested_legacy.w, stateToCommit->requested_legacy.h,
799 s.active_legacy.w, s.active_legacy.h, s.crop_legacy.left, s.crop_legacy.top,
800 s.crop_legacy.right, s.crop_legacy.bottom, s.crop_legacy.getWidth(),
801 s.crop_legacy.getHeight(), s.requested_legacy.w, s.requested_legacy.h);
802 }
803
804 // Don't let Layer::doTransaction update the drawing state
805 // if we have a pending resize, unless we are in fixed-size mode.
806 // the drawing state will be updated only once we receive a buffer
807 // with the correct size.
808 //
809 // In particular, we want to make sure the clip (which is part
810 // of the geometry state) is latched together with the size but is
811 // latched immediately when no resizing is involved.
812 //
813 // If a sideband stream is attached, however, we want to skip this
814 // optimization so that transactions aren't missed when a buffer
815 // never arrives
816 //
817 // In the case that we don't have a buffer we ignore other factors
818 // and avoid entering the resizePending state. At a high level the
819 // resizePending state is to avoid applying the state of the new buffer
820 // to the old buffer. However in the state where we don't have an old buffer
821 // there is no such concern but we may still be being used as a parent layer.
822 const bool resizePending =
823 ((stateToCommit->requested_legacy.w != stateToCommit->active_legacy.w) ||
824 (stateToCommit->requested_legacy.h != stateToCommit->active_legacy.h)) &&
825 (mActiveBuffer != nullptr);
826 if (!isFixedSize()) {
827 if (resizePending && mSidebandStream == nullptr) {
828 flags |= eDontUpdateGeometryState;
829 }
830 }
831
832 // Here we apply various requested geometry states, depending on our
833 // latching configuration. See Layer.h for a detailed discussion of
834 // how geometry latching is controlled.
835 if (!(flags & eDontUpdateGeometryState)) {
836 State& editCurrentState(getCurrentState());
837
838 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
839 // mode, which causes attributes which normally latch regardless of scaling mode,
840 // to be delayed. We copy the requested state to the active state making sure
841 // to respect these rules (again see Layer.h for a detailed discussion).
842 //
843 // There is an awkward asymmetry in the handling of the crop states in the position
844 // states, as can be seen below. Largely this arises from position and transform
845 // being stored in the same data structure while having different latching rules.
846 // b/38182305
847 //
848 // Careful that "stateToCommit" and editCurrentState may not begin as equivalent due to
849 // applyPendingStates in the presence of deferred transactions.
850 if (mFreezeGeometryUpdates) {
851 float tx = stateToCommit->active_legacy.transform.tx();
852 float ty = stateToCommit->active_legacy.transform.ty();
853 stateToCommit->active_legacy = stateToCommit->requested_legacy;
854 stateToCommit->active_legacy.transform.set(tx, ty);
855 editCurrentState.active_legacy = stateToCommit->active_legacy;
856 } else {
857 editCurrentState.active_legacy = editCurrentState.requested_legacy;
858 stateToCommit->active_legacy = stateToCommit->requested_legacy;
859 }
860 }
861
862 return flags;
863 }
864
doTransaction(uint32_t flags)865 uint32_t Layer::doTransaction(uint32_t flags) {
866 ATRACE_CALL();
867
868 if (mLayerDetached) {
869 return flags;
870 }
871
872 if (mChildrenChanged) {
873 flags |= eVisibleRegion;
874 mChildrenChanged = false;
875 }
876
877 pushPendingState();
878 State c = getCurrentState();
879 if (!applyPendingStates(&c)) {
880 return flags;
881 }
882
883 flags = doTransactionResize(flags, &c);
884
885 const State& s(getDrawingState());
886
887 if (getActiveGeometry(c) != getActiveGeometry(s)) {
888 // invalidate and recompute the visible regions if needed
889 flags |= Layer::eVisibleRegion;
890 }
891
892 if (c.sequence != s.sequence) {
893 // invalidate and recompute the visible regions if needed
894 flags |= eVisibleRegion;
895 this->contentDirty = true;
896
897 // we may use linear filtering, if the matrix scales us
898 const uint8_t type = getActiveTransform(c).getType();
899 mNeedsFiltering = (!getActiveTransform(c).preserveRects() || type >= ui::Transform::SCALE);
900 }
901
902 if (mCurrentState.inputInfoChanged) {
903 flags |= eInputInfoChanged;
904 mCurrentState.inputInfoChanged = false;
905 }
906
907 // Commit the transaction
908 commitTransaction(c);
909 mPendingStatesSnapshot = mPendingStates;
910 mCurrentState.callbackHandles = {};
911 return flags;
912 }
913
commitTransaction(const State & stateToCommit)914 void Layer::commitTransaction(const State& stateToCommit) {
915 mDrawingState = stateToCommit;
916 }
917
getTransactionFlags(uint32_t flags)918 uint32_t Layer::getTransactionFlags(uint32_t flags) {
919 return mTransactionFlags.fetch_and(~flags) & flags;
920 }
921
setTransactionFlags(uint32_t flags)922 uint32_t Layer::setTransactionFlags(uint32_t flags) {
923 return mTransactionFlags.fetch_or(flags);
924 }
925
setPosition(float x,float y,bool immediate)926 bool Layer::setPosition(float x, float y, bool immediate) {
927 if (mCurrentState.requested_legacy.transform.tx() == x &&
928 mCurrentState.requested_legacy.transform.ty() == y)
929 return false;
930 mCurrentState.sequence++;
931
932 // We update the requested and active position simultaneously because
933 // we want to apply the position portion of the transform matrix immediately,
934 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
935 mCurrentState.requested_legacy.transform.set(x, y);
936 if (immediate && !mFreezeGeometryUpdates) {
937 // Here we directly update the active state
938 // unlike other setters, because we store it within
939 // the transform, but use different latching rules.
940 // b/38182305
941 mCurrentState.active_legacy.transform.set(x, y);
942 }
943 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
944
945 mCurrentState.modified = true;
946 setTransactionFlags(eTransactionNeeded);
947 return true;
948 }
949
setChildLayer(const sp<Layer> & childLayer,int32_t z)950 bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
951 ssize_t idx = mCurrentChildren.indexOf(childLayer);
952 if (idx < 0) {
953 return false;
954 }
955 if (childLayer->setLayer(z)) {
956 mCurrentChildren.removeAt(idx);
957 mCurrentChildren.add(childLayer);
958 return true;
959 }
960 return false;
961 }
962
setChildRelativeLayer(const sp<Layer> & childLayer,const sp<IBinder> & relativeToHandle,int32_t relativeZ)963 bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
964 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
965 ssize_t idx = mCurrentChildren.indexOf(childLayer);
966 if (idx < 0) {
967 return false;
968 }
969 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
970 mCurrentChildren.removeAt(idx);
971 mCurrentChildren.add(childLayer);
972 return true;
973 }
974 return false;
975 }
976
setLayer(int32_t z)977 bool Layer::setLayer(int32_t z) {
978 if (mCurrentState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
979 mCurrentState.sequence++;
980 mCurrentState.z = z;
981 mCurrentState.modified = true;
982
983 // Discard all relative layering.
984 if (mCurrentState.zOrderRelativeOf != nullptr) {
985 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
986 if (strongRelative != nullptr) {
987 strongRelative->removeZOrderRelative(this);
988 }
989 setZOrderRelativeOf(nullptr);
990 }
991 setTransactionFlags(eTransactionNeeded);
992 return true;
993 }
994
removeZOrderRelative(const wp<Layer> & relative)995 void Layer::removeZOrderRelative(const wp<Layer>& relative) {
996 mCurrentState.zOrderRelatives.remove(relative);
997 mCurrentState.sequence++;
998 mCurrentState.modified = true;
999 setTransactionFlags(eTransactionNeeded);
1000 }
1001
addZOrderRelative(const wp<Layer> & relative)1002 void Layer::addZOrderRelative(const wp<Layer>& relative) {
1003 mCurrentState.zOrderRelatives.add(relative);
1004 mCurrentState.modified = true;
1005 mCurrentState.sequence++;
1006 setTransactionFlags(eTransactionNeeded);
1007 }
1008
setZOrderRelativeOf(const wp<Layer> & relativeOf)1009 void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
1010 mCurrentState.zOrderRelativeOf = relativeOf;
1011 mCurrentState.sequence++;
1012 mCurrentState.modified = true;
1013 setTransactionFlags(eTransactionNeeded);
1014 }
1015
setRelativeLayer(const sp<IBinder> & relativeToHandle,int32_t relativeZ)1016 bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
1017 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1018 if (handle == nullptr) {
1019 return false;
1020 }
1021 sp<Layer> relative = handle->owner.promote();
1022 if (relative == nullptr) {
1023 return false;
1024 }
1025
1026 if (mCurrentState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
1027 mCurrentState.zOrderRelativeOf == relative) {
1028 return false;
1029 }
1030
1031 mCurrentState.sequence++;
1032 mCurrentState.modified = true;
1033 mCurrentState.z = relativeZ;
1034
1035 auto oldZOrderRelativeOf = mCurrentState.zOrderRelativeOf.promote();
1036 if (oldZOrderRelativeOf != nullptr) {
1037 oldZOrderRelativeOf->removeZOrderRelative(this);
1038 }
1039 setZOrderRelativeOf(relative);
1040 relative->addZOrderRelative(this);
1041
1042 setTransactionFlags(eTransactionNeeded);
1043
1044 return true;
1045 }
1046
setSize(uint32_t w,uint32_t h)1047 bool Layer::setSize(uint32_t w, uint32_t h) {
1048 if (mCurrentState.requested_legacy.w == w && mCurrentState.requested_legacy.h == h)
1049 return false;
1050 mCurrentState.requested_legacy.w = w;
1051 mCurrentState.requested_legacy.h = h;
1052 mCurrentState.modified = true;
1053 setTransactionFlags(eTransactionNeeded);
1054
1055 // record the new size, from this point on, when the client request
1056 // a buffer, it'll get the new size.
1057 setDefaultBufferSize(mCurrentState.requested_legacy.w, mCurrentState.requested_legacy.h);
1058 return true;
1059 }
setAlpha(float alpha)1060 bool Layer::setAlpha(float alpha) {
1061 if (mCurrentState.color.a == alpha) return false;
1062 mCurrentState.sequence++;
1063 mCurrentState.color.a = alpha;
1064 mCurrentState.modified = true;
1065 setTransactionFlags(eTransactionNeeded);
1066 return true;
1067 }
1068
setBackgroundColor(const half3 & color,float alpha,ui::Dataspace dataspace)1069 bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
1070 if (!mCurrentState.bgColorLayer && alpha == 0) {
1071 return false;
1072 }
1073 mCurrentState.sequence++;
1074 mCurrentState.modified = true;
1075 setTransactionFlags(eTransactionNeeded);
1076
1077 if (!mCurrentState.bgColorLayer && alpha != 0) {
1078 // create background color layer if one does not yet exist
1079 uint32_t flags = ISurfaceComposerClient::eFXSurfaceColor;
1080 const String8& name = mName + "BackgroundColorLayer";
1081 mCurrentState.bgColorLayer = new ColorLayer(
1082 LayerCreationArgs(mFlinger.get(), nullptr, name, 0, 0, flags, LayerMetadata()));
1083
1084 // add to child list
1085 addChild(mCurrentState.bgColorLayer);
1086 mFlinger->mLayersAdded = true;
1087 // set up SF to handle added color layer
1088 if (isRemovedFromCurrentState()) {
1089 mCurrentState.bgColorLayer->onRemovedFromCurrentState();
1090 }
1091 mFlinger->setTransactionFlags(eTransactionNeeded);
1092 } else if (mCurrentState.bgColorLayer && alpha == 0) {
1093 mCurrentState.bgColorLayer->reparent(nullptr);
1094 mCurrentState.bgColorLayer = nullptr;
1095 return true;
1096 }
1097
1098 mCurrentState.bgColorLayer->setColor(color);
1099 mCurrentState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1100 mCurrentState.bgColorLayer->setAlpha(alpha);
1101 mCurrentState.bgColorLayer->setDataspace(dataspace);
1102
1103 return true;
1104 }
1105
setCornerRadius(float cornerRadius)1106 bool Layer::setCornerRadius(float cornerRadius) {
1107 if (mCurrentState.cornerRadius == cornerRadius) return false;
1108
1109 mCurrentState.sequence++;
1110 mCurrentState.cornerRadius = cornerRadius;
1111 mCurrentState.modified = true;
1112 setTransactionFlags(eTransactionNeeded);
1113 return true;
1114 }
1115
setMatrix(const layer_state_t::matrix22_t & matrix,bool allowNonRectPreservingTransforms)1116 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix,
1117 bool allowNonRectPreservingTransforms) {
1118 ui::Transform t;
1119 t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
1120
1121 if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
1122 ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER ignored");
1123 return false;
1124 }
1125 mCurrentState.sequence++;
1126 mCurrentState.requested_legacy.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx,
1127 matrix.dsdy);
1128 mCurrentState.modified = true;
1129 setTransactionFlags(eTransactionNeeded);
1130 return true;
1131 }
1132
setTransparentRegionHint(const Region & transparent)1133 bool Layer::setTransparentRegionHint(const Region& transparent) {
1134 mCurrentState.requestedTransparentRegion_legacy = transparent;
1135 mCurrentState.modified = true;
1136 setTransactionFlags(eTransactionNeeded);
1137 return true;
1138 }
setFlags(uint8_t flags,uint8_t mask)1139 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1140 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1141 if (mCurrentState.flags == newFlags) return false;
1142 mCurrentState.sequence++;
1143 mCurrentState.flags = newFlags;
1144 mCurrentState.modified = true;
1145 setTransactionFlags(eTransactionNeeded);
1146 return true;
1147 }
1148
setCrop_legacy(const Rect & crop,bool immediate)1149 bool Layer::setCrop_legacy(const Rect& crop, bool immediate) {
1150 if (mCurrentState.requestedCrop_legacy == crop) return false;
1151 mCurrentState.sequence++;
1152 mCurrentState.requestedCrop_legacy = crop;
1153 if (immediate && !mFreezeGeometryUpdates) {
1154 mCurrentState.crop_legacy = crop;
1155 }
1156 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1157
1158 mCurrentState.modified = true;
1159 setTransactionFlags(eTransactionNeeded);
1160 return true;
1161 }
1162
setOverrideScalingMode(int32_t scalingMode)1163 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1164 if (scalingMode == mOverrideScalingMode) return false;
1165 mOverrideScalingMode = scalingMode;
1166 setTransactionFlags(eTransactionNeeded);
1167 return true;
1168 }
1169
setMetadata(const LayerMetadata & data)1170 bool Layer::setMetadata(const LayerMetadata& data) {
1171 if (!mCurrentState.metadata.merge(data, true /* eraseEmpty */)) return false;
1172 mCurrentState.sequence++;
1173 mCurrentState.modified = true;
1174 setTransactionFlags(eTransactionNeeded);
1175 return true;
1176 }
1177
setLayerStack(uint32_t layerStack)1178 bool Layer::setLayerStack(uint32_t layerStack) {
1179 if (mCurrentState.layerStack == layerStack) return false;
1180 mCurrentState.sequence++;
1181 mCurrentState.layerStack = layerStack;
1182 mCurrentState.modified = true;
1183 setTransactionFlags(eTransactionNeeded);
1184 return true;
1185 }
1186
setColorSpaceAgnostic(const bool agnostic)1187 bool Layer::setColorSpaceAgnostic(const bool agnostic) {
1188 if (mCurrentState.colorSpaceAgnostic == agnostic) {
1189 return false;
1190 }
1191 mCurrentState.sequence++;
1192 mCurrentState.colorSpaceAgnostic = agnostic;
1193 mCurrentState.modified = true;
1194 setTransactionFlags(eTransactionNeeded);
1195 return true;
1196 }
1197
getLayerStack() const1198 uint32_t Layer::getLayerStack() const {
1199 auto p = mDrawingParent.promote();
1200 if (p == nullptr) {
1201 return getDrawingState().layerStack;
1202 }
1203 return p->getLayerStack();
1204 }
1205
deferTransactionUntil_legacy(const sp<Layer> & barrierLayer,uint64_t frameNumber)1206 void Layer::deferTransactionUntil_legacy(const sp<Layer>& barrierLayer, uint64_t frameNumber) {
1207 ATRACE_CALL();
1208 mCurrentState.barrierLayer_legacy = barrierLayer;
1209 mCurrentState.frameNumber_legacy = frameNumber;
1210 // We don't set eTransactionNeeded, because just receiving a deferral
1211 // request without any other state updates shouldn't actually induce a delay
1212 mCurrentState.modified = true;
1213 pushPendingState();
1214 mCurrentState.barrierLayer_legacy = nullptr;
1215 mCurrentState.frameNumber_legacy = 0;
1216 mCurrentState.modified = false;
1217 }
1218
deferTransactionUntil_legacy(const sp<IBinder> & barrierHandle,uint64_t frameNumber)1219 void Layer::deferTransactionUntil_legacy(const sp<IBinder>& barrierHandle, uint64_t frameNumber) {
1220 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1221 deferTransactionUntil_legacy(handle->owner.promote(), frameNumber);
1222 }
1223
1224 // ----------------------------------------------------------------------------
1225 // pageflip handling...
1226 // ----------------------------------------------------------------------------
1227
isHiddenByPolicy() const1228 bool Layer::isHiddenByPolicy() const {
1229 const State& s(mDrawingState);
1230 const auto& parent = mDrawingParent.promote();
1231 if (parent != nullptr && parent->isHiddenByPolicy()) {
1232 return true;
1233 }
1234 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1235 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1236 if (zOrderRelativeOf != nullptr) {
1237 if (zOrderRelativeOf->isHiddenByPolicy()) {
1238 return true;
1239 }
1240 }
1241 }
1242 return s.flags & layer_state_t::eLayerHidden;
1243 }
1244
getEffectiveUsage(uint32_t usage) const1245 uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
1246 // TODO: should we do something special if mSecure is set?
1247 if (mProtectedByApp) {
1248 // need a hardware-protected path to external video sink
1249 usage |= GraphicBuffer::USAGE_PROTECTED;
1250 }
1251 if (mPotentialCursor) {
1252 usage |= GraphicBuffer::USAGE_CURSOR;
1253 }
1254 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
1255 return usage;
1256 }
1257
updateTransformHint(const sp<const DisplayDevice> & display) const1258 void Layer::updateTransformHint(const sp<const DisplayDevice>& display) const {
1259 uint32_t orientation = 0;
1260 // Disable setting transform hint if the debug flag is set.
1261 if (!mFlinger->mDebugDisableTransformHint) {
1262 // The transform hint is used to improve performance, but we can
1263 // only have a single transform hint, it cannot
1264 // apply to all displays.
1265 const ui::Transform& planeTransform = display->getTransform();
1266 orientation = planeTransform.getOrientation();
1267 if (orientation & ui::Transform::ROT_INVALID) {
1268 orientation = 0;
1269 }
1270 }
1271 setTransformHint(orientation);
1272 }
1273
1274 // ----------------------------------------------------------------------------
1275 // debugging
1276 // ----------------------------------------------------------------------------
1277
1278 // TODO(marissaw): add new layer state info to layer debugging
getLayerDebugInfo() const1279 LayerDebugInfo Layer::getLayerDebugInfo() const {
1280 LayerDebugInfo info;
1281 const State& ds = getDrawingState();
1282 info.mName = getName();
1283 sp<Layer> parent = getParent();
1284 info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
1285 info.mType = std::string(getTypeId());
1286 info.mTransparentRegion = ds.activeTransparentRegion_legacy;
1287 info.mVisibleRegion = visibleRegion;
1288 info.mSurfaceDamageRegion = surfaceDamageRegion;
1289 info.mLayerStack = getLayerStack();
1290 info.mX = ds.active_legacy.transform.tx();
1291 info.mY = ds.active_legacy.transform.ty();
1292 info.mZ = ds.z;
1293 info.mWidth = ds.active_legacy.w;
1294 info.mHeight = ds.active_legacy.h;
1295 info.mCrop = ds.crop_legacy;
1296 info.mColor = ds.color;
1297 info.mFlags = ds.flags;
1298 info.mPixelFormat = getPixelFormat();
1299 info.mDataSpace = static_cast<android_dataspace>(mCurrentDataSpace);
1300 info.mMatrix[0][0] = ds.active_legacy.transform[0][0];
1301 info.mMatrix[0][1] = ds.active_legacy.transform[0][1];
1302 info.mMatrix[1][0] = ds.active_legacy.transform[1][0];
1303 info.mMatrix[1][1] = ds.active_legacy.transform[1][1];
1304 {
1305 sp<const GraphicBuffer> buffer = mActiveBuffer;
1306 if (buffer != 0) {
1307 info.mActiveBufferWidth = buffer->getWidth();
1308 info.mActiveBufferHeight = buffer->getHeight();
1309 info.mActiveBufferStride = buffer->getStride();
1310 info.mActiveBufferFormat = buffer->format;
1311 } else {
1312 info.mActiveBufferWidth = 0;
1313 info.mActiveBufferHeight = 0;
1314 info.mActiveBufferStride = 0;
1315 info.mActiveBufferFormat = 0;
1316 }
1317 }
1318 info.mNumQueuedFrames = getQueuedFrameCount();
1319 info.mRefreshPending = isBufferLatched();
1320 info.mIsOpaque = isOpaque(ds);
1321 info.mContentDirty = contentDirty;
1322 return info;
1323 }
1324
miniDumpHeader(std::string & result)1325 void Layer::miniDumpHeader(std::string& result) {
1326 result.append("-------------------------------");
1327 result.append("-------------------------------");
1328 result.append("-----------------------------\n");
1329 result.append(" Layer name\n");
1330 result.append(" Z | ");
1331 result.append(" Window Type | ");
1332 result.append(" Comp Type | ");
1333 result.append(" Transform | ");
1334 result.append(" Disp Frame (LTRB) | ");
1335 result.append(" Source Crop (LTRB)\n");
1336 result.append("-------------------------------");
1337 result.append("-------------------------------");
1338 result.append("-----------------------------\n");
1339 }
1340
miniDump(std::string & result,const sp<DisplayDevice> & displayDevice) const1341 void Layer::miniDump(std::string& result, const sp<DisplayDevice>& displayDevice) const {
1342 auto outputLayer = findOutputLayerForDisplay(displayDevice);
1343 if (!outputLayer) {
1344 return;
1345 }
1346
1347 std::string name;
1348 if (mName.length() > 77) {
1349 std::string shortened;
1350 shortened.append(mName.string(), 36);
1351 shortened.append("[...]");
1352 shortened.append(mName.string() + (mName.length() - 36), 36);
1353 name = shortened;
1354 } else {
1355 name = std::string(mName.string(), mName.size());
1356 }
1357
1358 StringAppendF(&result, " %s\n", name.c_str());
1359
1360 const State& layerState(getDrawingState());
1361 const auto& compositionState = outputLayer->getState();
1362
1363 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
1364 StringAppendF(&result, " rel %6d | ", layerState.z);
1365 } else {
1366 StringAppendF(&result, " %10d | ", layerState.z);
1367 }
1368 StringAppendF(&result, " %10d | ", mWindowType);
1369 StringAppendF(&result, "%10s | ", toString(getCompositionType(displayDevice)).c_str());
1370 StringAppendF(&result, "%10s | ",
1371 toString(getCompositionLayer() ? compositionState.bufferTransform
1372 : static_cast<Hwc2::Transform>(0))
1373 .c_str());
1374 const Rect& frame = compositionState.displayFrame;
1375 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1376 const FloatRect& crop = compositionState.sourceCrop;
1377 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, crop.right,
1378 crop.bottom);
1379
1380 result.append("- - - - - - - - - - - - - - - -");
1381 result.append("- - - - - - - - - - - - - - - -");
1382 result.append("- - - - - - - - - - - - - - -\n");
1383 }
1384
dumpFrameStats(std::string & result) const1385 void Layer::dumpFrameStats(std::string& result) const {
1386 mFrameTracker.dumpStats(result);
1387 }
1388
clearFrameStats()1389 void Layer::clearFrameStats() {
1390 mFrameTracker.clearStats();
1391 }
1392
logFrameStats()1393 void Layer::logFrameStats() {
1394 mFrameTracker.logAndResetStats(mName);
1395 }
1396
getFrameStats(FrameStats * outStats) const1397 void Layer::getFrameStats(FrameStats* outStats) const {
1398 mFrameTracker.getStats(outStats);
1399 }
1400
dumpFrameEvents(std::string & result)1401 void Layer::dumpFrameEvents(std::string& result) {
1402 StringAppendF(&result, "- Layer %s (%s, %p)\n", getName().string(), getTypeId(), this);
1403 Mutex::Autolock lock(mFrameEventHistoryMutex);
1404 mFrameEventHistory.checkFencesForCompletion();
1405 mFrameEventHistory.dump(result);
1406 }
1407
onDisconnect()1408 void Layer::onDisconnect() {
1409 Mutex::Autolock lock(mFrameEventHistoryMutex);
1410 mFrameEventHistory.onDisconnect();
1411 mFlinger->mTimeStats->onDestroy(getSequence());
1412 }
1413
addAndGetFrameTimestamps(const NewFrameEventsEntry * newTimestamps,FrameEventHistoryDelta * outDelta)1414 void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
1415 FrameEventHistoryDelta* outDelta) {
1416 if (newTimestamps) {
1417 mFlinger->mTimeStats->setPostTime(getSequence(), newTimestamps->frameNumber,
1418 getName().c_str(), newTimestamps->postedTime);
1419 }
1420
1421 Mutex::Autolock lock(mFrameEventHistoryMutex);
1422 if (newTimestamps) {
1423 // If there are any unsignaled fences in the aquire timeline at this
1424 // point, the previously queued frame hasn't been latched yet. Go ahead
1425 // and try to get the signal time here so the syscall is taken out of
1426 // the main thread's critical path.
1427 mAcquireTimeline.updateSignalTimes();
1428 // Push the new fence after updating since it's likely still pending.
1429 mAcquireTimeline.push(newTimestamps->acquireFence);
1430 mFrameEventHistory.addQueue(*newTimestamps);
1431 }
1432
1433 if (outDelta) {
1434 mFrameEventHistory.getAndResetDelta(outDelta);
1435 }
1436 }
1437
getChildrenCount() const1438 size_t Layer::getChildrenCount() const {
1439 size_t count = 0;
1440 for (const sp<Layer>& child : mCurrentChildren) {
1441 count += 1 + child->getChildrenCount();
1442 }
1443 return count;
1444 }
1445
addChild(const sp<Layer> & layer)1446 void Layer::addChild(const sp<Layer>& layer) {
1447 mChildrenChanged = true;
1448 setTransactionFlags(eTransactionNeeded);
1449
1450 mCurrentChildren.add(layer);
1451 layer->setParent(this);
1452 }
1453
removeChild(const sp<Layer> & layer)1454 ssize_t Layer::removeChild(const sp<Layer>& layer) {
1455 mChildrenChanged = true;
1456 setTransactionFlags(eTransactionNeeded);
1457
1458 layer->setParent(nullptr);
1459 return mCurrentChildren.remove(layer);
1460 }
1461
reparentChildren(const sp<IBinder> & newParentHandle)1462 bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
1463 sp<Handle> handle = nullptr;
1464 sp<Layer> newParent = nullptr;
1465 if (newParentHandle == nullptr) {
1466 return false;
1467 }
1468 handle = static_cast<Handle*>(newParentHandle.get());
1469 newParent = handle->owner.promote();
1470 if (newParent == nullptr) {
1471 ALOGE("Unable to promote Layer handle");
1472 return false;
1473 }
1474
1475 if (attachChildren()) {
1476 setTransactionFlags(eTransactionNeeded);
1477 }
1478 for (const sp<Layer>& child : mCurrentChildren) {
1479 newParent->addChild(child);
1480 }
1481 mCurrentChildren.clear();
1482
1483 return true;
1484 }
1485
setChildrenDrawingParent(const sp<Layer> & newParent)1486 void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
1487 for (const sp<Layer>& child : mDrawingChildren) {
1488 child->mDrawingParent = newParent;
1489 child->computeBounds(newParent->mBounds,
1490 newParent->getTransformWithScale(
1491 newParent->getBufferScaleTransform()));
1492 }
1493 }
1494
reparent(const sp<IBinder> & newParentHandle)1495 bool Layer::reparent(const sp<IBinder>& newParentHandle) {
1496 bool callSetTransactionFlags = false;
1497
1498 // While layers are detached, we allow most operations
1499 // and simply halt performing the actual transaction. However
1500 // for reparent != null we would enter the mRemovedFromCurrentState
1501 // state, regardless of whether doTransaction was called, and
1502 // so we need to prevent the update here.
1503 if (mLayerDetached && newParentHandle == nullptr) {
1504 return false;
1505 }
1506
1507 sp<Layer> newParent;
1508 if (newParentHandle != nullptr) {
1509 auto handle = static_cast<Handle*>(newParentHandle.get());
1510 newParent = handle->owner.promote();
1511 if (newParent == nullptr) {
1512 ALOGE("Unable to promote Layer handle");
1513 return false;
1514 }
1515 if (newParent == this) {
1516 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1517 return false;
1518 }
1519 }
1520
1521 sp<Layer> parent = getParent();
1522 if (parent != nullptr) {
1523 parent->removeChild(this);
1524 }
1525
1526 if (newParentHandle != nullptr) {
1527 newParent->addChild(this);
1528 if (!newParent->isRemovedFromCurrentState()) {
1529 addToCurrentState();
1530 } else {
1531 onRemovedFromCurrentState();
1532 }
1533
1534 if (mLayerDetached) {
1535 mLayerDetached = false;
1536 callSetTransactionFlags = true;
1537 }
1538 } else {
1539 onRemovedFromCurrentState();
1540 }
1541
1542 if (callSetTransactionFlags || attachChildren()) {
1543 setTransactionFlags(eTransactionNeeded);
1544 }
1545 return true;
1546 }
1547
detachChildren()1548 bool Layer::detachChildren() {
1549 for (const sp<Layer>& child : mCurrentChildren) {
1550 sp<Client> parentClient = mClientRef.promote();
1551 sp<Client> client(child->mClientRef.promote());
1552 if (client != nullptr && parentClient != client) {
1553 child->mLayerDetached = true;
1554 child->detachChildren();
1555 child->removeRemoteSyncPoints();
1556 }
1557 }
1558
1559 return true;
1560 }
1561
attachChildren()1562 bool Layer::attachChildren() {
1563 bool changed = false;
1564 for (const sp<Layer>& child : mCurrentChildren) {
1565 sp<Client> parentClient = mClientRef.promote();
1566 sp<Client> client(child->mClientRef.promote());
1567 if (client != nullptr && parentClient != client) {
1568 if (child->mLayerDetached) {
1569 child->mLayerDetached = false;
1570 changed = true;
1571 }
1572 changed |= child->attachChildren();
1573 }
1574 }
1575
1576 return changed;
1577 }
1578
setColorTransform(const mat4 & matrix)1579 bool Layer::setColorTransform(const mat4& matrix) {
1580 static const mat4 identityMatrix = mat4();
1581
1582 if (mCurrentState.colorTransform == matrix) {
1583 return false;
1584 }
1585 ++mCurrentState.sequence;
1586 mCurrentState.colorTransform = matrix;
1587 mCurrentState.hasColorTransform = matrix != identityMatrix;
1588 mCurrentState.modified = true;
1589 setTransactionFlags(eTransactionNeeded);
1590 return true;
1591 }
1592
getColorTransform() const1593 mat4 Layer::getColorTransform() const {
1594 mat4 colorTransform = mat4(getDrawingState().colorTransform);
1595 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
1596 colorTransform = parent->getColorTransform() * colorTransform;
1597 }
1598 return colorTransform;
1599 }
1600
hasColorTransform() const1601 bool Layer::hasColorTransform() const {
1602 bool hasColorTransform = getDrawingState().hasColorTransform;
1603 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
1604 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1605 }
1606 return hasColorTransform;
1607 }
1608
isLegacyDataSpace() const1609 bool Layer::isLegacyDataSpace() const {
1610 // return true when no higher bits are set
1611 return !(mCurrentDataSpace & (ui::Dataspace::STANDARD_MASK |
1612 ui::Dataspace::TRANSFER_MASK | ui::Dataspace::RANGE_MASK));
1613 }
1614
setParent(const sp<Layer> & layer)1615 void Layer::setParent(const sp<Layer>& layer) {
1616 mCurrentParent = layer;
1617 }
1618
getZ() const1619 int32_t Layer::getZ() const {
1620 return mDrawingState.z;
1621 }
1622
usingRelativeZ(LayerVector::StateSet stateSet) const1623 bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
1624 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1625 const State& state = useDrawing ? mDrawingState : mCurrentState;
1626 return state.zOrderRelativeOf != nullptr;
1627 }
1628
makeTraversalList(LayerVector::StateSet stateSet,bool * outSkipRelativeZUsers)1629 __attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
1630 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
1631 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1632 "makeTraversalList received invalid stateSet");
1633 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1634 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1635 const State& state = useDrawing ? mDrawingState : mCurrentState;
1636
1637 if (state.zOrderRelatives.size() == 0) {
1638 *outSkipRelativeZUsers = true;
1639 return children;
1640 }
1641
1642 LayerVector traverse(stateSet);
1643 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1644 sp<Layer> strongRelative = weakRelative.promote();
1645 if (strongRelative != nullptr) {
1646 traverse.add(strongRelative);
1647 }
1648 }
1649
1650 for (const sp<Layer>& child : children) {
1651 const State& childState = useDrawing ? child->mDrawingState : child->mCurrentState;
1652 if (childState.zOrderRelativeOf != nullptr) {
1653 continue;
1654 }
1655 traverse.add(child);
1656 }
1657
1658 return traverse;
1659 }
1660
1661 /**
1662 * Negatively signed relatives are before 'this' in Z-order.
1663 */
traverseInZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1664 void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
1665 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1666 // produce a new list for traversing, including our relatives, and not including our children
1667 // who are relatives of another surface. In the case that there are no relative Z,
1668 // makeTraversalList returns our children directly to avoid significant overhead.
1669 // However in this case we need to take the responsibility for filtering children which
1670 // are relatives of another surface here.
1671 bool skipRelativeZUsers = false;
1672 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
1673
1674 size_t i = 0;
1675 for (; i < list.size(); i++) {
1676 const auto& relative = list[i];
1677 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1678 continue;
1679 }
1680
1681 if (relative->getZ() >= 0) {
1682 break;
1683 }
1684 relative->traverseInZOrder(stateSet, visitor);
1685 }
1686
1687 visitor(this);
1688 for (; i < list.size(); i++) {
1689 const auto& relative = list[i];
1690
1691 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1692 continue;
1693 }
1694 relative->traverseInZOrder(stateSet, visitor);
1695 }
1696 }
1697
1698 /**
1699 * Positively signed relatives are before 'this' in reverse Z-order.
1700 */
traverseInReverseZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1701 void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1702 const LayerVector::Visitor& visitor) {
1703 // See traverseInZOrder for documentation.
1704 bool skipRelativeZUsers = false;
1705 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
1706
1707 int32_t i = 0;
1708 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
1709 const auto& relative = list[i];
1710
1711 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1712 continue;
1713 }
1714
1715 if (relative->getZ() < 0) {
1716 break;
1717 }
1718 relative->traverseInReverseZOrder(stateSet, visitor);
1719 }
1720 visitor(this);
1721 for (; i >= 0; i--) {
1722 const auto& relative = list[i];
1723
1724 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1725 continue;
1726 }
1727
1728 relative->traverseInReverseZOrder(stateSet, visitor);
1729 }
1730 }
1731
makeChildrenTraversalList(LayerVector::StateSet stateSet,const std::vector<Layer * > & layersInTree)1732 LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1733 const std::vector<Layer*>& layersInTree) {
1734 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1735 "makeTraversalList received invalid stateSet");
1736 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1737 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1738 const State& state = useDrawing ? mDrawingState : mCurrentState;
1739
1740 LayerVector traverse(stateSet);
1741 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1742 sp<Layer> strongRelative = weakRelative.promote();
1743 // Only add relative layers that are also descendents of the top most parent of the tree.
1744 // If a relative layer is not a descendent, then it should be ignored.
1745 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1746 traverse.add(strongRelative);
1747 }
1748 }
1749
1750 for (const sp<Layer>& child : children) {
1751 const State& childState = useDrawing ? child->mDrawingState : child->mCurrentState;
1752 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1753 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1754 // the child here since it won't be added later as a relative.
1755 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1756 childState.zOrderRelativeOf.promote().get())) {
1757 continue;
1758 }
1759 traverse.add(child);
1760 }
1761
1762 return traverse;
1763 }
1764
traverseChildrenInZOrderInner(const std::vector<Layer * > & layersInTree,LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1765 void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1766 LayerVector::StateSet stateSet,
1767 const LayerVector::Visitor& visitor) {
1768 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
1769
1770 size_t i = 0;
1771 for (; i < list.size(); i++) {
1772 const auto& relative = list[i];
1773 if (relative->getZ() >= 0) {
1774 break;
1775 }
1776 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1777 }
1778
1779 visitor(this);
1780 for (; i < list.size(); i++) {
1781 const auto& relative = list[i];
1782 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1783 }
1784 }
1785
getLayersInTree(LayerVector::StateSet stateSet)1786 std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1787 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1788 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1789
1790 std::vector<Layer*> layersInTree = {this};
1791 for (size_t i = 0; i < children.size(); i++) {
1792 const auto& child = children[i];
1793 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1794 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1795 }
1796
1797 return layersInTree;
1798 }
1799
traverseChildrenInZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1800 void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1801 const LayerVector::Visitor& visitor) {
1802 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1803 std::sort(layersInTree.begin(), layersInTree.end());
1804 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1805 }
1806
getTransform() const1807 ui::Transform Layer::getTransform() const {
1808 return mEffectiveTransform;
1809 }
1810
getAlpha() const1811 half Layer::getAlpha() const {
1812 const auto& p = mDrawingParent.promote();
1813
1814 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1815 return parentAlpha * getDrawingState().color.a;
1816 }
1817
getColor() const1818 half4 Layer::getColor() const {
1819 const half4 color(getDrawingState().color);
1820 return half4(color.r, color.g, color.b, getAlpha());
1821 }
1822
getRoundedCornerState() const1823 Layer::RoundedCornerState Layer::getRoundedCornerState() const {
1824 const auto& p = mDrawingParent.promote();
1825 if (p != nullptr) {
1826 RoundedCornerState parentState = p->getRoundedCornerState();
1827 if (parentState.radius > 0) {
1828 ui::Transform t = getActiveTransform(getDrawingState());
1829 t = t.inverse();
1830 parentState.cropRect = t.transform(parentState.cropRect);
1831 // The rounded corners shader only accepts 1 corner radius for performance reasons,
1832 // but a transform matrix can define horizontal and vertical scales.
1833 // Let's take the average between both of them and pass into the shader, practically we
1834 // never do this type of transformation on windows anyway.
1835 parentState.radius *= (t[0][0] + t[1][1]) / 2.0f;
1836 return parentState;
1837 }
1838 }
1839 const float radius = getDrawingState().cornerRadius;
1840 return radius > 0 && getCrop(getDrawingState()).isValid()
1841 ? RoundedCornerState(getCrop(getDrawingState()).toFloatRect(), radius)
1842 : RoundedCornerState();
1843 }
1844
commitChildList()1845 void Layer::commitChildList() {
1846 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
1847 const auto& child = mCurrentChildren[i];
1848 child->commitChildList();
1849 }
1850 mDrawingChildren = mCurrentChildren;
1851 mDrawingParent = mCurrentParent;
1852 }
1853
extractLayerFromBinder(const wp<IBinder> & weakBinderHandle)1854 static wp<Layer> extractLayerFromBinder(const wp<IBinder>& weakBinderHandle) {
1855 if (weakBinderHandle == nullptr) {
1856 return nullptr;
1857 }
1858 sp<IBinder> binderHandle = weakBinderHandle.promote();
1859 if (binderHandle == nullptr) {
1860 return nullptr;
1861 }
1862 sp<Layer::Handle> handle = static_cast<Layer::Handle*>(binderHandle.get());
1863 if (handle == nullptr) {
1864 return nullptr;
1865 }
1866 return handle->owner;
1867 }
1868
setInputInfo(const InputWindowInfo & info)1869 void Layer::setInputInfo(const InputWindowInfo& info) {
1870 mCurrentState.inputInfo = info;
1871 mCurrentState.touchableRegionCrop = extractLayerFromBinder(info.touchableRegionCropHandle);
1872 mCurrentState.modified = true;
1873 mCurrentState.inputInfoChanged = true;
1874 setTransactionFlags(eTransactionNeeded);
1875 }
1876
writeToProtoDrawingState(LayerProto * layerInfo,uint32_t traceFlags) const1877 void Layer::writeToProtoDrawingState(LayerProto* layerInfo, uint32_t traceFlags) const {
1878 ui::Transform transform = getTransform();
1879
1880 if (traceFlags & SurfaceTracing::TRACE_CRITICAL) {
1881 for (const auto& pendingState : mPendingStatesSnapshot) {
1882 auto barrierLayer = pendingState.barrierLayer_legacy.promote();
1883 if (barrierLayer != nullptr) {
1884 BarrierLayerProto* barrierLayerProto = layerInfo->add_barrier_layer();
1885 barrierLayerProto->set_id(barrierLayer->sequence);
1886 barrierLayerProto->set_frame_number(pendingState.frameNumber_legacy);
1887 }
1888 }
1889
1890 auto buffer = mActiveBuffer;
1891 if (buffer != nullptr) {
1892 LayerProtoHelper::writeToProto(buffer,
1893 [&]() { return layerInfo->mutable_active_buffer(); });
1894 LayerProtoHelper::writeToProto(ui::Transform(mCurrentTransform),
1895 layerInfo->mutable_buffer_transform());
1896 }
1897 layerInfo->set_invalidate(contentDirty);
1898 layerInfo->set_is_protected(isProtected());
1899 layerInfo->set_dataspace(
1900 dataspaceDetails(static_cast<android_dataspace>(mCurrentDataSpace)));
1901 layerInfo->set_queued_frames(getQueuedFrameCount());
1902 layerInfo->set_refresh_pending(isBufferLatched());
1903 layerInfo->set_curr_frame(mCurrentFrameNumber);
1904 layerInfo->set_effective_scaling_mode(getEffectiveScalingMode());
1905
1906 layerInfo->set_corner_radius(getRoundedCornerState().radius);
1907 LayerProtoHelper::writeToProto(transform, layerInfo->mutable_transform());
1908 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
1909 [&]() { return layerInfo->mutable_position(); });
1910 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
1911 LayerProtoHelper::writeToProto(visibleRegion,
1912 [&]() { return layerInfo->mutable_visible_region(); });
1913 LayerProtoHelper::writeToProto(surfaceDamageRegion,
1914 [&]() { return layerInfo->mutable_damage_region(); });
1915 }
1916
1917 if (traceFlags & SurfaceTracing::TRACE_EXTRA) {
1918 LayerProtoHelper::writeToProto(mSourceBounds,
1919 [&]() { return layerInfo->mutable_source_bounds(); });
1920 LayerProtoHelper::writeToProto(mScreenBounds,
1921 [&]() { return layerInfo->mutable_screen_bounds(); });
1922 }
1923 }
1924
writeToProtoCommonState(LayerProto * layerInfo,LayerVector::StateSet stateSet,uint32_t traceFlags) const1925 void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
1926 uint32_t traceFlags) const {
1927 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1928 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1929 const State& state = useDrawing ? mDrawingState : mCurrentState;
1930
1931 ui::Transform requestedTransform = state.active_legacy.transform;
1932
1933 if (traceFlags & SurfaceTracing::TRACE_CRITICAL) {
1934 layerInfo->set_id(sequence);
1935 layerInfo->set_name(getName().c_str());
1936 layerInfo->set_type(String8(getTypeId()));
1937
1938 for (const auto& child : children) {
1939 layerInfo->add_children(child->sequence);
1940 }
1941
1942 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1943 sp<Layer> strongRelative = weakRelative.promote();
1944 if (strongRelative != nullptr) {
1945 layerInfo->add_relatives(strongRelative->sequence);
1946 }
1947 }
1948
1949 LayerProtoHelper::writeToProto(state.activeTransparentRegion_legacy,
1950 [&]() { return layerInfo->mutable_transparent_region(); });
1951
1952 layerInfo->set_layer_stack(getLayerStack());
1953 layerInfo->set_z(state.z);
1954
1955 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(),
1956 [&]() {
1957 return layerInfo->mutable_requested_position();
1958 });
1959
1960 LayerProtoHelper::writeSizeToProto(state.active_legacy.w, state.active_legacy.h,
1961 [&]() { return layerInfo->mutable_size(); });
1962
1963 LayerProtoHelper::writeToProto(state.crop_legacy,
1964 [&]() { return layerInfo->mutable_crop(); });
1965
1966 layerInfo->set_is_opaque(isOpaque(state));
1967
1968
1969 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
1970 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
1971 LayerProtoHelper::writeToProto(state.color,
1972 [&]() { return layerInfo->mutable_requested_color(); });
1973 layerInfo->set_flags(state.flags);
1974
1975 LayerProtoHelper::writeToProto(requestedTransform,
1976 layerInfo->mutable_requested_transform());
1977
1978 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1979 if (parent != nullptr) {
1980 layerInfo->set_parent(parent->sequence);
1981 } else {
1982 layerInfo->set_parent(-1);
1983 }
1984
1985 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
1986 if (zOrderRelativeOf != nullptr) {
1987 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
1988 } else {
1989 layerInfo->set_z_order_relative_of(-1);
1990 }
1991 }
1992
1993 if (traceFlags & SurfaceTracing::TRACE_INPUT) {
1994 LayerProtoHelper::writeToProto(state.inputInfo, state.touchableRegionCrop,
1995 [&]() { return layerInfo->mutable_input_window_info(); });
1996 }
1997
1998 if (traceFlags & SurfaceTracing::TRACE_EXTRA) {
1999 auto protoMap = layerInfo->mutable_metadata();
2000 for (const auto& entry : state.metadata.mMap) {
2001 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2002 }
2003 }
2004 }
2005
writeToProtoCompositionState(LayerProto * layerInfo,const sp<DisplayDevice> & displayDevice,uint32_t traceFlags) const2006 void Layer::writeToProtoCompositionState(LayerProto* layerInfo,
2007 const sp<DisplayDevice>& displayDevice,
2008 uint32_t traceFlags) const {
2009 auto outputLayer = findOutputLayerForDisplay(displayDevice);
2010 if (!outputLayer) {
2011 return;
2012 }
2013
2014 writeToProtoDrawingState(layerInfo, traceFlags);
2015 writeToProtoCommonState(layerInfo, LayerVector::StateSet::Drawing, traceFlags);
2016
2017 const auto& compositionState = outputLayer->getState();
2018
2019 const Rect& frame = compositionState.displayFrame;
2020 LayerProtoHelper::writeToProto(frame, [&]() { return layerInfo->mutable_hwc_frame(); });
2021
2022 const FloatRect& crop = compositionState.sourceCrop;
2023 LayerProtoHelper::writeToProto(crop, [&]() { return layerInfo->mutable_hwc_crop(); });
2024
2025 const int32_t transform =
2026 getCompositionLayer() ? static_cast<int32_t>(compositionState.bufferTransform) : 0;
2027 layerInfo->set_hwc_transform(transform);
2028
2029 const int32_t compositionType =
2030 static_cast<int32_t>(compositionState.hwc ? (*compositionState.hwc).hwcCompositionType
2031 : Hwc2::IComposerClient::Composition::CLIENT);
2032 layerInfo->set_hwc_composition_type(compositionType);
2033 }
2034
isRemovedFromCurrentState() const2035 bool Layer::isRemovedFromCurrentState() const {
2036 return mRemovedFromCurrentState;
2037 }
2038
fillInputInfo()2039 InputWindowInfo Layer::fillInputInfo() {
2040 InputWindowInfo info = mDrawingState.inputInfo;
2041
2042 if (info.displayId == ADISPLAY_ID_NONE) {
2043 info.displayId = getLayerStack();
2044 }
2045
2046 ui::Transform t = getTransform();
2047 const float xScale = t.sx();
2048 const float yScale = t.sy();
2049 int32_t xSurfaceInset = info.surfaceInset;
2050 int32_t ySurfaceInset = info.surfaceInset;
2051 if (xScale != 1.0f || yScale != 1.0f) {
2052 info.windowXScale *= (xScale != 0.0f) ? 1.0f / xScale : 0.0f;
2053 info.windowYScale *= (yScale != 0.0f) ? 1.0f / yScale : 0.0f;
2054 info.touchableRegion.scaleSelf(xScale, yScale);
2055 xSurfaceInset = std::round(xSurfaceInset * xScale);
2056 ySurfaceInset = std::round(ySurfaceInset * yScale);
2057 }
2058
2059 // Transform layer size to screen space and inset it by surface insets.
2060 // If this is a portal window, set the touchableRegion to the layerBounds.
2061 Rect layerBounds = info.portalToDisplayId == ADISPLAY_ID_NONE
2062 ? getBufferSize(getDrawingState())
2063 : info.touchableRegion.getBounds();
2064 if (!layerBounds.isValid()) {
2065 layerBounds = getCroppedBufferSize(getDrawingState());
2066 }
2067 layerBounds = t.transform(layerBounds);
2068
2069 // clamp inset to layer bounds
2070 xSurfaceInset = (xSurfaceInset >= 0) ? std::min(xSurfaceInset, layerBounds.getWidth() / 2) : 0;
2071 ySurfaceInset = (ySurfaceInset >= 0) ? std::min(ySurfaceInset, layerBounds.getHeight() / 2) : 0;
2072
2073 layerBounds.inset(xSurfaceInset, ySurfaceInset, xSurfaceInset, ySurfaceInset);
2074
2075 // Input coordinate should match the layer bounds.
2076 info.frameLeft = layerBounds.left;
2077 info.frameTop = layerBounds.top;
2078 info.frameRight = layerBounds.right;
2079 info.frameBottom = layerBounds.bottom;
2080
2081 // Position the touchable region relative to frame screen location and restrict it to frame
2082 // bounds.
2083 info.touchableRegion = info.touchableRegion.translate(info.frameLeft, info.frameTop);
2084 info.visible = canReceiveInput();
2085
2086 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2087 if (info.replaceTouchableRegionWithCrop) {
2088 if (cropLayer == nullptr) {
2089 info.touchableRegion = Region(Rect{mScreenBounds});
2090 } else {
2091 info.touchableRegion = Region(Rect{cropLayer->mScreenBounds});
2092 }
2093 } else if (cropLayer != nullptr) {
2094 info.touchableRegion = info.touchableRegion.intersect(Rect{cropLayer->mScreenBounds});
2095 }
2096
2097 return info;
2098 }
2099
hasInput() const2100 bool Layer::hasInput() const {
2101 return mDrawingState.inputInfo.token != nullptr;
2102 }
2103
getCompositionLayer() const2104 std::shared_ptr<compositionengine::Layer> Layer::getCompositionLayer() const {
2105 return nullptr;
2106 }
2107
canReceiveInput() const2108 bool Layer::canReceiveInput() const {
2109 return !isHiddenByPolicy();
2110 }
2111
findOutputLayerForDisplay(const sp<const DisplayDevice> & display) const2112 compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2113 const sp<const DisplayDevice>& display) const {
2114 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionLayer().get());
2115 }
2116
2117 // ---------------------------------------------------------------------------
2118
2119 }; // namespace android
2120
2121 #if defined(__gl_h_)
2122 #error "don't include gl/gl.h in this file"
2123 #endif
2124
2125 #if defined(__gl2_h_)
2126 #error "don't include gl2/gl2.h in this file"
2127 #endif
2128