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