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